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): keep runs alive when a follow-up cannot be delivered (#82990)

Charles Viend71551cc73f6
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 842f3a04e1d7..7d043fae642b 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_followup.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_followup.py
@@ -14,6 +14,7 @@ from products.tasks.backend.temporal.process_task.activities.create_resume_snaps
CreateResumeSnapshotInput,
CreateResumeSnapshotOutput,
)
+from products.tasks.backend.temporal.process_task.activities.emit_progress_activity import EmitProgressInput
from products.tasks.backend.temporal.process_task.activities.get_pr_context import GetPrContextOutput
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.activities.provision_sandbox import (
@@ -36,6 +37,21 @@ _status_updates: list[tuple[str, str | None, bool]] = []
@activity.defn(name="get_task_processing_context")
def _mock_get_context(_input) -> TaskProcessingContext:
+ return TaskProcessingContext(
+ task_id="task-1",
+ run_id="run-1",
+ team_id=1,
+ team_uuid=str(uuid.uuid4()),
+ organization_id=str(uuid.uuid4()),
+ github_integration_id=1,
+ repository="org/repo",
+ distinct_id="user-1",
+ state={"mode": "interactive"},
+ )
+
+
[email protected](name="get_task_processing_context")
+def _mock_get_context_background(_input) -> TaskProcessingContext:
return TaskProcessingContext(
task_id="task-1",
run_id="run-1",
@@ -100,6 +116,14 @@ def _mock_send_followup_raises(_input) -> None:
raise RuntimeError("Sandbox session is dead")
+_progress_events: list[tuple[str, str, str, str | None, str]] = []
+
+
[email protected](name="emit_progress_activity")
+def _mock_emit_progress(input: EmitProgressInput) -> None:
+ _progress_events.append((input.step, input.status, input.label, input.detail, input.group))
+
+
@activity.defn(name="track_workflow_event")
def _mock_track(_input) -> None:
pass
@@ -119,12 +143,11 @@ pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
class TestFollowupDeliveryFailure:
+ @pytest.mark.parametrize("message_id", ["msg-1", None])
@pytest.mark.timeout(30, func_only=True)
- async def test_failed_followup_marks_run_as_failed_promptly(self):
- """The workflow must exit its main loop and mark the run as failed
- within seconds when a followup delivery fails — not after the
- full inactivity timeout."""
+ async def test_failed_interactive_followup_keeps_run_alive_and_surfaces_the_failure(self, message_id):
_status_updates.clear()
+ _progress_events.clear()
async with await WorkflowEnvironment.start_time_skipping() as env:
task_queue = f"test-{uuid.uuid4()}"
@@ -141,6 +164,80 @@ class TestFollowupDeliveryFailure:
_mock_start_agent,
_mock_forward,
_mock_send_followup_raises,
+ _mock_emit_progress,
+ _mock_track,
+ _mock_read_logs,
+ _mock_cleanup,
+ ],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ activity_executor=ThreadPoolExecutor(max_workers=5),
+ ):
+ handle = await env.client.start_workflow(
+ ProcessTaskWorkflow.run,
+ ProcessTaskInput(run_id="run-1"),
+ id=f"test-{uuid.uuid4()}",
+ task_queue=task_queue,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ # The inactivity exit time-skips hours past the failed delivery.
+ execution_timeout=timedelta(days=2),
+ )
+
+ # Let setup activities complete before signaling
+ await asyncio.sleep(2)
+
+ # A message_id is optional the whole way down: real user follow-ups
+ # (thread comments, first activation message, signal-report replies) reach
+ # this path with none, so the failure card must not hinge on one.
+ signal_args = ["test followup", []]
+ if message_id is not None:
+ signal_args.append(message_id)
+ await handle.signal(ProcessTaskWorkflow.send_followup_message, args=signal_args)
+
+ result = await handle.result()
+
+ assert result.success is True
+
+ assert [(s, e) for s, e, _ in _status_updates if s == "failed"] == []
+ inactivity_exits = [(s, timed_out) for s, _, timed_out in _status_updates if timed_out]
+ assert inactivity_exits == [("completed", True)]
+ delivery_failures = [event for event in _progress_events if event[0] == "followup_delivery"]
+ assert len(delivery_failures) == 1
+ step, status, label, detail, group = delivery_failures[0]
+ assert (step, status, label, detail) == (
+ "followup_delivery",
+ "failed",
+ "Couldn't deliver your message",
+ "RuntimeError: Sandbox session is dead",
+ )
+ if message_id is not None:
+ assert group == f"followup-delivery:{message_id}:run-1"
+ else:
+ # No id to key on, so the run-id-scoped group carries a generated middle segment.
+ assert group.startswith("followup-delivery:")
+ assert group.endswith(":run-1")
+ assert group != "followup-delivery::run-1"
+
+ @pytest.mark.timeout(30, func_only=True)
+ async def test_failed_background_followup_marks_run_as_failed_promptly(self):
+ _status_updates.clear()
+ _progress_events.clear()
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ task_queue = f"test-{uuid.uuid4()}"
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ProcessTaskWorkflow],
+ activities=[
+ _mock_get_context_background,
+ _mock_update_status,
+ _mock_prepare_sandbox,
+ _mock_create_sandbox,
+ _mock_clone_repository,
+ _mock_start_agent,
+ _mock_forward,
+ _mock_send_followup_raises,
+ _mock_emit_progress,
_mock_track,
_mock_read_logs,
_mock_cleanup,
@@ -154,6 +251,7 @@ class TestFollowupDeliveryFailure:
id=f"test-{uuid.uuid4()}",
task_queue=task_queue,
retry_policy=RetryPolicy(maximum_attempts=1),
+ # The short timeout is the assertion: failing fast, not at the inactivity exit.
execution_timeout=timedelta(minutes=2),
)
@@ -167,8 +265,8 @@ class TestFollowupDeliveryFailure:
assert result.success is True
failed_updates = [(s, e) for s, e, _ in _status_updates if s == "failed"]
- assert len(failed_updates) == 1
- assert failed_updates[0][1] == "Follow-up delivery failed: RuntimeError: Sandbox session is dead"
+ assert failed_updates == [("failed", "Follow-up delivery failed: RuntimeError: Sandbox session is dead")]
+ assert [event for event in _progress_events if event[0] == "followup_delivery"] == []
_ci_context_overrides: dict = {}
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 8b8061a5dacc..fe662035e989 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -60,6 +60,8 @@ from products.tasks.backend.temporal.process_task.activities import (
track_workflow_event,
update_task_run_status,
)
+from products.tasks.backend.temporal.process_task.activities.emit_progress_activity import EmitProgressInput
+from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import SendFollowupToSandboxInput
from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (
SANDBOX_GONE_STATE_KEY,
TIMED_OUT_WALL_CLOCK_STATE_KEY,
@@ -592,6 +594,54 @@ class TestProcessTaskFollowupDispatch:
assert workflow._pending_followups == []
+class TestFollowupDeliveryFailureBookkeeping:
+ def _workflow(self, monkeypatch, *, mode: str, patched: bool):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(github_integration_id=123, state={"mode": mode})
+ emitted: list[EmitProgressInput] = []
+
+ async def fake_execute_activity(_activity, activity_input, **_kwargs):
+ if isinstance(activity_input, SendFollowupToSandboxInput):
+ raise RuntimeError("delivery failed")
+ if isinstance(activity_input, EmitProgressInput):
+ emitted.append(activity_input)
+ return None
+
+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=patched))
+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
+ return workflow, emitted
+
+ async def test_failed_interactive_delivery_releases_the_message_for_retry(self, monkeypatch):
+ workflow, emitted = self._workflow(monkeypatch, mode="interactive", patched=True)
+
+ await workflow.send_followup_message("try this", [], "msg-1")
+ assert len(workflow._pending_followups) == 1
+
+ result = await workflow._send_followup_to_sandbox("try this", [], message_id="msg-1")
+
+ assert result is None
+ assert workflow._task_completed is False
+ assert workflow._completion_status == "completed"
+ assert [(e.step, e.status) for e in emitted] == [("followup_delivery", "failed")]
+
+ await workflow.send_followup_message("try this", [], "msg-1")
+ assert len(workflow._pending_followups) == 2
+
+ @pytest.mark.parametrize("mode,patched", [("interactive", False), ("background", True)])
+ async def test_failed_delivery_terminalizes_when_keep_alive_does_not_apply(self, monkeypatch, mode, patched):
+ workflow, emitted = self._workflow(monkeypatch, mode=mode, patched=patched)
+
+ result = await workflow._send_followup_to_sandbox("try this", [], message_id="msg-1")
+
+ assert result is None
+ assert workflow._task_completed is True
+ assert workflow._completion_status == "failed"
+ assert workflow._completion_error_type == "followup_delivery_failed"
+ assert emitted == []
+
+
@pytest.mark.django_db
class TestProcessTaskWorkflowUnit:
def test_quota_recheck_not_scheduled_for_non_pr_runs(self):
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index a0601ac97a37..2b2da61cee70 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -326,6 +326,11 @@ _PATCH_ID_RUN_LIFECYCLE_BOUNDS = "tasks-run-lifecycle-bounds"
_PATCH_ID_SNAPSHOT_BEFORE_CI_FOLLOW_UP = "tasks-snapshot-before-ci-follow-up"
+# 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.
+_PATCH_ID_FOLLOWUP_FAILURE_KEEPS_RUN = "tasks-followup-failure-keeps-run"
+
# `Task.OriginProduct.ONBOARDING`, mirrored as a literal so workflow code stays free of
# Django model imports.
_ONBOARDING_ORIGIN_PRODUCT = "onboarding"
@@ -801,7 +806,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._ci_repetitions += 1
ci_message = self.context.ci_prompt or DEFAULT_CI_MESSAGE
self._last_active_time = workflow.now()
- await self._send_followup_to_sandbox(ci_message, [])
+ await self._send_followup_to_sandbox(ci_message, [], user_originated=False)
@workflow.run
async def run(self, input: ProcessTaskInput) -> ProcessTaskOutput:
@@ -2566,6 +2571,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
context: dict[str, Any] | None = None,
*,
steer: bool = False,
+ user_originated: bool = True,
) -> str | None:
workflow.logger.info(
"send_followup_dispatch_begin",
@@ -2608,8 +2614,24 @@ class ProcessTaskWorkflow(PostHogWorkflow):
**error_properties,
},
)
- # Mark the run as failed so poll_for_turn sees a terminal status
- # immediately instead of waiting for the inactivity timeout.
+ if self.context.mode == "interactive" and workflow.patched(_PATCH_ID_FOLLOWUP_FAILURE_KEEPS_RUN):
+ if message_id:
+ dedupe_key = _message_dedupe_key(message_id, actor_user_id, context)
+ if dedupe_key in self._accepted_message_id_set:
+ self._accepted_message_id_set.discard(dedupe_key)
+ self._accepted_message_ids.remove(dedupe_key)
+ if user_originated:
+ # A user follow-up can arrive without a message_id, so the card can't hinge on
+ # one; the generated group still gives the user a failure notice instead of a
+ # silently frozen conversation. CI nudges skip it because the copy is user-facing.
+ await self._emit_progress(
+ step="followup_delivery",
+ status="failed",
+ label="Couldn't deliver your message",
+ group=f"followup-delivery:{message_id or workflow.uuid4()}",
+ detail=str(cause_message or e),
+ )
+ return None
self._completion_status = "failed"
self._completion_error = f"Follow-up delivery failed: {cause_message or e}"
self._completion_error_type = "followup_delivery_failed"