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): reduce scout run limit from 30 to 15 minutes (#63462)

Andrew Maguire430c8408f438
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.py
index 72aa7f8a48c4..bda3e91c6156 100644
--- a/products/signals/backend/scout_harness/limits.py
+++ b/products/signals/backend/scout_harness/limits.py
@@ -3,8 +3,11 @@ from __future__ import annotations
# A 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. Tuning this is a config decision, not a per-run override knob.
-DEFAULT_MAX_RUNTIME_S = 30 * 60
+# bridge. Also passed to `MultiTurnSession` as the per-turn poll budget
+# (`max_poll_seconds`) so the dropped-finalization salvage fires before the activity's
+# timeout — keep it below `WORKFLOW_HARD_CEILING_S`. Tuning this is a config decision,
+# not a per-run override knob.
+DEFAULT_MAX_RUNTIME_S = 15 * 60
# Slack added on top of `DEFAULT_MAX_RUNTIME_S` for the Temporal activity
# `start_to_close_timeout`, so heartbeat-based failures get a chance to surface
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 509b39ffaaa4..e10b84262b4b 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -14,6 +14,7 @@ from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
+from products.signals.backend.scout_harness.limits import DEFAULT_MAX_RUNTIME_S
from products.signals.backend.scout_harness.prompt import SignalScoutRunSummary, build_run_prompt
from products.signals.backend.scout_harness.skill_loader import LoadedSkill, load_skill_for_run
from products.signals.backend.temporal.agentic import (
@@ -284,6 +285,11 @@ async def _spawn_and_run(
verbose=verbose,
origin_product=Task.OriginProduct.SIGNALS_SCOUT,
on_task_run_created=_create_bridge_row,
+ # 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,
)
try:
# Persist the agent's end-of-turn close-out so non-emitting runs leave a
diff --git a/products/tasks/backend/services/custom_prompt_internals.py b/products/tasks/backend/services/custom_prompt_internals.py
index 71dd0359978f..bff85020d378 100644
--- a/products/tasks/backend/services/custom_prompt_internals.py
+++ b/products/tasks/backend/services/custom_prompt_internals.py
@@ -129,8 +129,17 @@ async def poll_for_turn(
verbose: bool = False,
output_fn: OutputFn = None,
workflow_handle: WorkflowHandle | None = None,
+ max_poll_seconds: int | None = None,
) -> tuple[str, str | None, int, int]:
- """Poll S3 logs until the agent finishes a turn."""
+ """Poll S3 logs until the agent finishes a turn.
+
+ `max_poll_seconds` overrides the default poll budget for callers whose activity
+ timeout is shorter than `MAX_POLL_SECONDS` — the dropped-finalization salvage only
+ runs once this budget is exhausted, so a caller must keep it below its own activity
+ `start_to_close_timeout` or the salvage never gets a chance to fire (the Signals
+ scout passes its 15-minute per-run budget for exactly this reason).
+ """
+ poll_budget = MAX_POLL_SECONDS if max_poll_seconds is None else max_poll_seconds
# Track the timing/errors
elapsed = 0
consecutive_storage_errors = 0
@@ -142,7 +151,7 @@ async def poll_for_turn(
# recover an agent_message emitted earlier in *this* turn without crossing the previous turn's
# boundary (which would return a stale previous-turn response in multi-turn sessions).
original_skip_lines = skip_lines
- while elapsed < MAX_POLL_SECONDS:
+ while elapsed < poll_budget:
await asyncio.sleep(POLL_INTERVAL_SECONDS)
elapsed += POLL_INTERVAL_SECONDS
# Send heartbeat signals to the ProcessTaskWorkflow on each poll cycle to prevent
diff --git a/products/tasks/backend/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/services/custom_prompt_multi_turn_runner.py
index eb8fe5fe5683..71e7af6d014c 100644
--- a/products/tasks/backend/services/custom_prompt_multi_turn_runner.py
+++ b/products/tasks/backend/services/custom_prompt_multi_turn_runner.py
@@ -42,6 +42,10 @@ class MultiTurnSession:
printed_lines: int = 0
verbose: bool = False
output_fn: OutputFn = field(default=None)
+ # Per-turn poll budget. None falls back to `poll_for_turn`'s default (`MAX_POLL_SECONDS`).
+ # Set this below the caller's Temporal activity `start_to_close_timeout` so the
+ # dropped-finalization salvage can fire before the activity is cancelled.
+ max_poll_seconds: int | None = None
_workflow_handle: WorkflowHandle | None = field(default=None, repr=False)
@classmethod
@@ -59,6 +63,7 @@ class MultiTurnSession:
signal_report_id: str | None = None,
internal: bool = False,
on_task_run_created: Callable[[TaskRun], Awaitable[None]] | None = None,
+ max_poll_seconds: int | None = None,
) -> tuple[MultiTurnSession, _ModelT]:
"""Start a multi-turn sandbox session and wait for the first structured response.
@@ -67,6 +72,8 @@ class MultiTurnSession:
TaskRun to be queryable during that first turn use this — e.g. the Signals
scout creates its `SignalScoutRun` bridge here so first-turn finding emits
can resolve the run by id instead of 404ing on a not-yet-created row.
+
+ `max_poll_seconds` caps each turn's poll budget — see the field docstring.
"""
session, last_message = await cls.start_raw(
prompt=prompt,
@@ -79,6 +86,7 @@ class MultiTurnSession:
signal_report_id=signal_report_id,
internal=internal,
on_task_run_created=on_task_run_created,
+ max_poll_seconds=max_poll_seconds,
)
try:
parsed = cls._parse_and_validate(last_message, model, label="initial turn")
@@ -105,11 +113,14 @@ class MultiTurnSession:
signal_report_id: str | None = None,
internal: bool = False,
on_task_run_created: Callable[[TaskRun], Awaitable[None]] | None = None,
+ max_poll_seconds: int | None = None,
) -> tuple[MultiTurnSession, str]:
"""Start a multi-turn sandbox session and return the first raw agent response.
`on_task_run_created`, if given, is awaited once the `TaskRun` exists but
BEFORE the agent's first turn runs — see `start` for the rationale.
+
+ `max_poll_seconds` caps each turn's poll budget — see the field docstring.
"""
task, task_run = await create_task_and_trigger(
prompt,
@@ -130,6 +141,7 @@ class MultiTurnSession:
task_run=task_run,
verbose=verbose,
output_fn=output_fn,
+ max_poll_seconds=max_poll_seconds,
_workflow_handle=workflow_handle,
)
if on_task_run_created is not None:
@@ -147,7 +159,11 @@ class MultiTurnSession:
started_at = time.monotonic()
try:
last_message, _, session.log_lines_seen, session.printed_lines = await poll_for_turn(
- task_run, verbose=verbose, output_fn=output_fn, workflow_handle=workflow_handle
+ task_run,
+ verbose=verbose,
+ output_fn=output_fn,
+ workflow_handle=workflow_handle,
+ max_poll_seconds=max_poll_seconds,
)
logger.info(
"multi_turn: initial turn completed run=%s duration=%.2fs",
@@ -224,6 +240,7 @@ class MultiTurnSession:
verbose=self.verbose,
output_fn=self.output_fn,
workflow_handle=self._workflow_handle,
+ max_poll_seconds=self.max_poll_seconds,
)
return last_message
# Catch empty turns, raise everything else
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index a8bc0e0aa54e..ef182fe924e0 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -193,6 +193,22 @@ class TestPollForTurnStaleSalvage:
assert last_message == "close-out summary"
assert total_lines == len(done)
+ @pytest.mark.asyncio
+ async def test_max_poll_seconds_overrides_module_budget(self):
+ # A caller-supplied max_poll_seconds bounds the loop instead of the module MAX_POLL_SECONDS:
+ # the module value is left larger, so the elapsed in the timeout error proves the override won.
+ log = _agent_message_line("intermediate") # no fingerprint — always times out
+ fake = FakeTaskRun()
+ with (
+ patch("posthog.storage.object_storage.read", return_value=log),
+ patch("asyncio.sleep", new=AsyncMock()),
+ patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 100),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
+ ):
+ with pytest.raises(RuntimeError, match="after 30s"):
+ await poll_for_turn(fake, skip_lines=0, max_poll_seconds=30)
+
@pytest.mark.asyncio
async def test_salvage_reassembles_chunked_message(self):
# Response split across agent_message_chunk slices, then null-cost usage_update — salvage