: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): keep the sandbox alive while a loop run's turn is in flight (#83860)
Tom Owers7cf4b93a6db7
diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex f6a37b03cfd0..3535089ba754 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -119,8 +119,10 @@ async def _relay_sandbox_events(input: RelaySandboxEventsInput, *, finalize_stretask_run = await TaskRunModel.objects.select_related("task__created_by", "task__team").aget(id=input.run_id)- # Match the freshness window to the workflow's inactivity timeout for this run- # so the heartbeat suppression below never resets a timer it shouldn't.+ # The workflow's inactivity timeout for this run also drives the heartbeat+ # freshness guard (floored at the background default while a turn is in+ # flight; see _background_heartbeat), so the relay never resets a timer for+ # a run that is genuinely idle.origin_product = task_run.task.origin_productis_user_origin = not origin_product or origin_product == TaskModel.OriginProduct.USER_CREATED.valueinactivity_timeout_seconds = resolve_inactivity_timeout(@@ -289,13 +291,12 @@ async def _background_heartbeat(except TimeoutError:activity.heartbeat()now = time.monotonic()- if (- workflow_handle is not None- and last_event_time is not None- and last_event_time[0] > 0- and (now - last_event_time[0]) < inactivity_timeout_seconds- and (last_workflow_signal is None or (now - last_workflow_signal[0]) >= HEARTBEAT_INTERVAL_SECONDS)- and (agent_active is None or agent_active[0])+ if workflow_handle is not None and _should_signal_workflow_heartbeat(+ now=now,+ last_event_time=last_event_time,+ last_workflow_signal=last_workflow_signal,+ agent_active=agent_active,+ inactivity_timeout_seconds=inactivity_timeout_seconds,):if last_workflow_signal is not None:last_workflow_signal[0] = now@@ -307,6 +308,32 @@ async def _background_heartbeat(logger.warning("relay_workflow_heartbeat_signal_failed", error=str(e))+def _should_signal_workflow_heartbeat(+ *,+ now: float,+ last_event_time: list[float] | None,+ last_workflow_signal: list[float] | None,+ agent_active: list[bool] | None,+ inactivity_timeout_seconds: float,+) -> bool:+ """Gate for the periodic workflow keep-alive signal sent by _background_heartbeat."""+ if last_event_time is None or last_event_time[0] <= 0:+ return False+ if agent_active is not None and not agent_active[0]:+ return False+ if last_workflow_signal is not None and (now - last_workflow_signal[0]) < HEARTBEAT_INTERVAL_SECONDS:+ return False+ # An in-flight turn can be legitimately quiet for minutes (a long tool call+ # emits no session events), so a short per-run idle window (loop runs: 2+ # minutes) must not starve keep-alives mid-turn and let the workflow tear+ # the sandbox down under the agent. Floor the freshness guard at the+ # background default; that still bounds how long a turn that hung without+ # an end_of_turn can pin the sandbox, and the short window keeps applying+ # to post-turn idleness because agent_active is false there.+ event_freshness_seconds = max(inactivity_timeout_seconds, INACTIVITY_TIMEOUT_DEFAULT_SECONDS)+ return (now - last_event_time[0]) < event_freshness_seconds++async def _relay_loop(*,events_url: str,diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex b4e0476076e2..66a6ef44e548 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -13,10 +13,12 @@ from parameterized import parameterizedfrom temporalio.exceptions import ApplicationErrorfrom products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_DEFAULT_SECONDSfrom products.tasks.backend.temporal.process_task import workflow as process_task_workflow_modulefrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextfrom products.tasks.backend.temporal.process_task.activities.relay_sandbox_events import (FINAL_MESSAGE_MAX_CHARS,+ HEARTBEAT_INTERVAL_SECONDS,FinalMessageTracker,RelaySandboxEventsInput,TaskRunRedisStream,@@ -29,6 +31,7 @@ from products.tasks.backend.temporal.process_task.activities.relay_sandbox_event_mark_sandbox_error_best_effort,_persist_final_message,_relay_loop,+ _should_signal_workflow_heartbeat,relay_sandbox_events,)from products.tasks.backend.temporal.process_task.workflow import (@@ -1068,3 +1071,71 @@ class TestFlushPendingText:parts = ["dropped"]await _flush_pending_text(None, parts, [0.0])assert parts == []+++class TestShouldSignalWorkflowHeartbeat:+ @parameterized.expand(+ [+ # Loop runs carry a 2-minute idle window; a quiet in-flight turn past that+ # window must still keep the workflow alive (the mid-turn teardown bug).+ ("mid_turn_quiet_past_short_run_window", True, 300.0, 120.0, True),+ # The floor is the background default, not unbounded: a turn that hung+ # without an end_of_turn stops pinning the sandbox past that window.+ (+ "mid_turn_quiet_past_default_window",+ True,+ float(INACTIVITY_TIMEOUT_DEFAULT_SECONDS) + 60.0,+ 120.0,+ False,+ ),+ # Idle after end_of_turn: the short loop window applies and the run winds down.+ ("idle_agent_stale_events", False, 300.0, 120.0, False),+ ("mid_turn_fresh_events", True, 30.0, 120.0, True),+ # Runs with a window above the default keep their longer window mid-turn.+ ("mid_turn_long_window_still_fresh", True, float(INACTIVITY_TIMEOUT_DEFAULT_SECONDS) + 60.0, 3600.0, True),+ ]+ )+ def test_freshness_gating(+ self,+ _name: str,+ agent_active: bool,+ event_age_seconds: float,+ inactivity_timeout_seconds: float,+ expected: bool,+ ) -> None:+ now = 100_000.0+ assert (+ _should_signal_workflow_heartbeat(+ now=now,+ last_event_time=[now - event_age_seconds],+ last_workflow_signal=[now - HEARTBEAT_INTERVAL_SECONDS - 1.0],+ agent_active=[agent_active],+ inactivity_timeout_seconds=inactivity_timeout_seconds,+ )+ is expected+ )++ @parameterized.expand(+ [+ ("no_events_yet", [0.0], None, False),+ ("signaled_within_interval", None, [100_000.0 - 1.0], False),+ ]+ )+ def test_rate_and_bootstrap_gating(+ self,+ _name: str,+ last_event_time: list[float] | None,+ last_workflow_signal: list[float] | None,+ expected: bool,+ ) -> None:+ now = 100_000.0+ assert (+ _should_signal_workflow_heartbeat(+ now=now,+ last_event_time=last_event_time if last_event_time is not None else [now - 10.0],+ last_workflow_signal=last_workflow_signal,+ agent_active=[True],+ inactivity_timeout_seconds=120.0,+ )+ is expected+ )