Skip to content

Dependencies

A task asks for what it needs in its signature: a parameter annotated with one of the handles of the run receives it, and a parameter annotated with Depends receives the value of a function called for the run. This page covers both, generator dependencies and the cache of a run.

Injection by annotation

A parameter annotated with one of these types is injected, not an input:

Annotation Receives
Context The context of the run: sandbox, lease, client, task, app, state, run_id, logger; for an agent task, agent and mcp_token(name)
Sandbox The sandbox of the run, ctx.sandbox
Client The client of the daemon, ctx.client
AgentRunner The agent of the sandbox, ctx.agent, for an agent task

The name of the parameter does not matter, its annotation does; subclasses of these types are injected as well.

Dependencies

Annotated[T, Depends(function)] calls function for each run, before the task, and passes what it returns. The dependency itself asks for what it needs the same way, here the sandbox:

docs_src/tasks/dependencies.py
import contextlib
from collections.abc import AsyncIterator
from typing import Annotated

from fastsandbox import Context, Depends, FastSandbox, Sandbox


@contextlib.asynccontextmanager
async def lifespan(app: FastSandbox) -> AsyncIterator[dict[str, str]]:
    yield {"registry": "https://pypi.org/simple"}


app = FastSandbox("deps", lifespan=lifespan)


async def python_version(sandbox: Sandbox) -> str:
    output = await sandbox.exec(["python3", "--version"], check=True)
    return output.stdout.strip()


async def scratch_dir(sandbox: Sandbox) -> AsyncIterator[str]:
    await sandbox.exec(["mkdir", "-p", "/tmp/scratch"], check=True)
    yield "/tmp/scratch"
    await sandbox.exec(["rm", "-rf", "/tmp/scratch"])


@app.task(kit="shell")
async def describe(
    ctx: Context,
    version: Annotated[str, Depends(python_version)],
    scratch: Annotated[str, Depends(scratch_dir)],
) -> dict[str, str]:
    """Describes the Python of the sandbox."""
    return {"python": version, "scratch": scratch, "registry": ctx.state["registry"]}

A dependency is a function, def or async def, or a generator, plain or async:

  • A function returns the value.
  • A generator yields it, once; the code after yield runs when the task has ended, before the sandbox is deleted. scratch_dir creates a directory and removes it that way. When the task raised, the error is raised at the yield: what must run in every case goes in a try/finally around it.

Its parameters can only be injected ones: the handles of the table above and other dependencies. A dependency with a plain parameter makes the run raise TaskError.

Dependencies are resolved in the order of the parameters, after the sandbox is ready and before the timeout of the task starts. A synchronous dependency runs on the event loop: keep it short, or make it async.

Dependencies of dependencies

A dependency can depend on another, and the value of a function is computed once per run: every parameter that depends on the same function receives the same value.

docs_src/tasks/nested_dependencies.py
from collections.abc import AsyncIterator
from typing import Annotated

from fastsandbox import Context, Depends, FastSandbox, Sandbox

app = FastSandbox("deps")


async def scratch_dir(sandbox: Sandbox) -> AsyncIterator[str]:
    output = await sandbox.exec(["mktemp", "-d"], check=True)
    path = output.stdout.strip()
    yield path
    await sandbox.exec(["rm", "-rf", path])


async def input_file(sandbox: Sandbox, scratch: Annotated[str, Depends(scratch_dir)]) -> str:
    path = f"{scratch}/input.txt"
    await sandbox.write_file(path, "one\ntwo\nthree\n")
    return path


@app.task(kit="shell")
async def count_lines(
    ctx: Context,
    path: Annotated[str, Depends(input_file)],
    scratch: Annotated[str, Depends(scratch_dir)],
) -> dict[str, str]:
    """Counts the lines of a file that dependencies prepared."""
    output = await ctx.sandbox.exec(["wc", "-l", path], check=True)
    return {"lines": output.stdout.split()[0], "scratch": scratch}

input_file needs scratch_dir, and so does count_lines: the run creates one directory, writes the file into it, gives both the same path, and removes the directory once the task has ended. Depends(function, use_cache=False) calls the function again for each parameter that asks for it.

The values are not shared between runs: each run has its own sandbox, and its dependencies are resolved anew. What lives as long as the application belongs to its lifespan.