Skip to content

The platform for continuously improving AI agents.

41.7 KB
Raw Blame
from __future__ import annotations

import gzip
import hashlib
import io
import itertools
import json
import math
import re
import threading
from collections.abc import Callable
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from decimal import Decimal
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from urllib.parse import parse_qs, urlparse

import httpx
import modal
from asgiref.sync import sync_to_async
from django.utils import timezone
from modal.exception import AlreadyExistsError, ConflictError, NotFoundError
from modal.volume import FileEntry, FileEntryType
from modal_proto import api_pb2

from modal_shared.decisions import DECISION_OBJECTIVES

_ids = itertools.count(1)


class _Method:
    def __init__(self, sync: Callable[..., Any]) -> None:
        self._sync = sync

    def __call__(self, *args, **kwargs):
        return self._sync(*args, **kwargs)

    async def aio(self, *args, **kwargs):
        return await sync_to_async(self._sync)(*args, **kwargs)


class _IteratorMethod(_Method):
    async def aio(self, *args, **kwargs):
        for chunk in self._sync(*args, **kwargs):
            yield chunk


@dataclass
class FakeCall:
    cloud: FakeModal
    name: str
    handler: Callable[..., Any]
    args: tuple
    kwargs: dict
    held: bool
    object_id: str = field(default_factory=lambda: f"fc-fake-{next(_ids)}")
    state: str = "pending"
    result: Any = None
    error: BaseException | None = None
    children: list[FakeCall] = field(default_factory=list)
    on_get: Callable[[], Any] | None = None
    unreachable: BaseException | None = None
    cancel_deferred: bool = False
    graph_truncated: bool = False

    def run(self) -> None:
        try:
            self.result = self.handler(*self.args, **self.kwargs)
            self.state = "done"
        except Exception as exc:  # noqa: BLE001
            self.error = exc
            self.state = "failed"

    def _get(self, timeout: float | None = None):
        if self.on_get is not None:
            self.on_get()
        if self.unreachable is not None:
            raise self.unreachable
        if self.state == "pending":
            raise TimeoutError(self.object_id)
        if self.state == "cancelled":
            raise modal.exception.InputCancellation(self.object_id)
        if self.error is not None:
            raise self.error
        return self.result

    def _cancel(self, *args, **kwargs) -> None:
        if self.unreachable is not None:
            raise self.unreachable
        self.cloud.cancelled.append((self.object_id, kwargs))
        if self.state == "pending" and not self.cancel_deferred:
            self.state = "cancelled"

    def _node(self):
        from modal.call_graph import InputStatus

        status = {
            "pending": InputStatus.PENDING,
            "done": InputStatus.SUCCESS,
            "failed": InputStatus.FAILURE,
            "cancelled": InputStatus.TERMINATED,
            "timeout": InputStatus.TIMEOUT,
        }[self.state]
        children = [child._node() for child in self.children]
        return SimpleNamespace(function_call_id=self.object_id, status=status, children=children)

    async def hydrate(self):
        return self

    @property
    def client(self):
        async def graph(request, *, retry=None, timeout=None):
            if self.unreachable is not None:
                raise self.unreachable
            inputs, calls = [], []

            def visit(node, parent=""):
                identifier = f"in-{node.function_call_id}"
                inputs.append(
                    api_pb2.InputCallGraphInfo(
                        input_id=identifier,
                        function_call_id=node.function_call_id,
                        status=int(node.status),
                    )
                )
                calls.append(
                    api_pb2.FunctionCallCallGraphInfo(
                        function_call_id=node.function_call_id, parent_input_id=parent
                    )
                )
                for child in node.children:
                    visit(child, identifier)

            visit(self._node())
            return api_pb2.FunctionGetCallGraphResponse(
                inputs=inputs, function_calls=calls, truncated=self.graph_truncated
            )

        return SimpleNamespace(stub=SimpleNamespace(FunctionGetCallGraph=graph))

    @property
    def get(self) -> _Method:
        return _Method(self._get)

    @property
    def cancel(self) -> _Method:
        return _Method(self._cancel)

    @property
    def get_call_graph(self) -> _Method:
        def graph():
            if self.unreachable is not None:
                raise self.unreachable
            return [self._node()]

        return _Method(graph)


class FakeFunction:
    def __init__(self, cloud: FakeModal, app: str, name: str) -> None:
        self.cloud, self.app, self.name = cloud, app, name
        self.options: dict[str, Any] = {}

    def info(self):
        self._handler()
        return SimpleNamespace(image_info=SimpleNamespace(image_id="im-training-fixture"))

    def _handler(self) -> tuple[Callable[..., Any], bool]:
        key = (self.app, self.name)
        if key not in self.cloud.handlers:
            raise NotFoundError(f"Function {self.app}/{self.name} is not deployed.")
        return self.cloud.handlers[key]

    def _remote(self, *args, **kwargs):
        handler, _ = self._handler()
        self.cloud.log.append(("remote", self.name, args, kwargs))
        return handler(*args, **kwargs)

    def _spawn(self, *args, **kwargs) -> FakeCall:
        handler, held = self._handler()
        call = FakeCall(self.cloud, self.name, handler, args, kwargs, held)
        self.cloud.log.append(("spawn", self.name, args, kwargs))
        self.cloud.calls[call.object_id] = call
        if not held:
            call.run()
        if self.cloud.function_spawn_acknowledger:
            self.cloud.function_spawn_acknowledger(call)
        return call

    @property
    def remote(self) -> _Method:
        return _Method(self._remote)

    def remote_gen(self, *args, **kwargs):
        handler, _ = self._handler()
        self.cloud.log.append(("remote_gen", self.name, args, kwargs))
        produced = handler(*args, **kwargs)
        if isinstance(produced, dict):
            yield produced
        else:
            yield from produced

    @property
    def spawn(self) -> _Method:
        return _Method(self._spawn)

    def _current_stats(self):
        self.cloud.log.append(("stats", self.name, (), {}))
        stats = self.cloud.worker_stats
        if isinstance(stats, BaseException):
            raise stats
        if stats is None:
            raise NotFoundError(f"{self.app}/{self.name} has no running pool.")
        return SimpleNamespace(**stats)

    @property
    def get_current_stats(self) -> _Method:
        return _Method(self._current_stats)

    def with_options(self, **options) -> FakeFunction:
        self.options.update(options)
        if self.cloud.function_options_handler:
            self.cloud.function_options_handler(self)
        return self


class _FakeInstance:
    def __init__(self, cloud: FakeModal, app: str, cls: str) -> None:
        self._cloud, self._app, self._cls = cloud, app, cls

    def update_autoscaler(self, **kwargs):
        self._cloud.log.append(("autoscaler", f"{self._app}/{self._cls}", (), kwargs))
        return None

    def __getattr__(self, method: str) -> FakeFunction:
        return FakeFunction(self._cloud, self._app, f"{self._cls}.{method}")


@dataclass
class _FakeCls:
    cloud: FakeModal
    app: str
    cls: str

    def with_options(self, **_options) -> _FakeCls:
        return self

    def __call__(self, **_parameters) -> _FakeInstance:
        return _FakeInstance(self.cloud, self.app, self.cls)


WORKSPACE_VOLUMES = "overmind-ws-"
# Modal's sandbox price in the fake: what a sandbox costs for each second it runs.
SANDBOX_COST_PER_SECOND = Decimal("0.0001")


@dataclass
class FakeProcess:
    code: int
    out: str
    err: str

    def __post_init__(self):
        self.stdout = SimpleNamespace(read=lambda: self.out)
        self.stderr = SimpleNamespace(read=lambda: self.err)
        self.stdin = SimpleNamespace(
            write=lambda _data: None, write_eof=lambda: None, drain=lambda: None
        )

    def wait(self) -> int:
        return self.code


@dataclass
class FakeSandbox:
    """A Modal sandbox: its mounts, the files it holds and the commands it ran. A ``mv``
    into a mount lands in that Volume; every other command answers ``cloud.exec_answer``."""

    cloud: FakeModal
    name: str | None
    tags: dict[str, str]
    region: list[str] | None
    mounts: dict[str, str]
    object_id: str = field(default_factory=lambda: f"sb-fake-{next(_ids)}")
    created_at: datetime = field(default_factory=timezone.now)
    ended_at: datetime | None = None
    files: dict[str, bytes] = field(default_factory=dict)
    commands: list[tuple[str, ...]] = field(default_factory=list)

    def get_tags(self) -> dict[str, str]:
        return dict(self.tags)

    def poll(self) -> int | None:
        return None if self.ended_at is None else 0

    def terminate(self, *, wait: bool = False) -> None:
        self.ended_at = self.ended_at or timezone.now()

    def wait(self, raise_on_termination: bool = True) -> None:
        self.terminate()

    def wait_until_ready(self, *, timeout: int = 300) -> None:
        if set(self.region or ()) & self.cloud.full_regions:
            raise modal.exception.TimeoutError("not ready")

    def exec(self, *args, timeout=None, **_) -> FakeProcess:
        self.commands.append(args)
        command = args[-1]
        moved = re.search(r"mv (\S+) (\S+)", command)
        if moved:
            source, target = moved.groups()
            volume, path = self._mount(target.strip("'"))
            volume[path] = self.files.pop(source)
        return FakeProcess(*self.cloud.exec_answer)

    def _mount(self, path: str) -> tuple[dict[str, bytes], str]:
        for root, name in self.mounts.items():
            if path.startswith(root + "/"):
                return self.cloud.volumes[name], path[len(root) :]
        raise AssertionError(f"{path} is on no mount")

    @property
    def filesystem(self):
        def copy_from_local(local, remote):
            if self.cloud.copy_fails:
                raise modal.exception.ConnectionError("reset")
            self.files[remote] = Path(local).read_bytes()

        return SimpleNamespace(copy_from_local=copy_from_local, read_bytes=self.files.__getitem__)

    def _experimental_stats(self, *, since: datetime, until: datetime):
        end = min(until, self.ended_at or until)
        ran = max(timedelta(0), end - max(since, self.created_at))
        measured = self.object_id not in self.cloud.unmeasured
        cost = SANDBOX_COST_PER_SECOND * int(ran.total_seconds()) if measured and ran else None
        return SimpleNamespace(
            duration=ran,
            cost=cost,
            cost_by_resource={"CPU": cost} if cost else {},
            billed_cpu_core_seconds=ran.total_seconds() * 0.25,
            billed_memory_gib_seconds=ran.total_seconds(),
        )


@dataclass
class FakeModal:
    handlers: dict[tuple[str, str], tuple[Callable[..., Any], bool]] = field(default_factory=dict)
    calls: dict[str, FakeCall] = field(default_factory=dict)
    log: list[tuple[str, str, tuple, dict]] = field(default_factory=list)
    cancelled: list[tuple[str, dict]] = field(default_factory=list)
    files: dict[str, bytes] = field(default_factory=dict)
    volume_read_handler: Callable[[str], None] | None = None
    dictionaries: dict[tuple[str, str], dict[str, Any]] = field(default_factory=dict)
    sandboxes: dict[str, Any] = field(default_factory=dict)
    sandbox_create_error: Exception | None = None
    function_spawn_acknowledger: Callable[[FakeCall], None] | None = None
    function_options_handler: Callable[[FakeFunction], None] | None = None
    sandbox_lookup_error: Exception | None = None
    sandbox_exit_on_exec: int | None = None
    sandbox_exec_error: Exception | None = None
    sandbox_exec_handler: Callable[..., Any] | None = None
    sandbox_expire_after_poll: bool = False
    app_logs: list[Any] = field(default_factory=list)
    worker_stats: dict[str, Any] | BaseException | None = None
    sandboxes: dict[str, FakeSandbox] = field(default_factory=dict)
    # Items of Workspace.billing.report: cost and environment_name each.
    billing_items: list[Any] = field(default_factory=list)
    # Files of each workspace Volume, by path in the Volume.
    volumes: dict[str, dict[str, bytes]] = field(default_factory=dict)
    full_regions: set[str] = field(default_factory=set)
    unmeasured: set[str] = field(default_factory=set)
    exec_answer: tuple[int, str, str] = (0, "", "")
    copy_fails: bool = False
    _lock: threading.Lock = field(default_factory=threading.Lock)

    def running(self, name: str) -> list[FakeSandbox]:
        return [
            s
            for s in self.sandboxes.values()
            if isinstance(s, FakeSandbox) and s.name == name and s.ended_at is None
        ]

    def deploy(
        self, app: str, name: str, handler: Callable[..., Any], *, held: bool = False
    ) -> None:
        self.handlers[(app, name)] = (handler, held)

    def adopt(self, object_id: str, name: str = "operation", **fields: Any) -> FakeCall:
        call = FakeCall(self, name, lambda: None, (), {}, True, object_id=object_id, **fields)
        self.calls[object_id] = call
        return call

    def spawns(self) -> list[str]:
        return [name for kind, name, _, _ in self.log if kind == "spawn"]

    def pending(self, name_prefix: str) -> list[FakeCall]:
        return [
            c
            for c in self.calls.values()
            if c.state == "pending" and c.name.startswith(name_prefix)
        ]

    def release(self, name_prefix: str) -> int:
        calls = self.pending(name_prefix)
        for call in calls:
            call.run()
        return len(calls)

    def fail(self, name_prefix: str, error: Exception) -> int:
        calls = self.pending(name_prefix)
        for call in calls:
            call.error = error
            call.state = "failed"
        return len(calls)

    def called(self, name_prefix: str) -> list[str]:
        return [kind for kind, name, _, _ in self.log if name.startswith(name_prefix)]

    def install(self, monkeypatch) -> FakeModal:
        cloud = self

        def fetch_logs(*, since, until, search_text=""):
            return [
                entry
                for entry in cloud.app_logs
                if since <= entry.timestamp <= until and search_text in entry.message
            ]

        monkeypatch.setattr(
            modal.App,
            "lookup",
            _Method(
                lambda *args, **kwargs: SimpleNamespace(
                    app_id="ap-fake", logs=SimpleNamespace(fetch=_IteratorMethod(fetch_logs))
                )
            ),
        )

        class Function:
            @staticmethod
            def from_name(app: str, name: str, **_) -> FakeFunction:
                return FakeFunction(cloud, app, name)

        class Dict:
            @staticmethod
            def from_name(name, *, environment_name="", **_):
                values = cloud.dictionaries.setdefault((environment_name, name), {})
                return SimpleNamespace(
                    get=_Method(values.get),
                    put=_Method(values.__setitem__),
                    items=_Method(lambda: list(values.items())),
                    pop=_Method(values.pop),
                )

        class Workspace:
            @staticmethod
            def from_context():
                return SimpleNamespace(
                    billing=SimpleNamespace(
                        report=_Method(lambda **_: list(cloud.billing_items)),
                        rates=_Method(
                            lambda: {
                                "gpu_hour_cost_h100": 3.95,
                                "gpu_hour_cost_h200": 4.54,
                                "cpu_hour_cost": 0.0473,
                                "mem_gib_hour_cost": 0.008,
                                "cpu_hour_cost_sandbox": 0.1419,
                                "mem_gib_hour_cost_sandbox": 0.024,
                            }
                        ),
                    )
                )

        class FunctionCall:
            @staticmethod
            def from_id(call_id: str) -> FakeCall:
                if call_id not in cloud.calls:
                    raise NotFoundError(call_id)
                return cloud.calls[call_id]

        class Cls:
            @staticmethod
            def from_name(app: str, cls: str, **_):
                return _FakeCls(cloud, app, cls)

        class Sandbox:
            def __init__(self, args, options):
                self.object_id = f"sb-fixture-{next(_ids)}"
                self.args, self.options = args, options
                self.exit_code = None
                # Bytes written through the file API, by path, until an exec moves them.
                self.files = {}
                self.filesystem = SimpleNamespace(
                    write_bytes=self.write_bytes, copy_to_local=self.copy_to_local
                )

            def write_bytes(self, data, path):
                self.files[path] = data

            def copy_to_local(self, remote, local):
                Path(local).write_bytes(self.files[remote])

            @staticmethod
            def create(*args, **kwargs):
                # The assistant's workspaces and the task sandboxes are two fakes behind one name.
                if str(kwargs.get("name") or "").startswith(WORKSPACE_VOLUMES):
                    return WorkspaceSandbox.create(*args, **kwargs)
                volumes = [volume.name for volume in kwargs.get("volumes", {}).values()]
                if len(volumes) != len(set(volumes)):
                    raise modal.exception.InvalidError("A Volume cannot be mounted twice")
                sandbox = Sandbox(args, kwargs)
                cloud.sandboxes[sandbox.object_id] = sandbox
                cloud.log.append(("sandbox", kwargs["name"], args, kwargs))
                if cloud.sandbox_create_error:
                    raise cloud.sandbox_create_error
                return sandbox

            @staticmethod
            def from_id(identity):
                return cloud.sandboxes[identity]

            @staticmethod
            def list(**kwargs):
                return WorkspaceSandbox.list(**kwargs)

            @staticmethod
            def from_name(app, name, **kwargs):
                if name.startswith(WORKSPACE_VOLUMES):
                    return WorkspaceSandbox.from_name(app, name, **kwargs)
                if cloud.sandbox_lookup_error:
                    raise cloud.sandbox_lookup_error
                for sandbox in cloud.sandboxes.values():
                    if (
                        isinstance(sandbox, Sandbox)
                        and sandbox.options["name"] == name
                        and sandbox.exit_code is None
                    ):
                        return sandbox
                raise NotFoundError(name)

            def poll(self):
                if cloud.sandbox_expire_after_poll:
                    cloud.sandbox_expire_after_poll = False
                    previous, self.exit_code = self.exit_code, 137
                    return previous
                return self.exit_code

            def terminate(self, **kwargs):
                self.exit_code = 137

            def create_connect_token(self, port):
                if self.options.get("block_network"):
                    raise ConflictError("Cannot connect to a Sandbox with blocked network access")
                return SimpleNamespace(
                    url=f"https://sandbox.test/{self.object_id}", token="fixture-connect-token"
                )

            def exec(self, *args, **kwargs):
                cloud.log.append(("sandbox_exec", self.object_id, args, kwargs))
                if self.exit_code is not None:
                    raise NotFoundError("Task has already finished")
                if cloud.sandbox_exec_handler is not None:
                    return cloud.sandbox_exec_handler(*args, sandbox=self, **kwargs)
                if cloud.sandbox_exec_error is not None:
                    error, cloud.sandbox_exec_error = cloud.sandbox_exec_error, None
                    raise error
                if cloud.sandbox_exit_on_exec is not None:
                    self.exit_code = cloud.sandbox_exit_on_exec
                    cloud.sandbox_exit_on_exec = None
                    raise NotFoundError("Task has already finished")
                payload = json.loads(args[4])
                response = httpx.request(
                    "POST" if payload is not None else "GET",
                    f"https://sandbox.test/{self.object_id}{args[3]}",
                    json=payload,
                )
                return SimpleNamespace(
                    stdout=io.StringIO(response.text),
                    stderr=io.StringIO(),
                    wait=lambda: 0 if response.status_code == 200 else 1,
                )

        class Volume:
            objects = SimpleNamespace(
                list=lambda **_: [SimpleNamespace(name=name) for name in cloud.volumes],
                delete=lambda name, **_: cloud.volumes.pop(name, None),
            )

            def __init__(self, name=""):
                self.name = name
                self.prefix = (
                    f"{name}:"
                    if name.startswith(("training-execution-", "training-diagnostic-"))
                    else ""
                )

            @staticmethod
            def from_name(name="", *args, create_if_missing=False, **kwargs):
                if not name.startswith(WORKSPACE_VOLUMES):
                    return Volume(name)
                if create_if_missing:
                    cloud.volumes.setdefault(name, {})
                return WorkspaceVolume(name)

            def with_mount_options(self, **options):
                return SimpleNamespace(name=self.name, **options)

            @contextmanager
            def batch_upload(self, **kwargs):
                yield self

            def put_file(self, local, remote):
                cloud.files[self.prefix + remote.lstrip("/") if self.prefix else remote] = (
                    local.read() if hasattr(local, "read") else Path(local).read_bytes()
                )

            def _read_file(self, path):
                path = self.prefix + path.lstrip("/") if self.prefix else path
                if cloud.volume_read_handler is not None:
                    cloud.volume_read_handler(path)
                if path not in cloud.files:
                    raise FileNotFoundError(path)
                yield cloud.files[path]

            @property
            def read_file(self):
                return _IteratorMethod(self._read_file)

        class WorkspaceVolume:
            def __init__(self, name):
                self.name = name

            def read_only(self):
                return self

            def hydrate(self):
                if self.name not in cloud.volumes:
                    raise NotFoundError(self.name)
                return self

            def listdir(self, path, **_):
                folder = path.rstrip("/") + "/"
                return [
                    FileEntry(path=key, type=FileEntryType.FILE, mtime=0, size=len(content))
                    for key, content in cloud.volumes[self.name].items()
                    if key.startswith(folder) and "/" not in key[len(folder) :]
                ]

            def read_file(self, path):
                yield cloud.volumes[self.name][path]

            def remove_file(self, path, recursive=False):
                files = cloud.volumes[self.name]
                for key in [k for k in files if k == path or k.startswith(path + "/")]:
                    del files[key]

        class WorkspaceSandbox:
            @staticmethod
            def create(*args, name=None, tags=None, region=None, volumes=None, **_):
                with cloud._lock:
                    if name and cloud.running(name):
                        raise AlreadyExistsError(name)
                    mounts = {root: volume.name for root, volume in (volumes or {}).items()}
                    sandbox = FakeSandbox(cloud, name, tags or {}, region, mounts)
                    cloud.sandboxes[sandbox.object_id] = sandbox
                return sandbox

            @staticmethod
            def from_name(app_name, name, **_):
                found = cloud.running(name)
                if not found:
                    raise NotFoundError(name)
                return found[0]

            @staticmethod
            def from_id(sandbox_id, **_):
                return cloud.sandboxes[sandbox_id]

            @staticmethod
            def list(*, app_id=None, tags=None, **_):
                return [
                    s
                    for s in cloud.sandboxes.values()
                    if isinstance(s, FakeSandbox)
                    and s.ended_at is None
                    and (tags or {}).items() <= s.tags.items()
                ]

        monkeypatch.setattr(modal, "Sandbox", Sandbox)
        monkeypatch.setattr(
            modal.Secret, "from_dict", staticmethod(lambda values: SimpleNamespace(values=values))
        )
        monkeypatch.setattr(
            modal.Image, "from_id", lambda identity: SimpleNamespace(object_id=identity)
        )
        monkeypatch.setattr(modal, "Volume", Volume)
        monkeypatch.setattr(modal, "Function", Function)
        monkeypatch.setattr(modal, "Cls", Cls)
        monkeypatch.setattr(modal, "FunctionCall", FunctionCall)
        monkeypatch.setattr(modal, "Dict", Dict)
        monkeypatch.setattr(modal, "Workspace", Workspace)
        return self


SFT_APP = "overmind-sft"


@dataclass
class SftBackend:
    cloud: FakeModal
    runs: dict[str, dict[str, Any]] = field(default_factory=dict)
    uploads: list[str] = field(default_factory=list)
    prepared: dict[str, dict] = field(default_factory=dict)
    materialized: dict[str, dict] = field(default_factory=dict)
    execution_events: dict[str, list[dict]] = field(default_factory=dict)

    def program(self, request):
        packet = json.loads(
            next(m["content"] for m in reversed(request.messages) if m["role"] == "user")
        )
        return json.dumps(
            {
                "rationale": "Use the pinned engine and exact prepared inputs",
                "evidence": packet["context"]["roots"][:1],
                "files": [
                    {
                        "path": "train.py",
                        "source": "from training_runtime.engine import train\ntrain()\n",
                    }
                ],
                "entrypoint": "train.py",
                "controls": [
                    "stop",
                    "checkpoint",
                    "evaluate",
                    "set_learning_rate",
                    "set_clip_norm",
                ],
                "checks": ["Exact labels and split membership"],
                "parameters": {},
            }
        )

    def execution(self, sandbox):
        volume = sandbox.options["volumes"]["/execution"].name
        contract = json.loads(self.cloud.files[f"{volume}:execution.json"])
        return volume, contract

    def emit(self, sandbox, kind, payload, step=0):
        from datetime import datetime

        volume, _ = self.execution(sandbox)
        events = self.execution_events.setdefault(sandbox.object_id, [])
        events.append(
            {
                "sequence": len(events) + 1,
                "kind": kind,
                "payload": payload,
                "step": step,
                "observed_at": datetime.now(UTC).isoformat(),
            }
        )
        self.cloud.files[f"{volume}:events.json"] = json.dumps(events).encode()

    def start(self, sandbox):
        if sandbox.object_id in self.execution_events:
            return
        _, contract = self.execution(sandbox)
        self.emit(
            sandbox,
            "qualification",
            {
                "identity": contract["qualification"]["identity"],
                "state": "passed",
                "evidence": {"fixture": "network provider"},
            },
        )
        self.emit(sandbox, "state", {"state": "running"})
        for step in (1, 2):
            self.emit(sandbox, "metrics", {"loss": 1 / step, "epoch": 1.0}, step)

    def release_training(self):
        from modal_shared.training_monitoring import fingerprint

        for sandbox in self.cloud.sandboxes.values():
            if sandbox.exit_code is not None:
                continue
            self.start(sandbox)
            volume, contract = self.execution(sandbox)
            run_id = sandbox.options["volumes"]["/inputs"].sub_path.split("/")[-1]
            self._train(run_id, contract["engine_environment"])
            artifact = {
                "files": {
                    "model.safetensors": {
                        "bytes": 7,
                        "sha256": hashlib.sha256(b"weights").hexdigest(),
                    }
                }
            }
            self.cloud.files[f"{volume}:output/model.safetensors"] = b"weights"
            self.emit(
                sandbox,
                "state",
                {"state": "succeeded", "artifact": artifact, "identity": fingerprint(artifact)},
                2,
            )
            sandbox.exit_code = 0

    def handle(self, method, url, body, headers):
        parsed = urlparse(url)
        if parsed.netloc != "sandbox.test":
            return None
        identity, endpoint = parsed.path.strip("/").split("/", 1)
        sandbox = self.cloud.sandboxes[identity]
        _, contract = self.execution(sandbox)
        self.start(sandbox)
        if endpoint == "status":
            result = {"identity": contract["identity"], "process": {"state": "running"}}
        elif endpoint == "events":
            cursor = int(parse_qs(parsed.query).get("after", [0])[0])
            result = {
                "generation": contract["generation"],
                "events": self.execution_events[identity][cursor : cursor + 500],
            }
        elif endpoint == "commands":
            commands = json.loads(body)["commands"]
            for command in commands:
                if command["operation"] == "stop":
                    self.emit(sandbox, "state", {"state": "stopped"}, 2)
                    sandbox.exit_code = 0
            result = {"accepted": [command["id"] for command in commands]}
        else:
            result = {}
        return 200, {"content-type": "application/json"}, json.dumps(result).encode()

    def publish(self, *, run_id, volume_name, manifest, identity):
        return {
            "execution_artifact": identity,
            "artifact_identity": identity,
            **(self._progress(run_id).get("native_artifact") or {}),
        }

    def install(self) -> SftBackend:
        from modal_shared.stacks import TRAIN_FUNCTION_NAMES
        from overbae.services.training_release import current

        release = current()
        app = release["app"]
        self.cloud.deploy(app, "release_identity", lambda: release)
        for name in TRAIN_FUNCTION_NAMES.values():
            self.cloud.deploy(app, name, self._train, held=True)
            self.cloud.deploy(app, f"prepare_{name}", self._prepare, held=True)
        self.cloud.deploy(app, "upload_dataset", self._upload)
        self.cloud.deploy(app, "get_progress", self._progress)
        self.cloud.deploy(app, "mark_cancelled", self._cancelled)
        self.cloud.deploy(app, "publish_native_training", self.publish)
        self.cloud.deploy("overmind-register", "fetch_base_model", lambda **_: {"ok": True})
        return self

    def _prepare(self, preparation_id: str, request: dict) -> dict:
        from modal_shared.training_data import row_key

        body = self.cloud.files[request["rows_path"].removeprefix("/data")]
        assert hashlib.sha256(body).hexdigest() == request["rows_sha256"]
        rows = [json.loads(line) for line in gzip.decompress(body).splitlines()]
        self.prepared[preparation_id] = {row_key(row): row for row in rows}
        return {
            "ready": True,
            "max_tokens": 64,
            "incompatible_rows": 0,
            "rows": len(rows),
            "artifact_sha256": hashlib.sha256(body).hexdigest(),
        }

    def _upload(
        self, run_id: str, *, preparation_id, artifact_sha256, selections, monitoring=None
    ) -> dict:
        self.uploads.append(run_id)
        self.runs[run_id] = {"status": "running", "steps": 2}
        rows = {}
        for name, spec in selections.items():
            content = self.cloud.files[f"/runs/{run_id}/selected-{name}.keys"]
            assert hashlib.sha256(content).hexdigest() == spec["sha256"]
            rows[name] = [
                self.prepared[preparation_id][content[i : i + 32].hex()]
                for i in range(0, len(content), 32)
            ]
            assert len(rows[name]) == spec["rows"]
        self.materialized[run_id] = rows
        return {"run_id": run_id, "rows": len(rows["data"])}

    def crash(self, message: str = "CUDA out of memory") -> None:
        for sandbox in self.cloud.sandboxes.values():
            self.start(sandbox)
            self.emit(sandbox, "state", {"state": "failed", "error": message})
            sandbox.exit_code = 1
        for run in self.runs.values():
            run["status"] = "failed"
        self.cloud.fail("sft_", RuntimeError(message))

    def _train(self, run_id: str, env: dict, *, gpu_type: str = "", gpu_count: int = 1) -> dict:
        self.runs[run_id].update(status="succeeded", objective=env.get("TRAINING_OBJECTIVE"))
        return {"run_id": run_id, "status": "succeeded"}

    def _cancelled(self, run_id: str) -> dict:
        self.runs.setdefault(run_id, {"steps": 0})["status"] = "cancelled"
        return {"run_id": run_id, "status": "cancelled"}

    def _progress(self, run_id: str) -> dict:
        run = self.runs.get(run_id)
        if run is None:
            return {"run_id": run_id, "found": False}
        metrics = [
            {
                "event": "BT_PROGRESS",
                "step": step,
                "total_steps": run["steps"],
                "loss": 1.0 / step,
                "epoch": 1.0,
            }
            for step in range(1, run["steps"] + 1)
        ]
        progress = {
            "run_id": run_id,
            "found": True,
            "meta": {"status": run["status"]},
            "metrics": metrics,
            "has_final_checkpoint": run["status"] == "succeeded" or bool(run.get("final")),
        }
        if run["status"] == "succeeded" and run.get("objective") in DECISION_OBJECTIVES:
            progress["native_artifact"] = {
                "artifact_identity": hashlib.sha256(run_id.encode()).hexdigest(),
                "reload_verification": {
                    "decisions": len(self.materialized[run_id]["data"]),
                    "max_absolute_error": 0.0,
                    "tolerance": 1e-4,
                    "weight_reload": "exact",
                },
                "training": {"objective": run["objective"]},
            }
        return progress


@dataclass
class ServingBackend:
    cloud: FakeModal
    url: str
    warmed: list[str] = field(default_factory=list)

    def install(self) -> ServingBackend:
        register = "overmind-register"
        self.cloud.deploy(register, "fetch_base_model", lambda **_: {"ok": True})
        self.cloud.deploy(register, "sync_modal_checkpoint_to_s3", lambda **_: {"ok": True})
        self.cloud.deploy(register, "publish_adapter", self._publish_adapter)
        self.cloud.deploy(register, "RegisterAPIServer.register", self._merged)
        self.cloud.deploy(register, "RegisterAPIServer.register_base", self._merged)
        self.cloud.deploy("overmind-inference", "InferenceAPIServer.register_model", self._register)
        self.cloud.deploy("overmind-inference", "pre_warm", self._pre_warm)
        return self

    def _publish_adapter(self, *, base_model: str, **_) -> dict:
        return {
            "base_path": f"/weights/.base_models/{base_model.replace('/', '--')}",
            "lora_rank": 16,
        }

    def _merged(self, *, model_id: str, **_) -> dict:
        return {"weights_path": f"/weights/{model_id}", "quantization": "bf16", "num_parameters": 0}

    def _register(self, **_) -> str:
        return self.url

    def _pre_warm(self, *, model_id: str, **_) -> dict:
        self.warmed.append(model_id)
        return {"ok": True}


def _uniform(request: dict, trained: bool) -> list[float]:
    return [1 / len(request["options"])] * len(request["options"])


@dataclass
class DecisionBackend:
    """Native decision evaluation on the training release and the decision serving worker.

    ``answer(request, trained)`` returns the option probabilities a model gives."""

    cloud: FakeModal
    answer: Callable[[dict, bool], list[float]] = _uniform
    prepared: dict[str, str] = field(default_factory=dict)

    def install(self) -> DecisionBackend:
        from overbae.services.decision_serving import current_runtime
        from overbae.services.native_evaluation import runtime

        self.release = runtime()
        serve = current_runtime()["app"]
        self.cloud.deploy(self.release["app"], "prepare", self._prepare)
        self.cloud.deploy(self.release["app"], "predict", self._predict)
        self.cloud.deploy(serve, "publish", self._publish)
        self.cloud.deploy(serve, "pre_warm", self._pre_warm)
        self.cloud.deploy(serve, "DecisionEndpoint.predict", self._serve)
        return self

    def _inputs(self, evaluation_id: str) -> tuple[bytes, list[dict]]:
        body = self.cloud.files[f"/decision-evaluations/{evaluation_id}/inputs.jsonl"]
        return body, [json.loads(line) for line in body.splitlines() if line]

    def _prepare(self, evaluation_id, model_run, input_sha256, *, foundation=None, inference=None):
        body, rows = self._inputs(evaluation_id)
        assert hashlib.sha256(body).hexdigest() == input_sha256
        identity = (
            hashlib.sha256(model_run.encode()).hexdigest()
            if model_run
            else f"foundation:{foundation['model']}"
        )
        self.prepared[evaluation_id] = identity
        self.cloud.files[f"/decision-evaluations/{evaluation_id}/failures.jsonl"] = b""
        return {
            "artifact_identity": identity,
            "input_sha256": input_sha256,
            "instructions": (inference or {}).get("instructions", ""),
            "ready_decisions": len(rows),
            "failures_sha256": hashlib.sha256(b"").hexdigest(),
        }

    def _predict(self, evaluation_id, model_run, *, base_only, inference=None):
        body, rows = self._inputs(evaluation_id)
        identity = self.prepared[evaluation_id]
        predictions = []
        for row in rows:
            probabilities = self.answer(row["decision"], not base_only)
            predictions.append(
                {
                    "key": row["key"],
                    "input_sha256": row["input_sha256"],
                    "kind": row["decision"]["kind"],
                    "model_identity": identity,
                    "probabilities": probabilities,
                    "log_probabilities": [math.log(p) for p in probabilities],
                }
            )
        output = "".join(json.dumps(p) + "\n" for p in predictions).encode()
        name = "base" if base_only else "candidate"
        self.cloud.files[f"/decision-evaluations/{evaluation_id}/{name}.jsonl"] = output
        return {
            "artifact_identity": identity,
            "input_sha256": hashlib.sha256(body).hexdigest(),
            "runtime_fingerprint": self.release["training"],
            "predictions_sha256": hashlib.sha256(output).hexdigest(),
            "decisions": len(predictions),
        }

    def _publish(self, *, remote_id, artifact_identity) -> dict:
        return {
            "weights_path": f"/weights/decisions/{remote_id}",
            "artifact_identity": artifact_identity,
        }

    def _pre_warm(
        self, *, weights_path, artifact_identity, max_model_len, gpu_type, base_model_id=""
    ) -> dict:
        return {"verified": True, "artifact_identity": artifact_identity}

    def _serve(self, requests: list[dict]) -> dict:
        return {
            "predictions": [
                {"options": request["options"], "probabilities": self.answer(request, True)}
                for request in requests
            ],
            "usage": {"prompt_tokens": 8 * len(requests), "completion_tokens": 0},
            "finish_reason": "stop",
        }


def open_chat_tunnel(cloud: FakeModal, cls_name: str, reply: dict, stream: bytes | None = None):
    """The dedicated worker's port forward. Chat posts here; the probe still uses infer."""
    encoded = json.dumps(reply).encode()

    class Handler(BaseHTTPRequestHandler):
        def do_POST(self):
            size = int(self.headers.get("Content-Length") or 0)
            incoming = json.loads(self.rfile.read(size) or b"{}")
            if incoming.get("stream"):
                body, content_type = stream or b"", "text/event-stream"
            else:
                body, content_type = encoded, "application/json"
            self.send_response(200)
            self.send_header("Content-Type", content_type)
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def log_message(self, format, *args):
            return

    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    url = f"http://127.0.0.1:{server.server_address[1]}"
    cloud.deploy("overmind-dedicated", f"{cls_name}.direct_url", lambda **_kwargs: url)
    return server