Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(signals): allow 30-minute trial scouts and judges (#114540)

Alex Lebedevae2617b00bbe
diff --git a/docs/internal/scout-online-evals-devbox.md b/docs/internal/scout-online-evals-devbox.md
index 8e005acc48d8..e2f0c2a0c9a3 100644
--- a/docs/internal/scout-online-evals-devbox.md
+++ b/docs/internal/scout-online-evals-devbox.md
@@ -47,6 +47,10 @@ Revoke or expire private tokens before rolling the gateway back to a version wit
The rubric stays fixed across scout edits, and saved results retain the rubric used for that trial. If a run is interrupted, reopen the existing trial before starting another paid attempt.
+Trial scouts have a 30-minute runtime limit. Regular scouts keep their 15-minute limit. Timed-out scouts cannot be scored; start a new trial to try again.
+
+Trial scout and judge deadlines include five minutes for startup and log reads, plus time to collect and save the final result.
+
Trial plans and evaluation documents keep one complete adopted reference each and exclude suggestion-generation history. The judge reads that same adopted reference from its evidence attachment.
Suggestion generation captures the complete scout instructions and reference files for judging, while keeping the generator's prompt bounded. If an older saved reference is incomplete, generate suggestions again, review and use the new reference, then save. You can keep your existing criteria.
@@ -65,6 +69,6 @@ Scout sandboxes keep private gateway capture and exclude shared context-layer in
The judge has no live project tools, external MCP connections or repository credentials. Its run disables live context, so the Tasks worker neither mounts the current wiki nor adds Store skill descriptions. Internal Tasks also exclude project and personal instructions. A retry to correct its JSON response uses the same sandbox and keeps these inputs disabled. Deploy the Tasks worker's support for this run setting before starting new judges.
-It returns one verdict per rubric check, with quotes checked against the original saved files. Missing evidence gives an unknown verdict. A judge failure is shown separately from a failed rubric check, and incomplete results cannot win. Judging has a 15-minute runtime limit per run; saved results never rerun the judge when viewed.
+It returns one verdict per rubric check, with quotes checked against the original saved files. Missing evidence gives an unknown verdict. A judge failure is shown separately from a failed rubric check, and incomplete results cannot win. Judging has a 30-minute runtime limit per run; saved results never rerun the judge when viewed.
Before dispatch, the full batch must fit the project's existing daily scout budget. Resuming counts only runs that have not already started. This is a capacity check, not a reservation: simultaneous submissions can still race, and the budget remains shared with ordinary scouts.
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.py
index 6f28e651e300..76b9726d5a31 100644
--- a/products/signals/backend/scout_harness/limits.py
+++ b/products/signals/backend/scout_harness/limits.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-# A scout run's hard runtime cap. Enforced via the Temporal activity's
+# A regular scout run's hard runtime cap. Enforced via the Temporal activity's
# `start_to_close_timeout` in `scout_scheduler.py` — if the agent is still going
# at this point, the activity is killed and the run row is marked failed by the
# bridge. Also passed to `MultiTurnSession` as the per-turn poll budget
@@ -14,8 +14,8 @@ DEFAULT_MAX_RUNTIME_S = 15 * 60
# before Temporal's own timeout fires.
ACTIVITY_SLACK_S = 60
-# Hard ceiling on how long a single agent activity can actually be running. The
-# workflow always sets `start_to_close_timeout = DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S`,
+# Hard ceiling on how long a regular scout activity can actually be running. The
+# workflow sets `start_to_close_timeout = DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S`,
# providing a heartbeat window before Temporal's own timeout fires. The stale-RUNNING
# self-heal in `runner.py` uses this as the staleness base.
WORKFLOW_HARD_CEILING_S = DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S
@@ -49,11 +49,19 @@ SCOUT_RUN_REAPED_METADATA_KEY = "reaped_at"
MAX_RUN_NOTE_CHARS = 1_000
SCOUT_TRIAL_METADATA_KEY = "scout_trial"
+TRIAL_MAX_RUNTIME_S = 30 * 60
+# Poll budgets count sleeps, excluding startup and I/O; keep that overhead separate from cleanup time.
+TRIAL_RUNTIME_OVERHEAD_S = 5 * 60
+TRIAL_ACTIVITY_TIMEOUT_S = TRIAL_MAX_RUNTIME_S + TRIAL_RUNTIME_OVERHEAD_S + ACTIVITY_SLACK_S
+# Time a trial scout activity can wait in the task queue before it starts.
+TRIAL_QUEUE_ALLOWANCE_MINUTES = 19
+# How long a comparison waits for its scout runs. The activity timeout does not include queue time.
+TRIAL_SCOUT_WAIT_MINUTES = TRIAL_ACTIVITY_TIMEOUT_S // 60 + TRIAL_QUEUE_ALLOWANCE_MINUTES
MAX_TRIAL_VARIANTS = 20
MAX_TRIAL_REPEATS = 20
MAX_TRIAL_RUNS = MAX_TRIAL_VARIANTS * MAX_TRIAL_REPEATS
TRIAL_JUDGE_CONCURRENCY = 3
-TRIAL_JUDGE_TIMEOUT_MINUTES = 18
+TRIAL_JUDGE_TIMEOUT_MINUTES = TRIAL_ACTIVITY_TIMEOUT_S // 60 + 2
# Leave time to load evidence and save the report after every judging wave.
TRIAL_EVALUATION_TIMEOUT_MINUTES = -(-MAX_TRIAL_RUNS // TRIAL_JUDGE_CONCURRENCY) * TRIAL_JUDGE_TIMEOUT_MINUTES + 10
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 4fac53fb428f..b4d1ab856309 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -43,6 +43,8 @@ from products.signals.backend.scout_harness.limits import (
FINISHED_ORPHAN_RECENT_RUNS,
SCOUT_RUN_REAPED_METADATA_KEY,
STALE_RUN_CUTOFF_S,
+ TRIAL_ACTIVITY_TIMEOUT_S,
+ TRIAL_MAX_RUNTIME_S,
TRIGGERED_BY_SCHEDULE,
failure_streak_pause_threshold,
interval_runs_in_tolerance_window,
@@ -957,6 +959,7 @@ async def _spawn_and_run(
reasoning_effort=reasoning_effort,
# Codex-only, and independent of the model pin: which OpenAI queue the run's turns join.
service_tier=service_tier,
+ sandbox_timeout_seconds=TRIAL_ACTIVITY_TIMEOUT_S + 60 if trial is not None else None,
)
project_has_governed_metrics = await database_sync_to_async(_project_has_governed_metrics, thread_sensitive=False)(
team, user_id
@@ -1068,11 +1071,8 @@ async def _spawn_and_run(
ai_agent_name=skill.name,
before_task_dispatch=_create_bridge_row,
origin_key=f"scout-trial:{trial.id}" if trial is not None else None,
- # Keep the per-turn poll budget at the run's runtime cap so the dropped-finalization
- # salvage fires before the activity's `start_to_close_timeout` (DEFAULT_MAX_RUNTIME_S +
- # ACTIVITY_SLACK_S) cancels the activity. Default budget (MAX_POLL_SECONDS) exceeds the
- # ceiling and would let the activity die before salvage could return the written summary.
- max_poll_seconds=DEFAULT_MAX_RUNTIME_S,
+ # Leave the activity's cleanup allowance after the scout's own timeout.
+ max_poll_seconds=TRIAL_MAX_RUNTIME_S if trial is not None else DEFAULT_MAX_RUNTIME_S,
# The close-out is free-text markdown — if the agent ends with prose or malformed JSON
# instead of a SignalScoutRunSummary object, keep the raw text as the summary rather than
# failing the whole run. A failed run never finalizes, so its scan-position close-out is
diff --git a/products/signals/backend/scout_harness/trial_judge.py b/products/signals/backend/scout_harness/trial_judge.py
index 6d34d8af3a51..280389d35978 100644
--- a/products/signals/backend/scout_harness/trial_judge.py
+++ b/products/signals/backend/scout_harness/trial_judge.py
@@ -12,6 +12,7 @@ from posthog.sync import database_sync_to_async
from products.signals.backend import trial_judging
from products.signals.backend.models import SignalScoutRun
+from products.signals.backend.scout_harness.limits import TRIAL_ACTIVITY_TIMEOUT_S
from products.signals.backend.scout_harness.trial_evaluation import (
read_trial_evidence_sources,
trial_evidence_storage_key,
@@ -34,7 +35,7 @@ from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession
from products.tasks.backend.facade.contracts import TaskRunInputFile
-JUDGE_MAX_RUNTIME_SECONDS = 15 * 60
+JUDGE_MAX_RUNTIME_SECONDS = 30 * 60
JUDGE_SANDBOX_ENVIRONMENT = "SIGNALS_SCOUT_TRIAL_JUDGE"
_JSON_RETRY_PROMPT = (
"Return the complete JSON object with summary and one result per supplied criterion. "
@@ -185,10 +186,10 @@ async def judge_trial_run(snapshot: TrialEvaluationSnapshot, evidence: TrialRunE
reasoning_effort="high",
initial_permission_mode="full-access",
github_read_access=False,
- sandbox_timeout_seconds=JUDGE_MAX_RUNTIME_SECONDS + 120,
+ sandbox_timeout_seconds=TRIAL_ACTIVITY_TIMEOUT_S + 60,
)
judge_run = _JudgeRun(snapshot=snapshot, evidence=evidence, prompt=prompt)
- async with asyncio.timeout(JUDGE_MAX_RUNTIME_SECONDS + 60):
+ async with asyncio.timeout(TRIAL_ACTIVITY_TIMEOUT_S):
session, output = await MultiTurnSession.start(
prompt=prompt,
context=context,
diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.py
index 6390fd66399b..17477f717aa5 100644
--- a/products/signals/backend/temporal/agentic/scout_scheduler.py
+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py
@@ -30,6 +30,7 @@ from products.signals.backend.quota import (
self_driving_quota_gate,
)
from products.signals.backend.scout_harness.limits import (
+ TRIAL_ACTIVITY_TIMEOUT_S,
TRIGGERED_BY_CHECK,
TRIGGERED_BY_MANUAL,
TRIGGERED_BY_SCHEDULE,
@@ -263,7 +264,9 @@ class RunSignalsScoutWorkflow:
output = await temporalio.workflow.execute_activity(
run_signals_scout_activity,
input,
- start_to_close_timeout=timedelta(seconds=WORKFLOW_HARD_CEILING_S),
+ start_to_close_timeout=timedelta(
+ seconds=TRIAL_ACTIVITY_TIMEOUT_S if input.trial_launch_id is not None else WORKFLOW_HARD_CEILING_S
+ ),
heartbeat_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=1),
)
diff --git a/products/signals/backend/temporal/agentic/scout_trial_comparison.py b/products/signals/backend/temporal/agentic/scout_trial_comparison.py
index f3ecc9cfc632..bb77c2a42d52 100644
--- a/products/signals/backend/temporal/agentic/scout_trial_comparison.py
+++ b/products/signals/backend/temporal/agentic/scout_trial_comparison.py
@@ -20,7 +20,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
from posthog.temporal.common.heartbeat import Heartbeater
-from products.signals.backend.scout_harness.limits import TRIAL_EVALUATION_TIMEOUT_MINUTES
+from products.signals.backend.scout_harness.limits import TRIAL_EVALUATION_TIMEOUT_MINUTES, TRIAL_SCOUT_WAIT_MINUTES
if TYPE_CHECKING:
from products.signals.backend.scout_harness.trial_result import TrialWorkflowStatus
@@ -128,7 +128,7 @@ class RunScoutTrialComparisonWorkflow:
heartbeat_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(maximum_attempts=3),
)
- deadline = workflow.now() + timedelta(minutes=35)
+ deadline = workflow.now() + timedelta(minutes=TRIAL_SCOUT_WAIT_MINUTES)
while not await workflow.execute_activity(
prepare_scout_trial_comparison_evaluation_activity,
inputs,
@@ -167,7 +167,7 @@ async def start_trial_comparison(team_id: int, comparison_id: UUID) -> str:
TrialComparisonInput(team_id=team_id, comparison_id=str(comparison_id)),
id=workflow_id,
task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
- execution_timeout=timedelta(minutes=TRIAL_EVALUATION_TIMEOUT_MINUTES + 70),
+ execution_timeout=timedelta(minutes=TRIAL_EVALUATION_TIMEOUT_MINUTES + TRIAL_SCOUT_WAIT_MINUTES + 35),
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
)
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index a09687b6be94..66998828d969 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -1852,8 +1852,10 @@ async def test_trial_runs_keep_runtime_and_state_separate_from_the_production_sc
assert outcome.status == expected_status
assert replay.run_id == outcome.run_id
assert len(captured) == 1
+ assert captured[0]["max_poll_seconds"] == 30 * 60
sandbox_context = captured[0]["context"]
assert isinstance(sandbox_context, CustomPromptSandboxContext)
+ assert sandbox_context.sandbox_timeout_seconds == 37 * 60
assert sandbox_context.model == "gpt-5.6-sol"
assert sandbox_context.reasoning_effort == "high"
assert sandbox_context.posthog_mcp_scopes == "signals_scout_experiment"
@@ -1922,6 +1924,8 @@ async def test_run_tags_session_with_scout_attribution(ateam, aerrors_skill):
# `signals-scout-errors` is not canonical, so only `ai_agent_name` can name it.
assert captured["ai_stage"] == "scout:custom"
assert captured["ai_agent_name"] == "signals-scout-errors"
+ assert captured["max_poll_seconds"] == 15 * 60
+ assert captured["context"].sandbox_timeout_seconds is None
@pytest.mark.asyncio
@@ -3572,8 +3576,13 @@ async def test_activity_wakes_the_workflow_step_that_started_the_run(ateam, work
@pytest.mark.asyncio
@pytest.mark.parametrize("outcome", ["completed", "preflight_error", "timeout", "cancelled"])
[email protected]("workflow_origin_key", ["job:step:1", None])
-async def test_workflow_delivers_scout_outcomes_even_when_the_run_activity_cannot(outcome, workflow_origin_key):
+ "workflow_origin_key,trial_launch_id,timeout_minutes",
+ [("job:step:1", None, 16), (None, None, 16), (None, "11111111-1111-1111-1111-111111111111", 36)],
+)
+async def test_workflow_delivers_scout_outcomes_even_when_the_run_activity_cannot(
+ outcome, workflow_origin_key, trial_launch_id, timeout_minutes
+):
output = RunSignalsScoutOutput(
run_id="abc",
task_run_id="def",
@@ -3600,6 +3609,7 @@ async def test_workflow_delivers_scout_outcomes_even_when_the_run_activity_canno
async def execute_activity(activity_function, input=None, **kwargs):
if activity_function is run_signals_scout_activity:
+ assert kwargs["start_to_close_timeout"] == timedelta(minutes=timeout_minutes)
if outcome == "cancelled":
raise asyncio.CancelledError()
if outcome != "completed":
@@ -3618,7 +3628,12 @@ async def test_workflow_delivers_scout_outcomes_even_when_the_run_activity_canno
patch("products.signals.backend.temporal.agentic.scout_scheduler.emit_workflow_step_resume") as resume,
):
workflow = RunSignalsScoutWorkflow()
- input = RunSignalsScoutInput(team_id=7, skill_name=output.skill_name, workflow_origin_key=workflow_origin_key)
+ input = RunSignalsScoutInput(
+ team_id=7,
+ skill_name=output.skill_name,
+ workflow_origin_key=workflow_origin_key,
+ trial_launch_id=trial_launch_id,
+ )
if outcome == "completed":
assert await workflow.run(input) == output
else:
diff --git a/products/signals/backend/test/test_scout_trial_comparison.py b/products/signals/backend/test/test_scout_trial_comparison.py
index 333e48c49408..8dafc300056f 100644
--- a/products/signals/backend/test/test_scout_trial_comparison.py
+++ b/products/signals/backend/test/test_scout_trial_comparison.py
@@ -66,24 +66,32 @@ class TestTrialCoordinator(SimpleTestCase):
class TestScoutTrialComparisonWorkflow(SimpleTestCase):
- @parameterized.expand([False, True])
- async def test_background_comparison_waits_for_runs_and_report_or_records_timeout(self, times_out: bool) -> None:
+ @parameterized.expand(
+ [
+ ("runs_finish_quickly", timedelta(seconds=10)),
+ ("queued_runs_use_full_trial_runtime", timedelta(minutes=7 + 29)),
+ ("runs_never_finish", None),
+ ]
+ )
+ async def test_background_comparison_waits_for_runs_and_report_or_records_timeout(
+ self, _name: str, runs_finish_after: timedelta | None
+ ) -> None:
+ times_out = runs_finish_after is None
inputs = TrialComparisonInput(team_id=2, comparison_id=str(uuid4()))
now = datetime(2026, 1, 1, tzinfo=UTC)
+ started = now
prepared = False
finished = False
failed = False
- prepare_calls = 0
report_calls = 0
async def execute(function: Callable[..., object], payload: object, **options: object) -> object:
- nonlocal prepared, finished, failed, prepare_calls, report_calls
+ nonlocal prepared, finished, failed, report_calls
assert payload == inputs
if function is dispatch_scout_trial_comparison_activity:
return None
if function is prepare_scout_trial_comparison_evaluation_activity:
- prepare_calls += 1
- prepared = prepare_calls > 1 and not times_out
+ prepared = runs_finish_after is not None and now - started >= runs_finish_after
return prepared
if function is finish_scout_trial_comparison_activity:
assert prepared
@@ -113,7 +121,7 @@ class TestScoutTrialComparisonWorkflow(SimpleTestCase):
assert prepared and finished and not failed
async def test_judging_wait_bounds_sandbox_evaluation_workflows(self) -> None:
- expected_minutes = 2427
+ expected_minutes = 5107
inputs = TrialComparisonInput(team_id=2, comparison_id=str(uuid4()))
now = datetime(2026, 1, 1, tzinfo=UTC)
started = now
@@ -158,7 +166,7 @@ class TestScoutTrialComparisonWorkflow(SimpleTestCase):
assert start_trial_comparison(2, comparison_id) == first
for call in client.start_workflow.await_args_list:
assert call.kwargs["id"] == first
- assert call.kwargs["execution_timeout"] == timedelta(minutes=2492)
+ assert call.kwargs["execution_timeout"] == timedelta(minutes=5192)
assert call.kwargs["id_conflict_policy"] == WorkflowIDConflictPolicy.USE_EXISTING
assert call.kwargs["id_reuse_policy"] == WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY
assert call.args[1] == TrialComparisonInput(team_id=2, comparison_id=str(comparison_id))
diff --git a/products/signals/backend/test/test_scout_trial_evaluation.py b/products/signals/backend/test/test_scout_trial_evaluation.py
index 2722d6235971..ab8bc904fdc0 100644
--- a/products/signals/backend/test/test_scout_trial_evaluation.py
+++ b/products/signals/backend/test/test_scout_trial_evaluation.py
@@ -1206,7 +1206,7 @@ class TestScoutTrialEvaluationWorkflow(SimpleTestCase):
policy = options["retry_policy"]
assert isinstance(policy, RetryPolicy) and policy.maximum_attempts == 1
timeout = options["start_to_close_timeout"]
- assert isinstance(timeout, timedelta) and timeout >= timedelta(minutes=17)
+ assert isinstance(timeout, timedelta) and timeout >= timedelta(minutes=37)
active += 1
highest_active = max(highest_active, active)
if active == 3:
@@ -1256,7 +1256,7 @@ class TestScoutTrialEvaluationWorkflow(SimpleTestCase):
with patch(f"{WORKFLOW_MODULE}.async_connect", AsyncMock(return_value=client)):
start_trial_evaluation(2, evaluation_id)
timeout = client.start_workflow.call_args.kwargs["execution_timeout"]
- assert timeout >= timedelta(minutes=-(-MAX_TRIAL_RUNS // 3) * 17 + 2)
+ assert timeout >= timedelta(minutes=-(-MAX_TRIAL_RUNS // 3) * 37 + 2)
assert client.start_workflow.call_args.args[1] == TrialEvaluationInput(
team_id=2, evaluation_id=str(evaluation_id)
)
diff --git a/products/signals/backend/test/test_scout_trial_judge_sandbox.py b/products/signals/backend/test/test_scout_trial_judge_sandbox.py
index 27d98b4e767f..f986a93c0c29 100644
--- a/products/signals/backend/test/test_scout_trial_judge_sandbox.py
+++ b/products/signals/backend/test/test_scout_trial_judge_sandbox.py
@@ -40,6 +40,8 @@ class TestSandboxJudgeLifecycle(SimpleTestCase):
output = output.model_copy(update={"criteria": output.criteria * 2})
async def start(**kwargs):
+ self.assertEqual(kwargs["max_poll_seconds"], 30 * 60)
+ self.assertEqual(kwargs["context"].sandbox_timeout_seconds, 37 * 60)
kwargs["before_task_dispatch"](run.id)
if outcome == "cancelled":
raise asyncio.CancelledError
@@ -48,6 +50,7 @@ class TestSandboxJudgeLifecycle(SimpleTestCase):
return session, output
with (
+ patch(f"{MODULE}.asyncio.timeout", wraps=asyncio.timeout) as timeout_guard,
patch(f"{MODULE}._assert_scout_available"),
patch(f"{MODULE}.read_trial_evidence_sources", return_value=evidence.sources),
patch(f"{MODULE}.tasks_facade.get_task_by_origin_key", return_value=None),
@@ -75,6 +78,7 @@ class TestSandboxJudgeLifecycle(SimpleTestCase):
self.assertEqual(update_run.call_args.kwargs["validated_data"]["status"], "failed")
if outcome == "invalid_result":
self.assertEqual(session.end.call_args.kwargs["status"], "failed")
+ timeout_guard.assert_called_once_with(36 * 60)
@parameterized.expand(["missing_evidence", "existing_judge"])
async def test_unavailable_input_and_existing_judge_do_not_start_a_paid_run(self, failure: str) -> None:
diff --git a/products/signals/backend/test/test_scout_trial_poll_budget.py b/products/signals/backend/test/test_scout_trial_poll_budget.py
new file mode 100644
index 000000000000..a9b439141cb1
--- /dev/null
+++ b/products/signals/backend/test/test_scout_trial_poll_budget.py
@@ -0,0 +1,67 @@
+import json
+import asyncio
+from types import SimpleNamespace
+from uuid import uuid4
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.signals.backend.scout_harness.limits import TRIAL_ACTIVITY_TIMEOUT_S, TRIAL_MAX_RUNTIME_S
+from products.tasks.backend.facade.agents import poll_for_turn
+from products.tasks.backend.facade.contracts import AgentTaskRunDTO
+
+
+class TestScoutTrialPollBudget(SimpleTestCase):
+ @parameterized.expand([0.4, 1.0])
+ async def test_trial_deadline_leaves_time_for_io_and_final_salvage(self, read_seconds: float) -> None:
+ task_run = AgentTaskRunDTO(task_id=uuid4(), run_id=uuid4(), team_id=2, workflow_id="synthetic-trial")
+ run = SimpleNamespace(
+ id=task_run.run_id, log_url="synthetic-trial-log", status="in_progress", error_message=None
+ )
+ updates = [
+ {"sessionUpdate": "agent_message", "content": {"type": "text", "text": "Synthetic final assessment."}},
+ {"sessionUpdate": "usage_update", "used": 1000, "cost": None},
+ ]
+ log = "\n".join(
+ json.dumps({"notification": {"method": "session/update", "params": {"update": update}}})
+ for update in updates
+ )
+ loop = asyncio.get_running_loop()
+ clock = SimpleNamespace(now=loop.time())
+ original_sleep = asyncio.sleep
+ sleeps = 0
+
+ async def sleep(seconds: float) -> None:
+ nonlocal sleeps
+ sleeps += 1
+ clock.now += seconds
+ await original_sleep(0)
+
+ def read_log(*_args: object, **_kwargs: object) -> str:
+ clock.now += read_seconds
+ return log
+
+ with (
+ patch.object(loop, "time", side_effect=lambda: clock.now),
+ patch.object(loop, "slow_callback_duration", float("inf")),
+ patch("asyncio.sleep", side_effect=sleep),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=run),
+ patch("posthog.storage.object_storage.read", side_effect=read_log) as read,
+ ):
+ with self.assertRaises(TimeoutError):
+ async with asyncio.timeout(31 * 60):
+ await asyncio.sleep(60)
+ await poll_for_turn(task_run, max_poll_seconds=TRIAL_MAX_RUNTIME_S)
+ self.assertLess(sleeps, 180)
+ sleeps = 0
+ read.reset_mock()
+ async with asyncio.timeout(TRIAL_ACTIVITY_TIMEOUT_S):
+ await asyncio.sleep(60)
+ result = await poll_for_turn(task_run, max_poll_seconds=TRIAL_MAX_RUNTIME_S)
+ await asyncio.sleep(30)
+ self.assertEqual(result.last_message, "Synthetic final assessment.")
+ self.assertEqual(result.total_lines, 2)
+ self.assertEqual(read.call_count, 181)