Skip to content

The platform for continuously improving AI agents.

6.8 KB
Raw Blame
"""Where a Workshop task runs code: one network-blocked Modal sandbox per task, created when
the task first runs code and ended when the task settles.

The agent's loop runs on the platform. The sandbox holds only a Python kernel, the task's
pinned inputs and its working files, so nothing in it can reach the platform or a provider.
"""

import base64
import time

import modal
from django.db import transaction
from django.db.models import Q
from django.utils import timezone

from overbae.core.errors import DatasetError
from overbae.models import WorkshopTask
from overbae.services import research_workspace
from overbae.services.workshop_agent import lifecycle

APP = "overmind-workshop"
SECONDS = 3600
SETTLE_SECONDS = 120


def image():
    """The research workspace's image, with the readers a consumer's rows are checked with."""
    return research_workspace.image().add_local_python_source("modal_shared", copy=True)


def existing(task):
    saved = task.workspace
    if not saved.get("sandbox") or saved.get("stopped_at"):
        return None
    sandbox = modal.Sandbox.from_id(saved["sandbox"])
    exit_code = sandbox.poll()
    if exit_code is None:
        return sandbox
    record(task, exit_code=exit_code, stopped_at=timezone.now().isoformat())
    return None


def reserve(task):
    with transaction.atomic():
        locked = WorkshopTask.objects.select_for_update().get(pk=task.pk)
        lifecycle.authorise(locked)
        saved = locked.workspace
        if not saved or saved.get("stopped_at"):
            generation = saved.get("generation", 0) + 1
            saved = {
                "generation": generation,
                "name": f"workshop-{task.pk}-{generation}",
                "environment": research_workspace.environment(),
                "creation_started": False,
                "staged": [],
            }
            locked.workspace = saved
            locked.save(update_fields=["workspace"])
    task.workspace = saved
    return saved


def attach(task):
    """The task's running sandbox, started on first use. A creation that was sent is looked
    for by its name before another is made, so one acknowledgement lost does not leave two."""
    task.refresh_from_db()
    sandbox = existing(task)
    if sandbox is not None:
        research_workspace.rpc(sandbox, operation="ensure")
        return sandbox
    saved = reserve(task)
    try:
        sandbox = modal.Sandbox.from_name(APP, saved["name"], environment_name=saved["environment"])
    except modal.exception.NotFoundError:
        app = modal.App.lookup(APP, create_if_missing=True, environment_name=saved["environment"])
        workspace_image = image()
        with transaction.atomic():
            current = WorkshopTask.objects.select_for_update().get(pk=task.pk)
            lifecycle.authorise(current)
            if current.workspace != saved or current.workspace["creation_started"]:
                raise modal.exception.Error(
                    "Workshop creation acknowledgement is unknown; reconcile the retained intent"
                ) from None
            current.workspace = {**saved, "creation_started": True}
            current.save(update_fields=["workspace"])
            task.workspace = current.workspace
        sandbox = modal.Sandbox.create(
            "sleep",
            str(SECONDS),
            app=app,
            name=saved["name"],
            image=workspace_image,
            cpu=(2, 2),
            memory=(4096, 4096),
            timeout=SECONDS,
            block_network=True,
            secrets=[],
            include_oidc_identity_token=False,
        )
    record(task, sandbox=sandbox.object_id, started_at=timezone.now().isoformat())
    research_workspace.rpc(sandbox, operation="ensure")
    return sandbox


def record(task, **fields):
    with transaction.atomic():
        locked = WorkshopTask.objects.select_for_update().get(pk=task.pk)
        if locked.workspace.get("name") != task.workspace.get("name"):
            raise DatasetError("The Workshop workspace generation changed.", code="dataset_busy")
        if fields.get("sandbox") and locked.workspace.get("sandbox") not in {
            None,
            fields["sandbox"],
        }:
            raise DatasetError("The Workshop provider identity conflicts.", code="dataset_busy")
        locked.workspace = {**locked.workspace, **fields}
        locked.save(update_fields=["workspace"])
    task.workspace = locked.workspace


def stage(task, sandbox, path, source):
    """Place the file at ``source`` read-only at ``inputs/<path>``, once per sandbox."""
    staged = task.workspace.get("staged", [])
    if path in staged:
        return
    research_workspace.stage(None, path, source.read_bytes(), sandbox=sandbox)
    record(task, staged=[*staged, path])


def python(sandbox, execution, code, *, timeout=SETTLE_SECONDS, stopped=lambda: False):
    """Run ``code`` in the task's kernel and wait for it. Variables and files stay for the
    next call. A program still running at the deadline is interrupted."""
    result = research_workspace.rpc(
        sandbox,
        {"operation": "submit", "execution": execution, "code": code, "timeout": timeout},
    )
    deadline = time.monotonic() + timeout + 5
    while result.get("state") in {"accepted", "running"}:
        if stopped() or time.monotonic() > deadline:
            return research_workspace.rpc(
                sandbox, {"operation": "interrupt", "execution": execution, "offset": 0}
            )
        time.sleep(0.2)
        result = research_workspace.rpc(sandbox, {"operation": "status", "execution": execution})
    return result


def read(sandbox, path):
    result = research_workspace.rpc(sandbox, {"operation": "read", "path": path}, operation="file")
    return base64.b64decode(result["base64"], validate=True)


def stop(task):
    """End the task's sandbox. ``False`` while its end is not yet confirmed."""
    task.refresh_from_db(fields=["workspace"])
    saved = task.workspace
    if saved.get("stopped_at") or not saved.get("creation_started") and not saved.get("sandbox"):
        return True
    try:
        if not saved.get("sandbox"):
            try:
                sandbox = modal.Sandbox.from_name(
                    APP, saved["name"], environment_name=saved["environment"]
                )
            except modal.exception.NotFoundError:
                return False
            record(task, sandbox=sandbox.object_id)
        sandbox = modal.Sandbox.from_id(task.workspace["sandbox"])
        exit_code = research_workspace.terminate(sandbox)
        if exit_code is None:
            return False
    except modal.exception.Error:
        return False
    record(task, exit_code=exit_code, stopped_at=timezone.now().isoformat())
    return True


def pending(queryset):
    return queryset.filter(
        Q(workspace__creation_started=True) | Q(workspace__has_key="sandbox")
    ).exclude(workspace__has_key="stopped_at")