Skip to content

Tasks

A task is a function declared with @app.task: each run launches its sandbox, runs the function and removes the sandbox. This page covers the options of a task, the defaults the application gives them, the sandbox of a run, timeouts, synchronous functions, and the Task object the decorator returns.

Declaring a task

@app.task is used bare, as in the first application, or with options:

docs_src/tasks/options.py
from fastsandbox import Context, FastSandbox, Network

app = FastSandbox("builds", kit="shell", max_concurrency=4)


@app.task(
    name="describe-sandbox",
    network=Network.allow("pypi.org"),
    timeout="5m",
    env={"STAGE": "ci"},
    cpus=2,
    memory="4g",
    max_concurrency=2,
)
async def describe(ctx: Context) -> dict[str, str]:
    """Reports the processors and the environment the sandbox was given."""
    cpus = await ctx.sandbox.exec("nproc", check=True)
    stage = await ctx.sandbox.exec(["printenv", "STAGE"], check=True)
    return {"cpus": cpus.stdout.strip(), "stage": stage.stdout.strip()}
Option Default What it does
name The name of the function The name the task is run by. A second task of the same name raises TaskError.
kit The kit of the application The kit of the sandbox: a name such as "shell" or "claude", a Kit composed with mixins and kit arguments, or a KitPackage, compiled, saved or held in memory, which the sandbox is launched on as it is.
network No rule The network rules of the sandbox.
timeout None The deadline of the function (see Timeouts).
env None Environment variables of the sandbox.
cpus The daemon's Number of virtual CPUs.
memory The daemon's Memory limit in sbx notation, e.g. "4g".
keep False Keeps the sandbox after the run, or after a launch that failed once it existed, to look into it.
description The docstring The documentation of the task.
max_concurrency None How many runs of this task may run at once.

The application has two defaults of its own: FastSandbox(kit=...) is the kit of the tasks that name none, "shell" unless set, and max_concurrency bounds how many runs of any of its tasks hold a sandbox at once. A run waits for a free slot of both bounds before it creates its sandbox.

The sandbox of a run

The sandbox of a run is named after the application and the task, with a random suffix: builds-describe-sandbox-1a2b3c4d. It is launched from a sandbox spec that the task and its inputs describe, and the run holds its Lease, ctx.lease: the answer of its creation (created) and the Report of what the launch did (report), its kits, its network rules, its keys, the keys it left out and the credentials the daemon withholds, never the value of a key:

docs_src/tasks/launch_report.py
from fastsandbox import Context, FastSandbox, Network

app = FastSandbox("reports")


@app.task(kit="shell", network=Network.allow("pypi.org") | Network.deny("example.org"))
async def launch_report(ctx: Context) -> dict[str, list[str]]:
    """What the launch of the sandbox of this run did, as its lease reports it."""
    created = ctx.lease.created
    ctx.log(f"created {created.name}, identifier {created.id}")
    report = ctx.lease.report
    return {
        "kits": report.kits,
        "allowed": report.network.allow,
        "denied": report.network.deny,
        "withheld": report.withheld,
    }

The kits are the base kit, by its digest, then the mixins the launch generated: /kits/docker-sandbox-network for the host rules of the task. For an agent task, report.keys names the variables whose keys go to the proxy, and report.keys_left_out the keys left out, with the reason.

At the end of the run, the lease is shut down: the sandbox is removed, with its network rules and its keys.

Keeping a sandbox

With keep=True, the sandbox is not removed after the run: the run lets the lease go, and sbx ls lists the sandbox, which the client reaches by name with client.sandbox(name); the task can log its name, ctx.sandbox.name. A launch that fails once the sandbox exists keeps it too, and its LaunchError says so (kept). The sandbox stops once no session holds it, keeps its network rules and the keys pushed to its proxy, and it is then yours to delete.

Timeouts

timeout is a number of seconds, a datetime.timedelta, or a duration in ms, s, m, h and d, such as "90s", "10m", "1h30m", "500ms" or "1d"; an unreadable duration raises ValueError when the task is declared. It bounds the call of the function: the launch of the sandbox, the uploads and the dependencies come before the deadline starts. A run that goes over raises SandboxTimeoutError, whose after attribute is the timeout in seconds, and its sandbox is deleted as on any other error.

Commands have deadlines of their own: ctx.sandbox.exec(..., timeout=30) bounds the wait for one command, and ctx.agent.prompt(..., timeout="15m") the wait for one agent run; neither stops the process in the sandbox, which the removal of the sandbox ends (see Timeouts and cancellation). Only the deadline of the task becomes the SandboxTimeoutError of the task: a timeout inside it, the SandboxTimeoutError of such a command or agent run, whose after is its own deadline, or any other TimeoutError the function raises, goes on as it is.

Synchronous tasks

A task can be a plain def. It then runs in a worker thread, so that it does not block the event loop, and reaches the sandbox, whose methods are coroutines, through ctx.wait, which runs an awaitable on the event loop of the run and returns its result:

docs_src/tasks/sync_task.py
from fastsandbox import Context, FastSandbox

app = FastSandbox("sync")


@app.task
def disk_usage(ctx: Context, path: str = "/") -> str:
    """Reports the disk usage of a directory of the sandbox, from synchronous code."""
    output = ctx.wait(ctx.sandbox.exec(["du", "-sh", path], check=True))
    return output.stdout.strip()

Timeouts of synchronous tasks

When a synchronous task goes over its timeout, the run raises SandboxTimeoutError and deletes the sandbox, but a thread cannot be interrupted: the function keeps running until it returns, and the calls it makes to the deleted sandbox fail. asyncio.run, and with it run_sync, fastsandbox.run and the command line, waits for that thread before it returns.

Logging and progress

ctx.log(message) logs through the logger of the task, fastsandbox.task.<name>, with the names of the task and the sandbox; ctx.logger is that logger. ctx.report_progress reports the progress of the run to the caller, as Running tasks shows.

The Task object

The decorator returns a Task, which keeps the options and the analysis of the signature. Calling it runs the task through its application: await describe() is await app.run("describe-sandbox"). The tasks of an application are in app.tasks, by name, and app.get_task(name) returns one, or raises TaskError naming the tasks there are. Task.input_schema and Task.output_schema are the JSON schemas of its inputs and result, as Inputs and outputs explains.