Skip to content

The platform for continuously improving AI agents.

19.9 KB
Raw Blame
import json
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import dataclass
from datetime import timedelta
from threading import Event
from unittest.mock import patch
from uuid import uuid4

import httpx
import pytest
from django.db import close_old_connections, connections
from django.utils import timezone
from test_experiment_assets import inputs
from test_experiment_engine import investigating

from overbae.core.errors import InputValidationError
from overbae.models import (
    Cell,
    DatasetPipelineRun,
    PredictionAttempt,
    ProjectMembership,
    ResearchAction,
    ResearchAssignment,
)
from overbae.services import (
    component_execution,
    execution_mandates,
    experiment_checkpoints,
    experiment_execution,
    research,
    research_agent,
    research_effects,
    research_experiments,
)
from overbae.services import experiment_assets as assets
from overbae.services import experiment_predictions as predictions
from overbae.services.datasets import pipeline_runner, workbench
from overbae.services.experiment_asset_contract import ComponentRequest
from overbae.services.isolated_execution import RuntimeUnavailableError, execute_jsonl
from overbae.services.workshop_agent import lifecycle
from overbae.services.workshop_agent.contracts import StartTask
from sandbox import packages
from sandbox.protocol import header_bytes
from tests.workshop_script_fixtures import identity_script, retained_package

pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("spend-stops")]


@pytest.fixture(autouse=True)
def checkpoint_schema():
    with experiment_checkpoints.store() as store:
        store.setup()


@pytest.fixture
def sandbox_api(settings, scripted):
    settings.SANDBOX_URL = "https://sandbox.settlement.test"
    settings.SANDBOX_TOKEN = "settlement-test-token"
    return scripted(settings.SANDBOX_URL)


def final_response(outcome, rows):
    if outcome == "disconnect":
        return httpx.ReadError("Accepted sandbox request lost its acknowledgement")
    if outcome == "refusal":
        return 400, {"content-type": "application/json"}, b'{"error":"Package refused"}'
    result = {
        "ok": outcome == "exit_zero",
        "seconds": 0.25,
        "stdout": "",
        "error": "" if outcome == "exit_zero" else "Provider stopped the package",
    }
    if outcome != "missing_exit":
        result["exit_code"] = 0 if outcome == "exit_zero" else 1
    body = header_bytes({"progress": {"batches": {"completed": 1}}})
    body += header_bytes(result)
    body += b"".join((json.dumps(row) + "\n").encode() for row in rows)
    return 200, {"content-type": "application/octet-stream"}, body


class HeldResponse:
    def __init__(self, response):
        self.response = response
        self.accepted = Event()
        self.release = Event()
        self.calls = 0

    def __call__(self, _request):
        self.calls += 1
        self.accepted.set()
        if not self.release.wait(20):
            raise AssertionError("The test did not release the provider response")
        return self.response


@contextmanager
def in_worker(function):
    def run():
        close_old_connections()
        try:
            return function()
        finally:
            connections.close_all()

    with ThreadPoolExecutor(max_workers=1) as executor:
        yield executor.submit(run)


@dataclass
class ScriptEffect:
    kind: str
    work: object
    cell: object
    record: object
    prediction_set: object = None

    @property
    def owners(self):
        return ResearchAssignment.objects.filter(pk=self.work.pk)

    def execute(self):
        if self.kind == "component":
            return component_execution.execute(self.record.pk)
        if self.kind == "pipeline":
            return workbench.execute(self.record.pk, script_executor=pipeline_runner.execute_script)
        return predictions.execute(self.record.pk)

    def cancel(self):
        if self.kind == "component":
            return component_execution.cancel(self.work)
        if self.kind == "pipeline":
            return workbench.cancel_run(self.work.project, self.record.pk)
        return predictions.cancel(self.prediction_set)

    def receipt(self):
        self.record.refresh_from_db()
        if self.kind == "pipeline":
            return (self.record.result.get("steps") or [{}])[0]
        return self.record.receipt

    def assert_pending(self, expected):
        assert research_effects.pending(self.owners) is expected
        if self.kind == "pipeline":
            owned, _ = research_effects.owned_data(self.owners)
            assert owned.filter(pk=self.record.pk).exists()
            assert research_effects.pending_pipelines(owned).exists() is expected
        else:
            assert experiment_execution.pending_work(self.owners) is expected

    def assert_no_publication(self):
        self.record.refresh_from_db()
        self.cell.dataset.refresh_from_db()
        assert self.cell.dataset.active_cell.pk == self.cell.pk
        assert list(
            Cell.objects.filter(dataset=self.cell.dataset).values_list("pk", flat=True)
        ) == [self.cell.pk]
        assert not self.work.artifacts.exists()
        if self.kind == "component":
            assert self.record.outputs == {}
        elif self.kind == "pipeline":
            assert self.record.output_id is None
        else:
            row = self.prediction_set.rows.get()
            assert row.output is None
            assert row.trace == {} and row.usage == {}

    def output_rows(self):
        if self.kind == "pipeline":
            return [{"source_row": 0, "input": "Say one", "expected_output": "one"}]
        return [{"port": "output", "value": "one"}]


def script_effect(kind, *, source=None, pipeline_key="cancel-run"):
    work, cell = source if source else inputs([{"input": "Say one", "expected_output": "one"}])[:2]
    if kind == "pipeline":
        package = retained_package(work.project, work.created_by, [identity_script()])
        pipeline = workbench.save_pipeline(
            work.project,
            work.created_by,
            name="Cancellation transform",
            request_key="cancel-transform",
            package=package,
            dataset=cell.dataset,
        )
        run = workbench.submit(
            cell.dataset,
            work.created_by,
            source_cell=cell.pk,
            source_fingerprint=cell.fingerprint,
            request_key=pipeline_key,
            pipeline=pipeline.pk,
            context={"assignment": str(work.pk)},
        )
        return ScriptEffect(kind, work, cell, run)
    component = assets.publish(
        work.project,
        work.created_by,
        kind="component",
        name="Cancellation component",
        request_key="cancel-component",
        specification={
            "runtime": packages.runtime_id(),
            "entrypoint": "predict.py",
            "limits": {"memory_mb": 2048},
            "files": {
                "predict.py": (
                    "import json,sys\n"
                    "with open(sys.argv[2], 'w') as output:\n"
                    "    output.write(json.dumps({'port':'output','value':'one'})+'\\n')\n"
                )
            },
            "inputs": {"input": {"type": "data", "schema": {}}},
            "outputs": {"output": {"schema": {"type": "string"}}},
        },
    )
    if kind == "component":
        request = ComponentRequest(
            operation="run",
            component=component.pk,
            inputs={"input": {"cell": str(cell.pk), "fingerprint": cell.fingerprint}},
        )
        action = research.claim(
            work.agents.get(parent__isnull=True),
            "component-run",
            "component",
            request.model_dump(mode="json", by_alias=True),
        )
        execution = component_execution.create(action, request)
        research.complete(action, component_execution.describe(execution), cost=0)
        return ScriptEffect(kind, work, cell, execution)
    candidate = assets.publish(
        work.project,
        work.created_by,
        kind="candidate",
        name="Component candidate",
        request_key="component-candidate",
        specification={"kind": "component", "component": str(component.pk)},
    )
    result = predictions.create(work, candidate.pk, cell.pk, "component-predictions")
    return ScriptEffect(
        kind, work, cell, PredictionAttempt.objects.get(row__prediction_set=result), result
    )


@pytest.mark.parametrize("kind", ["component", "pipeline", "component_prediction"])
def test_cancelled_queued_script_never_contacts_provider(kind, sandbox_api):
    effect = script_effect(kind)
    sandbox_api.then(lambda _: pytest.fail("Cancelled work reached the sandbox"))
    effect.cancel()
    effect.execute()
    effect.execute()
    effect.record.refresh_from_db()
    assert effect.record.state == "cancelled"
    assert not effect.receipt().get("submission_started_at")
    assert sandbox_api.calls == []
    effect.assert_no_publication()
    effect.assert_pending(False)


@pytest.mark.parametrize("boundary", [1, 2], ids=["before_submit", "before_http"])
def test_script_cancellation_at_submission_guard_records_confirmed_non_start(
    boundary, sandbox_api, tmp_path
):
    receipt, submissions = {}, 0

    def progress():
        nonlocal submissions
        if receipt.get("submission_started_at"):
            submissions += 1
            return submissions < boundary
        return True

    sandbox_api.then(lambda _: pytest.fail("Revoked submission reached the sandbox"))
    with pytest.raises(RuntimeUnavailableError):
        list(
            execute_jsonl(
                manifest={"runtime": packages.runtime_id()},
                records=[{"input": "one"}],
                directory=tmp_path,
                entrypoint="predict.py",
                files={"predict.py": "pass\n"},
                parameters={},
                receipt=receipt,
                progress=progress,
            )
        )
    assert sandbox_api.calls == []
    assert receipt["submission_started_at"]
    assert receipt["submission_rejected"] is True
    assert receipt.get("exit_code") is None


@pytest.mark.covers("recovery")
def test_late_pipeline_receipt_cannot_overwrite_a_replaced_attempt(sandbox_api):
    effect = script_effect("pipeline")
    held = HeldResponse(final_response("exit_zero", effect.output_rows()))
    sandbox_api.then(held)
    replacement = uuid4()
    replacement_result = {
        "stage": "cancelled",
        "attempt": str(replacement),
        "steps": [{"submission_started_at": "replacement", "submission_rejected": True}],
    }
    with in_worker(effect.execute) as worker:
        try:
            assert held.accepted.wait(15)
            effect.cancel()
            # A fixture of the persisted fence; no public API retries unknown work.
            DatasetPipelineRun.objects.filter(pk=effect.record.pk).update(
                attempt=replacement, result=replacement_result
            )
        finally:
            held.release.set()
        worker.result(timeout=20)
    effect.record.refresh_from_db()
    assert effect.record.attempt == replacement
    assert effect.record.result == replacement_result
    assert effect.record.state == "cancelled"
    effect.assert_no_publication()
    assert len(sandbox_api.calls) == 1


def test_cancelled_queued_model_prediction_creates_no_provider_ledger(fake_llm):
    work, cell, candidate = inputs([{"input": "Say one", "expected_output": "one"}])
    result = predictions.create(work, candidate.pk, cell.pk, "queued-model")
    attempt = PredictionAttempt.objects.get(row__prediction_set=result)
    predictions.cancel(result)
    predictions.execute(attempt.pk)
    predictions.execute(attempt.pk)
    assert fake_llm.requests == []
    assert not ResearchAction.objects.filter(
        agent__assignment=work, tool="prediction_model"
    ).exists()
    assert not research_effects.pending(ResearchAssignment.objects.filter(pk=work.pk))
    assert result.rows.get().output is None


@pytest.mark.parametrize("kind", ["component", "component_prediction"])
def test_late_script_exit_after_timeout_releases_effect_without_republishing(kind, sandbox_api):

    effect = script_effect(kind)
    held = HeldResponse(final_response("exit_zero", effect.output_rows()))
    sandbox_api.then(held)
    with in_worker(effect.execute) as worker:
        try:
            assert held.accepted.wait(15)
            type(effect.record).objects.filter(pk=effect.record.pk).update(
                expires_at=timezone.now() - timedelta(seconds=1)
            )
            if kind == "component":
                component_execution.reconcile(effect.work)
            else:
                predictions.dispatch(effect.prediction_set.pk)
            effect.record.refresh_from_db()
            assert effect.record.state == "unknown"
            effect.assert_pending(True)
        finally:
            held.release.set()
        worker.result(timeout=20)
    assert effect.receipt()["exit_code"] == 0
    effect.assert_no_publication()
    effect.assert_pending(False)
    effect.execute()
    assert held.calls == 1


def authority_owner(*, controlled):
    work, cell, _ = inputs([{"input": "Say one", "expected_output": "one"}])
    if not controlled:
        return work, cell, None
    # Reuse investigating's genuine flow->adaptive-research provenance, with
    # one input row so a prediction case owns exactly one queued attempt.
    experiment = research_experiments.create(
        work.project,
        work.created_by,
        name="Controlled execution",
        objective="Inspect the retained input",
        cells=[cell.pk],
        request_key="controlled-source",
    )
    document = deepcopy(experiment.revisions.get(number=1).document)
    document["nodes"][0]["title"] = "Pinned authority input"
    research_experiments.revise(
        experiment, expected_version=1, document=document, request_key="controlled-layout"
    )
    parent, _, child = investigating(experiment, work.created_by)
    assert execution_mandates.parent_assignment(child).pk == parent.pk
    return child, cell, parent


def authority_script_effect(kind, *, controlled=False):
    work, cell, parent = authority_owner(controlled=controlled)
    task, key = None, "authority-pipeline"
    if kind == "pipeline_workshop":
        task = lifecycle.start(
            lifecycle.NativeGrant(
                work.project,
                work.created_by,
                parent_assignment=work,
                execution_mandate=work.execution_mandate,
            ),
            StartTask(
                dataset=cell.dataset_id,
                objective="Prepare admitted input",
                request_key="workshop-authority",
            ),
        )
        key = f"workshop:{task.pk}:1"
    if kind == "pipeline_action":
        action = research.claim(
            work.agents.get(parent__isnull=True),
            "pipeline-authority",
            "platform",
            {"name": "run_dataset_pipeline", "arguments": {}},
        )
        key = f"research:{action.pk}"
        research.complete(action, {"retained": True}, cost=0)
    effect = script_effect(
        "pipeline" if kind.startswith("pipeline_") else kind, source=(work, cell), pipeline_key=key
    )
    return effect, parent, task


KINDS = [
    "component",
    "component_prediction",
    "pipeline_context",
    "pipeline_workshop",
    "pipeline_action",
]


def revoke_owner(effect, parent, reason):
    if reason == "membership":
        ProjectMembership.objects.filter(
            project=effect.work.project, user=effect.work.created_by
        ).delete()
        return
    assert parent is not None
    # Capture only task dispatch: executing stop propagation here would hide the
    # worker boundary under test. This is the repository's permitted Celery seam.
    with patch("overbae.tasks.research.settle_stop.delay") as dispatch:
        research.stop(parent)
    assert dispatch.called
    parent.refresh_from_db()
    effect.work.refresh_from_db()
    assert parent.state == "stopping"
    assert effect.work.state == "running"


def assert_native_effect_pending(effect, expected):
    if effect.kind == "pipeline":
        pipelines, _ = research_effects.owned_data(effect.owners)
        assert pipelines.filter(pk=effect.record.pk).exists()
        assert research_effects.pending_pipelines(pipelines).exists() is expected
    else:
        assert experiment_execution.pending_work(effect.owners) is expected
    # Do not use ScriptEffect.assert_pending(False) for a delegated pipeline:
    # its WorkshopTask remains active, independently of provider settlement.


@pytest.mark.covers("authentication")
@pytest.mark.parametrize("kind", KINDS)
@pytest.mark.parametrize("reason", ["membership", "parent_stop"])
def test_queued_native_effect_rechecks_retained_authority(kind, reason, sandbox_api):
    effect, parent, task = authority_script_effect(kind, controlled=reason == "parent_stop")
    sandbox_api.then(lambda _: pytest.fail("Revoked authority reached the sandbox"))
    revoke_owner(effect, parent, reason)
    if task:
        task.refresh_from_db()
        assert task.desired_state == "running"
    effect.execute()
    effect.execute()
    assert sandbox_api.calls == []
    assert not effect.receipt().get("submission_started_at")
    effect.assert_no_publication()
    assert_native_effect_pending(effect, False)


@pytest.mark.covers("recovery")
@pytest.mark.parametrize("kind", ["component", "component_prediction"])
@pytest.mark.parametrize("boundary", ["queued", "accepted"])
@pytest.mark.parametrize(
    "disposition", ["model_call_limit", "model_provider_unavailable", "model_provider_rejected"]
)
def test_unavailable_decisions_preserve_the_retained_script_effect(
    kind, boundary, sandbox_api, disposition
):
    effect = script_effect(kind)
    owner = effect.work
    owner.specification["budget"]["max_model_calls"] = 1 if disposition == "model_call_limit" else 4
    owner.save(update_fields=["specification"])
    lead = owner.agents.get(parent__isnull=True)
    last = research.claim(lead, "last-model", "model", {})
    research.complete(last, {}, cost=0)
    held = HeldResponse(final_response("exit_zero", effect.output_rows()))
    sandbox_api.then(held)

    def suspend():
        if disposition == "model_call_limit":
            research_agent.think(research_agent.lease(lead.pk), 1)
        else:
            owner.state, owner.result = "blocked", {"reason": disposition}
            owner.save(update_fields=["state", "result"])
            lead.state, lead.result = "blocked", {"provider_probe": True}
            lead.save(update_fields=["state", "result"])
            research_agent.reconcile(owner)

    if boundary == "queued":
        suspend()
        held.release.set()
        effect.execute()
    else:
        with in_worker(effect.execute) as worker:
            try:
                assert held.accepted.wait(15)
                suspend()
                effect.record.refresh_from_db()
                assert effect.record.state == "running"
                with pytest.raises(InputValidationError):
                    research.claim(lead, "forged-model", "model", {}, effect=effect.record)
            finally:
                held.release.set()
            worker.result(timeout=20)
    effect.record.refresh_from_db()
    assert effect.record.state == "completed", effect.record.error
    assert effect.receipt()["exit_code"] == 0
    if kind == "component":
        binding = effect.record.outputs["output"]
        artifact = owner.artifacts.get(pk=binding["artifact"])
        assert json.loads(research.artifact_bytes(artifact, limit=1000)) == "one"
        assert artifact.action.state == "completed"
    else:
        assert effect.prediction_set.rows.get().output == "one"
    effect.assert_pending(False)
    assert research.model_calls(owner) == 1
    assert research.claim(lead, "new-component", "component", {}).state == "denied"
    assert research.claim(lead, "new-model", "model", {}).state == "denied"
    effect.execute()
    assert held.calls == len(sandbox_api.calls) == 1