Skip to content

Running tasks

A task runs when it is asked to, from async code, from synchronous code or from the command line; each run gets its own sandbox. This page covers the ways to run a task, the progress a task reports, running several at once, and the errors a run raises.

From async code

docs_src/tasks/running.py
import asyncio

import fastsandbox
from fastsandbox import Context, FastSandbox

app = FastSandbox("digests", max_concurrency=2)


@app.task(kit="shell", timeout="2m")
async def sha256(ctx: Context, text: str) -> str:
    """The SHA-256 digest of a text, computed in a sandbox."""
    await ctx.report_progress(1, 2, "sandbox ready")
    output = await ctx.sandbox.exec(
        ["sh", "-c", 'printf %s "$1" | sha256sum', "sh", text], check=True
    )
    await ctx.report_progress(2, 2, "digest computed")
    return output.stdout.split()[0]


def show_progress(progress: float, total: float | None, message: str | None) -> None:
    print(f"{progress:g}/{total}: {message}")


async def main() -> None:
    print(await app.run("sha256", text="hello", on_progress=show_progress))
    digests = await asyncio.gather(*(sha256(text=text) for text in ("a", "b", "c")))
    print(digests)


if __name__ == "__main__":
    fastsandbox.run(main())
  • await app.run("sha256", text="hello") runs a task by name, or given its Task; the keyword arguments are its inputs. It returns the validated result.
  • await sha256(text="a") is the same call: the Task the decorator returned runs through its application.

From synchronous code

app.run_sync("sha256", text="hello") and fastsandbox.run(sha256, text="hello") run a task from a script, a notebook cell or a test, with an event loop of their own; fastsandbox.run(main()) runs any coroutine the same way, as the __main__ block above does. Neither can be called from a running event loop: there, await app.run.

From a shell, fastsandbox run runs a task of a file or a module; see Command line.

Progress

A task reports how far it got with await ctx.report_progress(progress, total, message); the caller receives it through the on_progress argument of app.run, a function, plain or async, called with the three values. sha256 reports two steps, and show_progress prints them. The progress is also logged at the debug level of the logger of the task.

Several runs at once

Runs are independent: asyncio.gather runs several, each in its own sandbox, as main does for three texts. Two bounds limit how many hold a sandbox at once, the others waiting for a free slot before they create theirs:

  • FastSandbox(max_concurrency=2), for every run of the application;
  • @app.task(max_concurrency=...), for the runs of one task.

A bound counts the runs of one event loop: the runs of each asyncio.run, or of each call of run_sync, wait for one another, never for those of another loop, thread or process (see Concurrency and resources).

A program that runs many tasks also starts the application once, with async with app:, so that they share one client and one lifespan (see Lifespan and state).

Errors

The sandbox of a run is deleted when the function returns, raises, times out or is cancelled, unless the task keeps it (keep=True); a killed process, or a second Ctrl-C during the removal, leaves it (see Sandbox lifecycle). A removal that fails never hides what the run did: the error of a run that failed goes on, the failed removal noted on it, and the result of a run that ended well is returned; either way the removal is logged as a warning on the logger of the task, fastsandbox.task.<name>, with the name and the identifier of the sandbox that may stay. The errors a run raises are:

Error When
pydantic.ValidationError The inputs do not match the signature, before anything is created; or the result does not match the return annotation, after the sandbox is deleted.
TaskError The application has no such task, or the task is misdeclared: two workspaces, a dependency with a plain parameter, an agent kit that describes no agent.
InvalidSpecError The spec of the sandbox breaks a rule, before anything is created: a host that is no host pattern, a refusal that covers the host of a key of the agent, a variable set twice.
InvalidKitError, KitForgeError The kit is not named as the sbx CLI names one, or the forge refuses it: a kit only the CLI builds needs a cache that compiles (see Kits).
LaunchError The sandbox, once created, failed to start, to take its HTTP rules or its keys (step); it is removed, unless the task keeps it (kept).
SandboxTimeoutError The task went over its timeout, and after is that timeout in seconds; or a command or an agent run of the task went over its own (exec(timeout=), prompt(timeout=)), and its error goes on as it is, after being its deadline.
CommandFailedError A command run with check=True exited with a non-zero code; exit_code, stdout and stderr tell how.
Another SandboxError The daemon refused or failed an operation: see Errors.
Any other exception Raised by the function of the task, passed on as it is.
docs_src/tasks/errors.py
from pydantic import ValidationError

import fastsandbox
from fastsandbox import CommandFailedError, Context, FastSandbox, SandboxTimeoutError

app = FastSandbox("scripts")


@app.task(kit="shell", timeout="30s")
async def run_script(ctx: Context, script: str) -> str:
    """Runs a shell script and returns what it printed."""
    output = await ctx.sandbox.exec(script, check=True)
    return output.stdout


async def main() -> None:
    try:
        await app.run("run_script")
    except ValidationError as error:
        print(f"invalid inputs: {error.error_count()} error")

    try:
        print(await app.run("run_script", script="exit 3"))
    except CommandFailedError as error:
        print(f"the script exited with code {error.exit_code}")
    except SandboxTimeoutError as error:
        print(f"the script ran over {error.after}s")


if __name__ == "__main__":
    fastsandbox.run(main())

Every error of fastsandbox derives from SandboxError, the framework's included; ValidationError is Pydantic's.