Skip to content

The platform for continuously improving AI agents.

44.9 KB
Raw Blame
import base64
import hashlib
import io
import json
from concurrent.futures import ThreadPoolExecutor
from contextlib import redirect_stdout
from copy import deepcopy
from threading import Event
from types import SimpleNamespace
from unittest.mock import patch

import modal
import pytest
from django.db import close_old_connections, connection, connections
from django.test.utils import CaptureQueriesContext
from factories import make_project, make_user
from test_research_experiments import continuation, execute_saved, invoke, start
from test_research_team import invoke as invoke_native
from test_research_team import specialist
from test_transform_spec import PASSENGERS, SPEC

from overbae.core.errors import InputValidationError
from overbae.models import (
    DataPartitionMember,
    DataPartitionPlan,
    Dataset,
    DatasetPipelineRun,
    Project,
    ResearchAction,
    ResearchEvent,
)
from overbae.services import (
    experiment_engine,
    research,
    research_agent,
    research_evidence,
    research_experiments,
    research_questions,
    research_tools,
)
from overbae.services.datasets import (
    land,
    lineage,
    partition_plans,
    paths,
    pipeline_runner,
    workbench,
)
from sandbox.protocol import header_bytes

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


@pytest.fixture(autouse=True)
def capture_queues():
    with (
        patch("overbae.tasks.datasets.execute_pipeline.delay"),
        patch("overbae.tasks.data_partitions.build_plan.delay") as partitions,
    ):
        yield partitions


def experiment_on(dataset, user, key="draft"):
    return research_experiments.create(
        dataset.project,
        user,
        name="Survival",
        objective="Train a model that predicts survival",
        cells=[dataset.source.pk],
        request_key=key,
    )


def passengers():
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name="Passengers")
    land.land_rows(dataset, PASSENGERS, user=user)
    dataset.refresh_from_db()
    return dataset, user


def prepare_and_partition(run, spec, split=None):
    """Stage a transform spec and its partition, run the flow and settle both stages."""
    prepared = invoke(
        run,
        "stage",
        id="prepare",
        kind="transform",
        inputs={"data": "data_0"},
        settings={"spec": spec},
    )
    assert prepared["ready"], prepared
    split = invoke(
        run, "stage", id="split", kind="split", inputs={"data": "prepare"}, settings=split or {}
    )
    assert split["ready"], split
    child = execute_saved(run, split["revision"])
    receipt = child.execution.nodes.get(node="prepare")
    native = DatasetPipelineRun.objects.get(request_key=f"research:{receipt.action_id}")
    with CaptureQueriesContext(connection) as queries:
        workbench.execute(native.pk, script_executor=pipeline_runner.execute_script)
    native.refresh_from_db()
    assert native.state == "completed", native.error
    # Publishing holds the project's row before it writes a version: a work-starting operation
    # locks that row and then reads datasets, and the other order deadlocks the two.
    statements = [query["sql"] for query in queries]
    held = next(
        i for i, sql in enumerate(statements) if "overbae_project" in sql and "FOR KEY SHARE" in sql
    )
    assert held < next(i for i, sql in enumerate(statements) if 'INSERT INTO "overbae_cell"' in sql)
    experiment_engine.advance(child.pk)
    experiment_engine.advance(child.pk)
    plan = DataPartitionPlan.objects.filter(source_cell=native.output).get()
    partition_plans.build(plan.pk)
    plan.refresh_from_db()
    assert plan.state == "completed", plan.error
    experiment_engine.advance(child.pk)
    child.refresh_from_db()
    assert child.state == "completed", child.result
    return split, plan


def execute_reusing(run, revision):
    """Run the saved flow again, reusing what the project's first completed flow run retained."""
    source = (
        type(run)
        .objects.filter(
            project=run.project, state="completed", specification__task__execution="flow"
        )
        .earliest("created_at")
    )
    receipt = invoke(
        run,
        "run",
        revision=revision,
        max_seconds=600,
        reuse_run=str(source.pk),
        admission=continuation(run, source),
    )
    assert "run" in receipt, receipt
    return type(run).objects.get(pk=receipt["run"])


def keys(cell):
    return set().union(*lineage.stream(cell))


def test_a_transform_spec_stage_prepares_and_its_partition_follows_the_spec():
    dataset, user = passengers()
    run = start(experiment_on(dataset, user), user)
    split, plan = prepare_and_partition(run, SPEC)
    assert plan.recipe["group_by"] == ["ticket_group"]
    assert plan.recipe["stratify_by"] == "decision.target_probabilities"
    members = {member.role: member.cell for member in plan.members.select_related("cell")}
    assert sum(cell.rows for cell in members.values()) == 40
    assert members["train"].intent_report["train"]["format"] == "decision"
    # No ticket group is in two partitions.
    tickets = {
        role: {value for kind, value in keys(cell) if kind == "ticket_group"}
        for role, cell in members.items()
    }
    assert not tickets["train"] & tickets["final"] and not tickets["train"] & tickets["development"]
    assert research_tools.source_cell(run, dataset.source.pk) == dataset.source
    flow = invoke(run, "inspect")
    assert flow["ready"], flow


def test_a_flow_with_a_second_source_prepares_its_partitioned_file_again():
    dataset, user = passengers()
    other = Dataset.objects.create(project=dataset.project, name="Holdout")
    land.land_rows(other, PASSENGERS[:8], user=user)
    other.refresh_from_db()
    experiment = research_experiments.create(
        dataset.project,
        user,
        name="Survival",
        objective="Train a model that predicts survival",
        cells=[dataset.source.pk, other.source.pk],
        request_key="two",
    )
    run = start(experiment, user)
    split, plan = prepare_and_partition(run, SPEC)
    completed_child = type(run).objects.get(
        project=run.project, state="completed", specification__task__execution="flow"
    )
    again = execute_saved(run, split["revision"], admission=continuation(run, completed_child))
    assert set(again.specification["context_roots"]) == {
        f"cell:{dataset.source.pk}",
        f"cell:{other.source.pk}",
    }
    prepared = again.execution.nodes.get(node="prepare")
    assert prepared.state != "failed", prepared.error
    # Reused from the first run, the partition's training rows are this run's own stage
    # output: the stage that trains on them is admitted to them.
    reused = execute_reusing(run, split["revision"])
    train = plan.members.get(role="train").cell
    assert reused.execution.nodes.get(node="split").reused_from_id is not None
    assert research_tools.source_cell(reused, train.pk) == train


def test_a_flow_whose_input_names_the_label_is_held_before_it_runs():
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name="Requests")
    land.land_rows(
        dataset,
        [
            {"queue": queue, "note": f"{index} routed to {queue} team", "words": index % 7}
            for index in range(60)
            for queue in ("payments", "account")
        ],
        user=user,
    )
    dataset.refresh_from_db()
    run = start(experiment_on(dataset, user), user)
    spec = {
        "target": {
            "column": "queue",
            "question": "Which queue handles this request?",
            "options": [{"value": "payments"}, {"value": "account"}],
        },
        "inputs": [{"name": "note", "sql": '"note"'}, {"name": "words", "sql": '"words"'}],
    }
    held = invoke(
        run,
        "stage",
        id="prepare",
        kind="transform",
        inputs={"data": "data_0"},
        settings={"spec": spec},
    )
    assert held["ready"] is False
    assert any("input note names the row's own queue value" in issue for issue in held["issues"])
    assert not DatasetPipelineRun.objects.exists()
    spec["inputs"] = spec["inputs"][1:]
    spec["excluded"] = [{"column": "note", "reason": "outcome"}]
    kept = invoke(run, "stage", id="prepare", settings={"spec": spec})
    assert kept["ready"] is True, kept["issues"]


@pytest.mark.covers("privacy")
@pytest.mark.parametrize("interruption", ["publication_failure", "cancelled"])
def test_interrupted_partition_does_not_publish_any_new_members(interruption):
    dataset, _ = passengers()
    plan = partition_plans.request_plan(
        dataset.project,
        name="Interrupted partition",
        request_key="interrupted-partition",
        source_cell=dataset.source,
        recipe={"seed": 7, "fractions": {"train": 0.5, "final": 0.5}},
    )
    if interruption == "publication_failure":
        destination = paths.media_root() / "data-partitions" / str(plan.pk) / "assignments.jsonl"
        destination.mkdir(parents=True)

    def cancel_before_publication(execute, sql, params, many, context):
        if (
            interruption == "cancelled"
            and sql.startswith(f'UPDATE "{DataPartitionPlan._meta.db_table}"')
            and any(
                isinstance(value := getattr(parameter, "obj", None), dict)
                and value.get("progress", {}).get("stage") == "writing"
                for parameter in params
            )
        ):
            partition_plans.cancel(plan)
        return execute(sql, params, many, context)

    with connection.execute_wrapper(cancel_before_publication):
        partition_plans.build(plan.pk)
    plan.refresh_from_db()
    assert plan.state == ("failed" if interruption == "publication_failure" else "cancelled")
    assert not plan.members.exists()
    assert not Dataset.objects.filter(source_spec__partition_plan=str(plan.pk)).exists()


def test_a_spec_that_does_not_fit_the_source_keeps_the_flow_from_running():
    dataset, user = passengers()
    run = start(experiment_on(dataset, user), user)
    spec = deepcopy(SPEC)
    spec["target"]["options"] = spec["target"]["options"][:1] + [{"value": "9", "label": "Other"}]
    spec["inputs"].append({"name": "leak", "sql": '"Outcome"'})
    staged = invoke(
        run,
        "stage",
        id="prepare",
        kind="transform",
        inputs={"data": "data_0"},
        settings={"spec": spec},
    )
    assert not staged["ready"]
    issue = next(item for item in staged["issues"] if item.startswith("prepare:"))
    assert "inputs.leak" in issue and '["1"]' in issue


def preparation_research(dataset, user, *, key):
    return research.create(
        dataset.project,
        user=user,
        request_key=key,
        objective="Prepare the admitted data",
        task={"deliverable": "Verified prepared data"},
        context_roots=[f"cell:{dataset.source.pk}"],
        budget={},
    )


def preparation_platform_call(owner, key, operation, **arguments):
    action = research.claim(
        owner.agents.get(parent__isnull=True),
        key,
        "platform",
        {"name": operation, "arguments": arguments},
    )
    result = research_tools.invoke(action)
    research.complete(action, result, cost=0)
    return result


def seal_preparation_source(dataset, key):
    plan = partition_plans.request_plan(
        dataset.project,
        name="Source holdout",
        request_key=key,
        source_cell=dataset.source,
        recipe={"seed": 7, "fractions": {"train": 0.5, "final": 0.5}},
    )
    partition_plans.build(plan.pk)
    plan.refresh_from_db()
    assert plan.state == "completed", plan.error
    return plan


@pytest.mark.covers("privacy")
@pytest.mark.parametrize("outcome", ["completed", "provider_error"])
def test_preparation_replies_retain_checks_errors_and_settled_identity(outcome, settings, scripted):
    dataset, user = passengers()
    spec = deepcopy(SPEC)
    spec["inputs"].append({"name": "sex", "sql": '"Sex"'})
    spec["excluded"] = [item for item in spec["excluded"] if item["column"] != "Sex"]
    first = start(experiment_on(dataset, user), user)
    _, sealed = prepare_and_partition(first, spec)
    verified = DatasetPipelineRun.objects.get(output_id=sealed.source_cell_id)
    assert verified.result["steps"][-1]["preparation"]["labels"]
    assert verified.result["steps"][-1]["preparation"]["flagged"]

    again = Dataset.objects.create(project=dataset.project, name="Replay source")
    land.land_rows(again, PASSENGERS, user=user)
    again.refresh_from_db()
    owner = start(experiment_on(again, user, key="private-replay"), user)
    staged = invoke(
        owner,
        "stage",
        id="prepare",
        kind="transform",
        inputs={"data": "data_0"},
        settings={"spec": spec},
    )
    assert staged["ready"], staged
    split = invoke(owner, "stage", id="split", kind="split", inputs={"data": "prepare"})
    assert split["ready"], split
    child = execute_saved(owner, split["revision"])
    node = child.execution.nodes.select_related("action").get(node="prepare")
    native = DatasetPipelineRun.objects.get(request_key=f"research:{node.action_id}")
    assert any(column.get("examples") for column in native.result["source_columns"])
    queued = preparation_platform_call(
        owner, "queued-replay-status", "get_job", kind="dataset_pipeline", id=str(native.pk)
    )
    assert node.action.result["run"]["id"] == str(native.pk)
    assert queued["progress"]["id"] == str(native.pk)
    assert queued["progress"]["result"]["source_columns"] == native.result["source_columns"]

    private_error = "private-source-runtime-detail-734"
    sandbox = None
    if outcome == "provider_error":
        settings.SANDBOX_URL = "https://sandbox.sealed-preparation.test"
        settings.SANDBOX_TOKEN = "sealed-preparation-test-token"
        sandbox = scripted(settings.SANDBOX_URL)
        body = header_bytes(
            {"ok": False, "exit_code": 1, "seconds": 0.25, "stdout": "", "error": private_error}
        )
        sandbox.then(lambda _: (200, {"content-type": "application/octet-stream"}, body))
    workbench.execute(native.pk, script_executor=pipeline_runner.execute_script)
    native.refresh_from_db()
    if outcome == "completed":
        assert native.state == "completed", native.error
        assert native.result["steps"][-1]["preparation"]["labels"]
        assert native.result["steps"][-1]["preparation"]["flagged"]
    else:
        assert native.state == "failed"
        assert private_error in native.error
        assert sandbox.calls
    settled = preparation_platform_call(
        owner, "settled-replay-status", "get_job", kind="dataset_pipeline", id=str(native.pk)
    )
    assert settled["progress"]["id"] == str(native.pk)
    assert settled["progress"]["error"] == native.error
    experiment_engine.advance(child.pk)
    observed = invoke(owner, "inspect")
    flow = next(run for run in observed["flow_runs"] if run["run"] == str(child.pk))
    if outcome == "completed":
        checks = native.result["steps"][-1]["preparation"]
        assert settled["progress"]["result"]["steps"][-1]["preparation"] == checks
        assert flow["data_checks"]["prepare"] == {
            "flagged": checks["flagged"],
            "failed": checks["failed"],
        }
    else:
        failed = next(item for item in flow["nodes"] if item["node"] == "prepare")
        assert failed["state"] == "failed" and private_error in failed["error"]
    retained = (native.state, native.output_id, deepcopy(native.result), native.error)
    provider_calls = len(sandbox.calls) if sandbox else None
    workbench.execute(native.pk, script_executor=pipeline_runner.execute_script)
    native.refresh_from_db()
    assert (native.state, native.output_id, native.result, native.error) == retained
    assert DatasetPipelineRun.objects.filter(request_key=f"research:{node.action_id}").count() == 1
    if sandbox:
        assert len(sandbox.calls) == provider_calls


@pytest.mark.covers("privacy")
@pytest.mark.parametrize("outcome", ["completed", "failed"])
def test_native_partition_retries_preserve_identity_reports_and_errors(outcome):
    dataset, user = passengers()
    owner = preparation_research(dataset, user, key="partition-projection")
    recipe = {
        "seed": 7,
        "fractions": {"train": 0.5, "final": 0.5},
        "stratify_by": "Ticket" if outcome == "completed" else "unavailable-column-detail",
    }
    action = research.claim(
        owner.agents.get(parent__isnull=True),
        "partition",
        "platform",
        {
            "name": "create_data_partition",
            "arguments": {
                "name": "Partition with retained details",
                "source_cell": str(dataset.source.pk),
                "recipe": recipe,
            },
        },
    )
    submitted = research_tools.invoke(action)
    plan = DataPartitionPlan.objects.get(pk=submitted["workflow"]["id"])
    partition_plans.build(plan.pk)
    plan.refresh_from_db()
    assert plan.state == outcome, plan.error
    if outcome == "completed":
        assert plan.report["strata"]["final"]
    else:
        assert "unavailable-column-detail" in plan.error
        seal_preparation_source(dataset, "seal-retained-error-source")
    # The first response was lost before the action settled; its retry returns the same work.
    repeated = research_tools.invoke(action)
    research.complete(action, repeated, cost=0)
    assert repeated["workflow"]["id"] == str(plan.pk)
    observed = preparation_platform_call(
        owner, "partition-status", "get_job", kind="data_partition", id=str(plan.pk)
    )
    for reply in (repeated, observed):
        progress = reply["progress"]
        assert progress["state"] == outcome
        assert progress["report"] == plan.report
        assert progress["error"] == plan.error
        for member in progress["members"]:
            assert not {"profile", "stats", "examples", "data"} & member["cell"].keys()
    evidence = research_tools.work_evidence(owner)
    if outcome == "failed":
        assert plan.error in json.dumps(evidence)


@pytest.fixture
def research_source_sandbox(fake_modal, monkeypatch):
    """The external session/file APIs with provider-owned bytes, memory and snapshots."""
    snapshots, mounts, terminations, deferred = {}, [], [], set()
    session_calls = []
    original_terminate = modal.Sandbox.terminate

    def process(value=None, *, error=None):
        return SimpleNamespace(
            stdout=io.StringIO(json.dumps(value) if value is not None else ""),
            stderr=io.StringIO(error or ""),
            wait=lambda: int(error is not None),
        )

    def path(value):
        value = str(value)
        return value if value.startswith("/") else "/workspace/work/" + value

    class WrittenFile(io.StringIO):
        def __init__(self, sandbox, name):
            super().__init__()
            self.sandbox, self.name = sandbox, name

        def close(self):
            if not self.closed:
                self.sandbox.files[self.name] = self.getvalue().encode()
            super().close()

    def execute(*arguments, sandbox, **kwargs):
        if arguments[:2] == ("du", "-sb"):
            return SimpleNamespace(
                stdout=io.StringIO(f"{sum(map(len, sandbox.files.values()))} /workspace\n"),
                stderr=io.StringIO(),
                wait=lambda: 0,
            )
        if arguments[:2] == ("python", "-c"):
            if len(arguments) == 6:
                destination, temporary, digest = arguments[3:]
                data = sandbox.files.pop(temporary)
                assert hashlib.sha256(data).hexdigest() == digest
                sandbox.files[destination] = data
                return process({"path": destination, "sha256": digest, "bytes": len(data)})
            if len(arguments) == 3 and "kernel.json" in arguments[2]:
                sandbox.__dict__.pop("kernel", None)
                return process()
            raise AssertionError(f"Unimplemented sandbox command: {arguments!r}")
        assert arguments[:3] == ("python", "-m", "agent_runtime.session"), arguments
        operation = arguments[5]
        payload = json.loads(base64.b64decode(arguments[7])) if len(arguments) > 6 else None
        session_calls.append((sandbox.object_id, operation, deepcopy(payload)))
        if operation == "ensure":
            return process({"ready": True})
        if operation == "file":
            name = path(payload["path"])
            if payload["operation"] == "write":
                sandbox.files[name] = payload["text"].encode()
                return process({"path": payload["path"], "bytes": len(sandbox.files[name])})
            assert payload["operation"] == "read", payload
            if name not in sandbox.files:
                return process(error="FileNotFoundError")
            return process({"base64": base64.b64encode(sandbox.files[name]).decode()})
        assert operation == "request", operation
        if payload["operation"] == "health":
            return process({"active": None})
        assert payload["operation"] == "submit", payload

        def open_file(name, mode="r", *args, **options):
            name = path(name)
            if mode == "w":
                return WrittenFile(sandbox, name)
            assert mode == "r", mode
            if name not in sandbox.files:
                raise FileNotFoundError(name)
            return io.StringIO(sandbox.files[name].decode())

        namespace = sandbox.__dict__.setdefault("kernel", {"open": open_file})
        output = io.StringIO()
        error = None
        with redirect_stdout(output):
            try:
                exec(payload["code"], namespace)
            except Exception as exc:
                error = type(exc).__name__
        return process(
            {
                "state": "completed",
                "exit_code": int(error is not None),
                "output": output.getvalue(),
                "error": error,
            }
        )

    def snapshot_directory(sandbox, root, **kwargs):
        assert root == "/workspace"
        identity = f"im-source-snapshot-{len(snapshots)}"
        snapshots[identity] = deepcopy(sandbox.files)
        return SimpleNamespace(object_id=identity)

    def mount_image(sandbox, root, image):
        assert root == "/workspace"
        mounts.append((sandbox.object_id, image.object_id))
        sandbox.files.update(deepcopy(snapshots[image.object_id]))

    def terminate(sandbox, **kwargs):
        terminations.append(sandbox.object_id)
        if sandbox.object_id not in deferred:
            original_terminate(sandbox, **kwargs)

    fake_modal.sandbox_exec_handler = execute
    monkeypatch.setattr(modal.Sandbox, "snapshot_directory", snapshot_directory, raising=False)
    monkeypatch.setattr(modal.Sandbox, "mount_image", mount_image, raising=False)
    monkeypatch.setattr(modal.Sandbox, "terminate", terminate)
    return SimpleNamespace(
        cloud=fake_modal,
        snapshots=snapshots,
        mounts=mounts,
        terminations=terminations,
        deferred=deferred,
        calls=session_calls,
    )


def stage_private_source(lead, dataset, transfer):
    if transfer == "artifact":
        exported = invoke_native(
            lead,
            "platform",
            {
                "name": "export_data",
                "arguments": {"source_cell": str(dataset.source.pk), "format": "jsonl"},
            },
        )
        return invoke_native(
            lead,
            "fetch_artifact",
            {"artifact": exported.result["outputs"]["artifact"]["artifact"]},
        ).result["path"]
    arguments = {"cell": str(dataset.source.pk)}
    if transfer == "original":
        data = b"original-withheld-source-917223\n"
        identity = hashlib.sha256(data).hexdigest()
        original = paths.source_path(dataset.pk, identity)
        original.parent.mkdir(parents=True, exist_ok=True)
        original.write_bytes(data)
        dataset.source_spec = {
            **dataset.source_spec,
            "sources": [{"id": identity, "filename": "source.txt"}],
        }
        dataset.save(update_fields=["source_spec"])
        arguments["original"] = identity
    else:
        arguments["export"] = True
    return invoke_native(lead, "inspect_source", arguments).result["path"]


def copy_source_and_checkpoint(lead, staged_path):
    copied = invoke_native(
        lead,
        "workspace",
        {
            "operation": "python",
            "code": (
                f"with open({staged_path!r}) as source:\n"
                "    source_memory = source.read()\n"
                "with open('copied.jsonl', 'w') as destination:\n"
                "    destination.write(source_memory)\n"
                "print(source_memory)\n"
            ),
        },
    )
    assert copied.result["exit_code"] == 0
    invoke_native(
        lead,
        "workspace",
        {"operation": "write", "path": "notes.md", "text": "Source inspection complete"},
    )
    lead.refresh_from_db()
    assert lead.workspace.get("snapshot"), lead.workspace
    return deepcopy(lead.workspace["snapshot"])


def assert_restored_source_workspace(lead, expected):
    checked = invoke_native(
        lead,
        "workspace",
        {
            "operation": "python",
            "code": (
                "print('source_memory' in globals())\n"
                "with open('copied.jsonl') as source:\n"
                "    print(source.read())\n"
            ),
        },
    )
    assert checked.result["exit_code"] == 0, checked.result
    assert checked.result["output"] == "False\n" + expected.decode() + "\n"


@pytest.mark.covers("privacy")
@pytest.mark.parametrize("transfer", ["export", "original", "artifact"])
@pytest.mark.parametrize("provided_sandbox", [False, True])
def test_partitioning_retains_published_workspace_bytes_and_memory(
    research_source_sandbox, transfer, provided_sandbox
):
    provider = research_source_sandbox
    dataset, user = passengers()
    owner = preparation_research(dataset, user, key="published-workspace-source")
    lead = owner.agents.get(parent__isnull=True)
    staged_path = stage_private_source(lead, dataset, transfer)
    before = invoke_native(lead, "workspace", {"operation": "read", "path": staged_path})
    snapshot = copy_source_and_checkpoint(lead, staged_path)
    old = provider.cloud.sandboxes[lead.workspace["sandbox"]]
    assert old.files["/workspace/work/copied.jsonl"] == old.files[staged_path]
    assert provider.snapshots[snapshot["image"]][staged_path] == old.files[staged_path]
    seal_preparation_source(dataset, "partition-workspace-source")
    read = research.claim(
        lead, "published-workspace-read", "workspace", {"operation": "read", "path": staged_path}
    )
    result = research_tools.invoke(read, workspace=old if provided_sandbox else None)
    research.complete(read, result, cost=0)
    assert result["text"] == before.result["text"]
    memory = invoke_native(
        lead, "workspace", {"operation": "python", "code": "print(source_memory)"}
    )
    assert memory.result["output"] == old.files[staged_path].decode() + "\n"
    lead.refresh_from_db()
    assert lead.workspace["sandbox"] == old.object_id
    assert lead.workspace["snapshot"] == snapshot
    assert old.poll() is None
    assert provider.terminations == [] and provider.mounts == []


@pytest.mark.covers("privacy")
def test_network_change_waits_for_confirmed_workspace_exit_and_restores_snapshot(
    research_source_sandbox,
):
    provider = research_source_sandbox
    dataset, user = passengers()
    owner = preparation_research(dataset, user, key="workspace-unknown-exit")
    lead = owner.agents.get(parent__isnull=True)
    staged_path = stage_private_source(lead, dataset, "export")
    copy_source_and_checkpoint(lead, staged_path)
    old = provider.cloud.sandboxes[lead.workspace["sandbox"]]
    saved = deepcopy(lead.workspace)
    expected = old.files[staged_path]
    provider.deferred.add(old.object_id)
    request = invoke_native(
        lead, "request_access", {"purpose": "Read project documentation", "hosts": ["example.org"]}
    )
    research_questions.answer(
        owner, question=request.pk, text="Approved", approved=True, request_key="network-change"
    )
    assert research_agent.prepare(lead)
    previous_calls = len(provider.calls)
    for index, arguments in enumerate(
        [
            {"operation": "read", "path": "copied.jsonl"},
            {"operation": "python", "code": "print(source_memory)"},
        ]
    ):
        action = research.claim(lead, f"await-workspace-exit-{index}", "workspace", arguments)
        with pytest.raises(InputValidationError, match="termination is still unconfirmed"):
            research_tools.invoke(action)
        lead.refresh_from_db()
        assert all(lead.workspace[key] == saved[key] for key in ("sandbox", "lease", "generation"))
        assert provider.snapshots[lead.workspace["snapshot"]["image"]][staged_path] == expected
        assert old.poll() is None
        assert len(provider.cloud.sandboxes) == 1
    assert not [
        call
        for call in provider.calls[previous_calls:]
        if call[2] and call[2].get("operation") != "health"
    ]
    assert old.object_id in provider.terminations
    snapshot = deepcopy(lead.workspace["snapshot"])
    old.exit_code = 137
    provider.deferred.remove(old.object_id)
    assert_restored_source_workspace(lead, expected)
    lead.refresh_from_db()
    assert lead.workspace["sandbox"] != old.object_id
    assert lead.workspace["generation"] != saved["generation"]
    assert provider.mounts == [(lead.workspace["sandbox"], snapshot["image"])]
    assert len(provider.cloud.sandboxes) == 2


@pytest.mark.covers("privacy")
def test_expired_workspace_restores_published_files_with_a_fresh_python_session(
    research_source_sandbox,
):
    provider = research_source_sandbox
    dataset, user = passengers()
    owner = preparation_research(dataset, user, key="workspace-expired")
    lead = owner.agents.get(parent__isnull=True)
    staged_path = stage_private_source(lead, dataset, "export")
    snapshot = copy_source_and_checkpoint(lead, staged_path)
    old = provider.cloud.sandboxes[lead.workspace["sandbox"]]
    expected = old.files[staged_path]
    old.exit_code = 0
    seal_preparation_source(dataset, "partition-expired-workspace-source")
    assert_restored_source_workspace(lead, expected)
    lead.refresh_from_db()
    assert lead.workspace["sandbox"] != old.object_id
    assert provider.mounts == [(lead.workspace["sandbox"], snapshot["image"])]
    assert len(provider.cloud.sandboxes) == 2


@pytest.mark.covers("privacy")
def test_concurrent_native_partition_publication_never_exposes_partial_training_rows():
    dataset, user = passengers()
    owner = preparation_research(dataset, user, key="concurrent-partitions")
    plans = []
    for key, role in (("first", "train"), ("second", "final")):
        submitted = preparation_platform_call(
            owner,
            key,
            "create_data_partition",
            name=key,
            source_cell=str(dataset.source.pk),
            recipe={
                "seed": 7,
                "fractions": {"train": 0.5, "final": 0.5},
                "holdouts": [{"field": "PassengerId", "values": [100], "role": role}],
            },
        )
        plans.append(DataPartitionPlan.objects.get(pk=submitted["workflow"]["id"]))
    first, second = plans
    first_train_written, release_first, contender_entered = Event(), Event(), Event()
    contender_boundary = []

    def build_first():
        close_old_connections()
        train_inserted = False

        def observe(execute, sql, params, many, context):
            nonlocal train_inserted
            if train_inserted and not first_train_written.is_set() and sql.startswith("SELECT"):
                first_train_written.set()
                assert release_first.wait(20), "The first partition was not released"
            result = execute(sql, params, many, context)
            if sql.startswith(f'INSERT INTO "{DataPartitionMember._meta.db_table}"'):
                train_inserted = train_inserted or "train" in params
            return result

        try:
            with connection.execute_wrapper(observe):
                partition_plans.build(first.pk)
        finally:
            connections.close_all()

    def build_second():
        close_old_connections()

        def observe(execute, sql, params, many, context):
            # A serialized publisher waits before its project lock. The old publisher
            # reaches a final insert while the first plan's train member is visible.
            if (
                not contender_entered.is_set()
                and "FOR UPDATE" in sql
                and f'"{Project._meta.db_table}"' in sql
                and f'"{DataPartitionPlan._meta.db_table}"' not in sql
            ):
                contender_boundary.append("project")
                contender_entered.set()
            result = execute(sql, params, many, context)
            if (
                not contender_entered.is_set()
                and sql.startswith(f'INSERT INTO "{DataPartitionMember._meta.db_table}"')
                and "final" in params
            ):
                contender_boundary.append("final")
                contender_entered.set()
            return result

        try:
            with connection.execute_wrapper(observe):
                partition_plans.build(second.pk)
        finally:
            connections.close_all()

    with ThreadPoolExecutor(max_workers=2) as pool:
        first_future = pool.submit(build_first)
        second_future = None
        try:
            assert first_train_written.wait(20), "The first partition did not reach publication"
            second_future = pool.submit(build_second)
            assert contender_entered.wait(20), "The competing partition did not reach publication"
            if contender_boundary == ["final"]:
                second_future.result(timeout=30)
            visible = list(first.members.select_related("cell__dataset"))
        finally:
            release_first.set()
        first_future.result(timeout=30)
        if second_future is not None:
            second_future.result(timeout=30)

    assert visible == []
    first.refresh_from_db()
    second.refresh_from_db()
    assert first.state == "completed", first.error
    assert second.state == "failed"
    assert not second.members.exists()
    final = first.members.select_related("cell__dataset").get(role="final").cell
    held = keys(final)
    train = first.members.select_related("cell__dataset").get(role="train").cell
    assert not keys(train) & held
    assert research_tools.source_cell(owner, train.pk) == train


def source_with_private_value(key):
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name=key)
    hidden = "withheld-mediated-source-517239"
    land.land_rows(dataset, [{**row, "Sex": hidden} for row in PASSENGERS], user=user)
    dataset.refresh_from_db()
    owner = preparation_research(dataset, user, key=key)
    return dataset, owner, owner.agents.get(parent__isnull=True), hidden


@pytest.mark.covers("privacy")
def test_cached_workspace_output_and_artifacts_retain_published_source_provenance(
    research_source_sandbox,
):
    dataset, owner, lead, hidden = source_with_private_value("cached-workspace-source")
    staged_path = stage_private_source(lead, dataset, "export")
    printed = invoke_native(
        lead,
        "workspace",
        {
            "operation": "python",
            "code": (
                f"with open({staged_path!r}) as source:\n"
                "    source_memory = source.read()\n"
                "with open('retained-copy.jsonl', 'w') as destination:\n"
                "    destination.write(source_memory)\n"
                "print(source_memory)"
            ),
        },
    )
    assert hidden in printed.result["output"]
    retained = deepcopy(printed.result)
    cached = invoke_native(lead, "inspect_action", {"action": str(printed.pk), "limit": 32000})
    assert hidden in cached.result["text"]
    copied = invoke_native(
        lead,
        "retain_artifact",
        {
            "path": "retained-copy.jsonl",
            "title": "Retained source copy",
            "kind": "data",
            "metadata": {"source_cells": []},
        },
    )
    artifact_id = copied.result["id"]
    artifact_page = invoke_native(lead, "inspect_action", {"action": artifact_id, "limit": 32000})
    assert hidden in artifact_page.result["text"]
    helper = specialist(lead)
    staged_copy = invoke_native(helper, "fetch_artifact", {"artifact": artifact_id})
    assert staged_copy.result["bytes"] > 0
    artifact = research_evidence.artifacts(owner).get(pk=artifact_id)
    assert str(dataset.source.pk) in artifact.metadata["source_cells"]
    assert str(dataset.source.pk) in research_evidence.artifact_sources(artifact)
    retained_artifact = (deepcopy(artifact.metadata), artifact.sha256, artifact.size)
    with artifact.file.open("rb") as source:
        artifact_bytes = source.read()
    seal_preparation_source(dataset, "partition-cached-workspace-source")
    read = invoke_native(lead, "workspace", {"operation": "read", "path": staged_path})
    assert hidden in read.result["text"]
    fetched = invoke_native(lead, "fetch_artifact", {"artifact": artifact_id})
    assert fetched.result["bytes"] == staged_copy.result["bytes"]
    helper_read = invoke_native(
        helper, "workspace", {"operation": "read", "path": staged_copy.result["path"]}
    )
    assert hidden in helper_read.result["text"]
    assert research_evidence.artifacts(owner).filter(pk=artifact_id).exists()
    for action in (printed, cached, artifact_page):
        reopened = invoke_native(lead, "inspect_action", {"action": str(action.pk), "limit": 32000})
        assert hidden in json.dumps(reopened.result)
    history = invoke_native(lead, "history", {"tool": "workspace", "query": hidden})
    assert history.result["actions"]
    artifact.refresh_from_db()
    assert (artifact.metadata, artifact.sha256, artifact.size) == retained_artifact
    with artifact.file.open("rb") as source:
        assert source.read() == artifact_bytes
    printed.refresh_from_db()
    assert printed.result == retained


def retain_source_tool_history(author, action):
    author.messages = [
        {"role": "system", "content": "Retained system"},
        {
            "role": "assistant",
            "tool_calls": [
                {
                    "id": action.request_key,
                    "type": "function",
                    "function": {
                        "name": action.tool,
                        "arguments": json.dumps(action.arguments),
                    },
                }
            ],
        },
        {
            "role": "tool",
            "tool_call_id": action.request_key,
            "content": json.dumps(research_agent.tool_observation(action)),
        },
    ]
    author.save(update_fields=["messages"])


@pytest.mark.covers("privacy")
def test_completed_workspace_history_does_not_block_new_input_or_execution(
    research_source_sandbox,
):
    dataset, user = passengers()
    owner = research.create(
        dataset.project,
        user=user,
        request_key="completed-workspace-history",
        objective="Inspect the public source contract",
        task={"deliverable": "Source audit"},
        context_roots=[f"cell:{dataset.source.pk}"],
        budget={},
    )
    lead = owner.agents.get(parent__isnull=True)
    initial = invoke_native(
        lead, "workspace", {"operation": "python", "code": "print('Public workspace ready')"}
    )
    assert initial.result["exit_code"] == 0
    lead.refresh_from_db()
    workspace = deepcopy(lead.workspace)
    completed = ResearchAction.objects.bulk_create(
        [
            ResearchAction(
                agent=lead,
                request_key=f"earlier-completed-python-{index}",
                fingerprint=initial.fingerprint,
                tool=initial.tool,
                arguments=initial.arguments,
                state="completed",
                result=initial.result,
                started_at=initial.started_at,
                completed_at=initial.completed_at,
                cost_usd=0,
            )
            for index in range(201)
        ]
    )
    ResearchEvent.objects.bulk_create(
        [
            ResearchEvent(
                assignment=owner,
                agent=lead,
                kind=kind,
                payload={
                    "action": str(action.pk),
                    "model": None,
                    "source_cells": [],
                    **(
                        {"sandbox": workspace["sandbox"], "lease": workspace["lease"]}
                        if kind == "workspace_inputs"
                        else {}
                    ),
                },
            )
            for action in completed
            for kind in ("authoring_sources", "workspace_inputs")
        ]
    )

    staged = invoke_native(lead, "inspect_source", {"cell": str(dataset.source.pk), "export": True})
    result = invoke_native(
        lead,
        "workspace",
        {
            "operation": "python",
            "code": (
                f"with open({staged.result['path']!r}) as source:\n"
                "    print(bool(source.read()))\n"
                "print('Public execution after retained history')"
            ),
        },
    )
    assert result.result["exit_code"] == 0
    assert result.result["output"].splitlines() == [
        "True",
        "Public execution after retained history",
    ]
    lead.refresh_from_db()
    assert lead.workspace["sandbox"] == workspace["sandbox"]
    assert lead.workspace["lease"] == workspace["lease"]


@pytest.mark.covers("privacy")
@pytest.mark.parametrize("result_hint", ["missing", "empty"])
def test_historical_workspace_literals_require_complete_source_provenance(
    research_source_sandbox, result_hint
):
    dataset, owner, author, hidden = source_with_private_value("historical-workspace-literal")
    recipient = specialist(author, "historical-workspace-reader")
    public_author = specialist(author, "proven-public-workspace-author")
    public = "The public interface remains readable"
    public_action = invoke_native(
        public_author, "workspace", {"operation": "python", "code": f"print({public!r})"}
    )
    invoke_native(author, "inspect_source", {"cell": str(dataset.source.pk), "limit": 1})
    private_action = invoke_native(
        author, "workspace", {"operation": "python", "code": f"print({hidden!r})"}
    )
    assert hidden in private_action.result["output"]

    # Before immutable receipts, bounded reads did not enter staged-input hints;
    # delayed collectors replaced the result and removed even those hints.
    owner.events.filter(
        kind__in=["authoring_sources", "workspace_inputs"],
        payload__action=str(private_action.pk),
    ).delete()
    private_action.result.pop("source_cells", None)
    if result_hint == "empty":
        private_action.result["source_cells"] = []
    private_action.save(update_fields=["result"])
    raw_arguments, raw_result = deepcopy(private_action.arguments), deepcopy(private_action.result)
    cached = invoke_native(
        recipient, "inspect_action", {"action": str(private_action.pk), "limit": 32000}
    )
    assert hidden in cached.result["text"]
    seal_preparation_source(dataset, "seal-historical-workspace-literal")

    for action in (private_action, cached):
        reopened = invoke_native(
            recipient, "inspect_action", {"action": str(action.pk), "limit": 32000}
        )
        assert hidden not in json.dumps(reopened.result)
        assert hidden not in json.dumps(research_agent.tool_content(action))
    history = invoke_native(recipient, "history", {"tool": "workspace", "query": hidden})
    assert history.result["actions"] == []
    readable = invoke_native(
        recipient, "inspect_action", {"action": str(public_action.pk), "limit": 32000}
    )
    assert public in readable.result["text"]
    assert public in json.dumps(research_agent.tool_content(public_action))
    private_action.refresh_from_db()
    assert private_action.arguments == raw_arguments
    assert private_action.result == raw_result


@pytest.mark.covers("privacy")
def test_historical_context_state_page_does_not_inherit_private_notes():
    dataset, owner, lead, hidden = source_with_private_value("safe-graph-state-source")
    author = specialist(lead, "safe-state-author")
    reader = specialist(lead, "safe-state-reader")
    invoke_native(author, "inspect_source", {"cell": str(dataset.source.pk), "limit": 1})
    invoke_native(author, "remember", {"text": hidden})
    state = invoke_native(
        reader,
        "explore_context",
        {
            "operation": "read",
            "reference": f"research_agent:{author.pk}",
            "path": "/state",
        },
    )
    state.result.pop("note_read", None)
    state.result.pop("delegation_read", None)
    state.save(update_fields=["result"])
    original = deepcopy(state.result)
    seal_preparation_source(dataset, "seal-safe-graph-state-source")

    assert research_evidence.action_result(owner, state) == original
    assert research_agent.tool_observation(state)["data"]["content"] == original["content"]
    author.refresh_from_db()
    assert author.notes == hidden