The platform for continuously improving AI agents.
import base64
import io
import json
import uuid
import zipfile
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier, Event
from types import SimpleNamespace
from unittest.mock import patch
import modal
import pytest
from django.db import close_old_connections
from fakes.responses_api import ResponsesAPI, response
from mcp_fixtures import call_tool, mcp_context
from rest_framework.test import APIClient
from test_research_experiments import setup_experiment, start
from test_transform_spec import PASSENGERS, SPEC
from test_workshop_session import session as session
from agent_runtime.session import ensure, file_request, request
from overbae.core.errors import DatasetError, InputValidationError
from overbae.models import Dataset, DatasetPipelineRun, User, WorkshopChatEvent
from overbae.services import research, research_tools, research_workshop
from overbae.services.datasets import (
land,
partition_plans,
pipeline_runner,
preparation,
store,
workbench,
)
from overbae.services.workshop_agent import agent, conversation, lifecycle, model_stream, sandbox
from overbae.services.workshop_agent.contracts import SendMessage, StartTask
pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("work-once")]
@pytest.fixture(autouse=True)
def workers():
"""The interactive worker, run in place: a queued pipeline run executes when it is sent."""
with (
patch("overbae.tasks.research.dispatch_wakes.delay"),
patch(
"overbae.tasks.datasets.execute_pipeline.delay",
side_effect=lambda run: workbench.execute(
run, script_executor=pipeline_runner.execute_script
),
),
):
yield
def passengers(objective="Prepare this data to train a model that predicts survival"):
grant = mcp_context(["read", "write"])
dataset = Dataset.objects.create(project=grant.project, name="Passengers")
land.land_rows(dataset, PASSENGERS, user=grant.user)
task = lifecycle.start(
grant, StartTask(dataset=dataset.pk, objective=objective, request_key="initial")
)
return grant, task
def drive(task, *replies):
"""Run the task against scripted model replies and return what the model was sent."""
with (
ResponsesAPI(*replies) as api,
model_stream.ModelStream(url=api.url, api_key="test", waits=(0,)) as model,
):
result = agent.run(task.pk, model)
task.refresh_from_db()
return result, api.requests
def messages(task):
latest = {}
for message in task.chat_events.order_by("pk").values_list("message", flat=True):
latest[message["id"]] = message
return latest
def prepared(partition=None, spec=SPEC):
arguments = {"summary": "Preparing survival decisions", "name": "Survival", "spec": spec}
if partition is not None:
arguments["partition"] = partition
return response("prepare", arguments, text="Survived is the target; tickets group rows.")
def finish(outcome, text):
return response("finish", {"outcome": outcome, "text": text})
@pytest.fixture
def local_sandbox(fake_modal, session):
"""A Modal sandbox whose kernel and files are a local session directory."""
def transport(*args, sandbox, **kwargs):
try:
if args[:2] == ("python", "-c"):
destination, temporary = args[3], args[4]
target = session / destination.removeprefix("/workspace/")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(sandbox.files.pop(temporary))
output = json.dumps({"path": destination})
else:
assert args[:3] == ("python", "-m", "agent_runtime.session")
operation = args[5]
payload = json.loads(base64.b64decode(args[7])) if len(args) > 6 else None
output = json.dumps(
ensure(session)
if operation == "ensure"
else file_request(session, payload)
if operation == "file"
else request(session, payload)
)
return SimpleNamespace(stdout=io.StringIO(output), stderr=io.StringIO(), wait=lambda: 0)
except Exception as exc:
return SimpleNamespace(
stdout=io.StringIO(), stderr=io.StringIO(str(exc)), wait=lambda: 1
)
fake_modal.sandbox_exec_handler = transport
return fake_modal, session
def test_a_spec_is_prepared_partitioned_and_published_in_two_model_requests():
_, task = passengers()
result, requests = drive(task, prepared(partition={}), finish("complete", "Published 40 rows."))
assert result["state"] == "completed" and len(requests) == 2
# The first request already holds the measured profile: nothing is read to choose a spec.
first = json.loads(requests[0]["input"][0]["content"])
assert first["source"]["profile"]["columns"]["Survived"]["values"]
record = research_workshop.describe(task)["published"]
assert record["partition"]["counts"].keys() == {"train", "development", "final"}
assert record["partition"]["recipe"]["group_by"] == ["ticket_group"]
assert task.preparation.state == "completed"
shown = messages(task)
assert shown["action:0"]["status"] == "completed" and shown["action:0"]["tool"] == "prepare"
assert shown["publication:0"]["cells"] and shown["result:2"]["text"] == "Published 40 rows."
assert [cell["id"] for cell in shown["result:2"]["cells"]] == task.result["outputs"]
# The tool result told the model what the platform verified.
returned = json.loads(requests[1]["input"][-1]["output"])
assert returned["checks"]["failed"] == [] and returned["rows"] == 40
@pytest.mark.parametrize("reference_source", [False, True])
def test_benchmark_publication_preserves_the_training_dataset(local_sandbox, reference_source):
_, directory = local_sandbox
grant = mcp_context(["read", "write"])
dataset = Dataset.objects.create(
project=grant.project, name="Training", intent="train", train_format="sft"
)
records = [
{
"input": {"messages": [{"role": "user", "content": "Question"}]},
"expected_output": "Answer",
"messages": [
{"role": "user", "content": "Question"},
{"role": "assistant", "content": "Answer"},
],
}
]
land.land_rows(dataset, records, user=grant.user)
dataset.refresh_from_db()
source = dataset.active_cell
selected = source
if reference_source:
reference = Dataset.objects.create(project=grant.project, name="Held-out source")
land.land_rows(
reference,
[{"input": "Held-out question", "expected_output": "Held-out answer"}],
user=grant.user,
)
reference.refresh_from_db()
selected = reference.active_cell
task = lifecycle.start(
grant,
StartTask(dataset=dataset.pk, objective="Prepare evaluation data", request_key="eval"),
)
with zipfile.ZipFile(directory / "work" / "benchmark.zip", "w") as bundle:
bundle.writestr(
"manifest.json",
json.dumps(
{
"version": 1,
"runtime": "platform",
"steps": [
{"name": "Benchmark", "entrypoint": "copy.py", "consumer": "model_eval"}
],
}
),
)
bundle.writestr(
"copy.py", "import shutil, sys\nshutil.copyfile(sys.argv[1], sys.argv[2])\n"
)
result, requests = drive(
task,
response(
"publish_package",
{
"name": "Benchmark",
"path": "benchmark.zip",
"mode": "publish",
**({"source_cell": str(selected.pk)} if reference_source else {}),
},
),
finish("complete", "Published evaluation data."),
)
assert result["state"] == "completed", requests[1]["input"][-1]
publication = research_workshop.describe(task)["published"]
output = Dataset.objects.get(pk=publication["prepared"]["dataset"]["id"])
dataset.refresh_from_db()
assert output.pk != dataset.pk and output.intent == "eval"
assert publication["prepared"]["rows"] == 1
assert dataset.intent == "train" and dataset.active_cell.pk == source.pk
assert (
DatasetPipelineRun.objects.get(output_id=publication["prepared"]["cell"]).source_id
== selected.pk
)
graph = preparation.with_task_cells(preparation.describe(dataset), dataset)
assert {str(source.pk), publication["prepared"]["cell"]} <= {
str(node["cell"].pk) for node in graph["nodes"]
}
assert any(
edge["source"] == str(selected.pk) and edge["target"] == publication["prepared"]["cell"]
for edge in graph["edges"]
)
def test_creator_revocation_after_claim_prevents_workshop_publication():
grant, task = passengers()
action, _ = lifecycle.claim(task.pk, 0, "prepare", {"name": "Survival", "spec": SPEC})
task = lifecycle.get(task.pk)
source = task.dataset.active_cell
turn = agent.Turn(task, source, {"turn": 0, "publications": []}, action)
User.objects.filter(pk=grant.user.pk).update(is_active=False)
with pytest.raises(DatasetError, match="revoked"):
turn.prepare("Survival", SPEC)
assert not DatasetPipelineRun.objects.filter(dataset=task.dataset).exists()
task.dataset.refresh_from_db()
assert task.dataset.active_cell.pk == source.pk
def test_project_source_read_pins_full_bytes_for_later_workshop_calls(local_sandbox):
_, directory = local_sandbox
grant, task = passengers("Compare the supplied sources")
reference = Dataset.objects.create(project=grant.project, name="Reference")
land.land_rows(reference, [{"value": number} for number in range(75)], user=grant.user)
reference.refresh_from_db()
cell = reference.active_cell
action, _ = lifecycle.claim(task.pk, 0, "read_rows", {"cell": str(cell.pk)})
task = lifecycle.get(task.pk)
turn = agent.Turn(task, task.dataset.active_cell, {"turn": 0, "publications": []}, action)
result = turn.read_rows(str(cell.pk), limit=1)
assert len(result["rows"]) == 1 and result["next_offset"] == 1
cell.refresh_from_db()
assert cell.used_at is not None
turn.read_rows(str(cell.pk), offset=1)
task.refresh_from_db()
assert len(task.context_sources) == 1
restored = agent.Turn(task, task.dataset.active_cell, {"turn": 1}, action)
restored.workspace()
staged = directory / result["path"].removeprefix("/workspace/")
assert [row["value"] for row in store.head(staged, 75)] == list(range(75))
assert str(cell.pk) in conversation.source_cells(task)
task.desired_state = "cancelled"
task.save(update_fields=["desired_state"])
with pytest.raises(DatasetError, match="not running"):
restored.read_rows(str(cell.pk))
@pytest.mark.covers("tenancy")
def test_project_source_read_rejects_foreign_and_unpublished_cells():
_, task = passengers()
_, foreign_task = passengers()
unreadable = task.dataset.cells.create(position=10, state="error")
for cell in (foreign_task.dataset.active_cell, unreadable):
with pytest.raises((DatasetError, InputValidationError)):
lifecycle.retain_source(task, cell.pk)
task.refresh_from_db()
assert task.context_sources == []
def test_a_spec_the_source_does_not_fit_is_returned_to_the_model_and_publishes_nothing():
_, task = passengers()
broken = json.loads(json.dumps(SPEC))
broken["inputs"].append({"name": "leak", "sql": '"Outcome"'})
result, requests = drive(
task,
prepared(spec=broken),
finish("complete", "Done."),
finish("blocked", "Outcome is recorded with the target. Which inputs may be used?"),
)
returned = json.loads(requests[1]["input"][-1]["output"])
assert "inputs.leak" in json.dumps(returned)
assert messages(task)["action:0"]["status"] == "failed"
# Nothing was published, so the task is told it cannot end as complete.
assert "Nothing was published" in json.loads(requests[2]["input"][-1]["output"])["error"]
assert result["state"] == "blocked" and not task.dataset.pipeline_runs.exists()
assert task.preparation.state == "paused"
def test_a_reply_without_a_tool_call_answers_and_ends_the_task():
_, task = passengers("How many passengers survived?")
reply = response(text="20 of 40 passengers survived.")
reply["output"] = reply["output"][:2]
result, requests = drive(task, reply)
assert result["state"] == "completed" and len(requests) == 1
assert task.result["reason"] == "20 of 40 passengers survived."
assert messages(task)["model:0"]["text"] == "20 of 40 passengers survived."
assert not any(key.startswith("result:") for key in messages(task))
assert task.preparation.state == "cancelled"
@pytest.mark.covers("sandbox")
def test_code_runs_in_the_task_sandbox_which_ends_with_the_task(local_sandbox):
cloud, directory = local_sandbox
_, task = passengers("How many rows are there?")
code = f"import pandas\nprint(len(pandas.read_parquet('{directory}/inputs/source.parquet')))"
result, requests = drive(
task,
response("python", {"summary": "Counting rows", "code": code}),
finish("answered", "There are 40 rows."),
)
assert result["state"] == "completed"
[sandbox] = cloud.sandboxes.values()
assert sandbox.options["block_network"] is True and sandbox.exit_code is not None
shown = messages(task)["action:0"]
assert shown["code"] == code and shown["status"] == "completed"
assert "40" in json.loads(requests[1]["input"][-1]["output"])["output"]
@pytest.mark.covers("recovery")
def test_an_unrecoverable_model_request_is_not_rebuilt_or_sent_again():
_, task = passengers()
action, _ = lifecycle.claim(task.pk, 1, "reason", {"turn": 0, "payload_sha256": "lost"})
with (
ResponsesAPI() as api,
model_stream.ModelStream(url=api.url, api_key="test", waits=(0,)) as model,
):
result = agent.reason(task, {"turn": 0, "items": []}, model)
assert result == {"unknown": True}
assert not api.requests
action.refresh_from_db()
assert action.state == "unknown"
assert action.result["error"] == "request_not_retained"
@pytest.mark.covers("recovery")
def test_an_unfinished_model_request_keeps_its_admitted_inputs_across_reload():
_, task = passengers()
body = {
"model": model_stream.configured_model(),
"instructions": "Use the admitted contract.",
"input": [{"role": "user", "content": "What is the target?"}],
"tools": [],
"parallel_tool_calls": False,
}
lifecycle.claim(task.pk, 1, "reason", {"turn": 0, "request": body})
with (
ResponsesAPI(finish("answered", "Survival.")) as api,
model_stream.ModelStream(url=api.url, api_key="test", waits=(0,)) as model,
):
state = {"turn": 0, "items": [{"role": "user", "content": "Changed transcript"}]}
result = agent.reason(task, state, model)
assert agent.reason(task, state, model) == result
assert len(api.requests) == 1
assert api.requests[0]["input"] == body["input"]
assert api.requests[0]["instructions"] == body["instructions"]
assert api.requests[0]["tools"] == []
@pytest.mark.covers("recovery")
def test_a_restarted_worker_continues_the_transcript_without_asking_or_publishing_again():
_, task = passengers()
transcript = agent.transcript_path(task)
pause = response("contract", {"topic": "decision_train"})
def then_pause(send, request):
lifecycle.control(task.project, task.pk, "pause")
return pause
result, _ = drive(task, prepared(), then_pause)
assert result["state"] == "paused" and task.dataset.pipeline_runs.count() == 1
# The worker died before it saved what the first turn did.
saved = json.loads(transcript.read_text())
saved.update(turn=0, items=saved["items"][:1], publications=[], events=[])
saved["items"][0]["content"] += "\n"
transcript.write_text(json.dumps(saved))
lifecycle.control(task.project, task.pk, "resume")
result, requests = drive(task, finish("complete", "Done."))
assert result["state"] == "completed", task.result
assert task.dataset.pipeline_runs.count() == 1
assert len(requests) == 1 and requests[0]["input"][-1]["type"] == "function_call_output"
def test_a_message_sent_while_the_task_works_reaches_the_next_request():
grant, task = passengers()
conversation.send(
grant,
SendMessage(
dataset=task.dataset_id, text="Leave Sex out of the inputs", request_key="later"
),
)
result, requests = drive(task, finish("blocked", "Which column is the target?"))
assert requests[0]["input"][-1] == {"role": "user", "content": "Leave Sex out of the inputs"}
assert messages(task)["user:later"]["status"] == "completed"
assert result["state"] == "blocked" and task.preparation.state == "paused"
def test_a_message_that_arrives_as_the_reply_is_written_is_answered_before_the_task_ends():
grant, task = passengers()
def as_it_ends(send, request):
conversation.send(
grant,
SendMessage(dataset=task.dataset_id, text="Also group by Ticket", request_key="late"),
)
return finish("blocked", "Which column is the target?")
result, requests = drive(task, as_it_ends, finish("blocked", "Understood. Which target?"))
assert len(requests) == 2
assert requests[1]["input"][-1] == {"role": "user", "content": "Also group by Ticket"}
assert result["state"] == "blocked" and task.result["reason"] == "Understood. Which target?"
def test_a_cancelled_task_settles_without_a_model_request():
grant, task = passengers()
lifecycle.control(grant.project, task.pk, "cancel")
result, requests = drive(task)
assert result["state"] == "cancelled" and requests == []
assert task.preparation.state == "cancelled"
@pytest.mark.covers("recovery")
def test_a_provider_that_never_answers_leaves_the_task_blocked_and_says_so():
_, task = passengers()
result, _ = drive(task, 503, 503, 503, 503, 503)
assert result["state"] == "blocked"
assert research_workshop.unanswered(task)
assert WorkshopChatEvent.objects.filter(task=task, message__role="assistant").exists()
@pytest.mark.covers("lineage")
def test_a_follow_up_prepares_the_raw_version_again_and_is_shown_the_published_spec():
grant, task = passengers()
drive(task, prepared(), finish("complete", "Published."))
raw = task.dataset.source
task.dataset.refresh_from_db()
assert task.dataset.active_cell.pk != raw.pk
later = conversation.send(
grant, SendMessage(dataset=task.dataset_id, text="Leave age out", request_key="again")
)
assert later.pk != task.pk
changed = json.loads(json.dumps(SPEC))
changed["inputs"] = [item for item in SPEC["inputs"] if item["name"] != "age_years"]
changed["excluded"].append({"column": "Age", "reason": "unusable"})
result, requests = drive(later, prepared(spec=changed), finish("complete", "Published again."))
assert result["state"] == "completed", later.result
first = json.loads(requests[0]["input"][0]["content"])
assert first["source"]["cell"] == str(raw.pk)
assert first["published_preparation"]["spec"]["target"]["column"] == "Survived"
assert [item["text"] for item in first["conversation"] if item["role"] == "assistant"]
assert research_workshop.pinned_source(later) == str(raw.pk)
def test_request_retry_preserves_task_and_changed_objective_conflicts():
grant = mcp_context(["read", "write"])
dataset = Dataset.objects.create(project=grant.project, name="Source", state="ready")
payload = StartTask(dataset=dataset.pk, objective="Prepare this dataset", request_key="prepare")
task = lifecycle.start(grant, payload)
assert lifecycle.start(grant, payload).pk == task.pk
with pytest.raises(DatasetError, match="conflicts"):
lifecycle.start(grant, payload.model_copy(update={"objective": "Different objective"}))
@pytest.mark.covers("tenancy")
def test_context_selection_rejects_foreign_missing_unreadable_and_repeated_datasets():
grant = mcp_context(["read", "write"])
dataset = Dataset.objects.create(project=grant.project, name="Source", state="ready")
payload = StartTask(dataset=dataset.pk, objective="Prepare this dataset", request_key="prepare")
foreign = Dataset.objects.create(project=mcp_context(["read", "write"]).project)
unreadable = Dataset.objects.create(project=grant.project)
for selection in (
[foreign.pk],
[uuid.uuid4()],
[unreadable.pk],
[payload.dataset],
[unreadable.pk, unreadable.pk],
):
result = call_tool(
"start_workshop_task",
payload.model_copy(update={"context_datasets": selection}).model_dump(mode="json"),
grant,
)
assert result.isError
assert not grant.project.workshoptask_set.exists()
def test_a_reply_to_a_task_that_asked_continues_that_task():
grant, task = passengers()
drive(task, finish("blocked", "Which column is the target?"))
assert task.state == "blocked" and task.preparation.state == "paused"
same = conversation.send(
grant, SendMessage(dataset=task.dataset_id, text="Survived", request_key="answer")
)
assert same.pk == task.pk
task.refresh_from_db()
assert task.state == "queued" and task.desired_state == "running" and not task.dispatched_at
result, requests = drive(task, prepared(), finish("complete", "Published."))
assert result["state"] == "completed", task.result
assert requests[0]["input"][-1] == {"role": "user", "content": "Survived"}
# The model is shown the question it asked before the answer to it.
assert any(item.get("type") == "function_call" for item in requests[0]["input"])
assert task.preparation.state == "completed"
@pytest.mark.covers("recovery")
def test_a_task_the_provider_did_not_answer_asks_again_when_it_is_resumed():
grant, task = passengers()
drive(task, 503, 503, 503, 503, 503)
assert task.state == "blocked"
lifecycle.control(grant.project, task.pk, "resume")
result, requests = drive(task, prepared(), finish("complete", "Published."))
assert result["state"] == "completed", task.result
assert len(requests) == 2 and task.used_tokens is not None
@pytest.mark.covers("tenancy")
def test_console_task_start_retry_and_cross_project_control():
grant = mcp_context(["read", "write"])
dataset = Dataset.objects.create(project=grant.project, name="Source", state="ready")
client = APIClient()
client.force_authenticate(grant.user, grant.token)
body = {
"project": str(grant.project.pk),
"dataset": str(dataset.pk),
"objective": "Prepare this dataset",
"request_key": "prepare",
}
response = client.post("/api/workshop-tasks/", body, format="json")
assert response.status_code == 201, response.data
task_id = response.data["id"]
assert client.post("/api/workshop-tasks/", body, format="json").data["id"] == task_id
listed = client.get(
"/api/workshop-tasks/", {"project": str(grant.project.pk), "dataset": str(dataset.pk)}
)
assert listed.data["tasks"][0]["id"] == task_id
other = mcp_context(["read", "write"])
assert call_tool("control_workshop_task", {"task": task_id, "command": "cancel"}, other).isError
client.force_authenticate(other.user, other.token)
assert (
client.post(
f"/api/workshop-tasks/{task_id}/control/", {"command": "cancel"}, format="json"
).status_code
== 404
)
@pytest.mark.covers("recovery")
def test_a_sandbox_whose_creation_went_unconfirmed_is_found_again_and_never_made_twice(
local_sandbox,
):
cloud, _ = local_sandbox
_, task = passengers("How many rows are there?")
# The provider made the sandbox and the reply was lost.
cloud.sandbox_create_error = modal.exception.Error("connection lost")
def recover(send, request):
cloud.sandbox_create_error = None
return response("python", {"summary": "Counting again", "code": "print(40)"})
result, requests = drive(
task,
response("python", {"summary": "Counting rows", "code": "print(40)"}),
recover,
finish("answered", "There are 40 rows."),
)
assert result["state"] == "completed", task.result
assert "sandbox is unavailable" in json.loads(requests[1]["input"][-1]["output"])["error"]
assert "40" in json.loads(requests[2]["input"][-1]["output"])["output"]
[sandbox] = cloud.sandboxes.values()
assert sandbox.exit_code is not None
@pytest.mark.covers("recovery")
def test_unknown_workspace_keeps_its_identity_and_cancellation_until_provider_reconciliation(
local_sandbox,
):
cloud, _ = local_sandbox
grant, task = passengers()
cloud.sandbox_create_error = modal.exception.Error("Acknowledgement lost after acceptance")
with pytest.raises(modal.exception.Error):
sandbox.attach(task)
task.refresh_from_db()
intent = dict(task.workspace)
[accepted] = cloud.sandboxes.values()
cloud.sandbox_create_error = None
cloud.sandbox_lookup_error = modal.exception.NotFoundError("Not yet discoverable")
for _ in range(2):
with pytest.raises(modal.exception.Error, match="acknowledgement is unknown"):
sandbox.attach(task)
assert sandbox.stop(task) is False
task.refresh_from_db()
assert task.workspace == intent
assert len(cloud.sandboxes) == 1
state = agent.load(task)
pending = agent.settle(task, state, "completed", "Retained answer", final=True)
assert pending["settlement_pending"] is True
task.refresh_from_db()
assert task.state == "running" and task.result["settlement"]["outcome"] == "completed"
with pytest.raises(DatasetError, match="settlement"):
lifecycle.control(grant.project, task.pk, "resume")
lifecycle.control(grant.project, task.pk, "cancel")
assert agent.run(task.pk, None)["settlement_pending"] is True
cloud.sandbox_lookup_error = None
assert agent.run(task.pk, None)["state"] == "cancelled"
task.refresh_from_db()
assert task.workspace["name"] == intent["name"]
assert task.workspace["sandbox"] == accepted.object_id
assert task.workspace["stopped_at"]
assert accepted.exit_code is not None
assert len(cloud.sandboxes) == 1
assert not task.actions.filter(name="reason").exists()
def independent_connection(function):
close_old_connections()
try:
return function()
finally:
close_old_connections()
@pytest.mark.covers("work-once")
def test_concurrent_workspace_absence_claims_only_one_creation(local_sandbox, monkeypatch):
cloud, _ = local_sandbox
_, task = passengers()
lookup = Barrier(2)
original = modal.Sandbox.from_name
def absent(*args, **kwargs):
lookup.wait(timeout=20)
raise modal.exception.NotFoundError("Not created at lookup")
def attach():
try:
return sandbox.attach(lifecycle.get(task.pk)).object_id
except modal.exception.Error:
return None
monkeypatch.setattr(modal.Sandbox, "from_name", absent)
with ThreadPoolExecutor(max_workers=2) as pool:
futures = [pool.submit(independent_connection, attach) for _ in range(2)]
results = [future.result(timeout=30) for future in futures]
monkeypatch.setattr(modal.Sandbox, "from_name", original)
[accepted] = cloud.sandboxes.values()
assert sorted(value for value in results if value) == [accepted.object_id]
assert sandbox.attach(lifecycle.get(task.pk)).object_id == accepted.object_id
assert sandbox.stop(lifecycle.get(task.pk))
@pytest.mark.covers("recovery")
@pytest.mark.parametrize("new_generation", [False, True])
def test_late_workspace_acknowledgement_preserves_exit_and_new_generation(
local_sandbox, monkeypatch, new_generation
):
cloud, _ = local_sandbox
_, task = passengers()
entered, release = Event(), Event()
original = modal.Sandbox.create
def held(*args, **kwargs):
provider = original(*args, **kwargs)
if len(cloud.sandboxes) == 1:
entered.set()
assert release.wait(30)
return provider
monkeypatch.setattr(modal.Sandbox, "create", held)
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(independent_connection, lambda: sandbox.attach(lifecycle.get(task.pk)))
try:
assert entered.wait(20)
current = lifecycle.get(task.pk)
assert sandbox.stop(current)
stopped = dict(current.workspace)
if new_generation:
sandbox.attach(current)
expected = dict(current.workspace)
finally:
release.set()
with pytest.raises(DatasetError if new_generation else modal.exception.Error):
future.result(timeout=30)
task.refresh_from_db()
if new_generation:
assert task.workspace == expected
assert sandbox.stop(task)
else:
for key in ("name", "sandbox", "exit_code", "stopped_at"):
assert task.workspace[key] == stopped[key]
assert len(cloud.sandboxes) == (2 if new_generation else 1)
@pytest.mark.covers("recovery")
def test_cancellation_wins_while_fence_waits_for_provider_exit(local_sandbox, monkeypatch):
_, _ = local_sandbox
grant, task = passengers()
provider = sandbox.attach(task)
entered, release = Event(), Event()
original = provider.terminate
def held(**kwargs):
entered.set()
assert release.wait(30)
return original(**kwargs)
monkeypatch.setattr(provider, "terminate", held)
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(independent_connection, lambda: agent.fence(task.pk))
try:
assert entered.wait(20)
lifecycle.control(grant.project, task.pk, "cancel")
with pytest.raises(DatasetError):
lifecycle.claim(task.pk, 99, "prepare", {})
finally:
release.set()
assert future.result(timeout=30)["state"] == "cancelled"
task.refresh_from_db()
assert task.state == task.desired_state == "cancelled"
lifecycle.control(grant.project, task.pk, "resume")
task.refresh_from_db()
assert task.state == "cancelled"
@pytest.mark.covers("recovery")
def test_known_workspace_not_found_does_not_prove_provider_exit(local_sandbox, monkeypatch):
cloud, _ = local_sandbox
_, task = passengers()
provider = sandbox.attach(task)
original = provider.poll
def unavailable():
raise modal.exception.NotFoundError("Temporarily unavailable")
monkeypatch.setattr(provider, "poll", unavailable)
assert not sandbox.stop(task)
assert "stopped_at" not in task.workspace and "exit_code" not in task.workspace
monkeypatch.setattr(provider, "poll", original)
assert sandbox.stop(task)
assert task.workspace["exit_code"] == provider.exit_code
assert len(cloud.sandboxes) == 1
@pytest.mark.parametrize("state", ["blocked", "paused"])
def test_cancel_ends_an_already_blocked_or_paused_workshop(state):
grant, task = passengers()
if state == "blocked":
agent.fence(task.pk)
else:
lifecycle.control(grant.project, task.pk, "pause")
agent.run(task.pk, None)
lifecycle.control(grant.project, task.pk, "cancel")
assert agent.run(task.pk, None)["state"] == "cancelled"
def test_stale_settlement_cannot_replace_an_already_completed_workshop():
_, task = passengers()
state = agent.load(task)
stale = lifecycle.get(task.pk)
assert (
agent.settle(task, state, "completed", "Measured answer", final=True)["state"]
== "completed"
)
task.refresh_from_db()
retained = task.result
assert (
agent.settle(stale, state, "blocked", "Late fence", final=True, fenced=True)["state"]
== "completed"
)
task.refresh_from_db()
assert task.result == retained
def test_followup_during_provider_cleanup_remains_unanswered(local_sandbox):
cloud, _ = local_sandbox
grant, task = passengers()
cloud.sandbox_create_error = modal.exception.Error("Lost acknowledgement")
with pytest.raises(modal.exception.Error):
sandbox.attach(task)
cloud.sandbox_create_error = None
cloud.sandbox_lookup_error = modal.exception.NotFoundError("Unknown creation")
state = agent.load(task)
assert agent.settle(task, state, "completed", "Original answer")["settlement_pending"]
conversation.send(
grant,
SendMessage(
dataset=task.dataset_id, text="Also check the class balance", request_key="late"
),
)
cloud.sandbox_lookup_error = None
task.refresh_from_db()
assert agent.settle(task, **task.result["settlement"]) is None
task.refresh_from_db()
assert task.state == "running" and "settlement" not in task.result
assert any(
message["text"] == "Also check the class balance" for message in conversation.inbox(task)
)
assert not task.actions.filter(name="reason").exists()
@pytest.mark.covers("lineage")
def test_what_a_delegated_task_publishes_is_its_assignments_own_work():
experiment, user, dataset = setup_experiment()
land.land_rows(dataset, PASSENGERS, user=user)
dataset.refresh_from_db()
assignment = start(experiment, user)
lead = assignment.agents.get(parent__isnull=True)
action = research.claim(
lead,
"prepare",
"workshop",
{
"operation": "prepare",
"source_cell": str(dataset.active_cell.pk),
"objective": "Prepare survival decisions",
},
)
research_tools.invoke(action)
task = research_workshop.owned(assignment).get()
result, _ = drive(task, prepared(partition={}), finish("complete", "Published."))
assert result["state"] == "completed", task.result
pipelines, partitions = research_tools.owned_work(assignment)
assert pipelines.count() == 1 and partitions.count() == 1
partition = partitions.get()
members = {member.role: member.cell for member in partition.members.select_related("cell")}
for role in ("train", "development"):
assert research_tools.source_cell(assignment, members[role].pk).pk == members[role].pk
with pytest.raises(partition_plans.SealedHoldoutError):
research_tools.source_cell(assignment, members["final"].pk)
# Reported once, in the Workshop's record, not again as the lead's own runs.
evidence = research_tools.work_evidence(assignment)
assert evidence["pipelines"] == [] and evidence["partitions"] == []
assert evidence["workshop"][0]["published"]["partition"]["counts"]
followup = research.claim(
lead,
"benchmark-view",
"workshop",
{
"operation": "prepare",
"source_cell": str(members["development"].pk),
"objective": "Prepare a benchmark view of this development partition",
},
)
result = research_tools.invoke(followup)
continued = research_workshop.owned(assignment).get(pk=result["task"])
assert continued.dataset_id == task.dataset_id
assert research_workshop.pinned_source(continued) == str(members["development"].pk)