Skip to content

The platform for continuously improving AI agents.

18.0 KB
Raw Blame
import asyncio
import ipaddress
import os
import secrets
import socket
import subprocess
import sys
import tempfile
import time
from pathlib import Path

import httpx
import pytest
import tiktoken
from asgiref.sync import SyncToAsync, async_to_sync
from django.db import connections, transaction
from django.test import TransactionTestCase
from fakes.clerk import ClerkAPI
from fakes.http import ScriptedAPI
from fakes.llm import FakeLLM, Network
from fakes.modal import DecisionBackend, FakeModal, ServingBackend, SftBackend
from fakes.stripe import StripeAPI
from temporalio.testing import WorkflowEnvironment

# tiktoken fetches its encodings on first use. Tests read them from a per-machine cache that
# the session fills before any test fakes the network.
os.environ.setdefault(
    "TIKTOKEN_CACHE_DIR", str(Path.home() / ".cache" / "overmind-tests" / "tiktoken")
)


def pytest_sessionstart(session):
    for name in ("cl100k_base", "o200k_base"):
        tiktoken.get_encoding(name)
    if not hasattr(session.config, "workerinput"):
        # Workflow tests run Temporal's test server, which is downloaded on first use; inside
        # a test the socket guard's proxy refuses that download, so the session fetches it.
        asyncio.run(_start_workflow_test_server())


async def _start_workflow_test_server():
    environment = await WorkflowEnvironment.start_time_skipping()
    await environment.shutdown()


def pytest_ignore_collect(collection_path, config):
    if collection_path.name != "journeys" or collection_path.parent != Path(__file__).parent:
        return None
    # `make test` is xdist over the whole suite and must not collect journeys.
    # `make test-journeys` sets OVERMIND_JOURNEY_XDIST and gives each worker its own Redis DB.
    if os.environ.get("OVERMIND_JOURNEY_XDIST"):
        return None if os.environ.get("TEST_REDIS_URL") else True
    parallel = hasattr(config, "workerinput") or config.getoption("numprocesses", default=None)
    return True if parallel or not os.environ.get("TEST_REDIS_URL") else None


# Static rows that post_migrate creates once per test database.
_KEPT_TABLES = {"django_content_type", "auth_permission", "django_migrations"}


def _truncate_written_tables(self):
    # Django's flush truncates every table and re-runs post_migrate (about 3 s a test);
    # emptying only the tables a test wrote leaves the database in the same state.
    for alias in self._databases_names(include_mirrors=False):
        connection = connections[alias]
        quote = connection.ops.quote_name
        tables = sorted(
            set(connection.introspection.django_table_names(only_existing=True)) - _KEPT_TABLES
        )
        with connection.cursor() as cursor:
            cursor.execute(
                " UNION ALL ".join(
                    f"SELECT %s WHERE EXISTS (SELECT 1 FROM {quote(table)})" for table in tables
                ),
                tables,
            )
            written = [row[0] for row in cursor.fetchall()]
            if written:
                # DELETE skips TRUNCATE's per-table file work; replica mode skips FK order.
                cursor.execute(
                    "SET session_replication_role = replica;"
                    + "".join(f"DELETE FROM {quote(table)};" for table in written)
                    + "SET session_replication_role = DEFAULT;"
                )


TransactionTestCase._fixture_teardown = _truncate_written_tables


def drain_stream(response) -> bytes:
    """Collect a streaming response body in a sync test.

    SSE views hand `StreamingHttpResponse` an async iterable so ASGI writes chunks as they
    are produced, which leaves `streaming_content` un-joinable from sync code.
    """
    if not response.streaming:
        return response.content
    content = response.streaming_content
    if not hasattr(content, "__aiter__"):
        return b"".join(content)

    async def _collect():
        return [chunk async for chunk in content]

    return b"".join(async_to_sync(_collect)())


def _loopback(address) -> bool:
    if not isinstance(address, tuple):
        return True
    host = address[0]
    if host == "localhost":
        return True
    try:
        return ipaddress.ip_address(host).is_loopback
    except ValueError:
        return False


@pytest.fixture(autouse=True)
def _no_outside_sockets(monkeypatch):
    connect = socket.socket.connect

    def guarded(sock, address):
        if not _loopback(address):
            raise ConnectionRefusedError(f"Tests may not reach {address}.")
        return connect(sock, address)

    monkeypatch.setattr(socket.socket, "connect", guarded)
    for proxy in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"):
        monkeypatch.setenv(proxy, "http://127.0.0.1:9")
    monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost")
    monkeypatch.setenv("no_proxy", "127.0.0.1,localhost")


@pytest.fixture
def eager(monkeypatch):
    """Celery tasks and on-commit hooks run inline; the test transaction never commits."""
    from overbae.celery import app as celery_app  # noqa: PLC0415 — Django is configured per test

    monkeypatch.setattr(celery_app.conf, "task_always_eager", True)
    monkeypatch.setattr(celery_app.conf, "task_eager_propagates", True)
    monkeypatch.setattr(transaction, "on_commit", lambda func, *args, **kwargs: func())


@pytest.fixture(autouse=True)
def fake_llm():
    llm = FakeLLM()
    with Network(llm) as network:
        llm.network = network
        yield llm
    assert not network.refused, f"Unrouted outbound calls: {network.refused}"


@pytest.fixture
def stripe_api(settings, fake_llm) -> StripeAPI:
    api = StripeAPI()
    settings.STRIPE_WEBHOOK_SECRET = api.webhook_secret
    fake_llm.network.vendors.append(api)
    return api


@pytest.fixture
def scripted(fake_llm):
    def install(host: str) -> ScriptedAPI:
        api = ScriptedAPI(host)
        fake_llm.network.vendors.append(api)
        return api

    return install


@pytest.fixture
def slept(monkeypatch) -> list[float]:
    import asyncio
    import time

    naps: list[float] = []
    monkeypatch.setattr(time, "sleep", naps.append)
    original_sleep = asyncio.sleep

    async def async_nap(delay, result=None):
        if delay > 0:
            naps.append(float(delay))
        return await original_sleep(0, result)

    monkeypatch.setattr(asyncio, "sleep", async_nap)
    return naps


def read_table(path):
    """A small frame file as one pandas frame."""
    from overbae.services.datasets import store

    return store.read_frame(path)


@pytest.fixture
def frame_of():
    """Small pandas frames for the retained dataset contract API."""
    import pandas as pd

    return pd.DataFrame


@pytest.fixture
def fake_modal(monkeypatch) -> FakeModal:
    return FakeModal().install(monkeypatch)


@pytest.fixture
def sft(fake_modal) -> SftBackend:
    return SftBackend(fake_modal).install()


@pytest.fixture
def serving(fake_modal) -> ServingBackend:
    return ServingBackend(fake_modal, url="http://inference.test").install()


@pytest.fixture
def decisions(fake_modal) -> DecisionBackend:
    return DecisionBackend(fake_modal).install()


@pytest.fixture(autouse=True)
def _close_sync_to_async_connections():
    yield
    SyncToAsync.single_thread_executor.submit(connections.close_all).result()


@pytest.fixture(autouse=True)
def _clerk_offline(settings):
    settings.CLERK_API_SECRET_KEY = ""


@pytest.fixture
def clerk(settings, fake_llm) -> ClerkAPI:
    api = ClerkAPI()
    settings.CLERK_API_SECRET_KEY = "sk_test_clerk"
    settings.CLERK_AUTHORIZED_PARTIES = ["http://localhost:5173"]
    fake_llm.network.vendors.append(api)
    return api


@pytest.fixture(autouse=True)
def _openrouter_key(monkeypatch):
    monkeypatch.setenv("OPENROUTER_API_KEY", "offline-test-key")


@pytest.fixture(autouse=True)
def _offline_compute_prices(monkeypatch):
    monkeypatch.setattr(
        "overbae.services.provider_pricing.current_rates",
        lambda: {
            "source": "offline-test-fixture",
            "status": "current",
            "fetched_at": "2026-10-04T00:00:00+00:00",
            "rates": {
                "gpu_hour_cost_h100": 3.95,
                "gpu_hour_cost_h200": 4.54,
                "gpu_hour_cost_l4": 0.74,
                "gpu_hour_cost_l40s": 1.99,
                "cpu_hour_cost": 0.0473,
                "mem_gib_hour_cost": 0.008,
                "cpu_hour_cost_sandbox": 0.1419,
                "mem_gib_hour_cost_sandbox": 0.024,
            },
        },
    )


@pytest.fixture(autouse=True)
def _offline_operational_provider(monkeypatch):
    async def absent(*args, **kwargs):
        return None, []

    monkeypatch.setattr("overbae.services.provider_progress.read_page", absent)
    monkeypatch.setattr(
        "modal_shared.operational_events.Journal.emit", lambda *args, **kwargs: None
    )


@pytest.fixture(autouse=True)
def _commercial_billing(settings):
    """Remaining-credit billing is on in tests unless a case clears the key."""
    settings.STRIPE_SECRET_KEY = "sk_test_billing"


EVAL_ROWS = [
    {"input": "q1", "expected_output": "a1"},
    {"input": "q2", "expected_output": "a2"},
]
TRAIN_ROWS = [
    {"messages": [{"role": "user", "content": "q1"}, {"role": "assistant", "content": "a1"}]},
    {"messages": [{"role": "user", "content": "q2"}, {"role": "assistant", "content": "a2"}]},
]


@pytest.fixture(autouse=True)
def _fresh_cache():
    from django.core.cache import cache

    cache.clear()


@pytest.fixture(autouse=True)
def _media_root(settings, tmp_path):
    """Every test writes dataset files under its own tmp dir."""
    settings.MEDIA_ROOT = tmp_path / "media"


@pytest.fixture(autouse=True)
def _inline_dataset_tasks(monkeypatch):
    """Landing and runs execute in-process: no worker in tests, and the API's
    202 answers still leave a finished version behind."""
    from overbae.tasks import datasets as dataset_tasks

    for task in (dataset_tasks.land,):
        monkeypatch.setattr(
            task,
            "apply_async",
            lambda kwargs, task_id=None, _t=task, **_: _t.apply(kwargs=kwargs, task_id=task_id),
        )


def _lift_messages(row):
    """The old canonical shape kept the transcript under ``input``; the product
    table carries it as a ``messages`` column."""
    row = dict(row)
    inp = row.get("input")
    if isinstance(inp, dict) and isinstance(inp.get("messages"), list) and "messages" not in row:
        row["messages"] = inp["messages"]
        if inp.get("tools"):
            row["tools"] = inp["tools"]
        rest = {k: v for k, v in inp.items() if k not in ("messages", "tools")}
        if rest:
            row["input"] = rest
        else:
            row.pop("input")
        if row.get("expected_output") is None:
            row.pop("expected_output", None)
    return row


def frozen_dataset(project, rows=None, *, capability=None, name="ds", contract=None, user=None):
    """A dataset whose source landed in-process, so its active version is
    ready. ``rows`` defaults to a two-row table of the requested intent."""
    from overbae.models import Dataset
    from overbae.services.datasets import land

    if rows is None:
        rows = TRAIN_ROWS if contract == "train" else EVAL_ROWS
    # This fixture declares an intent; production landing intentionally never infers it.
    contract = contract or (
        "train" if rows and "messages" in rows[0] and "input" not in rows[0] else "eval"
    )
    dataset = Dataset.objects.create(
        project=project, capability=capability, name=name, intent=contract
    )
    land.land_rows(dataset, [_lift_messages(r) for r in rows], user=user)
    dataset.refresh_from_db()
    return dataset


def import_version(dataset, records, *, name="Native transformation"):
    from unittest.mock import patch
    from uuid import uuid4

    from overbae.services.datasets import workbench

    source = dataset.active_cell
    imported = {"imported_rows": records}
    if len(records) > 2000:
        from overbae.models import Dataset
        from overbae.services.datasets import land

        artifact = Dataset.objects.create(project=dataset.project, name="Native artifact")
        land.land_rows(artifact, records)
        imported = {
            "artifact_cell": artifact.source.pk,
            "artifact_fingerprint": artifact.source.fingerprint,
        }
    with patch("overbae.tasks.datasets.execute_pipeline.delay"):
        run = workbench.submit(
            dataset,
            None,
            source_cell=source.pk,
            source_fingerprint=source.fingerprint,
            request_key=str(uuid4()),
            name=name,
            **imported,
            provenance="Explicit transformation supplied by the test's native-agent fixture.",
        )
    workbench.execute(run.pk)
    run.refresh_from_db()
    assert run.state == "completed", run.error
    dataset.refresh_from_db()
    return dataset.active_cell


@pytest.fixture(scope="session")
def sandbox_server():
    token = secrets.token_hex(16)
    scratch = tempfile.TemporaryDirectory(prefix="sandbox-test-")
    # Deeper than a Unix socket path holds, as a deployment's temporary directory may be.
    deep = Path(scratch.name) / ("deep-" * 20)
    deep.mkdir()
    env = {
        "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
        "SANDBOX_TOKEN": token,
        "SANDBOX_ALLOW_SHARED_UID": "1",
        "SANDBOX_WORKSPACES": str(deep / "workspaces"),
        # Its own memory ledger: parallel test servers must not share /tmp/sandbox.
        "TMPDIR": str(deep),
    }
    image = os.environ.get("SANDBOX_TEST_IMAGE", "overmind-dev")
    container = None
    proxy = None
    if sys.platform == "darwin" or os.environ.get("SANDBOX_CONTAINER_TESTS") == "1":
        container = "overmind-parser-test-" + secrets.token_hex(6)
        subprocess.run(
            ["docker", "network", "create", "--internal", container],
            check=True,
            capture_output=True,
        )
        command = [
            "docker",
            "run",
            "--rm",
            "--name",
            container,
            "--network",
            container,
            "--cap-drop=ALL",
            "--security-opt=no-new-privileges",
            "--init",
            "--tmpfs",
            "/tmp:size=4g",
            "-v",
            f"{Path(__file__).resolve().parents[1] / 'sandbox'}:/code/sandbox:ro",
            "-e",
            f"SANDBOX_TOKEN={token}",
            "-e",
            "SANDBOX_WORKSPACES=/tmp/workspaces",
            "--entrypoint",
            "python",
        ]
        for capability in (
            "CHOWN",
            "DAC_OVERRIDE",
            "FOWNER",
            "KILL",
            "SETGID",
            "SETUID",
            "SYS_PTRACE",
        ):
            command += ["--cap-add", capability]
        command += [image, "-m", "sandbox"]
        proc = subprocess.Popen(command, cwd=Path(__file__).resolve().parents[1], env=env)
    else:
        # The server inherits a socket this process already listens on. A port probed and then
        # released can be taken by another xdist worker's sandbox before this one binds it.
        with socket.create_server(("127.0.0.1", 0)) as listener:
            url = f"http://127.0.0.1:{listener.getsockname()[1]}"
            proc = subprocess.Popen(
                [sys.executable, "-m", "sandbox", "--fd", str(listener.fileno())],
                cwd=Path(__file__).resolve().parents[1],
                env=env,
                pass_fds=[listener.fileno()],
            )
    try:
        if container:
            # Docker Desktop cannot publish an internal-only container to macOS.
            # This fixed-destination proxy gives the test client ingress without giving scripts egress.
            proxy = container + "-ingress"
            forwarding = """import select,socket,socketserver,sys
class Relay(socketserver.BaseRequestHandler):
    def handle(self):
        with socket.create_connection((sys.argv[1],8080)) as upstream:
            peers={self.request:upstream,upstream:self.request}
            while True:
                for source in select.select(list(peers),[],[])[0]:
                    data=source.recv(65536)
                    if not data: return
                    peers[source].sendall(data)
socketserver.ThreadingTCPServer(('0.0.0.0',8080),Relay).serve_forever()
"""
            subprocess.run(
                [
                    "docker",
                    "run",
                    "--rm",
                    "-d",
                    "--name",
                    proxy,
                    "--network",
                    "bridge",
                    "-p",
                    "127.0.0.1::8080",
                    "--entrypoint",
                    "python",
                    image,
                    "-c",
                    forwarding,
                    container,
                ],
                check=True,
                capture_output=True,
            )
            subprocess.run(
                ["docker", "network", "connect", container, proxy], check=True, capture_output=True
            )
            published = subprocess.run(
                ["docker", "port", proxy, "8080/tcp"], check=True, capture_output=True, text=True
            )
            url = f"http://{published.stdout.split()[0]}"
        deadline = time.monotonic() + 30
        while True:
            try:
                if httpx.get(f"{url}/health", timeout=1).status_code == 200:
                    break
            except httpx.TransportError:
                pass
            if proc.poll() is not None or time.monotonic() > deadline:
                raise RuntimeError("The test sandbox did not start.")
            time.sleep(0.1)
        yield url, token
    finally:
        if container:
            if proxy:
                subprocess.run(["docker", "rm", "-f", proxy], check=False, capture_output=True)
            subprocess.run(["docker", "rm", "-f", container], check=False, capture_output=True)
            subprocess.run(["docker", "network", "rm", container], check=False, capture_output=True)
        elif proc.poll() is None:
            proc.terminate()
        proc.wait(timeout=10)
        scratch.cleanup()


@pytest.fixture(autouse=True)
def _sandbox(settings, sandbox_server):
    settings.SANDBOX_URL, settings.SANDBOX_TOKEN = sandbox_server