Skip to content

The platform for continuously improving AI agents.

47.9 KB
Raw Blame
import json
from copy import deepcopy
from datetime import timedelta

import pytest
from django.utils import timezone
from factories import decision_campaign, decision_row, make_matrix_row, make_project, make_user
from test_experiment_preparation import research_source_sandbox as research_source_sandbox
from test_experiment_preparation import retain_source_tool_history, seal_preparation_source
from test_research_team import assignment, invoke, specialist
from test_research_triggers import occurrence, settings_for

from overbae.core.errors import InputValidationError
from overbae.innermind import runs
from overbae.models import (
    ComponentExecution,
    Dataset,
    EvalSet,
    PredictionAttempt,
    ResearchExperimentTrigger,
)
from overbae.services import (
    component_execution,
    context_graph,
    execution_mandates,
    experiment_checkpoints,
    experiment_components,
    experiment_dispatch,
    experiment_engine,
    experiment_execution,
    experiment_scoring,
    research,
    research_agent,
    research_catalogue,
    research_evidence,
    research_experiments,
    research_tools,
    research_triggers,
)
from overbae.services import experiment_assets as assets
from overbae.services import experiment_predictions as predictions
from overbae.services.datasets import land
from overbae.services.research_contract import Artifact, Explore

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


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


def inputs(records=None):
    user = make_user()
    project = make_project(member=user)
    data = Dataset.objects.create(project=project, name="Prediction inputs", intent="train")
    land.land_rows(
        data,
        records
        or [
            {"input": "Say one", "expected_output": "one"},
            {"input": "Say two", "expected_output": "two"},
        ],
    )
    data.refresh_from_db()
    work, _ = assignment(project=project, user=user, context_roots=[f"cell:{data.active_cell.pk}"])
    candidate = assets.publish(
        work.project,
        work.created_by,
        kind="candidate",
        name="Baseline",
        specification={"kind": "catalogue", "model": "openai/gpt-5-mini"},
        request_key="candidate",
    )
    return work, data.active_cell, candidate


def drain(prediction_set):
    for _ in range(10):
        predictions.dispatch(prediction_set.pk)
        attempts = list(
            PredictionAttempt.objects.filter(row__prediction_set=prediction_set, state="queued")
        )
        if not attempts:
            break
        for attempt in attempts:
            predictions.execute(attempt.pk)
    prediction_set.refresh_from_db()


def suite(work, source="def evaluate(span):\n    return 1.0\n", key="suite"):
    metric = make_matrix_row(work.project, type="deterministic", source=source)
    tests = EvalSet.objects.create(project=work.project, name=key)
    tests.rows.add(metric)
    return (
        assets.publish(
            work.project,
            work.created_by,
            kind="suite",
            name=key,
            specification={"eval_set": str(tests.pk), "minimum_score": 0.8},
            request_key=key,
        ),
        tests,
        metric,
    )


def test_prediction_without_scorers_and_two_suite_revisions_rescore_retained_outputs(fake_llm):
    fake_llm.on(lambda _: True, "retained prediction")
    work, cell, candidate = inputs()
    result = predictions.create(work, candidate.pk, cell.pk, "predictions")
    drain(result)
    assert result.state == "completed", list(result.rows.values("state", "error"))
    calls = len(fake_llm.requests)
    assert calls == 2
    first, tests, metric = suite(work)
    metric.source = "def evaluate(span):\n    return 0.0\n"
    metric.save(update_fields=["source"])
    same = assets.publish(
        work.project,
        work.created_by,
        kind="suite",
        name="suite",
        specification={"eval_set": str(tests.pk), "minimum_score": 0.8},
        request_key="suite",
    )
    assert same.pk == first.pk
    second = assets.publish(
        work.project,
        work.created_by,
        kind="suite",
        name="Stricter",
        specification={"eval_set": str(tests.pk), "minimum_score": 0.8},
        request_key="suite-two",
        parent=first.pk,
    )
    for definition, expected in ((first, 1.0), (second, 0.0)):
        evaluation = experiment_scoring.create(
            work, result.pk, definition.pk, f"evaluate:{definition.pk}"
        )
        assert runs.start(evaluation.run_id) == "score"
        assert runs.score(evaluation.run_id, runs.hand_to_scoring(evaluation.run_id))
        evaluation.run.refresh_from_db()
        assert evaluation.run.summary["score"] == expected
        assert experiment_scoring.describe(evaluation)["accepted"] is (expected == 1.0)
    assert len(fake_llm.requests) == calls


def test_prediction_duplicate_delivery_and_unknown_deadline_never_replays(fake_llm):
    work, cell, candidate = inputs()
    result = predictions.create(work, candidate.pk, cell.pk, "predictions")
    attempt, stalled = list(
        PredictionAttempt.objects.filter(row__prediction_set=result).order_by("row__index")
    )
    predictions.execute(attempt.pk)
    predictions.execute(attempt.pk)
    assert len(fake_llm.requests) == 1
    PredictionAttempt.objects.filter(pk=stalled.pk).update(
        state="running", expires_at=timezone.now() - timedelta(seconds=1)
    )
    predictions.dispatch(result.pk)
    result.refresh_from_db()
    assert result.state == "failed"
    with pytest.raises(InputValidationError, match="Unconfirmed"):
        predictions.resume(result)
    assert len(fake_llm.requests) == 1


def test_prediction_reference_is_removed_from_all_transcript_representations():
    import json

    messages = [
        {"role": "user", "content": "question"},
        {"role": "assistant", "content": "SECRET_REFERENCE"},
    ]
    work, cell, candidate = inputs(
        [{"input": json.dumps(messages), "expected_output": "SECRET_REFERENCE"}]
    )
    result = predictions.create(work, candidate.pk, cell.pk, "predictions")
    assert "SECRET_REFERENCE" not in str(result.rows.get().input)


def test_assets_reject_unsupported_model_or_hidden_parameter_noops():
    work, _, candidate = inputs()
    for definition in (
        {"kind": "catalogue", "model": "jev-1.13"},
        {"kind": "catalogue", "model": "openai/gpt-5-mini", "parameters": {"temperature": 0.5}},
    ):
        with pytest.raises(InputValidationError):
            assets.publish(
                work.project,
                work.created_by,
                kind="candidate",
                name="Rejected",
                specification=definition,
                request_key="reject",
            )
    changed = deepcopy(candidate.definition)
    changed.pop("runtime")
    changed["system_prompt"] = "changed"
    with pytest.raises(InputValidationError, match="different asset"):
        assets.publish(
            work.project,
            work.created_by,
            kind="candidate",
            name="Baseline",
            specification=changed,
            request_key="candidate",
        )


def test_saved_flow_runs_two_candidates_and_compares_with_no_planning_calls(fake_llm):
    fake_llm.on(lambda _: True, "prediction")
    work, cell, first = inputs()
    second = assets.publish(
        work.project,
        work.created_by,
        kind="candidate",
        name="Prompt variant",
        specification={
            "kind": "catalogue",
            "model": "gpt-5-mini",
            "system_prompt": "Return a concise answer",
        },
        request_key="variant",
    )
    benchmark, _, _ = suite(work)
    experiment = research_experiments.create(
        work.project,
        work.created_by,
        name="Reusable benchmark",
        objective="Compare two frozen candidates",
        cells=[cell.pk],
        request_key="benchmark-flow",
    )
    document = deepcopy(experiment.revisions.get().document)

    def node(identifier, kind, config=None, tool=None):
        return {
            "id": identifier,
            "kind": kind,
            "title": identifier,
            "position": {"x": 0, "y": 0},
            "config": config or {},
            **({"operation": {"tool": tool, "arguments": {"operation": "run"}}} if tool else {}),
        }

    document["nodes"].append(
        node("suite", "suite", {"asset": str(benchmark.pk), "fingerprint": benchmark.fingerprint})
    )
    for key, candidate in (("a", first), ("b", second)):
        document["nodes"].extend(
            [
                node(
                    key, "model", {"asset": str(candidate.pk), "fingerprint": candidate.fingerprint}
                ),
                node(f"predict_{key}", "predict", tool="prediction"),
                node(f"score_{key}", "evaluate", tool="score"),
            ]
        )
        for source, output, target, port in (
            ("data_0", "data", f"predict_{key}", "data"),
            (key, "model", f"predict_{key}", "model"),
            (f"predict_{key}", "predictions", f"score_{key}", "predictions"),
            ("suite", "suite", f"score_{key}", "suite"),
        ):
            document["edges"].append(
                {"source": source, "output": output, "target": target, "input": port}
            )
    document["nodes"].append(
        node("compare", "compare", {"metric": "/report/score", "direction": "maximize"})
    )
    for key in ("a", "b"):
        document["edges"].append(
            {"source": f"score_{key}", "output": "scores", "target": "compare", "input": "scores"}
        )
    document["outputs"] = {
        "selected": {"node": "compare", "port": "model"},
        "comparison": {"node": "compare", "port": "scores"},
    }
    research_experiments.revise(
        experiment, expected_version=1, document=document, request_key="definition"
    )
    run = experiment_engine.start(
        experiment, work.created_by, revision=2, request_key="run", budget={}
    )
    for _ in range(8):
        experiment_engine.advance(run.pk)
        for prediction_set in run.predictionset_set.all():
            drain(prediction_set)
            for evaluation in prediction_set.evaluations.select_related("run"):
                if evaluation.run.status == "pending":
                    runs.start(evaluation.run_id)
                    runs.score(evaluation.run_id, runs.hand_to_scoring(evaluation.run_id))
        run.refresh_from_db()
        if run.state != "running":
            break
    assert run.state == "completed", (
        run.result,
        list(run.execution.nodes.values("node", "state", "error")),
    )
    outputs = run.execution.nodes.get(node="compare").outputs
    assert outputs["scores"]["outcome"] == "tie"
    assert outputs["scores"]["selected"] is None and "model" not in outputs
    assert {item["input"]["model"]["asset"] for item in outputs["scores"]["reports"]} == {
        str(first.pk),
        str(second.pk),
    }
    assert len(fake_llm.requests) == 4


@pytest.mark.parametrize("outcome", ["completed", "uncertain", "cancelled", "uncertain_trigger"])
def test_reusable_component_runs_actual_isolated_python_with_named_outputs(outcome):

    from overbae.models import ComponentExecution
    from overbae.services import component_execution, research_catalogue, research_tools
    from overbae.services.research_contract import Explore

    work, cell, _ = inputs()
    contract = research_catalogue.contracts(
        work.agents.get(parent__isnull=True), Explore(operation="contracts", kind="component")
    )["authoring"]
    component = assets.publish(
        work.project,
        work.created_by,
        kind="component",
        name="Count inputs",
        request_key="count",
        specification={
            "runtime": contract["runtime"],
            "entrypoint": "count.py",
            "limits": {"memory_mb": 2048},
            "files": {
                "count.py": "import json,sys\nwith open(sys.argv[1]) as f: value=json.loads(next(f))['value']\nwith open(sys.argv[2], 'w') as f: f.write(json.dumps({'port':'count','value':len(value)}))\n"
            },
            "inputs": {"examples": {"type": "data", "schema": {"type": "array"}}},
            "outputs": {"count": {"schema": {"type": "integer", "minimum": 1}}},
        },
    )
    experiment = research_experiments.create(
        work.project,
        work.created_by,
        name="Count",
        objective="Count retained inputs",
        cells=[cell.pk],
        request_key="count-flow",
    )
    document = deepcopy(experiment.revisions.get().document)
    document["nodes"].append(
        {
            "id": "count",
            "kind": "component",
            "title": "Count",
            "position": {"x": 500, "y": 0},
            "config": {"asset": str(component.pk), "fingerprint": component.fingerprint},
            "operation": {"tool": "component", "arguments": {"operation": "run"}},
        }
    )
    document["edges"] = [
        {"source": "data_0", "output": "data", "target": "count", "input": "examples"}
    ]
    document["outputs"] = {"count": {"node": "count", "port": "count"}}
    research_experiments.revise(
        experiment, expected_version=1, document=document, request_key="definition"
    )
    if outcome == "uncertain_trigger":
        settings = settings_for(experiment, target="run", authority="act")
        settings["configuration"]["revision"] = 2
        settings["configuration"]["mandate"]["sources"].append(
            {"kind": "asset", "id": str(component.pk), "fingerprint": component.fingerprint}
        )
        trigger = ResearchExperimentTrigger.objects.get(
            pk=research_triggers.create(
                experiment, work.created_by, request_key="component-events", **settings
            )["id"]
        )
        fire = research_triggers.admit(occurrence(trigger).pk)
        run = fire.assignment
    else:
        parent = research_experiments.start(
            experiment, work.created_by, revision=2, request_key="count", budget={}
        )
        lead = parent.agents.get(parent__isnull=True)
        invoke(lead, "experiment", {"operation": "run", "revision": 2})
        run = experiment_dispatch.owned(parent).get()
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "running"
    execution = ComponentExecution.objects.get(action__agent__assignment=run)
    assert execution.state == "queued"
    if outcome.startswith("uncertain"):
        ComponentExecution.objects.filter(pk=execution.pk).update(
            state="running", expires_at=timezone.now() - timedelta(seconds=1)
        )
        component_execution.reconcile(run)
    elif outcome == "cancelled":
        research_tools.stop_work(run)
    component_execution.execute(execution.pk)
    component_execution.execute(execution.pk)
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    execution.refresh_from_db()
    if outcome != "completed":
        assert execution.state == ("unknown" if outcome.startswith("uncertain") else "cancelled")
        # A stage stopped on request is cancelled; one whose outcome is unknown has failed.
        assert run.execution.nodes.get(node="count").state == (
            "failed" if outcome.startswith("uncertain") else "cancelled"
        )
        assert not run.artifacts.exists()
        if outcome.startswith("uncertain"):
            with pytest.raises(InputValidationError, match="acknowledgements"):
                experiment_engine.retry(run, request_key="do-not-replay-unknown")
        if outcome == "uncertain_trigger":
            assert run.state == "unmet"
            research_triggers.reconcile()
            fire.refresh_from_db()
            assert fire.state == "admitted" and fire.settled_at is None
            later = research_triggers.admit(occurrence(trigger).pk)
            assert later.state == "pending" and later.reason_code == "active_work"
            assert later.assignment_id is None
            trigger.refresh_from_db()
            assert trigger.sends == 1
        return
    assert run.state == "completed", (run.result, list(run.execution.nodes.values("error")))
    assert run.artifacts.filter(title="count").count() == 1
    artifact = run.artifacts.get(title="count")
    with artifact.file.open("rb") as stream:
        assert stream.read() == b"2"
    experiment_dispatch.reconcile(parent)
    assert research.accessible_artifact(parent, artifact.pk).pk == artifact.pk
    assert research.accessible_artifact(work, artifact.pk).pk == artifact.pk
    foreign, _, _ = inputs()
    with pytest.raises(InputValidationError):
        research.accessible_artifact(foreign, artifact.pk)
    retained = research.claim(run.agents.get(parent__isnull=True), "private", "artifact", {})
    unpublished = research.retain(
        retained, Artifact(path="private.txt", title="Private", kind="report"), b"unpublished"
    )
    assert research.accessible_artifact(parent, unpublished.pk).pk == unpublished.pk
    original_hash = artifact.sha256
    artifact.sha256 = "f" * 64
    artifact.save(update_fields=["sha256"])
    with pytest.raises(InputValidationError, match="fingerprint changed"):
        experiment_components.values(
            retained, {"input": {"artifact": str(artifact.pk), "fingerprint": original_hash}}
        )
    artifact.sha256, artifact.metadata = original_hash, {"access": "final_data"}
    artifact.save(update_fields=["sha256", "metadata"])
    assert research.accessible_artifact(parent, artifact.pk).pk == artifact.pk
    artifact.metadata = {}
    artifact.save(update_fields=["metadata"])
    # The run's own receipt names the output it retained: nobody re-verifies it by hand.
    receipt = parent.artifacts.get(metadata__flow_run=str(run.pk))
    assert str(artifact.pk) in research.artifact_bytes(receipt, limit=100000).decode()


def test_scoring_owner_is_independent_of_reused_prediction_owner(fake_llm):
    from overbae.services import research, research_agent, research_tools

    fake_llm.on(lambda _: True, "retained answer")
    original, cell, candidate = inputs()
    predicted = predictions.create(original, candidate.pk, cell.pk, "predict")
    drain(predicted)
    consumer = research.create(
        original.project,
        user=original.created_by,
        request_key="rescore",
        objective="Rescore retained predictions",
        task={"deliverable": "New benchmark evidence"},
        budget={},
        context_roots=[f"cell:{cell.pk}"],
        execution_mandate=execution_mandates.admission(roots=[f"cell:{cell.pk}"]),
    )
    benchmark, _, _ = suite(original)
    evaluation = experiment_scoring.create(consumer, predicted.pk, benchmark.pk, "rescore")
    assert evaluation.assignment_id == consumer.pk
    research_tools.stop_work(original)
    evaluation.run.refresh_from_db()
    assert evaluation.run.status == "pending"
    assert research_tools.pending_work(consumer)
    observed = research_agent.evidence(consumer.agents.get(parent__isnull=True))
    assert observed["data_work"]["scores"][0]["id"] == str(evaluation.run_id)
    experiment_scoring.reconcile(consumer)
    evaluation.run.refresh_from_db()
    token = evaluation.run.scoring_task_id
    assert token and evaluation.run.status == "running"
    assert runs.score(evaluation.run_id, token)
    assert not research_tools.pending_work(consumer)


def test_capacity_and_lost_delivery_recover_only_owned_prediction_sets(fake_llm, monkeypatch):
    from overbae.tasks.research import predict_row

    fake_llm.on(lambda _: True, "answer")
    work, cell, candidate = inputs(
        [{"input": str(i), "expected_output": "answer"} for i in range(4)]
    )
    deliveries = []
    monkeypatch.setattr(predict_row, "delay", lambda identifier: deliveries.append(identifier))
    sets = [predictions.create(work, candidate.pk, cell.pk, f"set-{i}") for i in range(3)]
    assert sets[2].rows.filter(state="pending").count() == 4
    lost = deliveries.pop()
    for identifier in list(deliveries):
        predictions.execute(identifier)
    PredictionAttempt.objects.filter(pk=lost).update(
        started_at=timezone.now() - timedelta(minutes=2)
    )
    deliveries.clear()
    predictions.reconcile(work)
    assert lost in deliveries
    assert sets[2].rows.filter(state="queued").count() == 4
    for identifier in deliveries:
        predictions.execute(identifier)
    assert all(predictions.get(work.project, item.pk).state == "completed" for item in sets)
    assert len(fake_llm.requests) == 12


def test_late_component_publication_cannot_create_artifacts_after_stop():
    from overbae.services import experiment_components, research
    from overbae.services.experiment_asset_contract import ComponentRequest

    work, _, _ = inputs()
    lead = work.agents.get(parent__isnull=True)
    action = research.claim(lead, "component", "component", {"operation": "run"})
    work.state = "stopping"
    work.save(update_fields=["state"])
    with pytest.raises(InputValidationError, match="publication authority"):
        experiment_components.publish(
            action, None, ComponentRequest(operation="run"), {"a": 1, "b": 2}, {}
        )
    assert not work.artifacts.exists()


def test_candidate_calls_ignore_historical_money_caps_and_keep_missing_cost_unknown(fake_llm):
    from overbae.services import research

    fake_llm.on(lambda _: True, {"content": "answer", "usage": {"cost": None}})
    work, cell, candidate = inputs()
    predicted = predictions.create(work, candidate.pk, cell.pk, "predict")
    drain(predicted)
    entries = work.agents.get(parent__isnull=True).actions.filter(tool="prediction_model")
    assert entries.count() == 2
    assert all(item.cost_usd is None and item.reservation_usd > 0 for item in entries)
    assert all(row.usage["cost_usd"] is None for row in predicted.rows.all())
    assert float(research.allowance(work)["committed_usd"]) > 0
    work.specification["budget"]["max_cost_usd"] = 0
    work.save(update_fields=["specification"])
    continued = predictions.create(work, candidate.pk, cell.pk, "continue")
    drain(continued)
    assert continued.state == "completed"
    assert len(fake_llm.requests) == 4
    assert all(row.usage["cost_usd"] is None for row in continued.rows.all())


def test_asset_api_and_context_graph_preserve_project_scope_and_lineage(fake_llm):
    from rest_framework.test import APIClient

    from overbae.models import ContextEdge, ContextNode
    from overbae.services import context_graph

    fake_llm.on(lambda _: True, "answer")
    work, cell, candidate = inputs()
    other, _ = assignment()
    client = APIClient()
    client.force_authenticate(user=work.created_by)
    reply = client.get(f"/api/experiment-assets/{candidate.pk}/")
    assert reply.status_code == 200
    assert reply.data["fingerprint"] == candidate.fingerprint
    assert (
        client.patch(
            f"/api/experiment-assets/{candidate.pk}/", {"name": "changed"}, format="json"
        ).status_code
        == 405
    )
    client.force_authenticate(user=other.created_by)
    assert client.get(f"/api/experiment-assets/{candidate.pk}/").status_code == 404
    assert (
        client.post(
            "/api/experiment-assets/",
            {
                "project": str(work.project_id),
                "kind": "candidate",
                "name": "Foreign",
                "specification": {"kind": "catalogue", "model": "gpt-5-mini"},
                "request_key": "foreign",
            },
            format="json",
        ).status_code
        == 404
    )
    predicted = predictions.create(work, candidate.pk, cell.pk, "predict")
    drain(predicted)
    context_graph.refresh(
        work.project,
        kinds=["experiment_asset", "prediction_set", "prediction_row", "prediction_attempt"],
    )
    source = ContextNode.objects.get(
        project=work.project, kind="prediction_set", object_id=str(predicted.pk)
    )
    target = ContextNode.objects.get(
        project=work.project, kind="experiment_asset", object_id=str(candidate.pk)
    )
    assert (
        ContextEdge.objects.filter(source=source, target=target).exists()
        or ContextEdge.objects.filter(source=target, target=source).exists()
    )
    assert not ContextNode.objects.filter(
        project=other.project, object_id=str(predicted.pk)
    ).exists()


def test_parameterized_candidate_references_are_deferred_until_binding():
    work, cell, candidate = inputs()
    document = {
        "parameters": {
            "candidate": {"type": "string", "default": str(candidate.pk)},
            "fingerprint": {"type": "string", "default": candidate.fingerprint},
        },
        "nodes": [
            {
                "id": "candidate",
                "kind": "predict",
                "title": "Candidate",
                "position": {"x": 0, "y": 0},
                "config": {
                    "model": {
                        "asset": {"$parameter": "candidate"},
                        "fingerprint": {"$parameter": "fingerprint"},
                    }
                },
            }
        ],
        "edges": [],
        "outputs": {},
    }
    saved = research_experiments.validate_document(work.project, document)
    assert saved["nodes"][0]["config"]["model"]["asset"] == {"$parameter": "candidate"}


def test_compare_keeps_candidate_provenance_through_join():
    from overbae.services.experiment_interfaces import output_formats

    document = {
        "nodes": [
            {
                "id": "score",
                "kind": "evaluate",
                "config": {},
                "operation": {"tool": "score", "arguments": {"operation": "run"}},
            },
            {"id": "join", "kind": "join", "config": {}},
            {"id": "select", "kind": "compare", "config": {}},
        ],
        "edges": [
            {"source": "score", "output": "scores", "target": "join", "input": "scores"},
            {"source": "join", "output": "scores", "target": "select", "input": "scores"},
        ],
    }
    assert output_formats(document, "select", "model") == ["candidate.definition"]


@pytest.mark.covers("recovery")
def test_model_call_exhaustion_finishes_only_the_admitted_predictions(fake_llm):
    from overbae.services import research_agent

    fake_llm.on(lambda _: True, "retained prediction")
    work, cell, candidate = inputs()
    predicted = predictions.create(work, candidate.pk, cell.pk, "predict")
    work.specification["budget"]["max_model_calls"] = 1
    work.save(update_fields=["specification"])
    lead = work.agents.get(parent__isnull=True)
    last = research.claim(lead, "last-model", "model", {})
    research.complete(last, {}, cost=0)
    research_agent.think(research_agent.lease(lead.pk), 1)
    work.refresh_from_db()
    assert work.state == "exhausted" and work.result["reason"] == "model_call_limit"
    drain(predicted)
    assert predicted.state == "completed", list(predicted.rows.values("state", "error"))
    assert set(predicted.rows.values_list("output", flat=True)) == {"retained prediction"}
    assert len(fake_llm.requests) == 2
    assert lead.actions.filter(tool="prediction_model", state="completed").count() == 2
    assert research.model_calls(work) == 1
    with pytest.raises(InputValidationError):
        predictions.create(work, candidate.pk, cell.pk, "new-predictions")
    with pytest.raises(InputValidationError):
        predictions.resume(predicted)
    assert research.claim(lead, "new-model", "model", {}).state == "denied"
    assert len(fake_llm.requests) == 2


def test_agent_can_plan_component_ports_before_authoring_without_executing_a_draft():
    from test_research_experiments import setup_experiment, start

    from overbae.services import research, research_agent

    experiment, user, _ = setup_experiment()
    assignment = start(experiment, user)
    lead = assignment.agents.get(parent__isnull=True)
    stages = [
        {
            "id": "profile",
            "kind": "component",
            "title": "Profile data",
            "inputs": {"examples": "data_0"},
            "settings": {
                "ports": {"inputs": {"examples": "data"}, "outputs": {"report": "artifact"}}
            },
        },
        {
            "id": "validate",
            "kind": "validate",
            "title": "Validate report",
            "inputs": {"artifact": "profile.report"},
        },
    ]
    for stage in stages:
        drafted = research.claim(
            lead, f"draft-{stage['id']}", "experiment", {"operation": "stage", **stage}
        )
        research_agent.run_tools(lead)
        drafted.refresh_from_db()
        assert drafted.state == "completed", drafted.result
    saved = experiment.revisions.get(number=3).document
    assert saved["edges"] == [
        {"source": "data_0", "output": "data", "target": "profile", "input": "examples"},
        {"source": "profile", "output": "report", "target": "validate", "input": "artifact"},
    ]
    assert saved["nodes"][1]["operation"] is None and drafted.result["ready"] is False
    assert "asset" in {tool["function"]["name"] for tool in research_agent.definitions(lead)}
    with pytest.raises(InputValidationError, match="published asset"):
        experiment_engine.start(experiment, user, revision=3, request_key="unconfigured", budget={})
    assert not assignment.artifacts.exists()


@pytest.mark.covers("recovery")
def test_model_call_exhaustion_preserves_only_the_admitted_prediction_scoring(fake_llm):
    from overbae.services import research_agent

    fake_llm.on(lambda _: True, "retained prediction")
    work, cell, candidate = inputs()
    predicted = predictions.create(work, candidate.pk, cell.pk, "predict")
    drain(predicted)
    benchmark, _, _ = suite(work)
    evaluation = experiment_scoring.create(work, predicted.pk, benchmark.pk, "score")
    work.specification["budget"]["max_model_calls"] = 1
    work.save(update_fields=["specification"])
    lead = work.agents.get(parent__isnull=True)
    last = research.claim(lead, "last-model", "model", {})
    research.complete(last, {}, cost=0)
    research_agent.think(research_agent.lease(lead.pk), 1)
    experiment_scoring.reconcile(work)
    evaluation.run.refresh_from_db()
    assert evaluation.run.status == "running" and evaluation.run.scoring_task_id
    assert runs.score(evaluation.run_id, evaluation.run.scoring_task_id)
    evaluation.run.refresh_from_db()
    assert experiment_scoring.describe(evaluation)["accepted"]
    with pytest.raises(InputValidationError):
        experiment_scoring.create(work, predicted.pk, benchmark.pk, "new-score")
    assert len(fake_llm.requests) == 2 and research.model_calls(work) == 1


def echo_component(owner, lead, *, raises=False):
    contract = research_catalogue.contracts(lead, Explore(operation="contracts", kind="component"))[
        "authoring"
    ]
    return assets.publish(
        owner.project,
        owner.created_by,
        kind="component",
        name="Echo exact input",
        request_key="echo-source",
        specification={
            "runtime": contract["runtime"],
            "entrypoint": "echo.py",
            "limits": {"memory_mb": 2048},
            "files": {
                "echo.py": "import json,sys\nwith open(sys.argv[1]) as f: value=json.loads(next(f))['value']\n"
                + (
                    "raise ValueError(value[0]['input'])\n"
                    if raises
                    else "with open(sys.argv[2], 'w') as f: f.write(json.dumps({'port':'copy','value':value}))\n"
                )
            },
            "inputs": {"source": {"schema": {"type": "array"}}},
            "outputs": {"copy": {"schema": {"type": "array"}}},
        },
    )


@pytest.mark.covers("privacy")
@pytest.mark.parametrize("historical", [False, True])
def test_component_artifacts_remain_readable_after_final_partitioning(
    research_source_sandbox, historical
):
    hidden = "withheld-component-source-870219"
    original, cell, _ = inputs(
        [{"input": f"{hidden}-{index}", "expected_output": str(index % 2)} for index in range(20)]
    )
    unrelated = Dataset.objects.create(
        project=original.project, name="Independent inputs", intent="train"
    )
    land.land_rows(unrelated, [{"input": "independent-source", "expected_output": "public"}])
    unrelated.refresh_from_db()
    owner = research.create(
        original.project,
        user=original.created_by,
        request_key="component-source-lineage",
        objective="Retain independently reproducible component outputs",
        task={"deliverable": "Retained outputs"},
        context_roots=[f"cell:{cell.pk}", f"cell:{unrelated.source.pk}"],
        budget={},
    )
    lead = owner.agents.get(parent__isnull=True)
    component = echo_component(owner, lead)

    def execute(binding, key):
        action = invoke(
            lead,
            "component",
            {"operation": "run", "component": str(component.pk), "inputs": {"source": binding}},
            key=key,
        )
        execution = ComponentExecution.objects.get(action=action)
        component_execution.execute(execution.pk)
        execution.refresh_from_db()
        assert execution.state == "completed", execution.error
        return research.accessible_artifact(owner, execution.outputs["copy"]["artifact"])

    first = execute({"cell": str(cell.pk), "fingerprint": cell.fingerprint}, "source-copy")
    copied = execute({"artifact": str(first.pk), "fingerprint": first.sha256}, "artifact-copy")
    before = invoke(lead, "inspect_action", {"action": str(copied.pk), "limit": 32000})
    assert hidden in before.result["text"]
    fetched = invoke(lead, "fetch_artifact", {"artifact": str(copied.pk)})
    read = invoke(
        lead, "workspace", {"operation": "read", "path": fetched.result["path"], "limit": 32000}
    )
    assert hidden in read.result["text"]
    independent = execute(
        {"cell": str(unrelated.source.pk), "fingerprint": unrelated.source.fingerprint},
        "unrelated-copy",
    )
    if historical:
        for artifact in (first, copied, independent):
            artifact.metadata = {**artifact.metadata, "source_cells": []}
            artifact.save(update_fields=["metadata"])
            artifact.action.result = research.artifact_record(artifact)
            artifact.action.save(update_fields=["result"])
    seal_preparation_source(cell.dataset, "seal-component-source")

    for artifact in (first, copied):
        assert research_evidence.artifacts(owner).filter(pk=artifact.pk).exists()
        assert invoke(lead, "fetch_artifact", {"artifact": str(artifact.pk)}).result["bytes"] > 0
        inspected = invoke(lead, "inspect_action", {"action": str(artifact.pk), "limit": 32000})
        assert hidden in json.dumps(inspected.result)
    reopened = invoke(lead, "inspect_action", {"action": str(before.pk), "limit": 32000})
    assert hidden in json.dumps(reopened.result)
    assert hidden in json.dumps(research_agent.tool_content(before))
    history = invoke(lead, "history", {"tool": "component", "query": str(cell.pk)})
    assert history.result["actions"]
    reread = invoke(lead, "workspace", {"operation": "read", "path": fetched.result["path"]})
    assert hidden in reread.result["text"]
    independent_page = invoke(
        lead, "inspect_action", {"action": str(independent.pk), "limit": 32000}
    )
    assert "independent-source" in independent_page.result["text"]
    assert invoke(lead, "fetch_artifact", {"artifact": str(independent.pk)}).result["bytes"] > 0
    assert hidden in research.artifact_bytes(copied, limit=32000).decode()
    before.refresh_from_db()
    assert hidden in before.result["text"]


@pytest.mark.covers("privacy")
def test_component_source_errors_are_projected_in_native_receipts_and_current_evidence():
    hidden = "withheld-component-error-590183"
    owner, cell, _ = inputs(
        [{"input": f"{hidden}-{index}", "expected_output": str(index % 2)} for index in range(20)]
    )
    lead = owner.agents.get(parent__isnull=True)
    component = echo_component(owner, lead, raises=True)
    action = research.claim(
        lead,
        "component-source-exception",
        "component",
        {
            "operation": "run",
            "component": str(component.pk),
            "inputs": {"source": {"cell": str(cell.pk), "fingerprint": cell.fingerprint}},
        },
    )
    research.complete(action, research_tools.invoke(action), state="running", cost=0)
    execution = ComponentExecution.objects.get(action=action)
    component_execution.execute(execution.pk)
    experiment_execution.reconcile(action)
    execution.refresh_from_db()
    action.refresh_from_db()
    assert execution.state == "failed"
    assert hidden in execution.error
    assert hidden in action.result["error"]
    assert hidden in json.dumps(research_agent.evidence(lead))
    before = invoke(lead, "inspect_action", {"action": str(action.pk), "limit": 32000})
    assert hidden in before.result["text"]
    seal_preparation_source(cell.dataset, "seal-component-error-source")

    assert hidden in json.dumps(research_agent.evidence(lead))
    assert hidden in json.dumps(research_agent.tool_content(action))
    assert hidden in json.dumps(research_agent.tool_content(before))
    after = invoke(lead, "inspect_action", {"action": str(action.pk), "limit": 32000})
    assert hidden in json.dumps(after.result)
    history = invoke(lead, "history", {"tool": "component", "query": hidden})
    assert history.result["actions"]
    observed = component_execution.observations(owner)[0]
    assert observed["state"] == "failed"
    assert observed["execution"] == str(execution.pk)
    execution.refresh_from_db()
    action.refresh_from_db()
    assert hidden in execution.error and hidden in action.result["error"]


@pytest.mark.covers("privacy")
@pytest.mark.parametrize("path", ["", "/error"])
@pytest.mark.parametrize("historical", [False, True])
def test_component_context_pages_preserve_project_evidence_after_partitioning(path, historical):
    hidden = "withheld-component-context-813709"
    owner, cell, _ = inputs(
        [{"input": f"{hidden}-{index}", "expected_output": str(index % 2)} for index in range(20)]
    )
    lead = owner.agents.get(parent__isnull=True)
    reader = specialist(lead, "component-context-reader")
    metadata_reader = specialist(lead, "component-state-reader")
    component = echo_component(owner, lead, raises=True)
    action = invoke(
        lead,
        "component",
        {
            "operation": "run",
            "component": str(component.pk),
            "inputs": {"source": {"cell": str(cell.pk), "fingerprint": cell.fingerprint}},
        },
    )
    execution = ComponentExecution.objects.get(action=action)
    component_execution.execute(execution.pk)
    experiment_execution.reconcile(action)
    execution.refresh_from_db()
    assert execution.state == "failed" and hidden in execution.error
    reference = f"component_execution:{execution.pk}"
    arguments = {"operation": "read", "reference": reference, "path": path}
    cached = invoke(reader, "explore_context", arguments)
    assert hidden in cached.result["content"]
    if historical:
        cached.result.pop("execution_read", None)
        cached.save(update_fields=["result"])
    retained = deepcopy(cached.result)
    retain_source_tool_history(reader, cached)
    stored_messages = deepcopy(reader.messages)
    state = invoke(metadata_reader, "explore_context", {**arguments, "path": "/state"})
    if historical:
        state.result.pop("execution_read", None)
        state.save(update_fields=["result"])
    public = Dataset.objects.create(
        project=owner.project, name="Public component inputs", intent="train"
    )
    land.land_rows(public, [{"input": "independent-component-input", "expected_output": "public"}])
    public.refresh_from_db()
    public_owner = research.create(
        owner.project,
        user=owner.created_by,
        request_key="public-component-context",
        objective="Inspect public diagnostics",
        task={"deliverable": "Retained diagnostics"},
        context_roots=[f"cell:{public.source.pk}", f"cell:{cell.pk}"],
        budget={},
    )
    public_lead = public_owner.agents.get(parent__isnull=True)
    public_action = invoke(
        public_lead,
        "component",
        {
            "operation": "run",
            "component": str(component.pk),
            "inputs": {
                "source": {"cell": str(public.source.pk), "fingerprint": public.source.fingerprint}
            },
        },
    )
    public_execution = ComponentExecution.objects.get(action=public_action)
    component_execution.execute(public_execution.pk)
    public_execution.refresh_from_db()
    assert "independent-component-input" in public_execution.error
    public_reference = f"component_execution:{public_execution.pk}"
    context_graph.refresh(owner.project, kinds=["component_execution"])
    packet = context_graph.inspect(
        owner.project,
        roots=[reference, public_reference],
        purpose="training",
        kind="component_execution",
    )
    assert hidden in context_graph.canonical(
        packet
    ) and "independent-component-input" in context_graph.canonical(packet)
    seal_preparation_source(cell.dataset, "seal-component-context-source")

    for result in (
        research_agent.tool_observation(cached),
        research_agent.messages(reader, tools=[]),
        research_evidence.visible(owner, {"context": packet}),
    ):
        assert hidden in context_graph.canonical(result)
    projected = research_evidence.visible(public_owner, {"context": packet})
    assert "independent-component-input" in context_graph.canonical(projected)
    public_page = invoke(
        public_lead,
        "explore_context",
        {"operation": "read", "reference": public_reference, "path": "/error"},
    )
    assert "independent-component-input" in public_page.result["content"]
    fresh = specialist(lead, "fresh-component-context-reader")
    for tool, request in (
        ("explore_context", arguments),
        ("inspect_action", {"action": str(cached.pk), "limit": 32000}),
    ):
        assert hidden in context_graph.canonical(invoke(fresh, tool, request).result)
    assert invoke(fresh, "history", {"tool": "explore_context", "query": hidden}).result["actions"]
    assert json.loads(research_evidence.action_result(owner, state)["content"]) == "failed"
    readable = invoke(metadata_reader, "explore_context", {**arguments, "path": "/state"})
    assert json.loads(readable.result["content"]) == "failed"
    execution.refresh_from_db()
    cached.refresh_from_db()
    reader.refresh_from_db()
    assert hidden in execution.error
    assert cached.result == retained and reader.messages == stored_messages


def failed_component_flow(settings, tmp_path):
    campaign, values = decision_campaign(settings, tmp_path)
    private = Dataset.objects.create(
        project=campaign.project, name="Private flow input", intent="train"
    )
    hidden = "withheld-native-graph-540813"
    land.land_rows(private, [decision_row(hidden, i) for i in range(20)], user=campaign.created_by)
    private.refresh_from_db()
    owner = research.create(
        campaign.project,
        user=campaign.created_by,
        request_key="graph-reader",
        objective="Inspect native execution receipts",
        task={"deliverable": "Retained diagnostics"},
        context_roots=[f"cell:{private.source.pk}", f"cell:{values['train_cell']}"],
        budget={},
    )
    lead = owner.agents.get(parent__isnull=True)
    reader = specialist(lead, "native-graph-reader")
    metadata_reader = specialist(lead, "native-graph-metadata")
    contract = research_catalogue.contracts(lead, Explore(operation="contracts", kind="component"))[
        "authoring"
    ]
    component = assets.publish(
        campaign.project,
        campaign.created_by,
        kind="component",
        name="Read two inputs",
        request_key="two-input-error",
        specification={
            "runtime": contract["runtime"],
            "entrypoint": "fail.py",
            "limits": {"memory_mb": 2048},
            "files": {
                "fail.py": "import json,sys\nwith open(sys.argv[1]) as f: inputs={row['port']:row['value'] for row in map(json.loads,f)}\nraise ValueError(inputs['private'][0]['input']['decision']['state'])\n"
            },
            "inputs": {
                name: {"type": "data", "schema": {"type": "array"}}
                for name in ("private", "public")
            },
            "outputs": {"result": {"schema": {"type": "string"}}},
        },
    )
    experiment = research_experiments.create(
        campaign.project,
        campaign.created_by,
        name="Native graph source isolation",
        objective="Read exact inputs",
        cells=[private.source.pk, values["train_cell"]],
        request_key="native-graph-flow",
    )
    document = deepcopy(experiment.revisions.get().document)
    document["nodes"].append(
        {
            "id": "read_inputs",
            "kind": "component",
            "title": "Read inputs",
            "position": {"x": 500, "y": 0},
            "config": {"asset": str(component.pk), "fingerprint": component.fingerprint},
            "operation": {"tool": "component", "arguments": {"operation": "run"}},
        }
    )
    document["edges"] = [
        {"source": f"data_{index}", "output": "data", "target": "read_inputs", "input": name}
        for index, name in enumerate(("private", "public"))
    ]
    document["outputs"] = {"result": {"node": "read_inputs", "port": "result"}}
    research_experiments.revise(
        experiment, expected_version=1, document=document, request_key="native-graph-definition"
    )
    parent = research_experiments.start(
        experiment, campaign.created_by, revision=2, request_key="native-graph-start", budget={}
    )
    invoke(
        parent.agents.get(parent__isnull=True), "experiment", {"operation": "run", "revision": 2}
    )
    run = experiment_dispatch.owned(parent).get()
    experiment_engine.advance(run.pk)
    execution = ComponentExecution.objects.get(action__agent__assignment=run)
    component_execution.execute(execution.pk)
    experiment_engine.advance(run.pk)
    node = run.execution.nodes.select_related("action").get(node="read_inputs")
    assert node.state == "failed" and hidden in node.error
    return campaign, values, private, owner, reader, metadata_reader, node, hidden


@pytest.mark.covers("privacy")
@pytest.mark.parametrize("historical", [False, True])
def test_saved_flow_graph_errors_remain_visible_after_partitioning(settings, tmp_path, historical):
    campaign, _, private, owner, reader, metadata_reader, node, hidden = failed_component_flow(
        settings, tmp_path
    )
    arguments = {"operation": "read", "reference": f"node_execution:{node.pk}", "path": "/error"}
    cached = invoke(reader, "explore_context", arguments)
    assert hidden in cached.result["content"]
    if historical:
        cached.result.pop("execution_read", None)
        cached.save(update_fields=["result"])
    retained = deepcopy(cached.result)
    retain_source_tool_history(reader, cached)
    stored_messages = deepcopy(reader.messages)
    state = invoke(metadata_reader, "explore_context", {**arguments, "path": "/state"})
    if historical:
        state.result.pop("execution_read", None)
        state.save(update_fields=["result"])
    seal_preparation_source(private, "seal-native-graph-source")
    for observed in (
        research_agent.tool_observation(cached),
        research_agent.messages(reader, tools=[]),
    ):
        assert hidden in context_graph.canonical(observed)
    fresh = specialist(owner.agents.get(parent__isnull=True), "fresh-native-graph-reader")
    for tool, request in (
        ("explore_context", arguments),
        ("inspect_action", {"action": str(cached.pk), "limit": 32000}),
    ):
        assert hidden in context_graph.canonical(invoke(fresh, tool, request).result)
    assert invoke(fresh, "history", {"tool": "explore_context", "query": hidden}).result["actions"]
    assert json.loads(research_evidence.action_result(owner, state)["content"]) in {
        "failed",
        "completed",
    }
    assert json.loads(
        invoke(metadata_reader, "explore_context", {**arguments, "path": "/state"}).result[
            "content"
        ]
    ) in {"failed", "completed"}
    node.refresh_from_db()
    node.action.refresh_from_db()
    cached.refresh_from_db()
    reader.refresh_from_db()
    assert hidden in node.error
    assert cached.result == retained and reader.messages == stored_messages