Skip to content

The platform for continuously improving AI agents.

9.5 KB
Raw Blame
import json
import tempfile
import time
from pathlib import Path

import httpx
import pyarrow as pa
import pyarrow.parquet as pq
from django.conf import settings
from django.utils import timezone

from overbae.services.datasets import store
from sandbox import packages
from sandbox.protocol import FramingError, HeaderReader, header_bytes

BUSY_SECONDS = 2
BUSY_LIMIT_SECONDS = 15 * 60
MAX_LINE = 4 * 1024 * 1024


class RuntimeUnavailableError(ValueError):
    pass


class SandboxLostError(RuntimeUnavailableError):
    """The sandbox stopped mid-step; a pipeline run goes back in the queue."""


def _refusal(response) -> str:
    """Why the sandbox took no run, in its own words when it gave any: a runtime that a
    package no longer matches is repaired by saving the package again."""
    try:
        reason = json.loads(response.read()).get("error")
    except (ValueError, AttributeError, httpx.HTTPError):
        reason = None
    if not reason and response.status_code == 503:
        reason = "The sandbox has no memory free now."
    return (
        f"{reason or f'The sandbox returned HTTP {response.status_code}.'} No script was replayed."
    )


def execute_jsonl(
    *,
    manifest,
    records,
    directory,
    entrypoint,
    files,
    parameters,
    receipt,
    progress,
    io="jsonl",
    batch_rows=None,
):
    if not settings.SANDBOX_URL or not settings.SANDBOX_TOKEN:
        raise RuntimeUnavailableError("The isolated sandbox is not configured.")
    if manifest["runtime"] != packages.runtime_id():
        raise RuntimeUnavailableError(
            "The pinned runtime is unavailable. Save a new package revision with the advertised sandbox runtime identity."
        )
    started, checkpoint, stage = time.monotonic(), time.monotonic(), None
    timings = {}

    def phase(next_stage):
        nonlocal stage, checkpoint
        now = time.monotonic()
        if stage:
            timings[stage] = round(timings.get(stage, 0) + now - checkpoint, 4)
        checkpoint, stage = now, next_stage
        receipt["runtime"] = {
            **receipt.get("runtime", {}),
            "backend": "sandbox",
            "identity": manifest["runtime"],
            "stage": stage,
            "stage_seconds": dict(timings),
            "seconds": round(now - started, 4),
        }
        if not progress() and next_stage != "script_execution":
            raise RuntimeUnavailableError(
                "Publication was cancelled; the sandbox request is closing."
            )

    with tempfile.TemporaryDirectory(dir=directory, prefix="script-") as scratch:
        root = Path(scratch)
        payload = root / "package.json"
        payload.write_text(json.dumps(files, ensure_ascii=False))
        if payload.stat().st_size > packages.MAX_PACKAGE_BYTES:
            raise RuntimeUnavailableError("The encoded package exceeds 20 MiB.")
        phase("input_transfer")
        incoming = root / "input.parquet"
        store.write_rows(incoming, records)
        metadata = pq.read_metadata(incoming)
        header = {
            "mode": "package",
            "rows": metadata.num_rows,
            **({"batch_rows": batch_rows} if batch_rows else {}),
            "input_bytes": incoming.stat().st_size,
            "expanded_bytes": sum(
                metadata.row_group(group).total_byte_size
                for group in range(metadata.num_row_groups)
            ),
            "package_bytes": payload.stat().st_size,
            "runtime": manifest["runtime"],
            "entrypoint": entrypoint,
            "parameters": parameters,
            "limits": manifest.get("limits", {}),
            "io": io,
        }
        output = root / f"output.{io}"
        receipt["submission_started_at"] = timezone.now().isoformat()
        if not progress():
            receipt["submission_rejected"] = True
            progress()
            raise RuntimeUnavailableError("Publication was cancelled before sandbox submission.")
        result = _submit(header, (payload, incoming), output, phase, receipt, progress)
        receipt["exit_code"] = result.get("exit_code")
        receipt["runtime"].update(result.get("runtime") or {})
        receipt["runtime"]["execution_seconds"] = result.get("seconds")
        (directory / "stdout.log").write_text(result.get("stdout", ""))
        (directory / "stderr.log").write_text(result.get("error", ""))
        if not result.get("ok"):
            progress()
            raise RuntimeUnavailableError(result.get("error") or "The sandbox package failed.")
        phase("output_reading")
        if io == "parquet":
            yield from _parquet_rows(output, result.get("segments") or [output.stat().st_size])
        else:
            yield from _jsonl_rows(output)
        phase("completed")


def _submit(header, parts, output, phase, receipt, progress) -> dict:
    """The sandbox's final reply, with the output written to ``output``. A busy sandbox
    has read nothing yet, so the request is sent again until it has room."""

    def body():
        yield header_bytes(header)
        for path in parts:
            with path.open("rb") as stream:
                while chunk := stream.read(64 * 1024):
                    yield chunk

    waited_until = time.monotonic() + BUSY_LIMIT_SECONDS
    while True:
        reader = HeaderReader()
        receipt["submission_rejected"] = False
        if not progress():
            receipt["submission_rejected"] = True
            progress()
            raise RuntimeUnavailableError("Publication was cancelled before sandbox submission.")
        try:
            with (
                httpx.stream(
                    "POST",
                    f"{settings.SANDBOX_URL}/v1/run",
                    content=body(),
                    headers={"Authorization": f"Bearer {settings.SANDBOX_TOKEN}"},
                    timeout=httpx.Timeout(1350, connect=5),
                    follow_redirects=False,
                ) as response,
                output.open("wb") as stream,
            ):
                if response.status_code != 200:
                    receipt["submission_rejected"] = True
                    progress()
                if response.status_code == 503:
                    if time.monotonic() > waited_until:
                        raise RuntimeUnavailableError(
                            "The sandbox stayed full for 15 minutes; the step did not start."
                        )
                    phase("waiting_for_sandbox")
                    time.sleep(BUSY_SECONDS)
                    continue
                if response.status_code != 200:
                    raise RuntimeUnavailableError(_refusal(response))
                for chunk in response.iter_bytes():
                    pending = reader.feed(chunk)
                    while reader.header is not None and "progress" in reader.header:
                        if "batches" in reader.header["progress"]:
                            receipt["batches"] = reader.header["progress"]["batches"]
                        phase("script_execution")
                        reader = HeaderReader()
                        pending = reader.feed(pending)
                    if stream.tell() + len(pending) > packages.MAX_OUTPUT_BYTES:
                        raise RuntimeUnavailableError("The sandbox output exceeds 2 GiB.")
                    stream.write(pending)
                return reader.finish()
        except (httpx.TransportError, FramingError) as exc:
            raise SandboxLostError("The sandbox stopped during the step.") from exc


def _checked(row):
    if not isinstance(row, dict) or len(row) > 200:
        raise RuntimeUnavailableError(
            "Every output line must be an object with at most 200 columns."
        )
    return row


def _jsonl_rows(path):
    with path.open("rb") as rows:
        for line in iter(lambda: rows.readline(MAX_LINE + 1), b""):
            if len(line) > MAX_LINE:
                raise RuntimeUnavailableError("An output row exceeds 4 MiB.")
            try:
                row = store.json_loads_finite(line)
            except ValueError as exc:
                raise RuntimeUnavailableError(
                    "Every output line must be one finite JSON object."
                ) from exc
            yield _checked(row)


def _parquet_rows(path, segments):
    """Rows of each batch's output.parquet, which arrive one after another in ``path``."""
    with path.open("rb") as combined:
        for size in segments:
            part = path.with_suffix(".part.parquet")
            with part.open("wb") as stream:
                remaining = size
                while remaining:
                    chunk = combined.read(min(remaining, 1 << 20))
                    if not chunk:
                        raise RuntimeUnavailableError("The sandbox output ended early.")
                    stream.write(chunk)
                    remaining -= len(chunk)
            try:
                parquet = pq.ParquetFile(part)
            except (OSError, pa.ArrowException) as exc:
                raise RuntimeUnavailableError(
                    "output.parquet is not a readable Parquet file."
                ) from exc
            if len(parquet.schema_arrow.names) > 200:
                raise RuntimeUnavailableError("The output has more than 200 columns.")
            for batch in parquet.iter_batches(batch_size=1024):
                for row in batch.to_pylist():
                    if not store.finite(row):
                        raise RuntimeUnavailableError("Provide finite values in output.parquet.")
                    yield row
            part.unlink()