The platform for continuously improving AI agents.
import json
import time
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from datetime import timedelta
from decimal import Decimal
from threading import Event, Lock
from unittest.mock import patch
from uuid import uuid4
import modal
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from django.contrib.auth import get_user_model
from django.db import close_old_connections, connection, transaction
from django.utils import timezone
from test_experiment_engine import checkpoint_schema as checkpoint_schema
from test_experiment_engine import flow, investigating
from test_research_experiments import setup_experiment
from test_research_team import assignment, invoke, specialist
from overbae.core.errors import InputValidationError
from overbae.models import (
BillingTelemetry,
DataPartitionPlan,
ExperimentExecution,
ProjectMembership,
ResearchAgent,
ResearchAssignment,
ResearchExperiment,
)
from overbae.services import (
context_graph,
experiment_dispatch,
experiment_engine,
experiment_research,
research,
research_acceptance,
research_agent,
research_experiments,
research_orchestration,
research_team,
research_tools,
research_workspace,
)
from overbae.services.datasets import partition_plans, rows, store
from overbae.services.research_contract import Artifact, Finish
from tests.fakes.llm import tool_call
pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("state-machines")]
SPLIT_STAGE = {
"operation": "stage",
"id": "split",
"kind": "split",
"inputs": {"data": "data_0"},
"settings": {
"name": "Named split",
"seed": 37,
"fractions": {"train": 0.8, "development": 0.2},
},
}
@pytest.mark.covers("lineage")
@pytest.mark.parametrize("format", ["jsonl", "parquet"])
@pytest.mark.parametrize("fault", [None, "changed", "missing", "reordered"])
def test_native_data_review_reloads_every_record_without_model_or_workspace(
format, fault, fake_llm
):
experiment, user, dataset = setup_experiment()
source = dataset.active_cell
# An adaptive investigation: its evaluator's handoff runs the same native check.
work = research.create(
experiment.project,
user=user,
request_key="verify-export",
objective="Verify the retained export",
task={"deliverable": "A verified export"},
context_roots=[f"cell:{source.pk}"],
budget={},
)
lead = work.agents.get(parent__isnull=True)
exported = list(store.iter_rows(rows.frame_path(source)))
if fault == "changed":
exported[-1]["input"] = "wrong value"
elif fault == "missing":
exported.pop()
elif fault == "reordered":
exported.reverse()
if format == "jsonl":
data = b"".join((json.dumps(row) + "\n").encode() for row in exported)
else:
buffer = pa.BufferOutputStream()
pq.write_table(pa.Table.from_pylist(exported), buffer)
data = buffer.getvalue().to_pybytes()
creation = research.claim(lead, "output", "platform", {"name": "export_data"})
artifact = research.retain(
creation,
Artifact(
kind="data",
path=f"output.{format}",
title="Retained output",
metadata={"cell": str(source.pk), "fingerprint": source.fingerprint, "format": format},
),
data,
)
action = research.claim(
lead, "verify", "review", {"operation": "data", "artifact": str(artifact.pk)}
)
checked = research_tools.invoke(action)
assert checked["accepted"] is (fault is None)
assert checked["subject"] == {"artifact": str(artifact.pk), "sha256": artifact.sha256}
assert checked["source"]["fingerprint"] == source.fingerprint
assert bool(checked["first_mismatched_indices"]) is (fault is not None)
research.complete(action, checked, cost=0)
invoke(lead, "review", {"operation": "data", "artifact": str(artifact.pk)})
lead.messages = research_agent.messages(lead)
lead.save(update_fields=["messages"])
lead.refresh_from_db()
current = json.loads(research_agent.messages(lead)[-1]["content"])
checks = current["observations"]["acceptance_reviews"]
assert len(checks) == 1
assert checks[0]["subject"] == checked["subject"]
assert checks[0]["accepted"] == checked["accepted"]
assert checks[0]["checked_records"] == checked["checked_records"]
evaluator = work.agents.get(role="evaluation")
completion = Finish(
outcome="completed",
summary="Review the retained export",
reviewed_artifacts=[artifact.pk],
verification_verdict="passed",
deliverables=[
{
"name": "verification",
"findings": [
{
"kind": "observation",
"statement": "The export was retained with the pinned source identity",
"evidence": [{"kind": "artifact", "id": str(artifact.pk)}],
}
],
}
],
)
handoff = research.claim(
evaluator, "verify-candidate", "finish", completion.model_dump(mode="json")
)
if fault:
with pytest.raises(InputValidationError, match="does not match"):
research_team.prepare_handoff(handoff, completion)
else:
bound = research_team.prepare_handoff(handoff, completion)
assert bound["verification"]["native_checks"] == [checked]
assert not fake_llm.requests
assert not work.agents.filter(actions__tool="workspace_lease").exists()
@pytest.mark.covers("recovery")
def test_a_lead_finish_is_not_refused_for_handoff_fields_it_has_no_use_for(fake_llm):
work, lead = assignment()
request = tool_call(
"finish",
{
"outcome": "blocked",
"summary": "No readable source",
# A specialist's handoff, written by the lead and malformed besides.
"deliverables": ["end", "ignore"],
"verification_verdict": "undecided",
},
)
fake_llm.on(lambda request: bool(request.body.get("tools")), {"tool_calls": [request]})
research_agent.think(research_agent.lease(lead.pk), "finish")
finish = lead.actions.get(tool="finish")
assert finish.state == "pending" and "deliverables" not in finish.arguments
assert "deliverables" not in next(
item["function"]["parameters"]["properties"]
for item in research_agent.definitions(lead)
if item["function"]["name"] == "finish"
)
@pytest.mark.covers("recovery")
def test_a_loop_that_keeps_failing_stops_the_run_where_its_user_can_see_it():
work, lead = assignment()
research_orchestration.fence(lead.pk, "RuntimeError", lead.execution_epoch)
work.refresh_from_db()
assert work.state == "blocked"
assert work.result["reason"] == "orchestration_failed"
assert research_orchestration.advance(lead.pk) == {"state": "end"}
def test_read_batch_cannot_cross_a_shared_mutation():
_, lead = assignment()
first = research.claim(lead, "read-one", "history", {})
second = research.claim(lead, "read-two", "history", {})
write = research.claim(lead, "write", "remember", {"text": "Observed source"})
later = research.claim(lead, "later", "history", {})
research_agent.run_tools(lead)
first.refresh_from_db()
second.refresh_from_db()
write.refresh_from_db()
later.refresh_from_db()
assert first.state == second.state == "completed"
assert write.state == later.state == "pending"
research_agent.run_tools(lead)
lead.refresh_from_db()
later.refresh_from_db()
assert lead.notes == "Observed source"
assert later.state == "pending"
@pytest.mark.parametrize("changed", [False, True])
def test_large_native_receipt_verification_checks_exact_record_without_model_call(
changed, fake_llm
):
experiment, user, _ = setup_experiment()
work = research_experiments.start(
experiment, user, revision=1, request_key="receipt", budget={}
)
lead = work.agents.get(parent__isnull=True)
action = research.claim(lead, "receipt", "flow_receipt", {"output": "retained" * 20000})
content = context_graph.canonical(action.arguments).encode()
receipt = research.retain(
action,
Artifact(path="receipt.json", title="Execution receipt", kind="report"),
content if not changed else content.replace(b"retained", b"modified"),
)
research.complete(action, research.artifact_record(receipt), cost=0)
if changed:
with pytest.raises(InputValidationError, match="differs"):
research_acceptance.verify_report(work, receipt)
else:
assert research_acceptance.verify_report(work, receipt)["accepted"]
assert not fake_llm.unscripted
@pytest.mark.django_db(transaction=True)
@pytest.mark.covers("state-machines")
def test_research_lease_proceeds_while_the_creator_row_is_locked():
work, lead = assignment()
def acquire_lease():
with transaction.atomic():
with connection.cursor() as cursor:
cursor.execute("SET LOCAL lock_timeout = '2s'")
return research_agent.lease(lead.pk)
with ThreadPoolExecutor(max_workers=1) as pool, transaction.atomic():
get_user_model().objects.select_for_update().get(pk=work.created_by_id)
leased = pool.submit(research_orchestration.in_thread, acquire_lease).result(timeout=10)
assert leased is not None
assert leased.pk == lead.pk
assert leased.lease is not None
lead.refresh_from_db()
assert lead.lease == leased.lease
assert lead.lease_expires_at == leased.lease_expires_at
def held_model_failure(fake_llm, failure):
entered, release, lock = Event(), Event(), Lock()
attempts = 0
def first(request):
nonlocal attempts
if not request.body.get("tools"):
return False
with lock:
attempts += 1
original = attempts == 1
if original:
entered.set()
assert release.wait(20), "The test did not release the original model failure"
return original
if failure == "rejected":
fake_llm.fail(first, status=401, message="Held provider rejection")
fake_llm.on(lambda request: bool(request.body.get("tools")), "Successor response")
else:
fake_llm.on(
lambda request: bool(request.body.get("tools")),
lambda request: (
{
"content": None,
"finish_reason": "length",
"usage": {"cost": 0.0123},
}
if first(request)
else "Successor response"
),
)
return entered, release
@pytest.mark.covers("recovery")
@pytest.mark.parametrize("failure", ["rejected", "incomplete"])
@pytest.mark.parametrize("boundary", ["stopping", "cancelled", "expired_lease"])
def test_late_model_failure_cannot_replace_current_research_state(fake_llm, failure, boundary):
work, lead = assignment()
entered, release = held_model_failure(fake_llm, failure)
captured = {}
def original_call():
close_old_connections()
try:
owner = research_agent.lease(lead.pk)
captured["fence"] = owner.lease
research_agent.think(owner, "original")
finally:
close_old_connections()
with ThreadPoolExecutor(max_workers=1) as pool:
original = pool.submit(original_call)
try:
assert entered.wait(15), "The original model request did not reach the provider"
original_action = lead.actions.get(tool="model")
if boundary == "replacement":
research_orchestration.advance(lead.pk, exclusive=True)
successor = lead.actions.exclude(pk=original_action.pk).get(tool="model")
assert successor.state == "completed"
elif boundary == "expired_lease":
ResearchAgent.objects.filter(pk=lead.pk).update(
lease_expires_at=timezone.now() - timedelta(seconds=1)
)
else:
with patch("overbae.tasks.research.settle_stop.delay"):
research.stop(work)
if boundary == "cancelled":
research_agent.reconcile(work)
lead.refresh_from_db()
work.refresh_from_db()
retained_agent = deepcopy(
(lead.messages, lead.state, lead.result, lead.lease, lead.lease_expires_at)
)
retained_assignment = deepcopy((work.state, work.result))
if boundary == "replacement":
assert "Successor response" in json.dumps(lead.messages)
elif boundary != "expired_lease":
assert work.state == boundary
finally:
release.set()
original.result(timeout=20)
lead.refresh_from_db()
work.refresh_from_db()
original_action.refresh_from_db()
assert (
lead.messages,
lead.state,
lead.result,
lead.lease,
lead.lease_expires_at,
) == retained_agent
assert (work.state, work.result) == retained_assignment
assert not work.events.filter(kind="blocked").exists()
assert original_action.state == "unknown"
assert original_action.result["tools_executed"] is False
assert original_action.result["retryable"] is (failure == "incomplete")
key = str(original_action.pk)
if failure == "incomplete":
assert original_action.usage["response_cost"] == pytest.approx(0.0123)
assert original_action.cost_usd == Decimal("0.01230000")
assert (
BillingTelemetry.objects.filter(cause_kind="research_action", cause_id=key).count() == 1
)
else:
assert original_action.result["http_status"] == 401
assert original_action.cost_usd is None
assert not BillingTelemetry.objects.filter(
cause_kind="research_action", cause_id=key
).exists()
# Re-delivery of the same retained failure cannot settle or charge it twice.
recorded = deepcopy(
(
original_action.result,
original_action.usage,
original_action.cost_usd,
original_action.completed_at,
)
)
events = work.events.filter(kind="action", payload__action=str(original_action.pk)).count()
billing = list(
BillingTelemetry.objects.filter(cause_kind="research_action", cause_id=key).values(
"id", "amount"
)
)
research_agent.accept_model_failure(
original_action,
captured["fence"],
original_action.arguments["appended"],
{key: value for key, value in original_action.result.items() if key != "tools_executed"},
original_action.usage,
)
original_action.refresh_from_db()
assert (
original_action.result,
original_action.usage,
original_action.cost_usd,
original_action.completed_at,
) == recorded
assert (
work.events.filter(kind="action", payload__action=str(original_action.pk)).count() == events
)
assert (
list(
BillingTelemetry.objects.filter(cause_kind="research_action", cause_id=key).values(
"id", "amount"
)
)
== billing
)
@pytest.mark.covers("recovery")
@pytest.mark.parametrize("arrival", ["unchanged", "before_tool", "before_wait"])
def test_automatic_flow_wait_retains_only_the_observed_evidence(arrival):
experiment, user, _ = setup_experiment()
work = research_experiments.start(
experiment, user, revision=1, request_key="automatic-wait", budget={}
)
lead = work.agents.get(parent__isnull=True)
invoke(lead, "experiment", SPLIT_STAGE)
lead = research_agent.lease(lead.pk)
model = research.claim(
lead,
"captured-model",
"model",
{"observation_identity": research_agent.evidence_identity(research_agent.evidence(lead))},
)
research.complete(model, {"calls": []}, cost=0)
action = research.claim(lead, "launch-flow", "experiment", {"operation": "run"})
if arrival == "before_tool":
research.event(work, "trigger_evidence", {"measurement": "arrived-during-model"})
completed = False
def settle_after_result(execute, sql, params, many, context):
nonlocal completed
result = execute(sql, params, many, context)
if (
arrival == "before_wait"
and not completed
and sql.startswith("UPDATE")
and f'"{action._meta.db_table}"' in sql
and str(action.pk) in {str(value) for value in params}
and "completed" in params
):
completed = True
child = experiment_dispatch.owned(work).get()
experiment_engine.advance(child.pk)
partition = DataPartitionPlan.objects.get()
partition_plans.build(partition.pk)
experiment_engine.advance(child.pk)
child.refresh_from_db()
assert child.state == "completed", child.result
return result
with connection.execute_wrapper(settle_after_result):
research_agent.run_tool(lead, action)
action.refresh_from_db()
lead.refresh_from_db()
assert action.state == "completed", action.result
assert lead.state == "waiting"
assert research_agent.prepare(lead) is (arrival != "unchanged")
if arrival == "before_wait":
assert completed
assert research_agent.state(lead)["observations"]["flow_runs"][0]["state"] == "completed"
if arrival == "unchanged":
assert not research_agent.prepare(lead)
assert lead.actions.filter(tool="model").count() == 1
@pytest.mark.covers("assistant-turn")
def test_automatic_yield_preserves_an_unanswered_user_question():
work, lead = assignment()
lead = research_agent.lease(lead.pk)
question = research.claim(
lead,
"user-question",
"ask_user",
{"questions": [{"id": "target", "question": "Which target?"}]},
)
research_agent.run_tool(lead, question)
lead.refresh_from_db()
waiting = dict(lead.wake)
research.event(work, "trigger_evidence", {"measurement": "new-evidence"})
research_agent.yield_turn(lead, "Waiting for native work")
lead.refresh_from_db()
assert lead.wake == waiting
assert not research_agent.prepare(lead)
assert not work.events.filter(kind="question_answered").exists()
@pytest.mark.covers("recovery")
@pytest.mark.parametrize("boundary", ["current", "expired_lease", "stop_resume"])
def test_successful_research_response_retains_usage_without_reviving_a_lost_turn(
fake_llm, boundary
):
work, lead = assignment()
entered, release = Event(), Event()
original_fence = {}
attempts = 0
counter = Lock()
def reply(request):
nonlocal attempts
with counter:
attempts += 1
original = attempts == 1
if not original:
return "Replacement remains current"
entered.set()
assert release.wait(20), "Original response was not released"
return {
"tool_calls": [tool_call("remember", {"text": "Original proposal"})],
"usage": {"cost": 0.0123},
}
fake_llm.on(lambda request: bool(request.body.get("tools")), reply)
def original():
close_old_connections()
try:
owner = research_agent.lease(lead.pk)
original_fence["value"] = owner.lease
research_agent.think(owner, "held-success")
finally:
connection.close()
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(original)
try:
assert entered.wait(15)
if boundary == "replacement":
research_orchestration.advance(lead.pk, exclusive=True)
elif boundary == "expired_lease":
ResearchAgent.objects.filter(pk=lead.pk).update(
lease_expires_at=timezone.now() - timedelta(seconds=1)
)
elif boundary == "stop_resume":
with patch("overbae.tasks.research.settle_stop.delay"):
research.stop(work)
research_agent.reconcile(work)
work.refresh_from_db()
assert work.state == "cancelled"
research.resume(
work,
request_key="resume-during-response",
instructions="Continue with the revised objective",
max_model_calls=work.specification["budget"]["max_model_calls"] + 1,
)
lead.refresh_from_db()
retained = deepcopy((lead.messages, lead.state, lead.result, lead.lease))
finally:
release.set()
future.result(timeout=20)
lead.refresh_from_db()
original_action = lead.actions.get(request_key="model:held-success")
assert original_action.usage["response_cost"] == pytest.approx(0.0123)
assert original_action.cost_usd == Decimal("0.01230000")
billing_key = str(original_action.pk)
assert (
BillingTelemetry.objects.filter(cause_kind="research_action", cause_id=billing_key).count()
== 1
)
if boundary == "current":
assert lead.actions.filter(tool="remember", state="pending").count() == 1
assert "Original proposal" in json.dumps(lead.messages)
else:
assert (lead.messages, lead.state, lead.result, lead.lease) == retained
assert original_action.result["accepted"] is False
assert not lead.actions.filter(tool="remember").exists()
recorded = deepcopy(
(original_action.result, original_action.usage, original_action.completed_at)
)
events = work.events.filter(kind="action", payload__action=str(original_action.pk)).count()
research_agent.accept_model_response(
original_action,
original_fence["value"],
original_action.arguments["appended"],
original_action.result.get("text", ""),
original_action.result["calls"],
original_action.usage,
)
original_action.refresh_from_db()
assert (original_action.result, original_action.usage, original_action.completed_at) == recorded
assert (
work.events.filter(kind="action", payload__action=str(original_action.pk)).count() == events
)
assert (
BillingTelemetry.objects.filter(cause_kind="research_action", cause_id=billing_key).count()
== 1
)
@pytest.mark.covers("recovery")
def test_successful_response_and_concurrent_claim_keep_original_tool_batch(fake_llm):
experiment, user, _ = setup_experiment()
work = research_experiments.start(
experiment, user, revision=1, request_key="lock-order", budget={}
)
lead = work.agents.get(parent__isnull=True)
response_ready, held, release = Event(), Event(), Event()
attempted, acquired = Event(), Event()
first_lock = {}
def reply(request):
response_ready.set()
return {"tool_calls": [tool_call("remember", {"text": "Original accepted proposal"})]}
fake_llm.on(lambda request: bool(request.body.get("tools")), reply)
def response():
close_old_connections()
def hold_first(execute, sql, params, many, context):
result = execute(sql, params, many, context)
if response_ready.is_set() and not first_lock and "FOR UPDATE" in sql.upper():
for model in (ResearchExperiment, ResearchAssignment):
if model._meta.db_table in sql:
first_lock["model"] = model
held.set()
assert release.wait(20), "Response transaction was not released"
break
return result
try:
with connection.execute_wrapper(hold_first):
research_agent.think(research_agent.lease(lead.pk), "response-race")
finally:
connection.close()
def other_claim():
close_old_connections()
def observe(execute, sql, params, many, context):
matches = "FOR UPDATE" in sql.upper() and ResearchExperiment._meta.db_table in sql
if matches:
attempted.set()
result = execute(sql, params, many, context)
if matches:
acquired.set()
return result
try:
with connection.execute_wrapper(observe):
return research.claim(lead, "parallel-read", "history", {})
finally:
connection.close()
with ThreadPoolExecutor(max_workers=2) as pool:
response_future = pool.submit(response)
try:
assert held.wait(15)
other = pool.submit(other_claim)
assert attempted.wait(15)
# Force the opposing lock to be acquired when the response has the inverse order.
if first_lock["model"] is ResearchAssignment:
assert acquired.wait(15)
finally:
release.set()
response_future.result(timeout=20)
assert other.result(timeout=20).state == "pending"
model = lead.actions.get(request_key="model:response-race")
assert model.state == "completed"
assert lead.actions.filter(tool="remember", state="pending").count() == 1
assert len(fake_llm.requests) == 1
@pytest.mark.covers("recovery")
def test_helper_resume_waits_for_the_original_workspace_exit(fake_modal):
work, lead = assignment()
child = specialist(lead)
fake_modal.sandbox_create_error = TimeoutError("Creation acknowledgement lost")
with pytest.raises(TimeoutError):
research_workspace.attach(child)
fake_modal.sandbox_create_error = None
fake_modal.sandbox_lookup_error = modal.exception.NotFoundError("Not yet discoverable")
stopped = invoke(
lead,
"manage_agent",
{"agent": str(child.pk), "operation": "stop", "reason": "Stop the original work"},
)
child.refresh_from_db()
assert stopped.result["state"] == "cancelled"
assert child.workspace["creation_started"] and not child.workspace.get("stopped_at")
with pytest.raises(InputValidationError):
invoke(
lead,
"manage_agent",
{"agent": str(child.pk), "operation": "resume", "reason": "Begin revised work"},
)
fake_modal.sandbox_lookup_error = None
invoke(
lead,
"manage_agent",
{"agent": str(child.pk), "operation": "stop", "reason": "Confirm the original exit"},
)
child.refresh_from_db()
assert child.workspace["stopped_at"]
invoke(
lead,
"manage_agent",
{"agent": str(child.pk), "operation": "resume", "reason": "Begin revised work"},
)
child.refresh_from_db()
assert child.state == "ready"
assert len(fake_modal.sandboxes) == 1
def change_research_parent(parent, child, boundary):
if boundary == "stop":
with patch("overbae.tasks.research.settle_stop.delay"):
research.stop(parent)
elif boundary == "deadline":
parent.deadline = timezone.now() - timedelta(seconds=1)
parent.save(update_fields=["deadline"])
elif boundary == "membership":
ProjectMembership.objects.filter(
project_id=parent.project_id, user_id=parent.created_by_id
).delete()
elif boundary == "missing_parent":
child.specification["task"]["flow_run"] = str(uuid4())
child.save(update_fields=["specification"])
@pytest.mark.covers("authentication")
@pytest.mark.parametrize("boundary", ["stop", "deadline", "membership", "missing_parent"])
def test_saved_research_child_checks_parent_before_new_model_call(fake_llm, boundary):
experiment, user = flow()
parent, _, child = investigating(experiment, user)
lead = child.agents.get(parent__isnull=True)
fake_llm.on(
lambda request: bool(request.body.get("tools")),
{"content": "No follow-up requested", "usage": {"cost": 0.0123}},
)
change_research_parent(parent, child, boundary)
child.refresh_from_db()
assert child.state == "running" and child.deadline > timezone.now()
if boundary != "membership":
assert research.authorized(child)
research_orchestration.advance(lead.pk)
requests = [request for request in fake_llm.requests if request.body.get("tools")]
expected = 1 if boundary == "current" else 0
assert len(requests) == expected
assert lead.actions.filter(tool="model").count() == expected
@pytest.mark.covers("recovery")
@pytest.mark.parametrize(
"boundary", ["current", "stop", "deadline", "membership", "missing_parent"]
)
def test_saved_research_child_retains_late_usage_without_accepting_revoked_turn(fake_llm, boundary):
experiment, user = flow()
parent, _, child = investigating(experiment, user)
lead = child.agents.get(parent__isnull=True)
entered, release = Event(), Event()
original_fence = {}
def reply(request):
entered.set()
assert release.wait(20), "Child response was not released"
return {
"tool_calls": [tool_call("remember", {"text": "Child proposal after parent change"})],
"usage": {"cost": 0.0123},
}
fake_llm.on(lambda request: bool(request.body.get("tools")), reply)
def decide():
close_old_connections()
try:
owner = research_agent.lease(lead.pk)
assert owner is not None
original_fence["value"] = owner.lease
research_agent.think(owner, "held-child-response")
finally:
connection.close()
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(decide)
try:
assert entered.wait(15)
change_research_parent(parent, child, boundary)
child.refresh_from_db()
assert child.state == "running" and child.deadline > timezone.now()
if boundary != "membership":
assert research.authorized(child)
lead.refresh_from_db()
retained = deepcopy((lead.messages, lead.state, lead.result, lead.lease))
finally:
release.set()
future.result(timeout=20)
lead.refresh_from_db()
action = lead.actions.get(request_key="model:held-child-response")
assert action.usage["response_cost"] == pytest.approx(0.0123)
assert action.cost_usd == Decimal("0.01230000")
billing_key = str(action.pk)
assert (
BillingTelemetry.objects.filter(cause_kind="research_action", cause_id=billing_key).count()
== 1
)
assert len([request for request in fake_llm.requests if request.body.get("tools")]) == 1
if boundary == "current":
assert lead.actions.filter(tool="remember", state="pending").count() == 1
assert "Child proposal after parent change" in json.dumps(lead.messages)
else:
assert (lead.messages, lead.state, lead.result, lead.lease) == retained
assert action.result["accepted"] is False
assert not lead.actions.filter(tool="remember").exists()
recorded = deepcopy((action.result, action.usage, action.completed_at))
events = child.events.filter(kind="action", payload__action=str(action.pk)).count()
research_agent.accept_model_response(
action,
original_fence["value"],
action.arguments["appended"],
action.result.get("text", ""),
action.result["calls"],
action.usage,
)
action.refresh_from_db()
assert (action.result, action.usage, action.completed_at) == recorded
assert child.events.filter(kind="action", payload__action=str(action.pk)).count() == events
assert (
BillingTelemetry.objects.filter(cause_kind="research_action", cause_id=billing_key).count()
== 1
)
@pytest.mark.covers("recovery")
@pytest.mark.parametrize("boundary", ["settlement", "retry"])
def test_parent_lifecycle_and_late_child_response_release_each_other(fake_llm, boundary):
experiment, user = flow()
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", "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-under-controller"
)
controller = research_experiments.start(
experiment, user, revision=3, request_key="controller", budget={}
)
controller_lead = controller.agents.get(parent__isnull=True)
launch = research.claim(
controller_lead, "launch-research", "experiment", {"operation": "run", "revision": 3}
)
with patch("overbae.tasks.research.advance_flow.delay"):
research.complete(launch, research_tools.invoke(launch), cost=0)
run = experiment_dispatch.owned(controller).get()
experiment_engine.advance(run.pk)
original = run.execution.nodes.get(node="investigation")
child = experiment_research.assignment_for(original)
lead = child.agents.get(parent__isnull=True)
entered, release = Event(), Event()
model_started, lifecycle_started = Event(), Event()
backends = {}
def reply(request):
entered.set()
assert release.wait(20), "Child response was not released"
return {
"tool_calls": [tool_call("remember", {"text": "Retained late answer"})],
"usage": {"cost": 0.0123},
}
fake_llm.on(lambda request: bool(request.body.get("tools")), reply)
def worker(name, started, work):
close_old_connections()
try:
with connection.cursor() as cursor:
cursor.execute("SET statement_timeout = '10s'")
cursor.execute("SELECT pg_backend_pid()")
backends[name] = cursor.fetchone()[0]
started.set()
return work()
finally:
connection.close()
def decide():
owner = research_agent.lease(lead.pk)
assert owner is not None
research_agent.think(owner, "late-settlement")
def blocked_by(waiter, blocker):
deadline = time.monotonic() + 5
while True:
with connection.cursor() as cursor:
cursor.execute("SELECT %s = ANY(pg_blocking_pids(%s))", [blocker, waiter])
if cursor.fetchone()[0]:
return
assert time.monotonic() < deadline, "Expected database wait did not occur"
time.sleep(0.01)
with ThreadPoolExecutor(max_workers=2) as pool:
model = pool.submit(worker, "model", model_started, decide)
try:
assert model_started.wait(5) and entered.wait(15)
with patch("overbae.tasks.research.settle_stop.delay"):
research_agent.reconcile(research.stop(child))
if boundary == "settlement":
research_agent.reconcile(research.stop(run))
research.stop(controller)
else:
experiment_engine.advance(run.pk)
child.refresh_from_db()
run.refresh_from_db()
assert child.state == "cancelled"
assert run.state == ("cancelled" if boundary == "settlement" else "unmet")
allocation = controller_lead.actions.get(tool="flow_allocation")
assert allocation.state == "running"
with transaction.atomic():
if boundary == "settlement":
ExperimentExecution.objects.select_for_update().get(pk=run.pk)
else:
ResearchAssignment.objects.select_for_update().get(pk=controller.pk)
with connection.cursor() as cursor:
cursor.execute("SELECT pg_backend_pid()")
holder = cursor.fetchone()[0]
if boundary == "settlement":
lifecycle = pool.submit(
worker,
"lifecycle",
lifecycle_started,
lambda: research_agent.reconcile(controller),
)
assert lifecycle_started.wait(5)
blocked_by(backends["lifecycle"], holder)
release.set()
blocked_by(backends["model"], backends["lifecycle"])
else:
release.set()
blocked_by(backends["model"], holder)
lifecycle = pool.submit(
worker,
"lifecycle",
lifecycle_started,
lambda: experiment_engine.retry(run, request_key="retry-held-response"),
)
assert lifecycle_started.wait(5)
blocked_by(backends["lifecycle"], backends["model"])
lifecycle.result(timeout=15)
model.result(timeout=15)
finally:
release.set()
controller.refresh_from_db()
child.refresh_from_db()
allocation.refresh_from_db()
action = lead.actions.get(request_key="model:late-settlement")
run.refresh_from_db()
assert child.state == "cancelled"
if boundary == "settlement":
assert controller.state == "cancelled" and run.state == "cancelled"
assert allocation.state == "completed"
assert controller_lead.actions.filter(tool="flow_receipt", state="completed").count() == 1
else:
assert controller.state == "running" and run.state == "running"
assert allocation.state == "running"
assert (
run.execution.nodes.filter(node="investigation", attempt=original.attempt + 1).count()
== 1
)
assert action.result["accepted"] is False
assert action.usage["response_cost"] == pytest.approx(0.0123)
assert action.cost_usd == Decimal("0.01230000")
assert (
BillingTelemetry.objects.filter(
cause_kind="research_action", cause_id=str(action.pk)
).count()
== 1
)