Skip to content

The platform for continuously improving AI agents.

100.0 KB
Raw Blame
import json
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from contextvars import copy_context
from copy import deepcopy
from datetime import timedelta
from threading import Event
from unittest.mock import patch
from uuid import uuid4

import pytest
from django.db import close_old_connections, connection, transaction
from django.utils import timezone
from factories import make_project, make_user
from fakes.modal import FakeCall
from rest_framework.test import APIClient
from test_research_experiments import case, continuation
from test_research_team import invoke

from overbae.core.errors import InputValidationError
from overbae.models import (
    Cell,
    DataPartitionPlan,
    Dataset,
    DeployedModel,
    ExperimentExecution,
    ExperimentNodeExecution,
    FinetuningJob,
    ProjectMembership,
    ResearchAction,
    ResearchAssignment,
    ResearchExperiment,
)
from overbae.services import (
    context_graph,
    execution_mandates,
    experiment_checkpoints,
    experiment_conversation,
    experiment_dispatch,
    experiment_engine,
    experiment_execution,
    experiment_plans,
    experiment_research,
    experiment_training,
    research,
    research_agent,
    research_experiments,
    research_tools,
)
from overbae.services.datasets import land, partition_plans, rows
from overbae.services.mcp import tools_experiments
from overbae.services.mcp.context import MCPContext, PlatformCredential
from overbae.services.mcp.contracts.experiments import StartExperimentRun
from overbae.services.research_contract import Artifact, Explore

pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("experiments")]


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


def flow():
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name="Cases", intent="train")
    land.land_rows(dataset, [case(i, str(i % 2)) for i in range(40)])
    dataset.refresh_from_db()
    experiment = research_experiments.create(
        project,
        user,
        name="Reusable partition",
        objective="Retain reproducible partitions",
        cells=[dataset.active_cell.pk],
        request_key="source",
    )
    document = deepcopy(experiment.revisions.get(number=1).document)
    document["parameters"] = {"seed": {"type": "integer", "default": 37}}
    document["nodes"].append(
        {
            "id": "partition",
            "kind": "split",
            "title": "Partition",
            "position": {"x": 500, "y": 0},
            "config": {},
            "operation": {
                "tool": "platform",
                "arguments": {
                    "name": "create_data_partition",
                    "arguments": {
                        "name": "Partition",
                        "recipe": {
                            "seed": {"$parameter": "seed"},
                            "fractions": {"train": 0.8, "development": 0.2},
                        },
                    },
                },
            },
        }
    )
    document["edges"] = [
        {"source": "data_0", "target": "partition", "output": "data", "input": "data"}
    ]
    document["outputs"] = {
        "training": {"node": "partition", "port": "train"},
        "development": {"node": "partition", "port": "development"},
    }
    research_experiments.revise(
        experiment, expected_version=1, document=document, request_key="partition"
    )
    return experiment, user


def admit_node(experiment, user, *, revision, node, request_key="admitted-node"):
    run = experiment_engine.start(
        experiment, user, revision=revision, request_key=request_key, budget={}
    )
    scope = run.execution.scopes.get(parent__isnull=True)
    receipt = scope.nodes.get(node=node)
    for _ in range(scope.nodes.count() + 1):
        ready = experiment_engine.inspect_scope(scope)
        assert ready, list(scope.nodes.values("node", "state", "error"))
        experiment_engine.execute({"execution": str(run.pk), "ready": ready})
        receipt.refresh_from_db()
        if receipt.action_id:
            assert receipt.state == "waiting", receipt.error
            assert receipt.action.state == "completed", receipt.action.result
            return run, receipt
    raise AssertionError("The requested native node was not admitted")


def test_saved_flow_replays_and_resumes_without_a_model_call():
    experiment, user = flow()
    run = experiment_engine.start(
        experiment,
        user,
        revision=2,
        request_key="first",
        budget={},
        parameters={"seed": 11},
    )
    experiment_engine.advance(run.pk)
    execution = run.execution
    assert execution.nodes.get(node="partition").state == "waiting"
    with experiment_checkpoints.store() as store:
        checkpoint = experiment_engine.graph(store).get_state(
            {"configurable": {"thread_id": f"flow:{run.pk}"}}
        )
        assert checkpoint.interrupts
    experiment_engine.advance(run.pk)
    assert DataPartitionPlan.objects.count() == 1
    partition_plans.build(DataPartitionPlan.objects.get().pk)
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed"
    assert run.result["outputs"]["training"]["fingerprint"]
    assert not ResearchAction.objects.filter(tool="model").exists()
    repeat = experiment_engine.start(
        experiment,
        user,
        revision=2,
        request_key="first",
        budget={},
        parameters={"seed": 11},
    )
    assert repeat.pk == run.pk
    with pytest.raises(InputValidationError, match="different"):
        experiment_engine.start(
            experiment,
            user,
            revision=2,
            request_key="first",
            budget={},
            parameters={"seed": 12},
        )
    second = experiment_engine.start(
        experiment,
        user,
        revision=2,
        request_key="second",
        budget={},
        parameters={"seed": 12},
    )
    experiment_engine.advance(second.pk)
    assert DataPartitionPlan.objects.count() == 2
    assert (
        execution.document["nodes"][1]["operation"]["arguments"]["arguments"]["recipe"]["seed"]
        == 11
    )
    assert (
        second.execution.document["nodes"][1]["operation"]["arguments"]["arguments"]["recipe"][
            "seed"
        ]
        == 12
    )


@pytest.fixture(autouse=True)
def openrouter(fake_llm):
    # A benchmark compares OpenRouter models that report token probabilities.
    fake_llm.catalog_payload = [
        {
            "id": "openai/gpt-4o",
            "name": "GPT-4o",
            "supported_parameters": ["logprobs", "top_logprobs"],
            "pricing": {"prompt": "0.000001", "completion": "0.000002"},
            "architecture": {"modality": "text->text"},
        }
    ]
    return fake_llm


def measured_flow():
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name="Development", intent="eval")
    land.land_rows(
        dataset,
        [
            {
                "input": {
                    "decision": {
                        "state": "A review",
                        "question": "Sentiment?",
                        "kind": "choice",
                        "options": ["positive", "negative"],
                    }
                },
                "expected_output": {"probabilities": [1, 0]},
            }
        ],
    )
    dataset.refresh_from_db()
    experiment = research_experiments.create(
        project,
        user,
        name="Measured comparison",
        objective="Compare recorded results",
        cells=[dataset.active_cell.pk],
        request_key="measured",
    )
    document = deepcopy(experiment.revisions.get(number=1).document)
    document["nodes"] += [
        {
            "id": "evaluate",
            "kind": "evaluate",
            "title": "Development",
            "position": {"x": 500, "y": 0},
            "operation": {
                "tool": "benchmark",
                "arguments": {
                    "operation": "run",
                    "phase": "development",
                    "baseline": "reference",
                    "participants": [
                        {
                            "key": "reference",
                            "name": "Reference",
                            "kind": "external",
                            "model": "openai/gpt-4o",
                        }
                    ],
                },
            },
        },
        {
            "id": "select",
            "kind": "compare",
            "title": "Select",
            "position": {"x": 900, "y": 0},
            "config": {"metric": "report.accuracy", "direction": "maximize"},
        },
    ]
    document["edges"] = [
        {"source": "data_0", "target": "evaluate", "output": "data", "input": "data"},
        {"source": "evaluate", "target": "select", "output": "scores", "input": "scores"},
    ]
    document["outputs"] = {"selection": {"node": "select", "port": "scores"}}
    research_experiments.revise(
        experiment, expected_version=1, document=document, request_key="compare"
    )
    run = experiment_engine.start(experiment, user, revision=2, request_key="measured", budget={})
    # A settled native receipt is the boundary this replay test consumes.
    run.execution.nodes.filter(node="evaluate").update(
        state="completed",
        outputs={
            "scores": {
                "kind": "scores",
                "phase": "development",
                "protocol": "decision-v1",
                "sample_manifest": "frozen-sample",
                "data": str(dataset.active_cell.pk),
                "report": {"completion": {"status": "complete"}, "accuracy": 0.8},
            }
        },
    )
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed", run.result
    experiment.refresh_from_db()
    return experiment, user, run


def test_reuse_recomputes_changed_comparison_and_retains_exact_measurement_provenance():
    experiment, user, original = measured_flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"][-1]["config"]["minimum"] = 0.7
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="threshold"
    )
    client = APIClient()
    client.force_authenticate(user)
    request = {
        "revision": 3,
        "request_key": "reuse",
        "reuse_run": str(original.pk),
        "budget": {},
    }
    response = client.post(
        f"/api/research-experiments/{experiment.pk}/run/", request, format="json"
    )
    assert response.status_code == 200, response.data
    run = experiment.revisions.get(number=3).runs.get()
    reused = run.execution.nodes.get(node="evaluate")
    assert reused.reused_from_id == original.execution.nodes.get(node="evaluate").pk
    assert reused.action_id is None
    assert run.execution.nodes.get(node="select").state == "pending"
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed"
    assert run.result["outputs"]["selection"]["selected"]["input"]["report"]["accuracy"] == 0.8
    assert not ResearchAction.objects.filter(agent__assignment=run, tool="benchmark").exists()
    repeated = client.post(
        f"/api/research-experiments/{experiment.pk}/run/", request, format="json"
    )
    assert repeated.status_code == 200, repeated.data
    assert experiment.revisions.get(number=3).runs.count() == 1


def test_tied_identical_branches_select_the_same_receipt_after_edge_reordering():
    experiment, user, measured = measured_flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    twin = deepcopy(next(node for node in document["nodes"] if node["id"] == "evaluate"))
    twin["id"] = "repeat"
    document["nodes"].append(twin)
    document["edges"] += [
        {"source": "data_0", "target": "repeat", "output": "data", "input": "data"},
        {"source": "repeat", "target": "select", "output": "scores", "input": "scores"},
    ]
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="repeat"
    )
    original = experiment_engine.start(
        experiment, user, revision=3, request_key="repeat", budget={}
    )
    measured_output = measured.execution.nodes.get(node="evaluate").outputs
    for node in ("evaluate", "repeat"):
        output = deepcopy(measured_output)
        output["scores"]["report"]["measurement"] = node
        original.execution.nodes.filter(node=node).update(state="completed", outputs=output)
    assert (
        original.execution.nodes.get(node="evaluate").identity
        == original.execution.nodes.get(node="repeat").identity
    )
    experiment_engine.advance(original.pk)
    original.refresh_from_db()
    assert original.state == "completed"
    document["edges"].reverse()
    research_experiments.revise(
        experiment, expected_version=3, document=document, request_key="reorder"
    )
    selections = []
    for rerun in ([], ["select"]):
        run = experiment_engine.start(
            experiment,
            user,
            revision=4,
            request_key=f"reorder-{bool(rerun)}",
            budget={},
            reuse_run=original.pk,
            rerun_from=rerun,
        )
        experiment_engine.advance(run.pk)
        run.refresh_from_db()
        assert run.state == "completed", run.result
        selections.append(run.result["outputs"]["selection"]["selected"])
    assert selections[0] == selections[1]


@pytest.mark.parametrize("source_state", ["completed", "cancelled"])
def test_comparison_output_can_feed_another_comparison_without_losing_measurement_identity(
    source_state,
):
    experiment, user, original = measured_flow()
    ResearchAssignment.objects.filter(pk=original.pk).update(state=source_state)
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"].append(
        {
            "id": "accept",
            "kind": "compare",
            "title": "Accept measured candidate",
            "position": {"x": 1200, "y": 0},
            "config": {"metric": "report.accuracy", "direction": "maximize", "minimum": 0.7},
        }
    )
    document["edges"].append(
        {"source": "select", "target": "accept", "output": "scores", "input": "scores"}
    )
    document["outputs"] = {"accepted": {"node": "accept", "port": "scores"}}
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="accept"
    )
    run = experiment_engine.start(
        experiment,
        user,
        revision=3,
        request_key="accept",
        reuse_run=original.pk,
        budget={},
    )
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed", run.result
    chosen = run.result["outputs"]["accepted"]["selected"]
    measured = original.execution.nodes.get(node="evaluate").outputs["scores"]
    assert chosen["value"] == 0.8
    assert chosen["input"]["selected"]["input"] == measured
    assert chosen["input"]["protocol"] == measured["protocol"]
    assert chosen["input"]["data"] == measured["data"]
    assert not ResearchAction.objects.filter(agent__assignment=run, tool="benchmark").exists()


@pytest.mark.parametrize("state", ["cancelled", "exhausted", "blocked"])
def test_a_run_that_did_not_finish_keeps_its_completed_stages_reusable(state):
    experiment, user, original = measured_flow()
    ResearchAssignment.objects.filter(pk=original.pk).update(state=state)
    run = experiment_engine.start(
        experiment, user, revision=2, request_key="reuse", budget={}, reuse_run=original.pk
    )
    reused = run.execution.nodes.get(node="evaluate")
    assert reused.reused_from_id == original.execution.nodes.get(node="evaluate").pk


@pytest.mark.parametrize("unsettled", ["unknown", "running", "pending", "lease"])
def test_cancelled_reuse_waits_for_execution_and_provider_settlement(unsettled):
    experiment, user, original = measured_flow()
    ResearchAssignment.objects.filter(pk=original.pk).update(state="cancelled")
    if unsettled == "lease":
        ExperimentExecution.objects.filter(pk=original.pk).update(
            lease=uuid4(), lease_expires_at=timezone.now() + timedelta(minutes=5)
        )
    else:
        action = research.claim(
            original.agents.get(parent__isnull=True), "unsettled", "benchmark", {}
        )
        ResearchAction.objects.filter(pk=action.pk).update(state=unsettled)
        original.execution.nodes.filter(node="evaluate").update(action=action)
    with pytest.raises(InputValidationError, match="Settle"):
        experiment_engine.start(
            experiment,
            user,
            revision=2,
            request_key="cancelled-reuse",
            budget={},
            reuse_run=original.pk,
        )


@pytest.mark.parametrize("change", ["forced", "incomplete", "final", "unknown"])
def test_reuse_never_skips_changed_or_unsettled_measurements(change):
    experiment, user, original = measured_flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    if change == "model":
        document["nodes"][1]["config"]["model"] = {"model": "Qwen/Qwen3-1.7B"}
    elif change in {"incomplete", "final"}:
        receipt = original.execution.nodes.get(node="evaluate")
        if change == "incomplete":
            receipt.outputs["scores"]["report"]["completion"]["status"] = "partial"
        else:
            receipt.outputs["scores"]["phase"] = "final"
        receipt.save(update_fields=["outputs"])
    elif change == "unknown":
        action = research.claim(
            original.agents.get(parent__isnull=True), "unknown", "benchmark", {}
        )
        action.state = "unknown"
        action.save(update_fields=["state"])
        original.execution.nodes.filter(node="evaluate").update(action=action)
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="change"
    )
    kwargs = dict(
        revision=3,
        request_key="replay",
        reuse_run=original.pk,
        budget={},
        rerun_from=["evaluate"] if change == "forced" else [],
    )
    if change == "unknown":
        with pytest.raises(InputValidationError, match="acknowledgements"):
            experiment_engine.start(experiment, user, **kwargs)
        return
    run = experiment_engine.start(experiment, user, **kwargs)
    assert run.execution.nodes.get(node="evaluate").state == "pending"
    assert run.execution.nodes.get(node="select").state == "pending"


def test_reuse_rejects_cross_project_runs_before_admission():
    experiment, user, _ = measured_flow()
    _, _, foreign = measured_flow()
    with pytest.raises(InputValidationError, match="in this project"):
        experiment_engine.start(
            experiment,
            user,
            revision=2,
            request_key="foreign",
            reuse_run=foreign.pk,
            budget={},
        )
    assert experiment.revisions.get(number=2).runs.count() == 1


def sealed_source_run():
    experiment, user = flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"][1]["operation"]["arguments"]["arguments"]["recipe"]["fractions"] = {
        "train": 0.6,
        "development": 0.2,
        "final": 0.2,
    }
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="sealed"
    )
    original = experiment_engine.start(
        experiment, user, revision=3, request_key="partition", budget={}
    )
    experiment_engine.advance(original.pk)
    plan = DataPartitionPlan.objects.get()
    partition_plans.build(plan.pk)
    experiment_engine.advance(original.pk)
    run = research_experiments.start(
        experiment, user, revision=3, request_key="research", budget={}
    )
    return experiment, user, plan, run


def test_partitioned_sources_stay_readable_except_the_final_holdout():
    experiment, user, plan, run = sealed_source_run()
    assert research_tools.source_cell(run, plan.source_cell_id) == plan.source_cell
    for member in plan.members.select_related("cell"):
        if member.role == "final":
            with pytest.raises(partition_plans.SealedHoldoutError):
                research_tools.source_cell(run, member.cell_id)
        else:
            assert research_tools.source_cell(run, member.cell_id) == member.cell
    context = research_tools.visible_context(
        run, Explore(operation="read", reference=f"cell:{plan.source_cell_id}")
    )
    assert "metadata_only" not in context["content"]
    partition = research_tools.visible_context(run, Explore(operation="partitions"))[
        "input_partitions"
    ][0]
    assert partition["source"]["cell"] == str(plan.source_cell_id)
    assert partition["recipe"] == plan.recipe
    assert {member["role"]: member["access"] for member in partition["members"]} == {
        "train": "readable",
        "development": "readable",
        "final": "metadata_only",
    }
    final = plan.members.get(role="final").cell
    inspection = research_experiments.create(
        experiment.project,
        user,
        name="Final data inspection",
        objective="Inspect source",
        cells=[final.pk],
        request_key="final-input",
    )
    arguments = {"revision": 1, "request_key": "read", "budget": {}}
    admitted = research_experiments.start(inspection, user, **arguments)
    assert research_experiments.start(inspection, user, **arguments).pk == admitted.pk
    with pytest.raises(partition_plans.SealedHoldoutError):
        research_tools.source_cell(admitted, final.pk)
    assert not admitted.events.filter(kind="input_reserved").exists()


def test_a_reserved_root_stays_admitted_when_the_agent_binds_it_by_cell_alone():
    experiment, _, _, run = sealed_source_run()
    document = experiment.revisions.get(number=3).document
    root = next(node for node in document["nodes"] if node["kind"] == "data")
    # A stage names its data by cell alone; the reserved root is not admitted a second time.
    action = research.claim(
        run.agents.get(parent__isnull=True),
        "by-cell",
        "experiment",
        {
            "operation": "stage",
            "id": root["id"],
            "settings": {"cell": root["config"]["cell"]},
            "notes": "Reserved source",
        },
    )
    saved = research_tools.invoke(action)
    assert saved["revision"] == 4
    assert experiment.revisions.get(number=4).document["nodes"][0]["config"] == root["config"]


def test_incomplete_flow_reports_all_unconfigured_nodes_before_starting_work():
    experiment, user = flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    del document["nodes"][1]["operation"]
    document["nodes"].append(
        {
            "id": "predict",
            "kind": "predict",
            "title": "Candidate predictions",
            "position": {"x": 500, "y": 300},
            "config": {"model": {}},
        }
    )
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="incomplete"
    )
    with pytest.raises(InputValidationError) as error:
        experiment_engine.start(experiment, user, revision=3, request_key="no-work", budget={})
    assert "partition" in str(error.value).lower()
    assert "model" in str(error.value).lower()
    assert not ResearchAssignment.objects.exists()
    assert not DataPartitionPlan.objects.exists()


@pytest.mark.parametrize("fault", ["recipe", "schema_only"])
def test_native_operation_contract_rejects_invalid_work_before_run_admission(fault):
    experiment, user = flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    arguments = document["nodes"][1]["operation"]["arguments"]
    if fault == "recipe":
        arguments["arguments"]["recipe"]["seed"] = -1
    else:
        arguments["describe"] = True
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key=fault
    )
    with pytest.raises(InputValidationError, match="seed|describe"):
        experiment_engine.start(experiment, user, revision=3, request_key=fault, budget={})
    assert not ResearchAssignment.objects.exists()
    assert not DataPartitionPlan.objects.exists()


def test_live_edits_leave_the_running_definition_and_receipts_unchanged():
    experiment, user = flow()
    run = experiment_engine.start(experiment, user, revision=2, request_key="pinned", budget={})
    original = deepcopy(run.execution.document)
    changed = deepcopy(experiment.revisions.get(number=2).document)
    changed["nodes"][1]["operation"]["arguments"]["arguments"]["recipe"]["fractions"] = {
        "train": 0.6,
        "development": 0.4,
    }
    revision = research_experiments.revise(
        experiment, expected_version=2, document=changed, request_key="edit-during-run"
    )
    experiment_engine.advance(run.pk)
    assert DataPartitionPlan.objects.get().recipe["fractions"] == {"train": 0.8, "development": 0.2}
    run.execution.refresh_from_db()
    assert run.execution.document == original
    assert revision.number == 3


@pytest.mark.parametrize("failure_when", ["admission", "execution"])
def test_failed_native_operation_keeps_failure_and_never_claims_success(failure_when):
    experiment, user = flow()
    run = experiment_engine.start(
        experiment,
        user,
        revision=2,
        request_key="bad",
        budget={},
    )
    if failure_when == "execution":
        experiment_engine.advance(run.pk)
    rows.frame_path(Dataset.objects.get().active_cell).write_bytes(b"corrupted retained input")
    if failure_when == "execution":
        partition_plans.build(DataPartitionPlan.objects.get().pk)
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "unmet"
    assert run.result["failed_nodes"] == ["partition"]
    failed = run.execution.nodes.get(node="partition")
    assert failed.error and failed.error != "The native operation failed"
    observed = next(
        node
        for node in research_experiments.run_record(run)["nodes"]
        if node["node"] == "partition"
    )
    assert observed["result"]["error"] == failed.error
    if failure_when == "admission":
        assert failed.action.state == "failed"
        assert not DataPartitionPlan.objects.exists()
    else:
        assert DataPartitionPlan.objects.get().state == "failed"


def staged_scope(run, stages, edges=()):
    """A started run's flow replaced by stages in given states: name -> (kind, state).
    Each edge is (source, port, target)."""
    scope = run.execution.scopes.get()
    scope.document = {
        **scope.document,
        "nodes": [
            {"id": name, "kind": kind, "title": name, "position": {"x": 0, "y": 0}, "config": {}}
            for name, (kind, _) in stages.items()
        ],
        "edges": [
            {"source": source, "output": port, "target": target, "input": port}
            for source, port, target in edges
        ],
        "outputs": {},
    }
    scope.save(update_fields=["document"])
    scope.nodes.all().delete()
    for name, (_, state) in stages.items():
        ExperimentNodeExecution.objects.create(
            execution=run.execution,
            scope=scope,
            node=name,
            identity=name,
            state=state,
            outputs={port: {"kind": port} for source, port, _ in edges if source == name},
        )
    return scope


def ready(scope):
    waiting = {str(node.pk): node.node for node in scope.nodes.all()}
    return [waiting[identifier] for identifier in experiment_engine.inspect_scope(scope)]


def test_a_stop_stage_waits_for_the_stages_that_use_its_deployment():
    experiment, user = flow()
    run = experiment_engine.start(experiment, user, revision=2, request_key="serve", budget={})
    scope = staged_scope(
        run,
        {
            "publish": ("publish", "completed"),
            "predict": ("inference", "waiting"),
            "stop": ("stop_deployment", "pending"),
        },
        [("publish", "deployment", "predict"), ("publish", "deployment", "stop")],
    )
    # Closing the deployment first would cancel the request the inference stage has out.
    assert ready(scope) == []
    scope.nodes.filter(node="predict").update(state="failed")
    assert ready(scope) == ["stop"]


def test_a_qualify_stage_waits_for_every_train_stage_of_its_flow():
    experiment, user = flow()
    run = experiment_engine.start(experiment, user, revision=2, request_key="arms", budget={})
    scope = staged_scope(
        run,
        {
            "full": ("train", "completed"),
            "half": ("train", "waiting"),
            "qualify_full": ("qualify", "pending"),
        },
        [("full", "model", "qualify_full")],
    )
    # Qualification is refused while any of the investigation's training still runs.
    assert ready(scope) == []
    scope.nodes.filter(node="half").update(state="completed")
    assert ready(scope) == ["qualify_full"]


def test_a_publish_stage_waits_for_its_checkpoints_earlier_deployment_to_stop(fake_modal):
    experiment, user = flow()
    run = experiment_engine.start(experiment, user, revision=2, request_key="serve", budget={})
    job = FinetuningJob.objects.create(
        project=run.project,
        dataset=Dataset.objects.get(project=run.project),
        base_model="Qwen/Qwen3-8B",
        provider="modal",
        status="deploying",
        remote_job_id="run:call",
    )
    model = DeployedModel.objects.create(
        project=run.project,
        finetuning_job=job,
        model_id="flow-publication",
        status="failed",
        deployment_stage="warm",
        deployment_call_id="fc-warm",
        deployment_cancel_pending=True,
        serving_runtime={
            "lease": {
                "assignment": str(run.pk),
                "allocation": str(uuid4()),
                "deadline": (timezone.now() - timedelta(minutes=1)).isoformat(),
            }
        },
    )
    gpu = FakeCall(fake_modal, "gpu", lambda: None, (), {}, True)
    fake_modal.adopt("fc-warm", "pre_warm").children.append(gpu)
    scope = staged_scope(
        run,
        {"train": ("train", "completed"), "publish": ("publish", "pending")},
        [("train", "model", "publish")],
    )
    scope.nodes.filter(node="train").update(
        outputs={"model": {"kind": "model", "job": str(job.pk)}}
    )
    # The provider has not confirmed that the earlier attempt's GPU work has stopped.
    assert ready(scope) == []
    gpu.state = "cancelled"
    DeployedModel.objects.filter(pk=model.pk).update(deployment_next_poll_at=timezone.now())
    assert ready(scope) == ["publish"]


def test_a_publish_stage_fails_with_its_deployment_error():
    experiment, user = flow()
    run = experiment_engine.start(experiment, user, revision=2, request_key="serve", budget={})
    allocation = str(uuid4())
    model = DeployedModel.objects.create(
        project=run.project,
        model_id="flow-publication",
        status="failed",
        error_message="The checkpoint archive is unreadable",
        serving_runtime={
            "lease": {
                "assignment": str(run.pk),
                "allocation": allocation,
                "deadline": (timezone.now() + timedelta(hours=1)).isoformat(),
            }
        },
    )
    action = research.claim(
        run.agents.get(parent__isnull=True),
        "publish",
        "serving",
        {"operation": "deploy", "deployment": str(model.pk)},
    )
    # Serving describes its deployments as a list.
    research.complete(
        action,
        [
            {
                "deployment": str(model.pk),
                "generation": str(model.deployment_generation),
                "lease": {"allocation": allocation},
            }
        ],
        cost=0,
    )
    scope = staged_scope(run, {"publish": ("publish", "waiting")})
    scope.nodes.filter(node="publish").update(action=action)
    experiment_engine.inspect_scope(scope)
    publish = scope.nodes.get(node="publish")
    assert (publish.state, publish.error) == ("failed", "The checkpoint archive is unreadable")


@pytest.mark.parametrize("score", [0.2, 0.9])
def test_join_waits_for_all_branches_and_collects_only_the_selected_path(score):
    experiment, user = flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"] = [document["nodes"][0]] + [
        {
            "id": "measure",
            "kind": "evaluate",
            "title": "Measure",
            "position": {"x": 300, "y": 0},
            "config": {"outputs": {"scores": {"path": "scores.json", "kind": "evaluation"}}},
            "operation": {
                "tool": "workspace",
                "arguments": {"operation": "python", "code": "pass"},
            },
        },
        {
            "id": "route",
            "kind": "condition",
            "title": "Route",
            "position": {"x": 600, "y": 0},
            "config": {"predicate": {"path": "report.accuracy", "operator": "gte", "value": 0.8}},
        },
        *[
            {
                "id": name,
                "kind": "join",
                "title": name,
                "position": {"x": 900, "y": y},
                "config": {},
            }
            for name, y in [("good", 0), ("poor", 300), ("merged", 600)]
        ],
    ]
    document["edges"] = [
        {"source": "data_0", "target": "measure", "input": "data", "output": "data"},
        {"source": "measure", "target": "route", "input": "scores", "output": "scores"},
        {"source": "route", "target": "good", "input": "scores", "output": "passed"},
        {"source": "route", "target": "poor", "input": "scores", "output": "otherwise"},
        *[
            {"source": name, "target": "merged", "input": "scores", "output": "scores"}
            for name in ["good", "poor"]
        ],
    ]
    document["outputs"] = {"result": {"node": "merged", "port": "scores"}}
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="branching"
    )
    run = experiment_engine.start(experiment, user, revision=3, request_key="join", budget={})
    # Resume from a retained measurement, with no repeated provider execution.
    run.execution.nodes.filter(node="measure").update(
        state="completed", outputs={"scores": {"kind": "scores", "report": {"accuracy": score}}}
    )
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed"
    assert run.execution.nodes.get(node="good" if score >= 0.8 else "poor").state == "completed"
    assert run.execution.nodes.get(node="poor" if score >= 0.8 else "good").state == "skipped"
    assert (
        run.result["outputs"]["result"]["reports"][0]["reports"][0]["report"]["accuracy"] == score
    )
    assert not ResearchAction.objects.filter(tool="model").exists()


def test_parameters_and_missing_implementations_reject_before_admission():
    experiment, user = flow()
    with pytest.raises(InputValidationError, match="type"):
        experiment_engine.start(
            experiment,
            user,
            revision=2,
            request_key="bad-type",
            budget={},
            parameters={"seed": "11"},
        )
    assert not experiment.revisions.get(number=2).runs.exists()


def parent_flow(child, user, kind="subflow", extra=None):
    cell = child.revisions.get(number=2).document["nodes"][0]["config"]["cell"]
    parent = research_experiments.create(
        child.project,
        user,
        name="Reusable parent",
        objective="Execute the retained child revision",
        cells=[cell],
        request_key=f"parent-{kind}",
    )
    document = deepcopy(parent.revisions.get(number=1).document)
    document["nodes"].append(
        {
            "id": "reuse",
            "kind": kind,
            "title": "Partition recipe",
            "position": {"x": 500, "y": 0},
            "config": {
                "experiment": str(child.pk),
                "revision": 2,
                "parameters": {"seed": 123},
                "outputs": {"data": "training"},
                **(extra or {}),
            },
        }
    )
    port = next(iter(document["nodes"][-1]["config"]["outputs"]))
    document["outputs"] = {"training": {"node": "reuse", "port": port}}
    research_experiments.revise(
        parent, expected_version=1, document=document, request_key="child-reference"
    )
    return parent


@pytest.mark.parametrize("fault", ["connected_input", "mapped_input", "mapped_connected_input"])
def test_nested_static_errors_reject_before_any_flow_is_admitted(fault):
    child, user = flow()
    document = deepcopy(child.revisions.get(number=2).document)
    if fault in {"connected_input", "mapped_connected_input"}:
        document["nodes"][1]["operation"]["arguments"]["arguments"]["source_cell"] = (
            "00000000-0000-0000-0000-000000000001"
        )
    else:
        document["nodes"][1]["operation"]["arguments"]["arguments"]["recipe"]["seed"] = -1
    if fault != "connected_input":
        document["parameters"]["upstream"] = {"type": "object"}
    research_experiments.revise(child, expected_version=2, document=document, request_key=fault)
    parent = parent_flow(child, user, extra={"revision": 3})
    if fault != "connected_input":
        document = deepcopy(parent.revisions.get(number=2).document)
        document["nodes"][-1]["config"]["inputs"] = {"upstream": "data"}
        document["edges"] = [
            {"source": "data_0", "target": "reuse", "output": "data", "input": "data"}
        ]
        research_experiments.revise(
            parent, expected_version=2, document=document, request_key="mapped"
        )
    parent.refresh_from_db()
    with pytest.raises(InputValidationError, match="source_cell|seed"):
        experiment_engine.start(parent, user, revision=parent.version, request_key=fault, budget={})
    assert not ResearchAssignment.objects.exists()
    assert not DataPartitionPlan.objects.exists()


@pytest.mark.parametrize("persisted_state", ["running", "unknown"])
def test_partition_admission_recovers_after_crash_before_domain_record_exists(persisted_state):
    experiment, user = flow()
    run = experiment_engine.start(
        experiment, user, revision=2, request_key="interrupted", budget={}
    )
    receipt = run.execution.nodes.get(node="partition")
    principal = run.agents.get(parent__isnull=True)
    source = experiment_execution.cell_output(
        Cell.objects.get(pk=run.execution.document["nodes"][0]["config"]["cell"])
    )
    node = run.execution.document["nodes"][1]
    action = research.claim(
        principal,
        f"flow:{receipt.pk}",
        "platform",
        {
            **node["operation"]["arguments"],
            "arguments": {
                **node["operation"]["arguments"]["arguments"],
                "source_cell": source["cell"],
            },
        },
    )
    action.state = persisted_state
    action.experiment_revision = run.execution.revision
    action.experiment_node = "partition"
    action.experiment_inputs = {"data": source}
    action.started_at = timezone.now()
    action.save()
    assert not DataPartitionPlan.objects.exists()
    experiment_engine.advance(run.pk)
    experiment_engine.advance(run.pk)
    plan = DataPartitionPlan.objects.get()
    partition_plans.build(plan.pk)
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed"
    assert DataPartitionPlan.objects.count() == 1
    assert principal.actions.filter(tool="platform").count() == 1


def test_subflow_pins_revision_and_shares_execution_authority():
    child, user = flow()
    parent = parent_flow(child, user)
    run = experiment_engine.start(parent, user, revision=2, request_key="nested", budget={})
    changed = deepcopy(child.revisions.get(number=2).document)
    changed["nodes"][1]["operation"]["arguments"]["arguments"]["recipe"]["fractions"] = {
        "train": 0.6,
        "development": 0.4,
    }
    research_experiments.revise(
        child, expected_version=2, document=changed, request_key="later-recipe"
    )
    experiment_engine.advance(run.pk)
    plan = DataPartitionPlan.objects.get()
    assert plan.recipe["fractions"] == {"train": 0.8, "development": 0.2}
    assert plan.recipe["seed"] == 123
    partition_plans.build(plan.pk)
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed"
    assert run.result["outputs"]["training"]["cell"] == str(plan.members.get(role="train").cell_id)
    assert run.execution.scopes.count() == 2
    assert not ResearchAction.objects.exclude(agent__assignment=run).exists()
    assert not ResearchAction.objects.filter(tool="model").exists()


@pytest.mark.parametrize("concurrency", [1, 2])
def test_map_validates_every_known_binding_before_admitting_the_run(concurrency):
    child, user = flow()
    document = deepcopy(child.revisions.get(number=2).document)
    document["nodes"].append(
        {
            "id": "measure",
            "kind": "evaluate",
            "title": "Measure partition",
            "position": {"x": 1000, "y": 0},
            "config": {"outputs": {"scores": {"path": "scores.json", "kind": "evaluation"}}},
            "operation": {
                "tool": "workspace",
                "arguments": {"operation": "python", "code": "pass"},
            },
        }
    )
    document["outputs"] = {"measurements": {"node": "measure", "port": "scores"}}
    research_experiments.revise(child, expected_version=2, document=document, request_key="measure")
    parent = parent_flow(
        child,
        user,
        "map",
        {
            "revision": 3,
            "outputs": {"scores": "measurements"},
            "bindings": [{"seed": 1}, {"seed": "invalid"}],
            "concurrency": concurrency,
        },
    )
    document = deepcopy(parent.revisions.get(number=2).document)
    document["outputs"] = {"measurements": {"node": "reuse", "port": "scores"}}
    research_experiments.revise(
        parent, expected_version=2, document=document, request_key="map-output"
    )
    with pytest.raises(InputValidationError, match="declared type"):
        experiment_engine.start(parent, user, revision=3, request_key="invalid-batch", budget={})
    assert not parent.revisions.get(number=3).runs.exists()
    assert not DataPartitionPlan.objects.exists()
    assert not ResearchAction.objects.filter(tool="workspace").exists()


def test_bounded_iteration_keeps_each_attempt_and_does_not_relax_stop_criterion():
    child, user = flow()
    parent = parent_flow(
        child,
        user,
        "iterate",
        {
            "max_iterations": 2,
            "until": {"path": "training.kind", "operator": "eq", "value": "model"},
        },
    )
    run = experiment_engine.start(parent, user, revision=2, request_key="bounded", budget={})
    experiment_engine.advance(run.pk)
    first = DataPartitionPlan.objects.get()
    partition_plans.build(first.pk)
    experiment_engine.advance(run.pk)
    second = DataPartitionPlan.objects.exclude(pk=first.pk).get()
    partition_plans.build(second.pk)
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "unmet"
    assert (
        run.execution.nodes.get(scope__parent__isnull=True, node="reuse").error
        == "Iteration limit reached without meeting the declared stop criterion"
    )
    assert run.execution.scopes.filter(parent__isnull=False, state="completed").count() == 2
    assert DataPartitionPlan.objects.count() == 2
    experiment_engine.advance(run.pk)
    assert DataPartitionPlan.objects.count() == 2


def test_definition_creation_does_not_start_an_agent_and_replays_exact_revision():
    experiment, user = flow()
    document = experiment.revisions.get(number=2).document
    client = APIClient()
    client.force_authenticate(user)
    body = {
        "project": str(experiment.project_id),
        "name": "Saved definition",
        "objective": "Retain reusable partitions",
        "cells": [document["nodes"][0]["config"]["cell"]],
        "document": document,
        "request_key": "definition",
    }
    first = client.post("/api/research-experiments/", body, format="json")
    assert first.status_code == 201, first.data
    assert first.data["version"] == 2
    assert first.data["record"]["document"]["outputs"] == document["outputs"]
    assert first.data["record"]["runs"] == []
    repeated = client.post("/api/research-experiments/", body, format="json")
    assert repeated.status_code == 201, repeated.data
    assert repeated.data["id"] == first.data["id"]
    body["document"]["nodes"][1]["title"] = "Changed definition"
    assert client.post("/api/research-experiments/", body, format="json").status_code == 400


def test_incompatible_evaluation_data_is_rejected_before_execution_admission():
    experiment, user = flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"] = document["nodes"][:1] + [
        {
            "id": "evaluate",
            "kind": "evaluate",
            "title": "Benchmark",
            "position": {"x": 500, "y": 0},
            "operation": {"tool": "benchmark", "arguments": {"operation": "run"}},
        }
    ]
    document["edges"] = [
        {"source": "data_0", "target": "evaluate", "input": "data", "output": "data"}
    ]
    document["outputs"] = {"scores": {"node": "evaluate", "port": "scores"}}
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="invalid-eval"
    )
    with pytest.raises(InputValidationError, match="native decision"):
        experiment_engine.start(experiment, user, revision=3, request_key="invalid-eval", budget={})
    assert not experiment.revisions.get(number=3).runs.exists()
    assert not ResearchAction.objects.exists()


def test_stopping_a_flow_settles_its_nodes_and_native_partition():
    experiment, user = flow()
    run = experiment_engine.start(experiment, user, revision=2, request_key="stop", budget={})
    experiment_engine.advance(run.pk)
    research.stop(run)
    run.refresh_from_db()
    research_agent.reconcile(run)
    run.refresh_from_db()
    assert run.state == "cancelled"
    assert run.execution.nodes.get(node="partition").state == "cancelled"
    assert run.execution.nodes.get(node="data_0").state == "completed"
    assert DataPartitionPlan.objects.get().state == "cancelled"
    experiment_engine.advance(run.pk)
    assert DataPartitionPlan.objects.count() == 1


def test_stop_accepted_before_flow_finish_cannot_be_overwritten():
    experiment, user = flow()
    run = experiment_engine.start(
        experiment, user, revision=2, request_key="stop-finish", budget={}
    )
    experiment_engine.advance(run.pk)
    research.stop(run)
    experiment_engine.finish({"execution": str(run.execution.pk)})
    run.refresh_from_db()
    assert run.state == "stopping"
    research_agent.reconcile(run)
    run.refresh_from_db()
    assert run.state == "cancelled"


def test_retry_keeps_completed_inputs_and_failed_attempts_without_duplicate_dispatch():
    experiment, user = flow()
    run = experiment_engine.start(experiment, user, revision=2, request_key="retry", budget={})
    experiment_engine.advance(run.pk)
    first = DataPartitionPlan.objects.get()
    partition_plans.cancel(first)
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "unmet"
    source_receipt = run.execution.nodes.get(node="data_0")
    research_agent.reconcile(run)
    experiment_engine.retry(run, request_key="retry-partition")
    experiment_engine.retry(run, request_key="retry-partition")
    experiment_engine.advance(run.pk)
    second = DataPartitionPlan.objects.exclude(pk=first.pk).get()
    partition_plans.build(second.pk)
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed"
    assert run.execution.nodes.get(node="data_0").pk == source_receipt.pk
    assert list(
        run.execution.nodes.filter(node="partition")
        .order_by("attempt")
        .values_list("state", flat=True)
    ) == ["cancelled", "completed"]
    history = research_experiments.run_record(run)["nodes"]
    assert len([node for node in history if node["node"] == "partition" and node["current"]]) == 1
    assert DataPartitionPlan.objects.count() == 2
    assert not ResearchAction.objects.filter(tool="model").exists()


@pytest.mark.parametrize("unknown_charge", [0, 0.5])
def test_controller_flow_retry_retains_a_new_immutable_terminal_receipt(unknown_charge):
    experiment, user = flow()
    parent, action = agent_flow(experiment, user)
    research.complete(action, research_tools.invoke(action), cost=0)
    child = experiment_dispatch.owned(parent).get()
    if unknown_charge:
        lease = research.claim(
            child.agents.get(parent__isnull=True),
            "incurred-workspace",
            "workspace_lease",
            {},
            unknown_charge,
        )
        research.complete(lease, {"lease": "ended-without-invoice"})
    experiment_engine.advance(child.pk)
    failed = DataPartitionPlan.objects.get()
    partition_plans.cancel(failed)
    experiment_engine.advance(child.pk)
    experiment_dispatch.reconcile(parent)
    allocation = parent.agents.get(parent__isnull=True).actions.get(tool="flow_allocation")
    assert float(allocation.reservation_usd) == unknown_charge
    assert float(research.allowance(parent)["committed_usd"]) == unknown_charge
    previous = parent.artifacts.get(metadata__flow_run=str(child.pk))
    previous_bytes = research.artifact_bytes(previous, limit=100000)
    assert json.loads(previous_bytes)["state"] == "unmet"
    child.refresh_from_db()
    stale_observation = deepcopy(child)
    experiment_engine.retry(child, request_key="recovery")
    experiment_engine.retry(child, request_key="recovery")
    assert not experiment_dispatch.reconcile_run(parent, stale_observation)
    allocation = parent.agents.get(parent__isnull=True).actions.get(tool="flow_allocation")
    assert allocation.state == "running"
    assert allocation.cost_usd is None
    assert float(allocation.reservation_usd) == unknown_charge
    experiment_engine.advance(child.pk)
    partition_plans.build(DataPartitionPlan.objects.exclude(pk=failed.pk).get().pk)
    experiment_engine.advance(child.pk)
    experiment_dispatch.reconcile(parent)
    experiment_dispatch.reconcile(parent)
    allocation.refresh_from_db()
    current = parent.artifacts.get(pk=allocation.result["artifact"])
    assert current.pk != previous.pk
    assert json.loads(research.artifact_bytes(current, limit=100000))["state"] == "completed"
    assert research.artifact_bytes(previous, limit=100000) == previous_bytes
    assert parent.artifacts.filter(metadata__flow_run=str(child.pk)).count() == 2
    assert float(allocation.reservation_usd) == unknown_charge
    assert research_experiments.require_outputs(parent).pk == child.pk
    if unknown_charge:
        research.complete(lease, {"lease": "settled"}, cost=0.2)
        experiment_dispatch.reconcile(parent)
        allocation.refresh_from_db()
        assert float(allocation.reservation_usd) == 0.2
        assert float(research.allowance(parent)["committed_usd"]) == 0.2
        assert parent.artifacts.filter(metadata__flow_run=str(child.pk)).count() == 2


def test_stale_settlement_waits_for_retry_commit_without_releasing_its_reservation():
    experiment, user = flow()
    parent, action = agent_flow(experiment, user)
    research.complete(action, research_tools.invoke(action), cost=0)
    child = experiment_dispatch.owned(parent).get()
    source = Dataset.objects.get().active_cell
    path = rows.frame_path(source)
    original = path.read_bytes()
    path.write_bytes(b"unreadable source")
    experiment_engine.advance(child.pk)
    experiment_dispatch.reconcile(parent)
    allocation = parent.agents.get(parent__isnull=True).actions.get(tool="flow_allocation")
    assert allocation.cost_usd == 0
    child.refresh_from_db()
    assert child.state == "unmet"
    stale = deepcopy(child)
    path.write_bytes(original)
    started = Event()

    def settle_stale():
        close_old_connections()
        try:
            started.set()
            return experiment_dispatch.reconcile_run(parent, stale)
        finally:
            close_old_connections()

    with ThreadPoolExecutor(max_workers=1) as pool:
        with transaction.atomic():
            ExperimentExecution.objects.select_for_update().get(pk=child.pk)
            experiment_engine.retry(child, request_key="concurrent-retry")
            future = pool.submit(settle_stale)
            assert started.wait(2)
            with pytest.raises(TimeoutError):
                future.result(timeout=0.1)
        assert future.result(timeout=5) is False
    allocation.refresh_from_db()
    assert allocation.state == "running"
    assert allocation.cost_usd is None
    assert allocation.reservation_usd == 0
    experiment_engine.advance(child.pk)
    partition_plans.build(DataPartitionPlan.objects.get().pk)
    experiment_engine.advance(child.pk)
    experiment_dispatch.reconcile(parent)
    allocation.refresh_from_db()
    receipt = parent.artifacts.get(pk=allocation.result["artifact"])
    assert json.loads(research.artifact_bytes(receipt, limit=100000))["state"] == "completed"


@pytest.mark.parametrize("path", ["/absolute.json", "result.json"])
def test_mapped_config_does_not_hide_known_python_output_constraints(path):
    child, user = flow()
    document = deepcopy(child.revisions.get(number=2).document)
    document["parameters"]["upstream"] = {"type": "object"}
    node = document["nodes"][1]
    node["kind"] = "transform"
    node["config"] = {
        "context": {"$parameter": "upstream"},
        "outputs": {"data": {"path": path, "kind": "data"}},
    }
    node["operation"] = {"tool": "workspace", "arguments": {"operation": "python", "code": "pass"}}
    document["outputs"] = {"training": {"node": "partition", "port": "data"}}
    research_experiments.revise(
        child, expected_version=2, document=document, request_key="deferred"
    )
    parent = parent_flow(child, user, extra={"revision": 3, "inputs": {"upstream": "data"}})
    document = deepcopy(parent.revisions.get(number=2).document)
    document["edges"] = [{"source": "data_0", "target": "reuse", "input": "data", "output": "data"}]
    research_experiments.revise(
        parent, expected_version=2, document=document, request_key="connect"
    )
    if path.startswith("/"):
        with pytest.raises(InputValidationError, match="Output files must be relative"):
            experiment_engine.start(parent, user, revision=3, request_key="deferred", budget={})
        assert not ResearchAssignment.objects.exists()
    else:
        run = experiment_engine.start(parent, user, revision=3, request_key="deferred", budget={})
        assert run.state == "running"


def investigating(experiment, user):
    """A started flow whose one stage is an adaptive investigation: the run, the stage's
    receipt and the investigation it started."""
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"] = [
        document["nodes"][0],
        {
            "id": "investigation",
            "kind": "research",
            "title": "Investigate data",
            "position": {"x": 500, "y": 0},
            "config": {
                "objective": "Inspect the source and retain a verified data artifact",
                "outputs": ["data"],
            },
        },
    ]
    document["edges"] = [
        {"source": "data_0", "output": "data", "target": "investigation", "input": "data"}
    ]
    document["outputs"] = {"data": {"node": "investigation", "port": "data"}}
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="research"
    )
    run = experiment_engine.start(experiment, user, revision=3, request_key="research", budget={})
    experiment_engine.advance(run.pk)
    receipt = run.execution.nodes.get(node="investigation")
    return run, receipt, experiment_research.assignment_for(receipt)


def test_an_investigations_evaluator_stays_out_of_the_experiments_chat():
    experiment, user = flow()
    _, _, child = investigating(experiment, user)
    for agent, text in (
        (child.agents.get(parent__isnull=True), "Auditing the source"),
        (child.agents.get(role="evaluation"), "I will ask the lead for a handoff"),
    ):
        research.complete(research.claim(agent, "said", "model", {}), {"text": text}, cost=0)
    transcript = str(experiment_conversation.conversation(experiment))
    assert "Auditing the source" in transcript and "I will ask the lead" not in transcript


def test_research_is_explicit_bounded_and_does_not_repeat_on_flow_wakes():
    experiment, user = flow()
    run, receipt, child = investigating(experiment, user)
    assert "max_cost_usd" not in child.specification["budget"]
    assert child.specification["task"]["inputs"]["data"]["fingerprint"]
    # Adaptive research keeps its independent evaluator.
    assert child.agents.filter(role="evaluation").exists()
    experiment_engine.advance(run.pk)
    assert experiment_research.assignment_for(receipt).pk == child.pk
    assert run.agents.get(parent__isnull=True).actions.count() == 1
    child.state = "blocked"
    child.result = {
        "reason": "model_provider_unavailable",
        "retry_at": (timezone.now() + timedelta(minutes=1)).isoformat(),
    }
    child.save(update_fields=["state", "result"])
    experiment_engine.advance(run.pk)
    receipt.refresh_from_db()
    run.refresh_from_db()
    assert receipt.state == "waiting"
    assert run.state == "running"
    research.stop(run)
    run.refresh_from_db()
    research_agent.reconcile(run)
    child.refresh_from_db()
    assert child.state == "stopping"
    research_agent.reconcile(child)
    research_agent.reconcile(run)
    run.refresh_from_db()
    assert run.state == "cancelled"
    assert not ResearchAction.objects.filter(tool="model").exists()


def agent_flow(experiment, user, *, seed=12):
    parent = research_experiments.start(
        experiment, user, revision=2, request_key="agent", budget={}
    )
    action = research.claim(
        parent.agents.get(parent__isnull=True),
        "run-saved-flow",
        "experiment",
        {
            "operation": "run",
            "revision": 2,
            "parameters": {"seed": seed},
        },
    )
    return parent, action


def test_agent_dispatch_resumes_the_same_flow_and_its_lead_completes_on_the_records(fake_llm):
    experiment, user = flow()
    parent, action = agent_flow(experiment, user)
    with patch("overbae.tasks.research.advance_flow.delay") as dispatch:
        result = research_tools.invoke(action)
        repeat = research_tools.invoke(action)
    assert result["run"] == repeat["run"]
    assert dispatch.call_count == 1
    child = experiment_dispatch.owned(parent).get()
    assert child.execution.parameters == {"seed": 12}
    assert research_tools.pending_work(parent)
    action.state = "unknown"
    action.save(update_fields=["state"])
    experiment_dispatch.reconcile(parent)
    action.refresh_from_db()
    assert action.state == "completed"
    assert action.result["run"] == str(child.pk)
    lead = parent.agents.get(parent__isnull=True)
    early = invoke(lead, "finish", {"outcome": "completed", "summary": "Partitions retained"})
    # Work the flow still has out is not a result yet.
    assert early.result["accepted"] is False
    experiment_engine.advance(child.pk)
    partition_plans.build(DataPartitionPlan.objects.get().pk)
    experiment_engine.advance(child.pk)
    assert not research_tools.pending_work(parent)
    research_experiments.require_outputs(parent)
    # The lead works alone, and nothing has asked a model anything yet.
    assert parent.agents.count() == 1
    assert not ResearchAction.objects.filter(tool="model").exists()

    completed = invoke(
        lead, "finish", {"outcome": "completed", "summary": "Retained the reproducible partitions"}
    )
    assert completed.result["outcome"] == "completed"
    # Finishing retained the run's receipt: the reconciler had not reached the settled run.
    receipt = parent.artifacts.get(metadata__flow_run=str(child.pk))
    assert experiment_dispatch.observations(parent)[0]["receipt"] == str(receipt.pk)
    assert not ResearchAction.objects.filter(tool="model").exists()
    parent.refresh_from_db()
    assert parent.state == "completed"


@pytest.mark.parametrize("substitute", ["authored_receipt"])
def test_a_lead_completes_only_on_the_latest_execution_of_the_current_flow(substitute):
    experiment, user = flow()
    parent, first = agent_flow(experiment, user)
    research.complete(first, research_tools.invoke(first), cost=0)
    old = experiment_dispatch.owned(parent).get()
    experiment_engine.advance(old.pk)
    partition_plans.build(DataPartitionPlan.objects.get().pk)
    experiment_engine.advance(old.pk)
    experiment_dispatch.reconcile(parent)
    lead = parent.agents.get(parent__isnull=True)
    next_action = invoke(
        lead,
        "experiment",
        {
            "operation": "run",
            "revision": 2,
            "parameters": {"seed": 99},
            "admission": continuation(parent, old),
        },
    )
    current = experiment_dispatch.owned(parent).get(pk=next_action.result["run"])
    experiment_engine.advance(current.pk)
    partition = DataPartitionPlan.objects.exclude(state="completed").get()
    if substitute == "latest_failed":
        partition_plans.cancel(partition)
        experiment_engine.advance(current.pk)
        # The earlier run completed; the flow's newest execution did not.
        held = invoke(lead, "finish", {"outcome": "completed", "summary": "Partitions retained"})
        assert held.result["accepted"] is False
        assert "Execute the current saved flow" in held.result["reason"]
        return
    partition_plans.build(partition.pk)
    experiment_engine.advance(current.pk)
    retention = research.claim(lead, "authored-receipt", "retain_artifact", {})
    authored = research.retain(
        retention,
        Artifact(
            path="report.json",
            title="Report",
            kind="report",
            metadata={"flow_run": str(current.pk)},
        ),
        b"An authored report is not the native execution receipt",
    )
    research.complete(retention, research.artifact_record(authored), cost=0)
    research_experiments.require_delivery(parent, [], "outputs")
    observed = {item["run"]: item["receipt"] for item in experiment_dispatch.observations(parent)}
    # Each run's receipt is the one the platform retained for it.
    assert observed[str(current.pk)] not in {None, str(authored.pk), observed[str(old.pk)]}


def test_agent_flow_admission_does_not_allocate_a_money_ceiling():
    experiment, user = flow()
    parent, action = agent_flow(experiment, user)
    result = research_tools.invoke(action)
    child = experiment_dispatch.owned(parent).get()
    assert result["run"] == str(child.pk)
    assert "max_cost_usd" not in child.specification["budget"]
    assert "available_usd" not in research.allowance(parent)


def test_failure_before_native_submission_releases_the_unused_flow_reservation():
    experiment, user = flow()
    parent, action = agent_flow(experiment, user)
    with patch("overbae.tasks.research.advance_flow.delay"):
        research_tools.invoke(action)
    child = experiment_dispatch.owned(parent).get()
    rows.frame_path(Dataset.objects.get().active_cell).write_bytes(b"corrupted retained input")
    experiment_engine.advance(child.pk)
    experiment_dispatch.reconcile(parent)
    assert parent.agents.get(parent__isnull=True).actions.get(tool="flow_allocation").cost_usd == 0
    assert research.number(research.allowance(parent)["committed_usd"]) == 0


def test_stopping_the_lead_stops_its_flow_and_native_work():
    experiment, user = flow()
    parent, action = agent_flow(experiment, user)
    with patch("overbae.tasks.research.advance_flow.delay"):
        research_tools.invoke(action)
    child = experiment_dispatch.owned(parent).get()
    experiment_engine.advance(child.pk)
    research.stop(parent)
    parent.refresh_from_db()
    research_agent.reconcile(parent)
    child.refresh_from_db()
    assert child.state == "stopping"
    research_agent.reconcile(child)
    research_agent.reconcile(parent)
    parent.refresh_from_db()
    assert parent.state == "cancelled"
    assert DataPartitionPlan.objects.get().state == "cancelled"


def test_research_handoff_rejects_changed_artifact_bytes_before_admitting_outputs():
    experiment, user = flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"][1] = {
        "id": "audit",
        "kind": "research",
        "title": "Audit",
        "position": {"x": 500, "y": 0},
        "config": {"objective": "Audit source quality", "outputs": ["scores"]},
    }
    document["edges"] = [{"source": "data_0", "output": "data", "target": "audit", "input": "data"}]
    document["outputs"] = {"scores": {"node": "audit", "port": "scores"}}
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="audit"
    )
    run = experiment_engine.start(experiment, user, revision=3, request_key="audit", budget={})
    experiment_engine.advance(run.pk)
    receipt = run.execution.nodes.get(node="audit")
    child = experiment_research.assignment_for(receipt)
    action = research.claim(child.agents.get(parent__isnull=True), "report", "artifact", {})
    artifact = research.retain(
        action, Artifact(path="report.json", title="Audit", kind="evaluation"), b'{"score":0.4}'
    )
    child.state = "completed"
    child.result = {
        "artifacts": [str(artifact.pk)],
        "deliverables": [{"name": "scores", "artifacts": [str(artifact.pk)]}],
    }
    child.save(update_fields=["state", "result"])
    with artifact.file.open("wb") as file:
        file.write(b'{"score":1.0}')
    experiment_engine.advance(run.pk)
    receipt.refresh_from_db()
    run.refresh_from_db()
    assert run.state == "unmet"
    assert receipt.outputs == {}
    assert "no longer matches" in receipt.error


def test_a_flow_with_a_train_stage_is_admitted_before_its_campaign_starts():
    experiment, user = flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"].extend(
        [
            {
                "id": "model",
                "kind": "model",
                "title": "Model",
                "position": {"x": 0, "y": 200},
                "config": {"model": "Cloudflare/clef-flash"},
            },
            {
                "id": "train",
                "kind": "train",
                "title": "Train",
                "position": {"x": 900, "y": 0},
                "config": {},
                "operation": {
                    "tool": "training",
                    "arguments": {
                        "operation": "create",
                        "arguments": {
                            "run": {"name": "Candidate", "hyperparameters": {}},
                            "trials": 1,
                        },
                    },
                },
            },
        ]
    )
    document["edges"].extend(
        [
            {"source": "partition", "output": "train", "target": "train", "input": "data"},
            {
                "source": "partition",
                "output": "development",
                "target": "train",
                "input": "development",
            },
            {"source": "model", "output": "model", "target": "train", "input": "model"},
        ]
    )
    document["outputs"] = {"model": {"node": "train", "port": "model"}}
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="training"
    )
    admitted = experiment_engine.start(
        experiment, user, revision=3, request_key="native-training", budget={}
    )
    assert not DataPartitionPlan.objects.exists()
    assert admitted.state == "running"
    assert not experiment_training.campaigns([admitted]).exists()


@pytest.mark.parametrize("missing", ["development", "all"])
def test_missing_native_output_fails_its_producer_before_downstream_execution(missing):
    experiment, user = flow()
    run = experiment_engine.start(
        experiment, user, revision=2, request_key="missing-output", budget={}
    )
    experiment_engine.advance(run.pk)
    plan = DataPartitionPlan.objects.get()
    partition_plans.build(plan.pk)
    (plan.members.all() if missing == "all" else plan.members.filter(role=missing)).delete()
    experiment_engine.advance(run.pk)
    producer = run.execution.nodes.get(node="partition")
    assert producer.state == "failed"
    assert "development" in producer.error
    assert not producer.outputs


def test_resolved_dataset_identity_is_checked_before_native_submission():
    experiment, user = flow()
    run = experiment_engine.start(
        experiment, user, revision=2, request_key="stale-input", budget={}
    )
    source = run.execution.nodes.get(node="data_0")
    experiment_engine.execute({"execution": str(run.execution.pk), "ready": [str(source.pk)]})
    source.refresh_from_db()
    source.outputs["data"]["fingerprint"] = "changed"
    source.save(update_fields=["outputs"])
    experiment_engine.advance(run.pk)
    producer = run.execution.nodes.get(node="partition")
    assert producer.state == "failed"
    assert "fingerprint" in producer.error.lower()
    assert not DataPartitionPlan.objects.exists()
    assert not ResearchAction.objects.filter(experiment_node="partition").exists()


def test_admitted_node_retry_reuses_receipt_without_rechecking_mutable_readiness():
    experiment, user = flow()
    run = experiment_engine.start(
        experiment, user, revision=2, request_key="retry-receipt", budget={}
    )
    experiment_engine.advance(run.pk)
    receipt = run.execution.nodes.select_related("action__agent", "execution__revision").get(
        node="partition"
    )
    node = next(item for item in run.execution.document["nodes"] if item["id"] == "partition")
    plan = DataPartitionPlan.objects.get()
    Cell.objects.filter(pk=receipt.inputs["data"]["cell"]).update(state="error")
    repeated = experiment_execution.submit(
        receipt.action.agent,
        run.execution.revision,
        node,
        receipt.inputs,
        key=receipt.action.request_key,
    )
    assert repeated.pk == receipt.action_id
    assert DataPartitionPlan.objects.get().pk == plan.pk
    with pytest.raises(InputValidationError, match="unavailable"):
        experiment_execution.submit(
            receipt.action.agent,
            run.execution.revision,
            node,
            receipt.inputs,
            key="new-admission",
        )
    changed = deepcopy(receipt.inputs)
    changed["data"]["fingerprint"] = "changed"
    with pytest.raises(InputValidationError, match="different"):
        experiment_execution.submit(
            receipt.action.agent,
            run.execution.revision,
            node,
            changed,
            key=receipt.action.request_key,
        )


@pytest.mark.parametrize("concurrency", [1, 2])
def test_inline_variants_preserve_independent_results_and_stable_keys(concurrency):
    experiment, user = flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    source = document["nodes"][0]
    recipe = {
        "parameters": {"source": {"type": "object"}, "column": {"type": "string"}},
        "nodes": [
            {
                "id": "input",
                "kind": "data",
                "title": "Shared data",
                "position": {"x": 0, "y": 0},
                "config": {"$parameter": "source"},
            },
            {
                "id": "check",
                "kind": "check_data",
                "title": "Check candidate",
                "position": {"x": 300, "y": 0},
                "config": {},
                "operation": {
                    "tool": "platform",
                    "arguments": {
                        "name": "check_data",
                        "arguments": {
                            "row_schema": {"type": "object", "required": [{"$parameter": "column"}]}
                        },
                    },
                },
            },
        ],
        "edges": [{"source": "input", "output": "data", "target": "check", "input": "data"}],
        "outputs": {"checked": {"node": "check", "port": "data"}},
    }
    document["nodes"] = [
        source,
        {
            "id": "candidates",
            "kind": "map",
            "title": "Variants",
            "position": {"x": 400, "y": 0},
            "config": {
                "recipe": recipe,
                "inputs": {"source": "data"},
                "bindings": [{"column": "absent"}, {"column": "input"}],
                "keys": ["fails", "passes"],
                "labels": {"fails": "Candidate A", "passes": "Candidate B"},
                "concurrency": concurrency,
            },
        },
    ]
    document["edges"] = [
        {"source": source["id"], "output": "data", "target": "candidates", "input": "data"}
    ]
    document["outputs"] = {"candidates": {"node": "candidates", "port": "variants"}}
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="variants"
    )
    run = experiment_engine.start(
        experiment, user, revision=3, request_key="run-variants", budget={}
    )
    for _ in range(6):
        experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed", run.result
    variants = {item["key"]: item for item in run.result["outputs"]["candidates"]["variants"]}
    assert variants["fails"]["state"] == "failed" and variants["fails"]["outputs"] == {}
    assert variants["passes"]["state"] == "completed"
    assert variants["passes"]["outputs"]["checked"]["cell"] == source["config"]["cell"]
    assert run.execution.scopes.count() == 3
    assert set(run.execution.scopes.exclude(parent=None).values_list("variant_key", flat=True)) == {
        "fails",
        "passes",
    }
    changed = deepcopy(document)
    config = changed["nodes"][1]["config"]
    config["keys"].reverse()
    config["bindings"].reverse()
    config["labels"]["passes"] = "Renamed"
    assert research_experiments.node_identity(
        document, "candidates"
    ) == research_experiments.node_identity(changed, "candidates")
    config["bindings"][0]["column"] = "expected_output"
    assert research_experiments.node_identity(
        document, "candidates"
    ) != research_experiments.node_identity(changed, "candidates")

    research_experiments.revise(
        experiment, expected_version=3, document=changed, request_key="change-one-variant"
    )
    review = experiment_plans.resolve(experiment, revision=4, reuse_run=run.pk)
    assert any(item["path"][-1:] == ["fails"] for item in review["entries"])
    rerun = experiment_engine.start(
        experiment, user, revision=4, request_key="retry-variants", budget={}, reuse_run=run.pk
    )
    for _ in range(6):
        experiment_engine.advance(rerun.pk)
    rerun.refresh_from_db()
    assert rerun.state == "completed", rerun.result
    # This row changed: the old measurement must not be substituted for the new column.
    changed_scope = rerun.execution.scopes.get(variant_key="passes")
    assert not changed_scope.nodes.exclude(reused_from=None).exists()
    unchanged = deepcopy(document)
    research_experiments.revise(
        experiment, expected_version=4, document=unchanged, request_key="restore-variant"
    )
    reused = experiment_engine.start(
        experiment, user, revision=5, request_key="reuse-variant", budget={}, reuse_run=run.pk
    )
    for _ in range(6):
        experiment_engine.advance(reused.pk)
    successful = reused.execution.scopes.get(variant_key="passes")
    assert (
        successful.nodes.get(node="check").reused_from_id
        == run.execution.scopes.get(variant_key="passes").nodes.get(node="check").pk
    )
    assert successful.nodes.get(node="check").action_id is None
    assert run.execution.scopes.get(variant_key="fails").state == "failed"
    evidence = research_experiments.run_record(reused)["scopes"]
    measured = next(scope for scope in evidence if scope["variant"] == "passes")
    check = next(node for node in measured["nodes"] if node["node"] == "check")
    assert check["outputs"]["data"]["cell"] == source["config"]["cell"]
    assert check["reused_from"]["run"] == str(run.execution.pk)
    assert next(scope for scope in evidence if scope["variant"] == "fails")["error"]

    complete = deepcopy(unchanged)
    complete["nodes"][1]["config"]["bindings"][0]["column"] = "input"
    research_experiments.revise(
        experiment, expected_version=5, document=complete, request_key="repair-candidate"
    )
    repaired = experiment_engine.start(
        experiment, user, revision=6, request_key="repaired", budget={}, reuse_run=reused.pk
    )
    for _ in range(6):
        experiment_engine.advance(repaired.pk)
    replay = experiment_engine.start(
        experiment, user, revision=6, request_key="reuse-group", budget={}, reuse_run=repaired.pk
    )
    for _ in range(6):
        experiment_engine.advance(replay.pk)
    replay.refresh_from_db()
    assert replay.state == "completed"
    evidence = research_experiments.run_record(replay)["scopes"]
    assert {scope["variant"] for scope in evidence} == {"passes", "fails"}
    assert all(scope["state"] == "completed" for scope in evidence)
    assert all(scope["document"]["nodes"] and scope["nodes"] for scope in evidence)


def test_run_review_is_read_only_and_stale_admission_cannot_start_unreviewed_work():
    experiment, user = flow()
    plan = experiment_plans.resolve(experiment, revision=2, parameters={"seed": 11})
    assert plan["node_attempts"] == 2
    assert plan["resources"] == {"preparation": 1}
    assert plan["cost_usd"] is None
    assert not ResearchAssignment.objects.exists() and not DataPartitionPlan.objects.exists()
    first = experiment_engine.start(
        experiment,
        user,
        revision=2,
        request_key="reviewed",
        budget={},
        parameters={"seed": 11},
        plan_fingerprint=plan["fingerprint"],
    )
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"][1]["title"] = "Renamed partition"
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="later"
    )
    with pytest.raises(InputValidationError, match="run plan changed"):
        experiment_engine.start(
            experiment,
            user,
            revision=2,
            request_key="stale",
            budget={},
            parameters={"seed": 11},
            plan_fingerprint=plan["fingerprint"],
        )
    assert ResearchAssignment.objects.count() == 1
    assert (
        experiment_engine.start(
            experiment,
            user,
            revision=2,
            request_key="reviewed",
            budget={},
            parameters={"seed": 11},
            plan_fingerprint=plan["fingerprint"],
        ).pk
        == first.pk
    )
    with pytest.raises(InputValidationError):
        experiment_engine.start(
            experiment,
            user,
            revision=2,
            request_key="reviewed",
            budget={},
            parameters={"seed": 12},
            plan_fingerprint=plan["fingerprint"],
        )


def connected(function):
    close_old_connections()
    try:
        return function()
    finally:
        connection.close()


def observe_lock_attempt(function, model, entered):
    def observed(execute, sql, params, many, context):
        if "FOR UPDATE" in sql.upper() and model._meta.db_table in sql:
            entered.set()
        return execute(sql, params, many, context)

    with connection.execute_wrapper(observed):
        return function()


def selected_child_with_queued_followup():
    with experiment_checkpoints.store() as store:
        store.setup()
    experiment, user, baseline = measured_flow()
    parent = research_experiments.start(
        experiment, user, revision=experiment.version, request_key="parent-selection", budget={}
    )
    admission = continuation(parent, baseline)
    launched = invoke(
        parent.agents.get(parent__isnull=True),
        "experiment",
        {
            "operation": "run",
            "revision": 2,
            "reuse_run": str(baseline.pk),
            "rerun_from": ["select"],
            "admission": admission,
        },
        key="select-again",
    )
    child = ResearchAssignment.objects.get(pk=launched.result["run"])
    assert child.execution.nodes.get(node="select").state == "pending"
    experiment_engine.advance(child.pk)
    child.refresh_from_db()
    assert child.state == "completed"
    assert child.result["outputs"]["selection"]["selected"]["input"]["report"]["accuracy"] == 0.8
    followup = research.claim(
        parent.agents.get(parent__isnull=True),
        "queued-followup",
        "experiment",
        {"operation": "run", "revision": 2, "admission": continuation(parent, child)},
    )
    return experiment, parent, child, followup


@pytest.mark.covers("assistant-turn")
def test_parent_stop_fences_queued_followup_and_late_selected_child_notification():
    experiment, parent, child, followup = selected_child_with_queued_followup()
    selected = deepcopy(child.result["outputs"]["selection"])
    followup_entered, notification_entered = Event(), Event()

    def admit_followup():
        fresh = ResearchAction.objects.select_related("agent__assignment").get(pk=followup.pk)
        return observe_lock_attempt(
            lambda: research_tools.invoke(fresh), ResearchExperiment, followup_entered
        )

    def deliver_selection():
        owner = ResearchAssignment.objects.get(pk=parent.pk)
        return observe_lock_attempt(
            lambda: experiment_dispatch.reconcile(owner),
            ResearchExperiment,
            notification_entered,
        )

    with ThreadPoolExecutor(max_workers=2) as pool:
        with transaction.atomic():
            ResearchExperiment.objects.select_for_update().get(pk=experiment.pk)
            ResearchAssignment.objects.select_for_update().get(pk=parent.pk)
            admission = pool.submit(connected, admit_followup)
            notification = pool.submit(connected, deliver_selection)
            assert followup_entered.wait(timeout=15) and not admission.done()
            assert notification_entered.wait(timeout=15) and not notification.done()
            research.stop(parent)
        denied = admission.result(timeout=20)
        assert denied["started"] is False and "run" not in denied, denied
        assert notification.result(timeout=20)
    assert experiment_dispatch.owned(parent).count() == 1
    research.complete(followup, denied, cost=0)
    assert research_agent.settle_stop(str(parent.pk))
    parent.refresh_from_db()
    child.refresh_from_db()
    assert parent.state == "cancelled"
    assert child.state == "completed" and child.result["outputs"]["selection"] == selected
    observations = experiment_dispatch.observations(parent, include_reports=True)
    retained = next(item for item in observations if item["run"] == str(child.pk))
    assert retained["state"] == "completed" and retained["receipt"]
    assert retained["outputs"]["selection"] == selected
    assert not research_tools.pending_work(parent)


@pytest.mark.parametrize("first_surface", ["rest", "mcp"])
@pytest.mark.covers("work-once")
def test_saved_run_replays_across_rest_and_mcp_with_the_same_effective_limits(first_surface):
    experiment, user = flow()
    client = APIClient()
    client.force_authenticate(user)
    path = f"/api/research-experiments/{experiment.pk}/"
    plan = client.post(path + "plan/", {"revision": 2, "parameters": {}}, format="json")
    assert plan.status_code == 200, plan.data
    payload = {
        "revision": 2,
        "plan_fingerprint": plan.data["fingerprint"],
        "request_key": "cross-surface-run",
    }
    context = MCPContext(
        user=user, token=PlatformCredential(experiment.project_id), project=experiment.project
    )

    def start_at(surface):
        if surface == "rest":
            response = client.post(path + "run/", payload, format="json")
            assert response.status_code == 200, response.data
            return next(
                run["id"] for run in response.data["record"]["runs"] if run.get("execution")
            )
        return tools_experiments.invoke(
            "start_experiment_run",
            StartExperimentRun.model_validate({"experiment": str(experiment.pk), **payload}),
            context,
        ).experiment["id"]

    with patch("overbae.tasks.research.advance_flow.delay"):
        first = start_at(first_surface)
        second = start_at("mcp" if first_surface == "rest" else "rest")
        assert str(first) == str(second)
        changed = client.post(
            path + "run/", {**payload, "budget": {"max_seconds": 600}}, format="json"
        )
    assert changed.status_code == 400, changed.data
    assert experiment.revisions.get(number=2).runs.filter(execution__isnull=False).count() == 1


def controlled_partition_check():
    experiment, user = flow()
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"].append(
        {
            "id": "check",
            "kind": "check_data",
            "title": "Check the partition",
            "position": {"x": 800, "y": 0},
            "config": {},
            "operation": {
                "tool": "platform",
                "arguments": {
                    "name": "check_data",
                    "arguments": {"row_schema": {"type": "object", "required": ["input"]}},
                },
            },
        }
    )
    document["edges"].append(
        {"source": "partition", "target": "check", "output": "train", "input": "data"}
    )
    document["outputs"] = {"checked": {"node": "check", "port": "data"}}
    research_experiments.revise(
        experiment, expected_version=2, document=document, request_key="check-partition"
    )
    controller = research_experiments.start(
        experiment, user, revision=3, request_key="controller", budget={}
    )
    with patch("overbae.tasks.research.advance_flow.delay"):
        action = invoke(
            controller.agents.get(parent__isnull=True),
            "experiment",
            {"operation": "run", "revision": 3, "max_seconds": 600},
        )
    run = ResearchAssignment.objects.get(pk=action.result["run"])
    with patch("overbae.tasks.data_partitions.build_plan.delay"):
        experiment_engine.advance(run.pk)
    partition = run.execution.nodes.select_related("action").get(node="partition")
    assert partition.state == "waiting"
    assert run.execution.nodes.get(node="check").action_id is None
    return controller, run, partition


def exhaust_controller(controller):
    lead = controller.agents.get(parent__isnull=True)
    lead.state, lead.result = "exhausted", {"reason": "model_call_limit"}
    lead.save(update_fields=["state", "result"])
    research_agent.exhaust(lead)
    controller.refresh_from_db()
    assert controller.state == "exhausted"


@pytest.mark.parametrize(
    "disposition", ["model_call_limit", "model_provider_unavailable", "model_provider_rejected"]
)
def test_pinned_flow_executes_its_next_node_while_controlling_decisions_are_unavailable(
    disposition,
):
    controller, run, partition = controlled_partition_check()
    if disposition == "model_call_limit":
        exhaust_controller(controller)
    else:
        controller.state, controller.result = "blocked", {"reason": disposition}
        controller.save(update_fields=["state", "result"])
        lead = controller.agents.get(parent__isnull=True)
        lead.state, lead.result = "blocked", {"provider_probe": True}
        lead.save(update_fields=["state", "result"])
        research_agent.reconcile(controller)
    plan = DataPartitionPlan.objects.get(request_key=f"research:{partition.action_id}")
    partition_plans.build(plan.pk)
    plan.refresh_from_db()
    assert plan.state == "completed", plan.error
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed", run.result
    checked = run.execution.nodes.select_related("action").get(node="check")
    assert checked.state == "completed"
    assert checked.action.result["passed"]
    assert checked.action.experiment_inputs["data"]["cell"] == str(
        plan.members.get(role="train").cell_id
    )
    assert run.result["outputs"]["checked"]["fingerprint"]
    assert not ResearchAction.objects.filter(
        agent__assignment__in=[controller, run], tool="model"
    ).exists()
    research_agent.reconcile(controller)
    controller.refresh_from_db()
    assert controller.state == ("exhausted" if disposition == "model_call_limit" else "blocked")
    assert controller.result["reason"] == disposition
    allocation = controller.agents.get(parent__isnull=True).actions.get(tool="flow_allocation")
    assert allocation.state == "completed"
    assert allocation.result["run"] == str(run.pk)


def test_node_continuation_does_not_authorize_other_actions_assignments_or_copied_contexts():
    controller, run, partition = controlled_partition_check()
    exhaust_controller(controller)
    unrelated = research.claim(
        run.agents.get(parent__isnull=True),
        "not-a-pinned-node",
        partition.action.tool,
        partition.action.arguments,
    )
    before = DataPartitionPlan.objects.count()
    with execution_mandates.continuing_node(partition.action):
        execution_mandates.require(run, "prepare")
        with pytest.raises(InputValidationError):
            research_tools.invoke(unrelated)
        with pytest.raises(InputValidationError):
            execution_mandates.require(controller, "prepare")
        inherited = copy_context()

        def require_in_worker():
            close_old_connections()
            try:
                execution_mandates.require(run, "prepare")
            finally:
                connection.close()

        with ThreadPoolExecutor(max_workers=1) as pool, pytest.raises(InputValidationError):
            pool.submit(inherited.run, require_in_worker).result(timeout=20)
    with pytest.raises(InputValidationError):
        inherited.run(execution_mandates.require, run, "prepare")
    with pytest.raises(InputValidationError):
        research_tools.invoke(unrelated)
    assert DataPartitionPlan.objects.count() == before


@pytest.mark.parametrize(
    "change", ["arguments", "inputs", "revision", "missing_revision", "receipt"]
)
def test_retained_worker_continuation_rejects_changed_pinned_action_bindings(change):
    controller, run, partition = controlled_partition_check()
    exhaust_controller(controller)
    action = partition.action
    if change == "arguments":
        arguments = deepcopy(action.arguments)
        arguments["arguments"]["recipe"]["seed"] += 1
        ResearchAction.objects.filter(pk=action.pk).update(
            arguments=arguments,
            fingerprint=context_graph.fingerprint({"tool": action.tool, "arguments": arguments}),
        )
    elif change == "inputs":
        ResearchAction.objects.filter(pk=action.pk).update(experiment_inputs={})
    elif change == "revision":
        ResearchAction.objects.filter(pk=action.pk).update(
            experiment_revision=run.execution.revision.experiment.revisions.get(number=2)
        )
    elif change == "missing_revision":
        ResearchAction.objects.filter(pk=action.pk).update(experiment_revision=None)
    else:
        ExperimentNodeExecution.objects.filter(pk=partition.pk).update(action=None)
    with pytest.raises(InputValidationError):
        execution_mandates.require_action_continuation(action, "prepare")
    plan = DataPartitionPlan.objects.get(request_key=f"research:{action.pk}")
    partition_plans.build(plan.pk)
    plan.refresh_from_db()
    assert plan.state == "failed"
    assert not plan.members.exists()


@pytest.mark.parametrize("revocation", ["cancelled", "deadline", "membership", "other_limit"])
def test_pinned_node_continuation_preserves_parent_revocation_and_non_model_limits(revocation):
    controller, run, partition = controlled_partition_check()
    exhaust_controller(controller)
    if revocation == "cancelled":
        ResearchAssignment.objects.filter(pk=controller.pk).update(state="cancelled")
    elif revocation == "deadline":
        ResearchAssignment.objects.filter(pk=controller.pk).update(
            deadline=timezone.now() - timedelta(seconds=1)
        )
    elif revocation == "membership":
        controller.project.memberships.filter(user=controller.created_by).delete()
    else:
        ResearchAssignment.objects.filter(pk=controller.pk).update(result={"reason": "deadline"})
    with pytest.raises(InputValidationError):
        execution_mandates.require_action_continuation(partition.action, "prepare")
    plan = DataPartitionPlan.objects.get(request_key=f"research:{partition.action_id}")
    partition_plans.build(plan.pk)
    plan.refresh_from_db()
    assert plan.state == "failed"
    assert not plan.members.exists()


@pytest.mark.covers("recovery")
@pytest.mark.parametrize("disposition", ["model_call_limit", "stopped", "revoked", "deadline"])
def test_terminal_flow_receipt_settles_after_controller_authority_ends(disposition):
    experiment, user = flow()
    parent, action = agent_flow(experiment, user)
    research.complete(action, research_tools.invoke(action), cost=0)
    child = experiment_dispatch.owned(parent).get()
    experiment_engine.advance(child.pk)
    partition_plans.build(DataPartitionPlan.objects.get().pk)
    experiment_engine.advance(child.pk)
    child.refresh_from_db()
    assert child.state == "completed"
    lead = parent.agents.get(parent__isnull=True)
    allocation = lead.actions.get(tool="flow_allocation")
    assert allocation.state == "running"
    record = experiment_dispatch.receipt_record(child)
    with pytest.raises(InputValidationError):
        research.claim(
            lead,
            "forged-receipt",
            "flow_receipt",
            {**record, "state": "cancelled"},
            effect=child.execution,
        )
    for tool in ("model", "artifact"):
        with pytest.raises(InputValidationError):
            research.claim(lead, f"forged-{tool}", tool, record, effect=child.execution)
    assert not parent.artifacts.filter(metadata__flow_run=str(child.pk)).exists()
    if disposition == "model_call_limit":
        parent.specification["budget"]["max_model_calls"] = 1
        parent.save(update_fields=["specification"])
        last = research.claim(lead, "last-model", "model", {})
        research.complete(last, {}, cost=0)
        research_agent.think(research_agent.lease(lead.pk), 1)
        parent.refresh_from_db()
        assert parent.state == "exhausted"
    elif disposition == "stopped":
        with patch("overbae.tasks.research.settle_stop.delay"):
            research.stop(parent)
    elif disposition == "revoked":
        ProjectMembership.objects.filter(project=parent.project, user=user).delete()
    else:
        ResearchAssignment.objects.filter(pk=parent.pk).update(
            deadline=timezone.now() - timedelta(seconds=1)
        )
    assert experiment_dispatch.reconcile(parent)
    assert experiment_dispatch.reconcile(parent)
    allocation.refresh_from_db()
    assert allocation.state == "completed" and allocation.result["run"] == str(child.pk)
    artifact = parent.artifacts.get(metadata__flow_run=str(child.pk))
    assert allocation.result["artifact"] == str(artifact.pk)
    assert artifact.action.tool == "flow_receipt" and artifact.action.state == "completed"
    observed = json.loads(research.artifact_bytes(artifact, limit=100000))
    assert observed["run"] == str(child.pk) and observed["state"] == "completed"
    assert observed["definition"] == child.execution.fingerprint
    assert parent.artifacts.filter(metadata__flow_run=str(child.pk)).count() == 1
    assert lead.actions.filter(tool="flow_receipt").count() == 1
    assert research.claim(lead, "new-flow", "experiment", {"operation": "run"}).state == "denied"
    assert DataPartitionPlan.objects.count() == 1


@pytest.mark.covers("work-once")
@pytest.mark.parametrize("kind", ["controlled_flow", "adaptive_child"])
def test_child_resume_does_not_compete_with_its_running_controller(kind):
    experiment, user = flow()
    if kind == "controlled_flow":
        parent, action = agent_flow(experiment, user)
        with patch("overbae.tasks.research.advance_flow.delay"):
            research_tools.invoke(action)
        child = experiment_dispatch.owned(parent).get()
    else:
        parent, _, child = investigating(experiment, user)
    research.stop(child)
    assert research_agent.settle_stop(child.pk)
    child.refresh_from_db()
    assert child.state == "cancelled"

    resumed = research.resume(
        child, request_key="resume-child", instructions="Continue the admitted child work"
    )
    parent.refresh_from_db()
    assert parent.state == "running" and resumed.state == "running"
    assert execution_mandates.require(resumed, "read")["authority"] == "act"


@pytest.mark.parametrize(
    "change",
    [
        "none",
        "parameters",
        "definition",
        "native_action",
        "running",
        "completed",
        "cancelled",
        "newer",
        "lease",
        "child",
        "older_native_action",
        "multiple_failures",
    ],
)
def test_pre_execution_correction_requires_no_previous_admitted_work(change):
    experiment, user = flow()
    experiment.refresh_from_db()
    owner = research_experiments.start(
        experiment, user, revision=experiment.version, request_key="lead", budget={}
    )
    lead = owner.agents.get(parent__isnull=True)
    first_action = research.claim(lead, "first", "experiment", {"operation": "run"})
    prior = experiment_engine.start(
        experiment,
        user,
        revision=experiment.version,
        request_key="first",
        budget={},
        controller=first_action,
    )
    scope = prior.execution.scopes.get(parent__isnull=True)
    failed = scope.nodes.get(node="partition")
    failed.state = "failed"
    failed.error = "Native input admission failed before submission"
    failed.save(update_fields=["state", "error"])
    prior.state = "unmet"
    prior.save(update_fields=["state"])
    if change in {"native_action", "older_native_action"}:
        native = research.claim(
            prior.agents.get(parent__isnull=True),
            "unknown",
            "platform",
            {"name": "create_data_partition", "arguments": {}},
        )
        native.state = "unknown"
        native.save(update_fields=["state"])
        failed.action = native
        failed.save(update_fields=["action"])
    elif change in {"running", "completed", "cancelled"}:
        prior.state = change
        prior.save(update_fields=["state"])
    elif change == "newer":
        experiment_engine.start(
            experiment, user, revision=experiment.version, request_key="newer", budget={}
        )
    elif change == "lease":
        prior.execution.lease = uuid4()
        prior.execution.save(update_fields=["lease"])
    elif change == "child":
        child = research.create(
            experiment.project,
            user=user,
            request_key="descendant",
            objective="Child investigation",
            task={"flow_run": str(prior.pk)},
            budget={},
        )
        child.state = "completed"
        child.save(update_fields=["state"])
    if change in {"older_native_action", "multiple_failures"}:
        prior = experiment_engine.start(
            experiment, user, revision=experiment.version, request_key="later-failure", budget={}
        )
        prior.execution.nodes.filter(node="partition").update(state="failed", error="Not submitted")
        prior.state = "unmet"
        prior.save(update_fields=["state"])
    if change == "definition":
        document = deepcopy(prior.execution.document)
        document["nodes"][1]["operation"]["arguments"]["arguments"]["recipe"]["fractions"] = {
            "train": 0.7,
            "development": 0.3,
        }
        research_experiments.revise(
            experiment,
            expected_version=experiment.version,
            document=document,
            request_key="correct",
        )
        experiment.refresh_from_db()
    retry_action = research.claim(lead, "repair", "experiment", {"operation": "run"})
    arguments = dict(
        revision=experiment.version,
        request_key="repair",
        budget={},
        controller=retry_action,
        parameters={"seed": 99} if change == "parameters" else {},
    )
    if change not in {"none", "parameters", "definition", "multiple_failures"}:
        with pytest.raises(InputValidationError, match="scientific decision"):
            experiment_engine.start(experiment, user, **arguments)
        return
    retried = experiment_engine.start(experiment, user, **arguments)
    assert retried.specification["task"]["scientific_admission"]["prior_run"] == str(prior.pk)
    assert experiment_engine.start(experiment, user, **arguments).pk == retried.pk
    assert not retried.execution.nodes.exclude(action=None).exists()