Skip to content

The platform for continuously improving AI agents.

21.9 KB
Raw Blame
"""Workspaces in Modal sandboxes: one sandbox for each project, one kernel for each
conversation in it. The project's files live on two Volumes, so they outlive the sandbox,
which ends after an idle hour or at Modal's 24-hour limit, and its kernels with it.

    /workspace/data/<name>            the project's versions: root's, read-only to kernels
    /workspace/conversations/<c>/     a kernel's folder, under the conversation's own uid

A version goes in and a file comes out through the running sandbox: a Volume that a
sandbox mounts refuses outside reads and writes. With no sandbox running, the Volume API
serves them directly.
"""

import contextlib
import hashlib
import json
import logging
import os
import shlex
import tempfile
import threading
import time
import tomllib
import uuid
from datetime import timedelta
from decimal import Decimal
from functools import cache
from pathlib import Path
from typing import BinaryIO

import modal
from django.conf import settings
from django.db import connection, transaction
from django.utils import timezone
from modal.exception import AlreadyExistsError, NotFoundError
from modal.volume import FileEntryType

from overbae.models import BillingService, Project, WorkspaceSandbox
from overbae.services.billing_ledger import Cause, charge
from overbae.services.workspaces import (
    MAX_FILE_BYTES,
    DataTooLargeError,
    Execution,
    WorkspaceUnavailableError,
)
from sandbox import execute
from sandbox.kernel import __file__ as kernel_file
from sandbox.workspaces import ID, NAME, RESTARTED

logger = logging.getLogger(__name__)

APP = "overmind-workspaces"
PREFIX = "overmind-ws-"
# The libraries a kernel imports, at the versions the app locks.
LIBRARIES = (
    "beautifulsoup4",
    "datasketch",
    "duckdb",
    "emoji",
    "ftfy",
    "jellyfish",
    "jsonschema",
    "langcodes",
    "langdetect",
    "levenshtein",
    "lxml",
    "markdownify",
    "matplotlib",
    "numpy",
    "pandas",
    "pillow",
    "pyarrow",
    "python-dateutil",
    "pytz",
    "pyyaml",
    "rapidfuzz",
    "regex",
    "scikit-learn",
    "scipy",
    "simhash",
    "tiktoken",
    "unidecode",
    "wordfreq",
)
PYTHON = "3.13"
TOKENIZER_ENCODINGS = ("cl100k_base", "o200k_base")
TOKENIZERS = "/opt/overmind/tiktoken"
KERNEL = Path(kernel_file)
KERNEL_PATH = "/opt/overmind/kernel.py"
WORKSPACE = "/workspace"
DATA = f"{WORKSPACE}/data"
CONVERSATIONS = f"{WORKSPACE}/conversations"
# Billed at the greater of request and use: an idle kernel costs its request, a cell may
# burst to the limit.
CPU = (0.25, 8.0)
MEMORY = (1024, 16 * 1024)
IDLE_SECONDS = 60 * 60
LIFE_SECONDS = 24 * 60 * 60
MAX_DATA_BYTES = 4 * execute.GIB
# A sandbox in the preferred region that is not ready in this time starts in any region.
REGION_SECONDS = 20
# A cell's own deadline is the kernel's; this one catches a kernel stuck outside Python.
GRACE_SECONDS = 30
# A known sandbox is not looked up again within this time.
FRESH_SECONDS = 60
# Modal reports a sandbox's usage a few minutes late: a window is charged once this old.
BILLING_LAG = timedelta(minutes=10)
LIMITS = {
    "readable": [DATA],
    "rlimits": {
        "RLIMIT_NPROC": execute.PROCESSES,
        "RLIMIT_NOFILE": execute.FILE_DESCRIPTORS,
    },
}
LOST = (
    "The kernel ended during the cell: it ran out of memory or stopped answering. "
    "Variables are gone, files remain."
)
UNKNOWN = (
    "The workspace stopped during the cell: it may have run. Variables may be gone, files remain."
)


@cache
def image() -> tuple[modal.Image, str]:
    """The sandbox image, and a digest of everything a kernel runs on: a sandbox of another
    digest is replaced at its next use."""
    lock = tomllib.loads((KERNEL.parent.parent / "uv.lock").read_text())
    versions = {package["name"]: package["version"] for package in lock["package"]}
    requirements = [f"{name}=={versions[name]}" for name in LIBRARIES]
    cache_tokenizers = (
        'python -c "import tiktoken; [tiktoken.get_encoding(name) for name in '
        f'{TOKENIZER_ENCODINGS!r}]"'
    )
    built = (
        modal.Image.debian_slim(PYTHON)
        .uv_pip_install(*requirements)
        .env({"TIKTOKEN_CACHE_DIR": TOKENIZERS})
        .run_commands(cache_tokenizers)
        .add_local_file(KERNEL, KERNEL_PATH)
    )
    recipe = "\n".join((PYTHON, *requirements, cache_tokenizers)).encode()
    return built, hashlib.sha256(recipe + KERNEL.read_bytes()).hexdigest()[:12]


def _environment() -> str:
    return os.environ["MODAL_ENVIRONMENT"]


@cache
def _app() -> modal.App:
    return modal.App.lookup(APP, environment_name=_environment(), create_if_missing=True)


def _key(project: str) -> str:
    return uuid.UUID(project).hex


def _name(project: str) -> str:
    return PREFIX + _key(project)


def _volume(project: str, part: str, *, create: bool) -> modal.Volume | None:
    volume = modal.Volume.from_name(
        f"{_name(project)}-{part}",
        environment_name=_environment(),
        create_if_missing=create,
        version=2,
    )
    if not create:
        try:
            volume.hydrate()
        except NotFoundError:
            return None
    return volume


def _exec(sandbox: modal.Sandbox, command, *, timeout: int, stdin: str | None = None):
    args = ["sh", "-c", command] if isinstance(command, str) else command
    process = sandbox.exec(*args, timeout=timeout)
    if stdin is not None:
        process.stdin.write(stdin)
        process.stdin.write_eof()
        process.stdin.drain()
    out, err = process.stdout.read(), process.stderr.read()
    return process.wait(), out, err


class ModalProvider:
    _lock = threading.Lock()
    # Sandbox of each project, and when it was last looked up.
    _sandboxes: dict[str, tuple[modal.Sandbox, float]] = {}

    def _remember(self, project: str, sandbox: modal.Sandbox | None) -> None:
        with self._lock:
            if sandbox is None:
                self._sandboxes.pop(project, None)
            else:
                self._sandboxes[project] = (sandbox, time.monotonic())

    def _find(self, project: str) -> modal.Sandbox | None:
        with self._lock:
            known = self._sandboxes.get(project)
        if known is not None and time.monotonic() - known[1] < FRESH_SECONDS:
            return known[0]
        try:
            sandbox = modal.Sandbox.from_name(APP, _name(project), environment_name=_environment())
        except NotFoundError:
            sandbox = None
        if sandbox is not None and sandbox.get_tags().get("image") != image()[1]:
            # Started by an earlier release: its kernels restart in a new one, with the files.
            sandbox.terminate(wait=True)
            sandbox = None
        self._remember(project, sandbox)
        return sandbox

    def _sandbox(self, project: str, *, create: bool = True) -> modal.Sandbox | None:
        try:
            sandbox = self._find(project)
            if sandbox is None and create:
                sandbox = self._create(project)
                self._remember(project, sandbox)
        except modal.exception.Error as exc:
            self._remember(project, None)
            logger.warning("Modal workspace for %s is not available: %s", project, exc)
            raise WorkspaceUnavailableError(f"The workspace did not start: {exc}") from exc
        return sandbox

    def _create(self, project: str) -> modal.Sandbox:
        built, digest = image()
        options = {
            "app": _app(),
            "name": _name(project),
            "tags": {"project": _key(project), "image": digest},
            "image": built,
            "block_network": True,
            "cpu": CPU,
            "memory": MEMORY,
            "timeout": LIFE_SECONDS,
            "idle_timeout": IDLE_SECONDS,
            "workdir": WORKSPACE,
            "readiness_probe": modal.Probe.with_exec("true"),
            "volumes": {
                DATA: _volume(project, "data", create=True),
                CONVERSATIONS: _volume(project, "work", create=True),
            },
        }
        region = settings.MODAL_WORKSPACE_REGION
        sandbox = self._start(project, options | {"region": [region]}) if region else None
        return sandbox or self._start(project, options, wait=False)

    def _start(self, project: str, options: dict, *, wait: bool = True) -> modal.Sandbox | None:
        """The project's sandbox; None when one in the preferred region is not ready in
        time, so that the caller starts it anywhere."""
        try:
            sandbox = modal.Sandbox.create(**options)
        except AlreadyExistsError:
            # Another worker started it first.
            return modal.Sandbox.from_name(APP, options["name"], environment_name=_environment())
        if wait:
            try:
                sandbox.wait_until_ready(timeout=REGION_SECONDS)
            except modal.exception.TimeoutError:
                sandbox.terminate(wait=True)
                return None
        try:
            owner = Project.objects.filter(pk=project).values_list("owner_id", flat=True).first()
            WorkspaceSandbox.objects.create(
                sandbox_id=sandbox.object_id,
                project_id=project if owner is not None else None,
                user_id=owner,
                billed_until=timezone.now(),
            )
            code, _, err = _exec(
                sandbox, f"chmod 755 {DATA} && chmod 711 {CONVERSATIONS}", timeout=60
            )
            if code:
                raise WorkspaceUnavailableError(f"The workspace did not start: {err.strip()}")
        except BaseException:
            # Unregistered or unprepared, it must not serve cells. A registered one is still
            # charged to its end.
            sandbox.terminate()
            raise
        return sandbox

    def warm(self, project: str) -> None:
        """Starts the sandbox while the model writes its reply. A failure is the next
        cell's to report."""

        def start():
            try:
                with contextlib.suppress(WorkspaceUnavailableError):
                    self._sandbox(project)
            finally:
                # This thread's own connection, which nothing else closes.
                connection.close()

        threading.Thread(target=start, daemon=True).start()

    def bill(self) -> int:
        """Charge each sandbox's owner for its usage since the last charge, at Modal's cost:
        the greater of request and use, at our rates. A window Modal has not measured yet
        waits for the next charge."""
        until = timezone.now() - BILLING_LAG
        charged = 0
        rows = WorkspaceSandbox.objects.filter(finished=False, billed_until__lt=until)
        for since, pk, sandbox_id in rows.values_list("billed_until", "pk", "sandbox_id"):
            try:
                sandbox = modal.Sandbox.from_id(sandbox_id)
                usage = sandbox._experimental_stats(since=since, until=until)
                ended = sandbox.poll() is not None
            except modal.exception.Error as exc:
                logger.warning("usage of sandbox %s is not available: %s", sandbox_id, exc)
                continue
            if usage.cost is None and not ended:
                continue
            with transaction.atomic():
                row = (
                    WorkspaceSandbox.objects.select_for_update(of=("self",))
                    .select_related("user")
                    .get(pk=pk)
                )
                # Another run charged this window since it was measured.
                if row.billed_until != since:
                    continue
                if usage.cost and row.project_id is not None:
                    seconds = Decimal(str((until - row.billed_until).total_seconds()))
                    cost = Decimal(str(usage.cost))
                    charge(
                        Cause(
                            project_id=str(row.project_id),
                            service=BillingService.WORKSPACE,
                            kind="workspace_sandbox",
                            id=row.sandbox_id,
                            payer_id=row.user_id,
                            resolved=True,
                        ),
                        cost,
                        key=f"modal-sandbox:{row.sandbox_id}:{row.billed_until.isoformat()}",
                        resource="modal sandbox",
                        quantity=seconds,
                        unit="second",
                        unit_usd=cost / seconds if seconds else None,
                        provider_ref=row.sandbox_id,
                        started_at=row.billed_until,
                        ended_at=until,
                        metadata={
                            "cpu_core_seconds": usage.billed_cpu_core_seconds,
                            "memory_gib_seconds": usage.billed_memory_gib_seconds,
                            "cost_by_resource": {
                                k: str(v) for k, v in usage.cost_by_resource.items()
                            },
                        },
                    )
                    charged += 1
                row.billed_until = until
                # Its last window had no time left in it: all of it is charged.
                row.finished = ended and not usage.duration
                row.save(update_fields=["billed_until", "finished"])
        return charged

    def projects(self) -> list[str]:
        names = {
            volume.name for volume in modal.Volume.objects.list(environment_name=_environment())
        }
        keys = {name[len(PREFIX) : -5] for name in names if name.startswith(PREFIX)}
        return sorted(str(uuid.UUID(key)) for key in keys)

    def has_data(self, project: str, name: str) -> bool:
        volume = _volume(project, "data", create=False)
        if volume is None:
            return False
        try:
            return any(Path(entry.path).name == name for entry in volume.listdir("/"))
        except modal.exception.Error as exc:
            raise WorkspaceUnavailableError(str(exc)) from exc

    def put_data(self, project: str, name: str, source: BinaryIO) -> None:
        if not NAME.fullmatch(name):
            raise ValueError("Invalid file name.")
        if self.has_data(project, name):
            return
        with tempfile.NamedTemporaryFile() as local:
            copied = 0
            while chunk := source.read(1024**2):
                copied += len(chunk)
                if copied > MAX_DATA_BYTES:
                    raise DataTooLargeError(
                        f"The version is larger than {MAX_DATA_BYTES // execute.GIB} GiB."
                    )
                local.write(chunk)
            local.flush()
            sandbox = self._sandbox(project)
            # Under its name only when whole: has_data takes a name that is there as copied.
            partial = f"{DATA}/.{uuid.uuid4().hex}"
            try:
                sandbox.filesystem.copy_from_local(local.name, partial)
                code, _, err = _exec(
                    sandbox,
                    f"chown 0:0 {partial} && chmod 444 {partial} "
                    f"&& mv {partial} {shlex.quote(f'{DATA}/{name}')} && sync {DATA}",
                    timeout=120,
                )
            except modal.exception.Error as exc:
                self._remember(project, None)
                raise WorkspaceUnavailableError(str(exc)) from exc
            if code:
                with contextlib.suppress(modal.exception.Error):
                    _exec(sandbox, f"rm -f {partial}", timeout=30)
                raise WorkspaceUnavailableError(f"The version was not copied: {err.strip()}")

    def run(self, project: str, conversation: str, code: str, timeout: int) -> Execution:
        if not ID.fullmatch(conversation):
            raise ValueError("Invalid conversation.")
        sandbox = self._sandbox(project)
        work = f"{CONVERSATIONS}/{conversation}"
        command = ["python", "-I", "-S", KERNEL_PATH, "cell", work, DATA, json.dumps(LIMITS)]
        try:
            status, out, err = _exec(
                sandbox,
                command,
                stdin=json.dumps({"code": code, "timeout": timeout}),
                timeout=timeout + GRACE_SECONDS,
            )
        except modal.exception.ExecTimeoutError:
            self.stop(project, conversation)
            return Execution(False, "", LOST, False, float(timeout))
        except modal.exception.Error:
            # The cell was sent: it may have run, so it is not reported as never run.
            self._remember(project, None)
            return Execution(False, "", UNKNOWN, False, float(timeout))
        if status != 0:
            # The kernel stopped answering past its own deadline: end it.
            self.stop(project, conversation)
            if "did not start" in err:
                raise WorkspaceUnavailableError("The kernel did not start.")
            return Execution(False, "", LOST, False, float(timeout))
        if not out.strip():
            return Execution(False, "", LOST, False, 0.0)
        answer = json.loads(out.strip().splitlines()[-1])
        restarted = RESTARTED if answer["restarted"] else None
        if answer["reply"] is None:
            return Execution(False, "", LOST, False, 0.0, restarted)
        return Execution(**answer["reply"], restarted=restarted)

    def read_file(self, project: str, conversation: str, name: str) -> bytes:
        if not NAME.fullmatch(name) or not ID.fullmatch(conversation):
            raise FileNotFoundError(name)
        try:
            sandbox = self._sandbox(project, create=False)
            if sandbox is None:
                return self._read_volume(project, conversation, name)
            # Copied first: the cell may still write the file while it is read.
            copy = f"/tmp/overmind-read-{uuid.uuid4().hex}"
            try:
                status, _, _ = _exec(
                    sandbox,
                    [
                        "python",
                        "-I",
                        "-S",
                        KERNEL_PATH,
                        "copy",
                        f"{CONVERSATIONS}/{conversation}/{name}",
                        copy,
                        str(MAX_FILE_BYTES),
                    ],
                    timeout=60,
                )
                if status != 0:
                    raise FileNotFoundError(name)
                return sandbox.filesystem.read_bytes(copy)
            finally:
                with contextlib.suppress(modal.exception.Error):
                    _exec(sandbox, f"rm -f {copy}", timeout=30)
        except modal.exception.Error as exc:
            raise WorkspaceUnavailableError(str(exc)) from exc

    def _read_volume(self, project: str, conversation: str, name: str) -> bytes:
        volume = _volume(project, "work", create=False)
        if volume is None:
            raise FileNotFoundError(name)
        try:
            entries = {Path(entry.path).name: entry for entry in volume.listdir(f"/{conversation}")}
        except NotFoundError:
            raise FileNotFoundError(name) from None
        entry = entries.get(name)
        if entry is None or entry.type != FileEntryType.FILE or entry.size > MAX_FILE_BYTES:
            raise FileNotFoundError(name)
        received = bytearray()
        for chunk in volume.read_file(f"/{conversation}/{name}"):
            received += chunk
            if len(received) > MAX_FILE_BYTES:
                raise FileNotFoundError(name)
        return bytes(received)

    def stop(self, project: str, conversation: str) -> None:
        if not ID.fullmatch(conversation):
            return
        sandbox = self._sandbox(project, create=False)
        if sandbox is None:
            return
        with contextlib.suppress(modal.exception.Error):
            _exec(
                sandbox,
                ["python", "-I", "-S", KERNEL_PATH, "stop", f"{CONVERSATIONS}/{conversation}"],
                timeout=30,
            )

    def forget(self, project: str, data: list[str], conversations: list[str]) -> None:
        data = [name for name in data if NAME.fullmatch(name)]
        conversations = [c for c in conversations if ID.fullmatch(c)]
        if not data and not conversations:
            return
        sandbox = self._sandbox(project, create=False)
        if sandbox is not None:
            # A running sandbox keeps its own view of the Volumes: it deletes the files.
            for conversation in conversations:
                self.stop(project, conversation)
            paths = [f"{DATA}/{name}" for name in data]
            paths += [f"{CONVERSATIONS}/{c}" for c in conversations]
            try:
                status, _, err = _exec(
                    sandbox,
                    f"rm -rf {' '.join(map(shlex.quote, paths))} "
                    f"&& sync {DATA} && sync {CONVERSATIONS}",
                    timeout=120,
                )
            except modal.exception.Error as exc:
                raise WorkspaceUnavailableError(str(exc)) from exc
            if status:
                raise WorkspaceUnavailableError(f"The files were not deleted: {err.strip()}")
            return
        for part, names in (("data", data), ("work", conversations)):
            volume = _volume(project, part, create=False) if names else None
            for name in names if volume is not None else ():
                with contextlib.suppress(NotFoundError, FileNotFoundError):
                    volume.remove_file(f"/{name}", recursive=True)

    def remove(self, project: str) -> None:
        self._remember(project, None)
        tags = {"project": _key(project)}
        try:
            for sandbox in modal.Sandbox.list(app_id=_app().app_id, tags=tags):
                sandbox.terminate(wait=True)
            for part in ("data", "work"):
                modal.Volume.objects.delete(
                    f"{_name(project)}-{part}", environment_name=_environment(), allow_missing=True
                )
        except modal.exception.Error as exc:
            raise WorkspaceUnavailableError(str(exc)) from exc
        if any(True for _ in modal.Sandbox.list(app_id=_app().app_id, tags=tags)):
            raise WorkspaceUnavailableError("The workspace is not deleted yet.")