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(tasks): fail runs whose agent dies mid-turn and hold the idle window open (#98358)

Harley Alexander0b9db689894f
diff --git a/docs/internal/workflow-ai-task-limits.md b/docs/internal/workflow-ai-task-limits.md
index 959ed1a9a02c..9baa774efcf2 100644
--- a/docs/internal/workflow-ai-task-limits.md
+++ b/docs/internal/workflow-ai-task-limits.md
@@ -18,7 +18,7 @@ Keep both limits enabled when raising capacity. Set the per-workflow limit for t
A workflow run pauses at an AI task step or a scout step until the run it started reaches a terminal status.
After success, the next step sees the dispatch IDs, `status: completed`, and a capped `final_message` (tasks) or `summary` (scouts). The result also includes `pr_urls` when present.
A failed or cancelled run fails the step. The step's `on_error` setting decides whether the workflow continues.
-With `on_error: continue`, the dispatch IDs remain available. The failed step does not store the terminal status, message, or `error_message` in its result.
+With `on_error: continue`, the next step sees the dispatch IDs, the terminal `status`, and `error_message`, so a condition step can route a failed run to a notification.
### Fields the agent returns
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
index 61d6ab47621d..058e1e28a955 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -572,6 +572,31 @@ describe('HogFunctionHandler', () => {
expect(billableMetrics).toHaveLength(0)
})
+ it('drops the stale execResult when the function fails so the step stores no result', async () => {
+ jest.spyOn(mockHogFlowFunctionsService, 'executeWithAsyncFunctions').mockResolvedValueOnce({
+ finished: true,
+ error: 'Request failed with status 500',
+ execResult: { status: 500, body: 'upstream down' },
+ invocation: invocation as any,
+ logs: [],
+ metrics: [],
+ capturedPostHogEvents: [],
+ warehouseWebhookPayloads: [],
+ messageAssets: [],
+ conversionWatchers: [],
+ })
+
+ const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {
+ queue: 'hog',
+ queuePriority: 0,
+ })
+
+ const handlerResult = await hogFunctionHandler.execute({ invocation, action, result: invocationResult })
+
+ expect(handlerResult.error).toBe('Request failed with status 500')
+ expect(handlerResult.result).toBeUndefined()
+ })
+
it('should not emit a billable_invocation metric when recipient opts out', async () => {
;(mockRecipientPreferencesService.shouldSkipAction as jest.Mock).mockResolvedValueOnce('opted_out')
@@ -905,14 +930,22 @@ describe('HogFunctionHandler', () => {
)
})
- it('fails the step when the task did not complete', async () => {
+ it('fails the step with the outcome as its result when the task did not complete', async () => {
invocation.state.currentAction!.resumeResult = {
key: dispatchKey,
status: 'failed',
result: { error_message: 'sandbox crashed' },
}
- await expect(execute()).rejects.toThrow('The task failed: sandbox crashed')
+ const { handlerResult } = await execute()
+
+ expect(handlerResult.error).toEqual(new Error('The task failed: sandbox crashed'))
+ expect(handlerResult.result).toEqual({
+ id: 't1',
+ run_id: 'r1',
+ status: 'failed',
+ error_message: 'sandbox crashed',
+ })
expect(executeSpy).not.toHaveBeenCalled()
})
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index c4f62ae317bb..71534aa5a09c 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -204,9 +204,10 @@ export class HogFunctionHandler implements ActionHandler {
)
}
+ // A failed step keeps its variable untouched: execResult may still hold an earlier fetch response.
return {
nextAction: findContinueAction(invocation),
- result: functionResult.execResult,
+ result: functionResult.error ? undefined : functionResult.execResult,
error: functionResult.error,
}
}
@@ -265,7 +266,7 @@ export class HogFunctionHandler implements ActionHandler {
if (resume.status !== 'completed') {
const detail = typeof payload.error_message === 'string' ? `: ${payload.error_message}` : ''
const outcome = resume.status === 'cancelled' ? 'was cancelled' : 'failed'
- throw new Error(`The ${label} ${outcome}${detail}`)
+ return { error: new Error(`The ${label} ${outcome}${detail}`), result: payload }
}
result.logs.push({
level: 'info',
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index 9938e40ba56c..1b9be3619de8 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -1611,6 +1611,35 @@ describe('Hogflow Executor', () => {
)
})
+ it('stores the output variable of a failed step so the next action can branch on it', async () => {
+ const action = hogFlow.actions.find((a) => a.id === 'function_id_1')!
+ action.on_error = 'continue'
+ action.output_variable = { key: 'task' }
+
+ const functionHandler = executor['actionHandlers']['function']
+ jest.spyOn(functionHandler, 'execute').mockResolvedValueOnce({
+ error: new Error('The task failed'),
+ result: { run_id: 'r1', status: 'failed' },
+ })
+
+ const invocation = createExampleHogFlowInvocation(hogFlow, {
+ event: {
+ ...createHogExecutionGlobals().event,
+ properties: { name: 'Test User' },
+ },
+ })
+ invocation.state.currentAction = {
+ id: 'function_id_1',
+ startedAtTimestamp: DateTime.now().toMillis(),
+ }
+
+ const result = await executor.executeCurrentAction(invocation)
+
+ expect(result.error).toBe('The task failed')
+ expect(result.invocation.state.variables).toEqual({ task: { run_id: 'r1', status: 'failed' } })
+ expect(result.invocation.state.currentAction?.id).toBe('middle_action')
+ })
+
it('does NOT continue to next action when on_error is abort', async () => {
const action = hogFlow.actions.find((a) => a.id === 'function_id_1')!
action.on_error = 'abort'
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index 754895bbbccd..054dce0f01d9 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -595,15 +595,16 @@ export class HogFlowExecutorService {
hogExecutorOptions: options?.hogExecutorOptions,
})
- if (handlerResult.error) {
- throw handlerResult.error instanceof Error ? handlerResult.error : new Error(handlerResult.error)
- }
-
+ // Stored before the error so `on_error: continue` still sees what the step returned.
if (handlerResult.result) {
this.trackActionResult(result, currentAction, handlerResult.result)
result.execResult = handlerResult.result
}
+ if (handlerResult.error) {
+ throw handlerResult.error instanceof Error ? handlerResult.error : new Error(handlerResult.error)
+ }
+
if (handlerResult.finished) {
result.finished = true
result.skipped = handlerResult.skipped
diff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.py
index 2eaddafb7dd6..0526fb6cd24b 100644
--- a/products/tasks/backend/agent_proxy_callback.py
+++ b/products/tasks/backend/agent_proxy_callback.py
@@ -142,6 +142,7 @@ def agent_proxy_callback(request, run_id: str) -> JsonResponse:
task_run = TaskRun.objects.select_related("task__created_by").get(
id=run_id, task_id=task_id, team_id=team_id
)
+ task_run.signal_agent_turn_completed()
if task_run.mode == "interactive":
notify_task_run_turn_completed(task_run)
dispatched = True
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index 5fe006a11fe7..3454c3c21535 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -394,7 +394,7 @@ async def _heartbeat_workflow_if_needed(redis_stream: TaskRunRedisStream, run_id
if is_turn_complete(event):
await redis_stream.set_agent_active(False)
- await _dispatch_turn_completed_if_interactive(run_id)
+ await _dispatch_turn_completed(run_id)
return
if _is_session_update(event):
@@ -445,11 +445,11 @@ def _signal_agent_boot_milestone(
return task_run.signal_agent_boot_milestone(milestone)
-async def _dispatch_turn_completed_if_interactive(run_id: str) -> None:
- await sync_to_async(_dispatch_turn_completed_if_interactive_sync, thread_sensitive=True)(run_id)
+async def _dispatch_turn_completed(run_id: str) -> None:
+ await sync_to_async(_dispatch_turn_completed_sync, thread_sensitive=True)(run_id)
-def _dispatch_turn_completed_if_interactive_sync(run_id: str) -> None:
+def _dispatch_turn_completed_sync(run_id: str) -> None:
if not settings.TEST:
close_old_connections()
@@ -459,6 +459,7 @@ def _dispatch_turn_completed_if_interactive_sync(run_id: str) -> None:
logger.warning("task_run_event_ingest_turn_completed_run_missing", run_id=run_id)
return
+ task_run.signal_agent_turn_completed()
if task_run.mode != "interactive":
return
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index dbfdd0dd0e44..3a3d0a79e39b 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -2524,6 +2524,20 @@ class TaskRun(models.Model):
except Exception as e:
logger.warning("task_run.heartbeat_failed", task_run_id=str(self.id), error=str(e))
+ def signal_agent_turn_completed(self) -> None:
+ import asyncio
+
+ from posthog.temporal.common.client import sync_connect
+
+ from products.tasks.backend.temporal.process_task.workflow import ProcessTaskWorkflow
+
+ try:
+ client = sync_connect()
+ handle = client.get_workflow_handle(self.workflow_id)
+ asyncio.run(handle.signal(ProcessTaskWorkflow.agent_state_changed, arg=False))
+ except Exception as e:
+ logger.warning("task_run.turn_completed_signal_failed", task_run_id=str(self.id), error=str(e))
+
def signal_agent_boot_milestone(
self, milestone: Literal["agent_command_dispatched", "agent_activity_observed"]
) -> bool:
diff --git a/products/tasks/backend/temporal/constants.py b/products/tasks/backend/temporal/constants.py
index 83221b608025..1e5004b50525 100644
--- a/products/tasks/backend/temporal/constants.py
+++ b/products/tasks/backend/temporal/constants.py
@@ -36,6 +36,10 @@ LOOP_RUN_IDLE_TIMEOUT_SECONDS = 2 * 60 # 2 minutes
# a human-driven resume run omits it and keeps the normal come-and-go window.
WORKFLOW_RUN_IDLE_TIMEOUT_SECONDS = 2 * 60 # 2 minutes
+# A single model call over a large context can run a few minutes without emitting an event,
+# so a short idle window only applies once the agent's turn has ended.
+IN_FLIGHT_TURN_IDLE_TIMEOUT_SECONDS = 10 * 60 # 10 minutes
+
# When a loop run's workflow dies without terminalizing (sandbox killed, worker crash),
# the run row is stuck non-terminal and would block every future fire under SKIP forever.
# A live run keeps bumping `updated_at` within its inactivity window, so a non-terminal
diff --git a/products/tasks/backend/temporal/process_task/tests/test_followup.py b/products/tasks/backend/temporal/process_task/tests/test_followup.py
index a41e9fa43a64..fa144d6710e3 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_followup.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_followup.py
@@ -505,6 +505,13 @@ class TestCIFollowUpLoop:
retry_policy=RetryPolicy(maximum_attempts=1),
execution_timeout=timedelta(hours=4),
)
+ # Let setup activities complete before signaling
+ await asyncio.sleep(2)
+ # The agent ends the turn that boot and each CI nudge opened; a run that idles out
+ # with a turn still open is recorded as failed.
+ for _ in range(MAX_CI_REPETITIONS + 1):
+ await handle.signal(ProcessTaskWorkflow.agent_state_changed, False)
+ await env.sleep(CI_FOLLOW_UP_DELAY.total_seconds() + 60)
result = await handle.result()
assert result.success is True
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index c13888f41740..2e4ee6db6d18 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -29,6 +29,7 @@ from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxBase,
from products.tasks.backend.models import SandboxSnapshot, TaskRun
from products.tasks.backend.temporal.babysit_pr.snapshot import BabysitJournal
from products.tasks.backend.temporal.constants import (
+ IN_FLIGHT_TURN_IDLE_TIMEOUT_SECONDS,
INACTIVITY_TIMEOUT_USER_SECONDS,
SANDBOX_TTL_SNAPSHOT_LEAD,
WARM_IDLE_TIMEOUT,
@@ -81,6 +82,7 @@ from products.tasks.backend.temporal.process_task.credential_refresh import (
CredentialRefreshExitReason,
)
from products.tasks.backend.temporal.process_task.workflow import (
+ AGENT_LOST_ERROR_MESSAGE,
PendingFollowup,
PendingPermissionResponse,
ProcessTaskInput,
@@ -1695,6 +1697,66 @@ class TestProcessTaskWorkflowUnit:
def test_warm_idle_timeout_is_shorter_than_active_inactivity(self):
assert WARM_IDLE_TIMEOUT < timedelta(seconds=INACTIVITY_TIMEOUT_USER_SECONDS)
+ @pytest.mark.parametrize(
+ "end_of_turn_received, expected_seconds",
+ [(None, 120), (False, IN_FLIGHT_TURN_IDLE_TIMEOUT_SECONDS), (True, 120)],
+ )
+ async def test_wait_for_event_holds_a_short_idle_window_open_mid_turn(
+ self, monkeypatch, end_of_turn_received, expected_seconds
+ ):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(
+ github_integration_id=123, state={"inactivity_timeout_seconds": 120}, create_pr=False
+ )
+ workflow._end_of_turn_received = end_of_turn_received
+ inactivity_mock = AsyncMock(return_value=process_task_workflow_module.TaskEvent.TIMEOUT_REACHED)
+
+ async def never():
+ await asyncio.sleep(3600)
+
+ monkeypatch.setattr(workflow, "_wait_for_inactivity", inactivity_mock)
+ monkeypatch.setattr(workflow, "_wait_for_task_external_event", AsyncMock(side_effect=never))
+ monkeypatch.setattr(process_task_workflow_module, "_run_lifecycle_bounds_enabled", Mock(return_value=False))
+ monkeypatch.setattr(process_task_workflow_module.workflow, "wait", asyncio.wait)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "set_current_details", Mock())
+
+ assert await workflow._wait_for_event() == process_task_workflow_module.TaskEvent.TIMEOUT_REACHED
+ assert inactivity_mock.await_args is not None
+ assert inactivity_mock.await_args.args[0] == timedelta(seconds=expected_seconds)
+
+ async def test_turn_end_wakes_the_wait_so_the_short_idle_window_re_arms(self, monkeypatch):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(github_integration_id=123)
+
+ async def fake_wait_condition(condition):
+ assert condition()
+
+ monkeypatch.setattr(process_task_workflow_module.workflow, "wait_condition", fake_wait_condition)
+
+ await workflow.agent_state_changed(False)
+
+ assert await workflow._wait_for_task_external_event() == process_task_workflow_module.TaskEvent.SIGNAL_RECEIVED
+ assert workflow._end_of_turn_received is True
+
+ @pytest.mark.parametrize(
+ "outcome, expected",
+ [(None, False), (STEER_DECLINED_OUTCOME, True), (RuntimeError("Sandbox session is dead"), True)],
+ )
+ async def test_a_delivered_followup_opens_the_turn_before_any_heartbeat(self, monkeypatch, outcome, expected):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(github_integration_id=123)
+ workflow._end_of_turn_received = True
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))
+ monkeypatch.setattr(process_task_workflow_module.workflow, "uuid4", Mock(return_value="uuid"))
+ monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())
+ activity = AsyncMock(side_effect=outcome) if isinstance(outcome, Exception) else AsyncMock(return_value=outcome)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", activity)
+
+ await workflow._send_followup_to_sandbox("go", [])
+
+ assert workflow._end_of_turn_received is expected
+
async def test_credential_refresh_exit_marks_sandbox_gone(self, monkeypatch):
workflow = ProcessTaskWorkflow()
workflow._context = _build_context(github_integration_id=123)
@@ -1962,23 +2024,26 @@ class TestProcessTaskWorkflowUnit:
relay_agent_design_signals_mock.assert_called_once()
@pytest.mark.parametrize(
- "origin_product, pr_progress_emitted, ci_repetitions, expected_status",
+ "origin_product, pr_progress_emitted, ci_repetitions, end_of_turn_received, expected_status",
[
- (None, False, 1, "completed"),
- ("user_created", False, 1, "completed"),
+ (None, False, 1, None, "completed"),
+ (None, False, 1, True, "completed"),
+ # The agent was mid-turn when the sandbox vanished, so its work is gone.
+ (None, False, 1, False, "failed"),
+ ("user_created", False, 1, None, "completed"),
# Onboarding runs are one-shot, so a vanished sandbox is a failed setup rather than a
# resumable snapshot.
- ("onboarding", False, 1, "failed"),
+ ("onboarding", False, 1, None, "failed"),
# Unless the PR is already open: the wizard reads the terminal status, so a downgrade
# would report a failed install over a PR the user can merge.
- ("onboarding", True, 1, "completed"),
+ ("onboarding", True, 1, None, "completed"),
# No follow-up round ever ran, so the empty PR latch is unobserved rather than evidence
# of no PR. Downgrading here would fail a run whose PR the loop never got to look at.
- ("onboarding", False, 0, "completed"),
+ ("onboarding", False, 0, None, "completed"),
],
)
async def test_run_completes_when_credential_refresh_detects_sandbox_gone(
- self, monkeypatch, origin_product, pr_progress_emitted, ci_repetitions, expected_status
+ self, monkeypatch, origin_product, pr_progress_emitted, ci_repetitions, end_of_turn_received, expected_status
):
workflow = ProcessTaskWorkflow()
workflow._pr_progress_emitted = pr_progress_emitted
@@ -2021,9 +2086,13 @@ class TestProcessTaskWorkflowUnit:
)
monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())
monkeypatch.setattr(workflow, "_run_credential_refresh_until_sandbox_gone", AsyncMock())
- monkeypatch.setattr(
- workflow, "_wait_for_event", AsyncMock(return_value=process_task_workflow_module.TaskEvent.SANDBOX_GONE)
- )
+
+ # Boot opens the turn, so the parametrized flag state is applied at wait time.
+ async def wait_for_event():
+ workflow._end_of_turn_received = end_of_turn_received
+ return process_task_workflow_module.TaskEvent.SANDBOX_GONE
+
+ monkeypatch.setattr(workflow, "_wait_for_event", wait_for_event)
monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))
# run() awaits the permission-response drainer on the completion path; outside a
@@ -2047,13 +2116,14 @@ class TestProcessTaskWorkflowUnit:
cleanup_sandbox_mock.assert_awaited_once_with("sandbox-123", complete_stream=True)
@pytest.mark.parametrize(
- "event, origin_product, pr_progress_emitted, ci_repetitions, expected_status, expected_kwargs",
+ "event, origin_product, pr_progress_emitted, ci_repetitions, end_of_turn_received, expected_status, expected_kwargs",
[
(
process_task_workflow_module.TaskEvent.TIMEOUT_REACHED,
None,
False,
1,
+ None,
"completed",
{"timed_out_inactivity": True},
),
@@ -2062,6 +2132,7 @@ class TestProcessTaskWorkflowUnit:
"onboarding",
False,
1,
+ None,
"failed",
{"timed_out_inactivity": True},
),
@@ -2072,6 +2143,7 @@ class TestProcessTaskWorkflowUnit:
"onboarding",
True,
1,
+ None,
"completed",
{"timed_out_inactivity": True},
),
@@ -2082,14 +2154,26 @@ class TestProcessTaskWorkflowUnit:
"onboarding",
False,
0,
+ None,
"completed",
{"timed_out_inactivity": True},
),
+ # The agent was still mid-turn when the timer fired, so it died rather than finished.
+ (
+ process_task_workflow_module.TaskEvent.TIMEOUT_REACHED,
+ None,
+ False,
+ 1,
+ False,
+ "failed",
+ {"error_message": AGENT_LOST_ERROR_MESSAGE, "timed_out_inactivity": True},
+ ),
(
process_task_workflow_module.TaskEvent.MAX_DURATION_REACHED,
None,
False,
1,
+ None,
"failed",
{"timeout_marker": TIMED_OUT_WALL_CLOCK_STATE_KEY},
),
@@ -2098,13 +2182,22 @@ class TestProcessTaskWorkflowUnit:
"onboarding",
False,
1,
+ None,
"failed",
{"timeout_marker": TIMED_OUT_WALL_CLOCK_STATE_KEY},
),
],
)
async def test_run_terminalizes_timeouts_with_their_marker(
- self, monkeypatch, event, origin_product, pr_progress_emitted, ci_repetitions, expected_status, expected_kwargs
+ self,
+ monkeypatch,
+ event,
+ origin_product,
+ pr_progress_emitted,
+ ci_repetitions,
+ end_of_turn_received,
+ expected_status,
+ expected_kwargs,
):
# The wall-clock cap is a failure for every origin; the inactivity timeout only fails for
# onboarding runs that delivered nothing, because other origins resume from the timed-out
@@ -2148,7 +2241,12 @@ class TestProcessTaskWorkflowUnit:
),
)
monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())
- monkeypatch.setattr(workflow, "_wait_for_event", AsyncMock(return_value=event))
+
+ async def wait_for_event():
+ workflow._end_of_turn_received = end_of_turn_received
+ return event
+
+ monkeypatch.setattr(workflow, "_wait_for_event", wait_for_event)
monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))
# workflow.logger resolves the replay flag off the workflow event loop, which this
# loop-free unit test doesn't have.
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index f197774fa7e3..c096816255f2 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -318,6 +318,7 @@ class _BabysitDispatch:
from products.tasks.backend.temporal.constants import ( # noqa: E402
CI_FOLLOW_UP_DELAY,
DEFAULT_CI_MESSAGE,
+ IN_FLIGHT_TURN_IDLE_TIMEOUT_SECONDS,
INACTIVITY_TIMEOUT,
MAX_CI_REPETITIONS,
PENDING_MESSAGE_FORWARD_TIMEOUT_SECONDS,
@@ -414,6 +415,18 @@ _PATCH_ID_RUN_LIFECYCLE_BOUNDS = "tasks-run-lifecycle-bounds"
_PATCH_ID_SNAPSHOT_BEFORE_CI_FOLLOW_UP = "tasks-snapshot-before-ci-follow-up"
+AGENT_LOST_ERROR_MESSAGE = "The agent stopped before finishing its turn"
+
+# Replays of pre-rollout histories must keep recording an idle exit as completed.
+_PATCH_ID_TURN_OPENS_ON_DISPATCH = "tasks-turn-opens-on-dispatch"
+
+
+def _turn_opens_on_dispatch() -> bool:
+ if not workflow.in_workflow():
+ return True
+ return workflow.patched(_PATCH_ID_TURN_OPENS_ON_DISPATCH)
+
+
# Keeps an interactive run alive when follow-up delivery exhausts retries, releasing
# the message's dedupe key so a retry can land; background runs keep the fail-fast
# terminalization poll_for_turn callers rely on. Same cleanup lifecycle as above.
@@ -480,6 +493,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._client_activity_received: bool = False
self._agent_active: Optional[bool] = None
self._end_of_turn_received: Optional[bool] = None
+ self._turn_ended_received = False
self._last_agent_heartbeat_at: Optional[datetime] = None
self._prewarmed: bool = False
self._first_user_message_received: bool = False
@@ -571,6 +585,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
or self._sandbox_gone
or self._heartbeat_received
or self._client_activity_received
+ or self._turn_ended_received
or self._has_dispatchable_followup()
or len(self._pending_permission_responses) > 0
)
@@ -852,6 +867,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
inactivity_timeout = max(base_timeout, ci_follow_up_floor)
else:
inactivity_timeout = base_timeout
+ if self._end_of_turn_received is False and not testing_override_active:
+ inactivity_timeout = max(inactivity_timeout, timedelta(seconds=IN_FLIGHT_TURN_IDLE_TIMEOUT_SECONDS))
workflow.set_current_details(
self._describe_wait(
@@ -1208,6 +1225,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._pending_followups.append(input.initial_message)
await self._dispatch_next_followup()
elif input.resumed_sandbox is None and self._should_forward_pending_user_message():
+ # A non-interactive agent starts its first turn on boot, before any event arrives.
+ if _turn_opens_on_dispatch():
+ self._end_of_turn_received = False
await self._forward_pending_user_message()
# Wait for completion signal or inactivity timeout.
@@ -1461,6 +1481,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):
)
self._client_activity_received = False
continue
+
+ # Re-arm the wait so the idle window drops back to the short one.
+ if self._turn_ended_received:
+ self._turn_ended_received = False
+ continue
case _:
raise ValueError(f"Unknown event type: {event}")
@@ -1494,6 +1519,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# A run that outlived the hard cap is a failure, not a completion, and the
# state marker carries the reason so error_message stays empty.
await self._update_task_run_status("failed", timeout_marker=TIMED_OUT_WALL_CLOCK_STATE_KEY)
+ elif timeout_event is not None and self._end_of_turn_received is False:
+ # A turn still open at the timeout means the agent died, not that it finished.
+ await self._update_task_run_status(
+ "failed", error_message=AGENT_LOST_ERROR_MESSAGE, timed_out_inactivity=True
+ )
elif timeout_event is not None:
inactivity_status = "failed" if self._onboarding_exit_is_failure() else "completed"
await self._update_task_run_status(inactivity_status, timed_out_inactivity=True)
@@ -2754,9 +2784,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):
return not self.context.create_pr or self._ci_repetitions > 0
def _mark_sandbox_gone(self) -> None:
- # A sandbox that vanished mid-setup is a failed setup for onboarding; see
- # _onboarding_exit_is_failure for why a run that already opened its PR is exempt.
- self._completion_status = "failed" if self._onboarding_exit_is_failure() else "completed"
+ # A sandbox that vanished mid-turn took the agent's work with it. Mid-setup it is a failed
+ # setup for onboarding; see _onboarding_exit_is_failure for the open-PR exemption.
+ agent_lost = self._end_of_turn_received is False
+ self._completion_status = "failed" if agent_lost or self._onboarding_exit_is_failure() else "completed"
self._completion_error = SANDBOX_GONE_ERROR_MESSAGE
self._completion_timeout_marker = SANDBOX_GONE_STATE_KEY
self._task_completed = True
@@ -3248,6 +3279,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._heartbeat_received = True
self._last_active_time = now
self._last_agent_heartbeat_at = now
+ self._end_of_turn_received = False
@temporalio.workflow.signal
async def client_activity(self) -> None:
@@ -3258,6 +3290,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
async def agent_state_changed(self, agent_active: bool) -> None:
self._agent_active = agent_active
self._end_of_turn_received = not agent_active
+ if not agent_active:
+ self._turn_ended_received = True
@temporalio.workflow.signal
async def agent_command_dispatched(self) -> None:
@@ -3435,7 +3469,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
)
try:
max_attempts = 1 if self.context.task_runtime == "pi" else SEND_FOLLOWUP_MAX_ATTEMPTS
- return await workflow.execute_activity(
+ outcome = await workflow.execute_activity(
send_followup_to_sandbox,
SendFollowupToSandboxInput(
run_id=self.context.run_id,
@@ -3455,6 +3489,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):
maximum_attempts=max_attempts,
),
)
+ # A delivered message opens a turn: the first heartbeat may lag or be throttled away.
+ if outcome != STEER_DECLINED_OUTCOME and _turn_opens_on_dispatch():
+ self._end_of_turn_received = False
+ return outcome
except Exception as e:
error_properties = self._activity_error_properties(e)
cause_message = error_properties.get("cause_error_message")
diff --git a/products/tasks/backend/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.py
index 1f5e56ba89a2..b331f70850ab 100644
--- a/products/tasks/backend/tests/test_agent_proxy_callback.py
+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py
@@ -170,12 +170,16 @@ class TestAgentProxyCallback(TestCase):
self.assertTrue(response.json()["dispatched"])
notify.assert_called_once()
- def test_awaiting_input_skipped_for_background_run(self) -> None:
- with patch("products.tasks.backend.agent_proxy_callback.notify_task_run_turn_completed") as notify:
+ def test_awaiting_input_signals_turn_end_but_skips_push_for_background_run(self) -> None:
+ with (
+ patch("products.tasks.backend.agent_proxy_callback.notify_task_run_turn_completed") as notify,
+ patch.object(TaskRun, "signal_agent_turn_completed") as signal_turn_completed,
+ ):
response = self._post(self._body(kind="awaiting_input", agent_active=False), token=self._token())
self.assertEqual(response.status_code, 200)
self.assertFalse(response.json()["dispatched"])
notify.assert_not_called()
+ signal_turn_completed.assert_called_once()
def test_unknown_run_returns_200_not_dispatched(self) -> None:
run = self.task.create_run()
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index e22914894e74..b5e18db390b3 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -420,6 +420,18 @@ class TestTaskRunEventIngest(TestCase):
notify_turn_completed.assert_called_once()
self.assertEqual(notify_turn_completed.call_args.args[0].id, self.task_run.id)
+ def test_turn_complete_ingest_signals_the_workflow_for_a_background_run(self) -> None:
+ token = self._create_token()
+
+ with patch.object(TaskRun, "signal_agent_turn_completed") as signal_turn_completed:
+ status, _ = self._call_ingest(
+ token,
+ [{"seq": 1, "event": {"type": "notification", "notification": {"method": "_posthog/turn_complete"}}}],
+ )
+
+ self.assertEqual(status, 200)
+ signal_turn_completed.assert_called_once()
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_workflow_heartbeat_does_not_block_event_loop(self) -> None:
token = self._create_token()