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.

feat(tasks): cap run duration independently of heartbeats (#74039)

Fernando Gomes57c128deeb7d
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 0f7fafc99d77..d8233fb03375 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -102,6 +102,13 @@ TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD: int = get_from_env(
# fast.
TASKS_INACTIVITY_TIMEOUT_SECONDS: int = get_from_env("TASKS_INACTIVITY_TIMEOUT_SECONDS", 0, type_cast=int)
+# Hard wall-clock cap on a process_task run, measured from the start of the
+# continue_as_new chain and never reset by heartbeats, so it bounds total run time even
+# while a wedged agent keeps heartbeating. Interactive sessions are exempt at the call
+# site. Set low (e.g. 60) for local testing; 0 or negative disables the cap entirely,
+# matching TASKS_INACTIVITY_TIMEOUT_SECONDS above.
+TASKS_MAX_RUN_DURATION_SECONDS: int = get_from_env("TASKS_MAX_RUN_DURATION_SECONDS", 3 * 60 * 60, type_cast=int)
+
# Override the delay before the first in-sandbox credential refresh (default 20
# minutes). Set this low (e.g. 30) for local testing so the refresh loop fires
# quickly instead of waiting out the GitHub token's lifetime.
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 91da06c3473c..2e5bdb2433b0 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1851,6 +1851,10 @@ def _sync_automation_schedule(automation: TaskAutomation) -> None:
# signal or terminate-and-restart it.
# - pending_external_followups / pending_external_followups_generation are the workflow-owned
# durable queue; a caller could otherwise inject actor identity into a restored follow-up.
+# - timed_out_inactivity / timed_out_wall_clock / sandbox_gone are the workflow's terminal reason
+# markers, written only by the update_task_run_status activity. Slack reads them to decide that
+# a FAILED run was a timeout and stays quiet (post_slack_update._post_failure_or_timeout), so a
+# caller could otherwise stamp one on a genuine failure and suppress its error card.
# These keys are reserved for server-owned run state, never PATCH input.
_PROTECTED_RUN_STATE_KEYS = frozenset(
{
@@ -1888,6 +1892,13 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
"cancel_fallback_cleanup_complete",
"pending_external_followups",
"pending_external_followups_generation",
+ # Terminal reason markers owned by the workflow (see the note above). Spelled as literals
+ # rather than imported from the update_task_run_status activity, which would pull temporalio
+ # onto this module's import path; the workflow writes them through
+ # TaskRun.update_state_atomic, which does not go through this filter.
+ "timed_out_inactivity",
+ "timed_out_wall_clock",
+ "sandbox_gone",
# Credential grant decided at Task.create_and_run time by server-owned callers (the scout
# runner); a PATCHable key would let any task controller mint a GitHub token onto a
# queued repo-less run.
diff --git a/products/tasks/backend/temporal/constants.py b/products/tasks/backend/temporal/constants.py
index fe298898a161..5726dfb518c2 100644
--- a/products/tasks/backend/temporal/constants.py
+++ b/products/tasks/backend/temporal/constants.py
@@ -65,6 +65,23 @@ def resolve_inactivity_timeout(*, is_user_origin: bool = False, state: dict | No
# don't have task context. The CI follow-up timing lives in `task_management`.
INACTIVITY_TIMEOUT = resolve_inactivity_timeout()
+
+def resolve_max_run_duration() -> timedelta | None:
+ """Hard wall-clock cap on a single run, or None when the cap is disabled.
+
+ Independent of the inactivity timer: every agent heartbeat resets that timer, so
+ an agent that is wedged but still emitting activity never trips it. This cap bounds
+ total run time regardless of heartbeats, so it sits well above the largest
+ legitimate autonomous run (inactivity grace plus the CI follow-up rounds).
+
+ A non-positive setting means "no cap", the same convention
+ `TASKS_INACTIVITY_TIMEOUT_SECONDS` uses. Reading 0 as a zero-second cap would
+ terminalize every non-interactive run in the deployment on its first loop iteration.
+ """
+ seconds = settings.TASKS_MAX_RUN_DURATION_SECONDS
+ return timedelta(seconds=seconds) if seconds > 0 else None
+
+
WARM_IDLE_TIMEOUT = timedelta(minutes=10)
# CI follow-up cadence after the agent has been idle.
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 2f6456967e7a..f73f9e62f0ab 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -35,7 +35,7 @@ from products.tasks.backend.logic.services.sandbox_config import (
MAX_SANDBOX_TTL_SECONDS,
)
from products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRun
-from products.tasks.backend.temporal.constants import resolve_inactivity_timeout
+from products.tasks.backend.temporal.constants import resolve_inactivity_timeout, resolve_max_run_duration
from products.tasks.backend.temporal.observability import emit_agent_log, log_with_activity_context
from products.tasks.backend.temporal.process_task.utils import (
format_allowed_domains_for_log,
@@ -215,6 +215,19 @@ class TaskProcessingContext:
)
return resolve_inactivity_timeout(is_user_origin=is_user_origin, state=self.state)
+ def max_run_duration(self) -> timedelta | None:
+ """Hard wall-clock cap on total run time, or None when the run is exempt.
+
+ Unlike the inactivity timeout, this is not reset by heartbeats, so it stops a
+ wedged-but-heartbeating agent that would otherwise run forever. Interactive
+ sessions can legitimately stay open for hours under a human, so they are
+ uncapped; autonomous runs get the cap as a safety net, unless the setting
+ disables it deployment-wide.
+ """
+ if self.mode == "interactive":
+ return None
+ return resolve_max_run_duration()
+
def sandbox_resource_overrides(self) -> dict[str, float | int]:
"""Per-task SandboxConfig overrides (compute + TTL), clamped to server-owned bounds.
`bool` is excluded explicitly — it's an `int` subclass and would slip through as 0/1."""
diff --git a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
index 3ef7be8fada5..e7760f0a3871 100644
--- a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
+++ b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
@@ -12,6 +12,7 @@ from posthog.temporal.common.utils import close_db_connections
from products.tasks.backend.access import has_tasks_access
from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (
TIMED_OUT_INACTIVITY_STATE_KEY,
+ TIMED_OUT_WALL_CLOCK_STATE_KEY,
)
logger = get_logger(__name__)
@@ -136,8 +137,7 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:
elif task_run.status == TaskRun.Status.CANCELLED:
_post_cancelled_once(task_run, handler, task_url)
elif task_run.status == TaskRun.Status.FAILED:
- error = task_run.error_message or "Unknown error"
- _post_error_once(task_run, handler, error, task_url)
+ _post_failure_or_timeout(task_run, handler, task_url)
return
if task_run.status == TaskRun.Status.COMPLETED:
@@ -152,8 +152,7 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:
elif task_run.status == TaskRun.Status.CANCELLED:
_post_cancelled_once(task_run, handler, task_url)
elif task_run.status == TaskRun.Status.FAILED:
- error = task_run.error_message or "Unknown error"
- _post_error_once(task_run, handler, error, task_url)
+ _post_failure_or_timeout(task_run, handler, task_url)
else:
if pr_url:
_post_pr_opened_notification_once(task_run, handler, pr_url, task_url)
@@ -173,14 +172,36 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:
logger.exception("post_slack_update_failed", run_id=input.run_id)
-def _is_timed_out_completion(task_run: Any) -> bool:
- """The error_message check covers runs finalized before the state marker existed."""
+def _has_timeout_marker(task_run: Any) -> bool:
+ """True only for runs the workflow itself terminalized as a timeout."""
state = task_run.state if isinstance(task_run.state, dict) else {}
- if state.get(TIMED_OUT_INACTIVITY_STATE_KEY):
+ return bool(state.get(TIMED_OUT_INACTIVITY_STATE_KEY) or state.get(TIMED_OUT_WALL_CLOCK_STATE_KEY))
+
+
+def _is_timed_out_completion(task_run: Any) -> bool:
+ """The error_message check covers COMPLETED runs finalized before the state markers existed."""
+ if _has_timeout_marker(task_run):
return True
return bool(task_run.error_message and "timed out" in task_run.error_message)
+def _post_failure_or_timeout(task_run: Any, handler: Any, task_url: str | None) -> None:
+ """A genuine failure posts an error card; a timeout stays quiet (just clears progress).
+
+ Timeouts are recorded as FAILED so the UI and analytics can tell a hang apart from a
+ success, but Slack should not ping a loud error card on every timeout. Only the explicit
+ state markers count here: plenty of genuine failures carry "timed out" in their message
+ (sandbox request timeouts, agent command timeouts, the wizard's own deadline), and those
+ still deserve an error card.
+ """
+ if _has_timeout_marker(task_run):
+ handler.update_reaction("hedgehog")
+ handler.delete_progress()
+ return
+ error = task_run.error_message or "Unknown error"
+ _post_error_once(task_run, handler, error, task_url)
+
+
def _get_stage_from_status(status: str, stage: str | None = None) -> str:
"""Map task run status to human-readable stage. Uses the run's stage field when available."""
if stage:
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
index 6557eddf4e93..6fd07a4b6d3d 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
@@ -6,6 +6,8 @@ from temporalio.exceptions import ApplicationError
from products.tasks.backend.models import Loop, TaskRun
from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (
+ SANDBOX_GONE_STATE_KEY,
+ TIMED_OUT_WALL_CLOCK_STATE_KEY,
UpdateTaskRunStatusInput,
update_task_run_status,
)
@@ -84,6 +86,37 @@ class TestUpdateTaskRunStatusActivity:
# Merge, not replace: pre-existing state keys survive the marker write.
assert test_task_run.state.get("existing_key") == "kept"
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ "marker",
+ [TIMED_OUT_WALL_CLOCK_STATE_KEY, SANDBOX_GONE_STATE_KEY],
+ )
+ def test_timeout_marker_is_recorded_in_state(self, activity_environment, test_task_run, marker):
+ input_data = UpdateTaskRunStatusInput(
+ run_id=str(test_task_run.id),
+ status=TaskRun.Status.FAILED,
+ timeout_marker=marker,
+ )
+ async_to_sync(activity_environment.run)(update_task_run_status, input_data)
+
+ test_task_run.refresh_from_db()
+ assert test_task_run.status == TaskRun.Status.FAILED
+ assert test_task_run.error_message is None
+ assert test_task_run.state.get(marker) is True
+
+ @pytest.mark.django_db(transaction=True)
+ def test_unknown_timeout_marker_is_not_written(self, activity_environment, test_task_run):
+ # The marker comes off the wire, so only allowlisted keys may reach TaskRun.state.
+ input_data = UpdateTaskRunStatusInput(
+ run_id=str(test_task_run.id),
+ status=TaskRun.Status.FAILED,
+ timeout_marker="arbitrary_key",
+ )
+ async_to_sync(activity_environment.run)(update_task_run_status, input_data)
+
+ test_task_run.refresh_from_db()
+ assert "arbitrary_key" not in (test_task_run.state or {})
+
@pytest.mark.django_db(transaction=True)
@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
def test_publishes_stream_state_event(self, mock_publish_stream_state_event, activity_environment, test_task_run):
diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
index 3646f6abc184..143d11ff2b4e 100644
--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
@@ -18,6 +18,19 @@ from products.tasks.backend.temporal.observability import log_with_activity_cont
# TaskRun.state marker for runs completed by the inactivity timeout; kept out of
# error_message so a normal completion never reads as a failure.
TIMED_OUT_INACTIVITY_STATE_KEY = "timed_out_inactivity"
+# TaskRun.state marker for runs stopped by the hard wall-clock cap. Written without an
+# error_message: the marker is the machine-readable reason, and a fabricated prose
+# message would just get parroted back to users by every error surface.
+TIMED_OUT_WALL_CLOCK_STATE_KEY = "timed_out_wall_clock"
+# TaskRun.state marker for runs terminalized because their sandbox disappeared.
+SANDBOX_GONE_STATE_KEY = "sandbox_gone"
+
+# Allowlist for `timeout_marker` so the activity never writes an arbitrary state key.
+_TERMINAL_STATE_MARKERS = (
+ TIMED_OUT_INACTIVITY_STATE_KEY,
+ TIMED_OUT_WALL_CLOCK_STATE_KEY,
+ SANDBOX_GONE_STATE_KEY,
+)
_TERMINAL_STATUSES = (TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED)
@@ -31,6 +44,9 @@ class UpdateTaskRunStatusInput:
# Optional with a default so payloads from in-flight workflows started
# before this field existed still deserialize.
error_type: Optional[str] = None
+ # One of _TERMINAL_STATE_MARKERS, recorded as a True key in TaskRun.state.
+ # Optional with a default for the same in-flight payload reason as error_type.
+ timeout_marker: Optional[str] = None
@activity.defn
@@ -71,11 +87,10 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:
task_run.status = input.status
if input.error_message:
task_run.error_message = input.error_message
- if input.timed_out_inactivity:
+ marker = TIMED_OUT_INACTIVITY_STATE_KEY if input.timed_out_inactivity else input.timeout_marker
+ if marker in _TERMINAL_STATE_MARKERS:
# Atomic merge so concurrent state writers aren't clobbered; reassigned so reads below see it.
- task_run.state = TaskRun.update_state_atomic(
- task_run.id, updates={TIMED_OUT_INACTIVITY_STATE_KEY: True}
- )
+ task_run.state = TaskRun.update_state_atomic(task_run.id, updates={marker: True})
if input.status in [TaskRun.Status.COMPLETED, TaskRun.Status.FAILED]:
task_run.completed_at = timezone.now()
elif (
diff --git a/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py b/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py
new file mode 100644
index 000000000000..11dd3b357321
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py
@@ -0,0 +1,65 @@
+from datetime import timedelta
+
+from django.test import override_settings
+
+from products.tasks.backend.temporal.constants import MAX_INACTIVITY_TIMEOUT_SECONDS, resolve_max_run_duration
+from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
+
+DEFAULT_CAP_SECONDS = 3 * 60 * 60
+
+
+def _context(state: dict | None) -> TaskProcessingContext:
+ return TaskProcessingContext(
+ task_id="task-id",
+ run_id="run-id",
+ team_id=1,
+ team_uuid="team-uuid",
+ organization_id="org-id",
+ github_integration_id=123,
+ repository="posthog/posthog-js",
+ distinct_id="distinct",
+ state=state,
+ )
+
+
+class TestMaxRunDuration:
+ @override_settings(TASKS_MAX_RUN_DURATION_SECONDS=DEFAULT_CAP_SECONDS)
+ def test_interactive_sessions_are_uncapped(self):
+ # A human may legitimately keep an interactive session open for hours; capping it
+ # would kill a live session mid-use.
+ assert _context({"mode": "interactive"}).max_run_duration() is None
+
+ @override_settings(TASKS_MAX_RUN_DURATION_SECONDS=DEFAULT_CAP_SECONDS)
+ def test_background_runs_get_the_default_cap(self):
+ assert _context({"mode": "background"}).max_run_duration() == timedelta(seconds=DEFAULT_CAP_SECONDS)
+ # Default mode (no explicit mode in state) is background.
+ assert _context(None).max_run_duration() == timedelta(seconds=DEFAULT_CAP_SECONDS)
+
+ @override_settings(TASKS_MAX_RUN_DURATION_SECONDS=90)
+ def test_setting_override_applies_to_capped_runs(self):
+ assert resolve_max_run_duration() == timedelta(seconds=90)
+ assert _context({"mode": "background"}).max_run_duration() == timedelta(seconds=90)
+
+ @override_settings(TASKS_MAX_RUN_DURATION_SECONDS=90)
+ def test_setting_override_does_not_cap_interactive(self):
+ assert _context({"mode": "interactive"}).max_run_duration() is None
+
+ @override_settings(TASKS_MAX_RUN_DURATION_SECONDS=DEFAULT_CAP_SECONDS)
+ def test_cap_clears_the_longest_inactivity_grace(self):
+ # The cap must sit above the largest legitimate idle window (2h per-task max),
+ # or it would fire before the inactivity timer on healthy long runs.
+ cap = resolve_max_run_duration()
+ assert cap is not None
+ assert cap > timedelta(seconds=MAX_INACTIVITY_TIMEOUT_SECONDS)
+
+ @override_settings(TASKS_MAX_RUN_DURATION_SECONDS=0)
+ def test_zero_disables_the_cap_rather_than_capping_at_zero(self):
+ # 0 is the "unset" convention TASKS_INACTIVITY_TIMEOUT_SECONDS already uses. Reading it
+ # as a zero-second cap would terminalize every non-interactive run on its first loop
+ # iteration, which is the opposite of what an operator disabling the cap wants.
+ assert resolve_max_run_duration() is None
+ assert _context({"mode": "background"}).max_run_duration() is None
+
+ @override_settings(TASKS_MAX_RUN_DURATION_SECONDS=-1)
+ def test_negative_disables_the_cap(self):
+ assert resolve_max_run_duration() is None
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 740be49f1848..0f7ffb6b0b13 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -59,6 +59,10 @@ from products.tasks.backend.temporal.process_task.activities import (
track_workflow_event,
update_task_run_status,
)
+from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (
+ SANDBOX_GONE_STATE_KEY,
+ TIMED_OUT_WALL_CLOCK_STATE_KEY,
+)
from products.tasks.backend.temporal.process_task.credential_refresh import (
SANDBOX_GONE_ERROR_MESSAGE,
CredentialRefreshExitReason,
@@ -82,6 +86,8 @@ def _build_context(
environment: str | None = None,
use_modal_vm_sandbox: bool = False,
custom_image_name: str | None = None,
+ origin_product: str | None = None,
+ create_pr: bool = True,
) -> TaskProcessingContext:
return TaskProcessingContext(
task_id="task-id",
@@ -92,8 +98,9 @@ def _build_context(
github_integration_id=github_integration_id,
repository=repository,
distinct_id="distinct-id",
+ origin_product=origin_product,
environment=environment,
- create_pr=True,
+ create_pr=create_pr,
state=state or {},
_branch="feature-branch",
use_modal_resume_snapshots=use_modal_resume_snapshots,
@@ -1152,9 +1159,29 @@ class TestProcessTaskWorkflowUnit:
relay_sandbox_events_mock.assert_not_called()
relay_agent_design_signals_mock.assert_called_once()
- async def test_run_completes_when_credential_refresh_detects_sandbox_gone(self, monkeypatch):
+ @pytest.mark.parametrize(
+ "origin_product, pr_progress_emitted, ci_repetitions, expected_status",
+ [
+ (None, False, 1, "completed"),
+ ("user_created", False, 1, "completed"),
+ # Onboarding runs are one-shot, so a vanished sandbox is a failed setup rather than a
+ # resumable snapshot.
+ ("onboarding", False, 1, "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"),
+ # 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"),
+ ],
+ )
+ async def test_run_completes_when_credential_refresh_detects_sandbox_gone(
+ self, monkeypatch, origin_product, pr_progress_emitted, ci_repetitions, expected_status
+ ):
workflow = ProcessTaskWorkflow()
- context = _build_context(github_integration_id=123)
+ workflow._pr_progress_emitted = pr_progress_emitted
+ workflow._ci_repetitions = ci_repetitions
+ context = _build_context(github_integration_id=123, origin_product=origin_product)
update_task_run_status_mock = AsyncMock()
cleanup_sandbox_mock = AsyncMock()
@@ -1208,14 +1235,206 @@ class TestProcessTaskWorkflowUnit:
result = await workflow.run(ProcessTaskInput(run_id="run-id"))
assert result.success is True
- assert workflow._completion_status == "completed"
+ assert workflow._completion_status == expected_status
update_task_run_status_mock.assert_any_await(
- "completed",
+ expected_status,
error_message=SANDBOX_GONE_ERROR_MESSAGE,
error_type=None,
+ timeout_marker=SANDBOX_GONE_STATE_KEY,
)
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",
+ [
+ (
+ process_task_workflow_module.TaskEvent.TIMEOUT_REACHED,
+ None,
+ False,
+ 1,
+ "completed",
+ {"timed_out_inactivity": True},
+ ),
+ (
+ process_task_workflow_module.TaskEvent.TIMEOUT_REACHED,
+ "onboarding",
+ False,
+ 1,
+ "failed",
+ {"timed_out_inactivity": True},
+ ),
+ # An onboarding run that already opened its PR delivered its install; the CI
+ # follow-up loop simply ran out, so the wizard must still read success.
+ (
+ process_task_workflow_module.TaskEvent.TIMEOUT_REACHED,
+ "onboarding",
+ True,
+ 1,
+ "completed",
+ {"timed_out_inactivity": True},
+ ),
+ # The follow-up loop never ran, so nothing ever checked for a PR. Without that
+ # observation the empty latch proves nothing and the run keeps completing.
+ (
+ process_task_workflow_module.TaskEvent.TIMEOUT_REACHED,
+ "onboarding",
+ False,
+ 0,
+ "completed",
+ {"timed_out_inactivity": True},
+ ),
+ (
+ process_task_workflow_module.TaskEvent.MAX_DURATION_REACHED,
+ None,
+ False,
+ 1,
+ "failed",
+ {"timeout_marker": TIMED_OUT_WALL_CLOCK_STATE_KEY},
+ ),
+ (
+ process_task_workflow_module.TaskEvent.MAX_DURATION_REACHED,
+ "onboarding",
+ False,
+ 1,
+ "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
+ ):
+ # 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
+ # run and a PR-bearing onboarding run already succeeded.
+ workflow = ProcessTaskWorkflow()
+ workflow._pr_progress_emitted = pr_progress_emitted
+ workflow._ci_repetitions = ci_repetitions
+ context = _build_context(github_integration_id=123, origin_product=origin_product)
+ update_task_run_status_mock = AsyncMock()
+
+ monkeypatch.setattr(workflow, "_get_task_processing_context", AsyncMock(return_value=context))
+ monkeypatch.setattr(workflow, "_update_task_run_status", update_task_run_status_mock)
+ monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())
+ monkeypatch.setattr(workflow, "_post_slack_update", AsyncMock())
+ monkeypatch.setattr(workflow, "_read_sandbox_logs", AsyncMock())
+ monkeypatch.setattr(workflow, "_cleanup_sandbox", AsyncMock())
+ monkeypatch.setattr(workflow, "_create_resume_snapshot", AsyncMock())
+ monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())
+ monkeypatch.setattr(workflow, "_forward_pending_user_message", AsyncMock())
+ monkeypatch.setattr(
+ workflow,
+ "_get_sandbox_for_repository",
+ AsyncMock(
+ return_value=GetSandboxForRepositoryOutput(
+ sandbox_id="sandbox-123",
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ used_snapshot=False,
+ should_create_snapshot=False,
+ )
+ ),
+ )
+ monkeypatch.setattr(
+ workflow,
+ "_start_agent_server",
+ AsyncMock(
+ return_value=StartAgentServerOutput(
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ )
+ ),
+ )
+ monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())
+ monkeypatch.setattr(workflow, "_wait_for_event", AsyncMock(return_value=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.
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
+
+ result = await workflow.run(ProcessTaskInput(run_id="run-id"))
+
+ assert result.success is True
+ update_task_run_status_mock.assert_any_await(expected_status, **expected_kwargs)
+
+ @pytest.mark.parametrize(
+ "create_pr, pr_progress_emitted, ci_repetitions, expected",
+ [
+ # The follow-up loop looked and found no PR, so the run provably delivered nothing.
+ (True, False, 1, True),
+ # The loop looked and found one: the install landed.
+ (True, True, 1, False),
+ # The loop never ran (disabled for the org, or the exit landed inside the first
+ # follow-up delay), so the empty latch is an absence of observation, not of a PR.
+ (True, False, 0, False),
+ # No PR was ever expected, so there is nothing to observe and nothing was delivered.
+ (False, False, 0, True),
+ ],
+ )
+ def test_onboarding_exit_is_failure_requires_an_observed_pr_absence(
+ self, monkeypatch, create_pr, pr_progress_emitted, ci_repetitions, expected
+ ):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(github_integration_id=123, origin_product="onboarding", create_pr=create_pr)
+ workflow._pr_progress_emitted = pr_progress_emitted
+ workflow._ci_repetitions = ci_repetitions
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))
+
+ assert workflow._onboarding_exit_is_failure() is expected
+
+ async def test_run_keeps_completing_inactivity_timeouts_before_the_lifecycle_patch(self, monkeypatch):
+ # Replaying a pre-patch history: the onboarding FAILED terminalization must not apply, or the
+ # replay would write a different terminal status than the recorded one.
+ workflow = ProcessTaskWorkflow()
+ context = _build_context(github_integration_id=123, origin_product="onboarding")
+ update_task_run_status_mock = AsyncMock()
+
+ monkeypatch.setattr(workflow, "_get_task_processing_context", AsyncMock(return_value=context))
+ monkeypatch.setattr(workflow, "_update_task_run_status", update_task_run_status_mock)
+ monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())
+ monkeypatch.setattr(workflow, "_post_slack_update", AsyncMock())
+ monkeypatch.setattr(workflow, "_read_sandbox_logs", AsyncMock())
+ monkeypatch.setattr(workflow, "_cleanup_sandbox", AsyncMock())
+ monkeypatch.setattr(workflow, "_create_resume_snapshot", AsyncMock())
+ monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())
+ monkeypatch.setattr(workflow, "_forward_pending_user_message", AsyncMock())
+ monkeypatch.setattr(
+ workflow,
+ "_get_sandbox_for_repository",
+ AsyncMock(
+ return_value=GetSandboxForRepositoryOutput(
+ sandbox_id="sandbox-123",
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ used_snapshot=False,
+ should_create_snapshot=False,
+ )
+ ),
+ )
+ monkeypatch.setattr(
+ workflow,
+ "_start_agent_server",
+ AsyncMock(
+ return_value=StartAgentServerOutput(
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ )
+ ),
+ )
+ monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())
+ monkeypatch.setattr(
+ workflow, "_wait_for_event", AsyncMock(return_value=process_task_workflow_module.TaskEvent.TIMEOUT_REACHED)
+ )
+ # The patch helpers short-circuit to "enabled" outside a workflow, so the replay case only
+ # exists once in_workflow() is true and the marker is absent.
+ monkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=False))
+
+ result = await workflow.run(ProcessTaskInput(run_id="run-id"))
+
+ assert result.success is True
+ update_task_run_status_mock.assert_any_await("completed", timed_out_inactivity=True)
+
@pytest.mark.parametrize(
"patched, expected_post_slack_calls",
[
@@ -1837,7 +2056,11 @@ class TestContinueAsNew:
wf._context = ctx
return wf
- def test_build_and_restore_round_trips_loop_state(self) -> None:
+ def test_build_and_restore_round_trips_loop_state(self, monkeypatch) -> None:
+ chain_start = datetime(2026, 7, 16, 9, 0, tzinfo=UTC)
+ monkeypatch.setattr(
+ process_task_workflow_module.workflow, "info", Mock(return_value=Mock(start_time=chain_start))
+ )
wf = self._idle_enabled_workflow()
wf._sandbox_url = "https://sandbox.example"
wf._sandbox_connect_token = "tok"
@@ -1869,6 +2092,13 @@ class TestContinueAsNew:
assert restored._is_agent_design_enabled is True
# The datetime survives the ISO round-trip.
assert restored._last_active_time == datetime(2026, 7, 16, 10, 30, tzinfo=UTC)
+ # The wall-clock cap anchors on the chain start, so the first execution seeds it from
+ # its own start_time and every later continuation carries that same value forward.
+ assert restored._chain_started_at == chain_start
+ assert restored._chain_start_time() == chain_start
+ second_hop = restored._build_resumed_input(ProcessTaskInput(run_id="run-id"), sandbox_id="sb-2")
+ assert second_hop.resumed_sandbox is not None
+ assert second_hop.resumed_sandbox.chain_started_at == chain_start.isoformat()
@parameterized.expand(
[
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 62fb637df7e5..38ad732200a2 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -102,7 +102,12 @@ from .activities.start_agent_server import (
start_agent_server,
)
from .activities.track_workflow_event import TrackWorkflowEventInput, track_workflow_event
-from .activities.update_task_run_status import UpdateTaskRunStatusInput, update_task_run_status
+from .activities.update_task_run_status import (
+ SANDBOX_GONE_STATE_KEY,
+ TIMED_OUT_WALL_CLOCK_STATE_KEY,
+ UpdateTaskRunStatusInput,
+ update_task_run_status,
+)
from .credential_refresh import SANDBOX_GONE_ERROR_MESSAGE, CredentialRefreshExitReason, run_credential_refresh_loop
from .slack_agent_design_relay import SlackAgentDesignRelayInput, SlackAgentDesignRelayWorkflow
@@ -141,6 +146,9 @@ class ResumedSandboxState:
# Defaulted so continue_as_new payloads from pre-rollout runs deserialize.
pr_unresolved_threads: int = 0
accepted_message_ids: list[str] = field(default_factory=list)
+ # ISO8601 start of the whole continue_as_new chain, so the wall-clock cap is not
+ # reset by a continuation. None on payloads written before this field existed.
+ chain_started_at: Optional[str] = None
@dataclass
@@ -190,6 +198,7 @@ class ProcessTaskOutput:
class TaskEvent(StrEnum):
SIGNAL_RECEIVED = "signal_received"
TIMEOUT_REACHED = "timeout_reached"
+ MAX_DURATION_REACHED = "max_duration_reached"
CI_FOLLOW_UP = "ci_follow_up"
SANDBOX_GONE = "sandbox_gone"
QUOTA_RECHECK = "quota_recheck"
@@ -287,6 +296,16 @@ _PATCH_ID_SKIP_LOCAL_ENVIRONMENT_RUNS = "tasks-skip-local-environment-runs"
_PATCH_ID_DEFER_RUN_STREAM_COMPLETION = "tasks-defer-run-stream-completion"
_PATCH_ID_COMPLETE_STREAM_AFTER_CLEANUP_FAILURE = "tasks-complete-stream-after-cleanup-failure"
+# Gates the run lifecycle bounds: the hard wall-clock timer added to `_wait_for_event`
+# (a new Timer command, so replays of pre-rollout histories must not schedule it) and the
+# onboarding-origin FAILED terminalizations for the inactivity and sandbox-gone paths.
+# Same two-step deprecate-then-delete cleanup lifecycle as the patches above.
+_PATCH_ID_RUN_LIFECYCLE_BOUNDS = "tasks-run-lifecycle-bounds"
+
+# `Task.OriginProduct.ONBOARDING`, mirrored as a literal so workflow code stays free of
+# Django model imports.
+_ONBOARDING_ORIGIN_PRODUCT = "onboarding"
+
def _deprecate_ci_follow_up_pr_context_patch() -> None:
workflow.deprecate_patch(_PATCH_ID_CI_FOLLOW_UP_PR_CONTEXT)
@@ -304,6 +323,12 @@ def _complete_stream_after_cleanup_failure() -> bool:
return workflow.patched(_PATCH_ID_COMPLETE_STREAM_AFTER_CLEANUP_FAILURE)
+def _run_lifecycle_bounds_enabled() -> bool:
+ if not workflow.in_workflow():
+ return True
+ return workflow.patched(_PATCH_ID_RUN_LIFECYCLE_BOUNDS)
+
+
@temporalio.workflow.defn(name="process-task")
class ProcessTaskWorkflow(PostHogWorkflow):
def __init__(self) -> None:
@@ -318,6 +343,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._completion_status: str = "completed"
self._completion_error: Optional[str] = None
self._completion_error_type: Optional[str] = None
+ # State marker recorded with the terminal status (e.g. sandbox_gone), so the
+ # reason a run ended stays machine-readable without abusing error_message.
+ self._completion_timeout_marker: Optional[str] = None
self._heartbeat_received: bool = False
self._prewarmed: bool = False
self._first_user_message_received: bool = False
@@ -332,6 +360,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._pending_permission_responses: list[PendingPermissionResponse] = []
self._ci_repetitions: int = 0
self._last_active_time: Optional[datetime] = None
+ # Start of the continue_as_new chain, carried across continuations so the
+ # wall-clock cap measures the whole chain rather than restarting per run.
+ # None on the first execution, where workflow.info().start_time is the anchor.
+ self._chain_started_at: Optional[datetime] = None
# Tracks which progress step is currently in-progress (step, label,
# group) so we can emit a "failed" transition from the workflow-level
# exception handler onto the right card.
@@ -496,6 +528,21 @@ class ProcessTaskWorkflow(PostHogWorkflow):
await workflow.sleep(timeout.total_seconds())
return TaskEvent.TIMEOUT_REACHED
+ async def _wait_for_max_run_duration(self, cap: timedelta):
+ """Hard wall-clock cap, measured from the chain start and never reset by heartbeats.
+
+ The inactivity timer restarts on every heartbeat, so a wedged-but-heartbeating
+ agent never trips it; this ceiling catches that case. The anchor comes from
+ `_chain_start_time`, which survives continue_as_new; both it and
+ `workflow.info().start_time` are deterministic across replays, so recomputing the
+ remaining time on each loop iteration is replay-safe.
+ """
+ elapsed = workflow.now() - self._chain_start_time()
+ remaining = (cap - elapsed).total_seconds()
+ if remaining > 0:
+ await workflow.sleep(remaining)
+ return TaskEvent.MAX_DURATION_REACHED
+
async def _wait_for_ci_follow_up(self):
if self._last_active_time:
elapsed = workflow.now() - self._last_active_time
@@ -596,6 +643,13 @@ class ProcessTaskWorkflow(PostHogWorkflow):
asyncio.create_task(self._wait_for_task_external_event()),
asyncio.create_task(self._wait_for_inactivity(inactivity_timeout)),
]
+ # Hard wall-clock cap, independent of the heartbeat-reset inactivity timer. The
+ # patch gate keeps replays of pre-rollout histories from scheduling the new timer;
+ # None means the run is exempt (interactive sessions a human may keep open for hours).
+ if _run_lifecycle_bounds_enabled():
+ max_run_duration = self.context.max_run_duration()
+ if max_run_duration is not None:
+ possible_events.append(asyncio.create_task(self._wait_for_max_run_duration(max_run_duration)))
if ci_follow_up_scheduled:
possible_events.append(asyncio.create_task(self._wait_for_ci_follow_up()))
if not warm_idle and self._self_driving_quota_recheck_scheduled():
@@ -729,7 +783,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
sandbox_id = None
sandbox_cleaned = False
run_stream_completed = False
- timed_out = False
+ timeout_event: Optional[TaskEvent] = None
# Handing the live sandbox to the next execution — the finally must not tear it down.
continuing_as_new = False
run_id = input.run_id
@@ -824,7 +878,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):
event = await self._wait_for_event()
match event:
case TaskEvent.TIMEOUT_REACHED:
- timed_out = True
+ timeout_event = event
+ break
+ case TaskEvent.MAX_DURATION_REACHED:
+ workflow.logger.warning(
+ "max_run_duration_reached",
+ extra={"run_id": self.context.run_id},
+ )
+ timeout_event = event
break
case TaskEvent.CI_FOLLOW_UP:
workflow.logger.info(
@@ -954,9 +1015,16 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._completion_status,
error_message=self._completion_error,
error_type=self._completion_error_type,
+ timeout_marker=self._completion_timeout_marker,
)
- elif timed_out:
- await self._update_task_run_status("completed", timed_out_inactivity=True)
+ elif timeout_event == TaskEvent.MAX_DURATION_REACHED:
+ # Only reachable under the lifecycle-bounds patch (the timer is gated on it).
+ # 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:
+ inactivity_status = "failed" if self._onboarding_exit_is_failure() else "completed"
+ await self._update_task_run_status(inactivity_status, timed_out_inactivity=True)
# Close out the keep-it-green step so a finished run doesn't show a still-spinning CI step.
if self._pr_progress_emitted:
@@ -1220,10 +1288,21 @@ class ProcessTaskWorkflow(PostHogWorkflow):
is_agent_design_enabled=self._is_agent_design_enabled,
last_active_time=self._last_active_time.isoformat() if self._last_active_time else None,
accepted_message_ids=self._accepted_message_ids,
+ chain_started_at=self._chain_start_time().isoformat(),
),
)
+ def _chain_start_time(self) -> datetime:
+ """Start of the continue_as_new chain, falling back to this run's start time.
+
+ `workflow.info().start_time` is per-run, so a continuation would otherwise restart
+ the wall-clock cap from zero, and continuations are triggered by history growth,
+ which heartbeats drive.
+ """
+ return self._chain_started_at or workflow.info().start_time
+
def _restore_resumed_state(self, resumed: ResumedSandboxState) -> None:
+ self._chain_started_at = datetime.fromisoformat(resumed.chain_started_at) if resumed.chain_started_at else None
self._is_agent_design_enabled = resumed.is_agent_design_enabled
self._ci_repetitions = resumed.ci_repetitions
self._pr_fingerprint = resumed.pr_fingerprint
@@ -1782,6 +1861,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
run_id: Optional[str] = None,
timed_out_inactivity: bool = False,
error_type: Optional[str] = None,
+ timeout_marker: Optional[str] = None,
) -> None:
await workflow.execute_activity(
update_task_run_status,
@@ -1791,6 +1871,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
error_message=error_message,
timed_out_inactivity=timed_out_inactivity,
error_type=error_type,
+ timeout_marker=timeout_marker,
),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -1819,9 +1900,36 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# of leaving it waiting on signals that can never arrive.
self._sandbox_gone = True
+ def _onboarding_exit_is_failure(self) -> bool:
+ """Whether a non-signal exit should terminalize an onboarding run as FAILED.
+
+ Onboarding runs are one-shot: nobody resumes them, so a run that stopped without
+ delivering anything is a failed setup and must read as one. A run that already
+ opened its PR did deliver, and the wizard keys its success headline and PR CTA off
+ the terminal status, so downgrading that run would report a failed install over a
+ perfectly good PR. Other origins keep completing either way, because their resume
+ flows treat the stopped run as the resumable snapshot.
+
+ `_pr_progress_emitted` only ever flips inside the CI follow-up loop's `get_pr_context`
+ call, so a false latch means "no PR" only once that loop has actually looked. A run
+ whose loop never ran (disabled for the org, or the exit landed inside the first
+ `CI_FOLLOW_UP_DELAY`) has no observation either way, and downgrading on the unobserved
+ latch would report a failed install over a PR sitting on the user's repo. Requiring a
+ completed follow-up round makes the downgrade evidence-based; a run that never intended
+ to open a PR needs no observation, since there is nothing for it to have delivered.
+ """
+ if self.context.origin_product != _ONBOARDING_ORIGIN_PRODUCT or not _run_lifecycle_bounds_enabled():
+ return False
+ if self._pr_progress_emitted:
+ return False
+ return not self.context.create_pr or self._ci_repetitions > 0
+
def _mark_sandbox_gone(self) -> None:
- self._completion_status = "completed"
+ # 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"
self._completion_error = SANDBOX_GONE_ERROR_MESSAGE
+ self._completion_timeout_marker = SANDBOX_GONE_STATE_KEY
self._task_completed = True
async def _relay_sandbox_events(
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index ca26eb32dee6..e77f69ce9a25 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -5011,6 +5011,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"pending_dispatch": {"workflow_id_prefix": "review-real", "create_pr": True},
"pending_external_followups": pending_external_followups,
"pending_external_followups_generation": 7,
+ "sandbox_gone": False,
"ai_stage": "research",
"self_driving_head_branch": "posthog-self-driving/real-3f9a2c",
"runtime_adapter": "claude",
@@ -5027,7 +5028,9 @@ class TestTaskRunAPI(BaseTaskAPITest):
# decisions, change Modal resume snapshot metadata, repoint the run at another
# team's Temporal workflow, or steer an orphan re-dispatch (workflow ID prefix / MCP
# scopes) via pending_dispatch, or repoint the run at a costlier model (which for a run
- # routed to an unbilled gateway product is free spend). Non-protected keys still merge.
+ # routed to an unbilled gateway product is free spend). Nor can a caller stamp a
+ # workflow-owned terminal reason marker, which would make a genuine FAILED run read as a
+ # timeout and skip its Slack error card. Non-protected keys still merge.
response = self.client.patch(
f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
{
@@ -5057,6 +5060,9 @@ class TestTaskRunAPI(BaseTaskAPITest):
}
],
"pending_external_followups_generation": 999,
+ "timed_out_inactivity": True,
+ "timed_out_wall_clock": True,
+ "sandbox_gone": True,
# implementation provenance is what the self-driving review carve-outs trust
"ai_stage": "implementation",
# the stamped branch is the unforgeable run->PR link; a writable value re-aims it
@@ -5091,6 +5097,9 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["pending_dispatch"] == {"workflow_id_prefix": "review-real", "create_pr": True}
assert run.state["pending_external_followups"] == pending_external_followups
assert run.state["pending_external_followups_generation"] == 7
+ assert "timed_out_inactivity" not in run.state # caller cannot forge a timeout reason
+ assert "timed_out_wall_clock" not in run.state
+ assert run.state["sandbox_gone"] is False
assert run.state["ai_stage"] == "research" # cannot forge implementation provenance
assert run.state["self_driving_head_branch"] == "posthog-self-driving/real-3f9a2c"
assert run.state["runtime_adapter"] == "claude"
@@ -5117,6 +5126,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"pending_dispatch",
"pending_external_followups",
"pending_external_followups_generation",
+ "sandbox_gone",
"runtime_adapter",
"provider",
"model",
@@ -5140,6 +5150,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["pending_dispatch"] == {"workflow_id_prefix": "review-real", "create_pr": True}
assert run.state["pending_external_followups"] == pending_external_followups
assert run.state["pending_external_followups_generation"] == 7
+ assert run.state["sandbox_gone"] is False # protected key survives removal
# Dropping the model posture is as good as repointing it: the processing context reads these
# back with .get(), so an absent key silently falls back to the runtime's default rather than
# the pin the server chose.
diff --git a/products/tasks/backend/tests/test_post_slack_update.py b/products/tasks/backend/tests/test_post_slack_update.py
index 1d641789d576..c57bdfdcdbfe 100644
--- a/products/tasks/backend/tests/test_post_slack_update.py
+++ b/products/tasks/backend/tests/test_post_slack_update.py
@@ -263,6 +263,80 @@ class TestPostSlackUpdate(TestCase):
mock_delete_progress.assert_called_once()
mock_post_completion.assert_not_called()
+ @parameterized.expand(
+ [
+ ({"state": {"timed_out_wall_clock": True}, "error_message": None},),
+ ({"state": {"timed_out_inactivity": True}, "error_message": None},),
+ ]
+ )
+ @patch.object(SlackThreadHandler, "post_error")
+ @patch.object(SlackThreadHandler, "delete_progress")
+ @patch.object(SlackThreadHandler, "update_reaction")
+ @patch.object(SlackThreadHandler, "__init__", return_value=None)
+ @patch("products.tasks.backend.models.TaskRun")
+ def test_failed_timeout_run_stays_quiet_instead_of_posting_an_error_card(
+ self,
+ run_kwargs,
+ mock_task_run_class,
+ mock_handler_init,
+ mock_update_reaction,
+ mock_delete_progress,
+ mock_post_error,
+ ):
+ # Timeouts can now land as FAILED, but they carry a state marker and no error_message, so
+ # the thread clears its progress marker rather than posting an error card with no reason.
+ mock_run = self._make_mock_run(
+ mock_task_run_class.Status.FAILED,
+ output={},
+ **run_kwargs,
+ )
+ mock_task_run_class.objects.select_related.return_value.get.return_value = mock_run
+
+ post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
+
+ mock_update_reaction.assert_called_once_with("hedgehog")
+ mock_delete_progress.assert_called_once()
+ mock_post_error.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("PostHog setup wizard timed out after 30 minutes",),
+ ("Sandbox request timed out",),
+ ("Execution timed out after 600 seconds",),
+ ]
+ )
+ @patch.object(SlackThreadHandler, "post_error")
+ @patch.object(SlackThreadHandler, "delete_progress")
+ @patch.object(SlackThreadHandler, "update_reaction")
+ @patch.object(SlackThreadHandler, "__init__", return_value=None)
+ @patch("products.tasks.backend.models.TaskRun")
+ def test_failed_run_whose_message_mentions_a_timeout_still_posts_an_error_card(
+ self,
+ error_message,
+ mock_task_run_class,
+ mock_handler_init,
+ mock_update_reaction,
+ mock_delete_progress,
+ mock_post_error,
+ ):
+ # Only the workflow's own state markers make a FAILED run quiet. Several genuine failures
+ # carry "timed out" in their message (wizard deadline, sandbox request, agent command), and
+ # swallowing those would leave the thread silent on a real error.
+ mock_run = self._make_mock_run(
+ mock_task_run_class.Status.FAILED,
+ output={},
+ state={},
+ error_message=error_message,
+ )
+ mock_task_run_class.objects.select_related.return_value.get.return_value = mock_run
+
+ post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
+
+ mock_update_reaction.assert_called_once_with("x")
+ mock_post_error.assert_called_once()
+ assert mock_post_error.call_args.args[0] == error_message
+ mock_delete_progress.assert_not_called()
+
@patch.object(SlackThreadHandler, "post_pr_opened")
@patch.object(SlackThreadHandler, "update_reaction")
@patch.object(SlackThreadHandler, "__init__", return_value=None)