: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): bound task management ci polling (#108364)
Alessandro Pogliaghiefbabf432c7e
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex d11a6fee121e..d5ab411bdf7b 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -73,6 +73,11 @@ fine — they get converted to newlines.Temporal and the temporal-django-worker start automatically via phrocs when yourun `hogli start`.+The separate `task-management` implementation is not registered with the worker.+It stops polling closed or merged PRs and caps background runs at two idle checks; pending CI and merge-queue checks do not consume that budget.+Pending CI and merge queues have a separate limit of 96 waiting checks (24 hours at the normal cadence).+Follow-ups and sandbox-session boundaries reset both budgets, and the counters persist in server-owned `TaskRun.state` across orchestrator restarts.+The `process-task` workflow defined in`products/tasks/backend/temporal/process_task/workflow.py` provisions a sandbox,starts an agent inside it, and waits for the agent to finish. The workflowdiff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex e433ea644778..5c6a6364293f 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -2670,6 +2670,8 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("cancel_fallback_cleanup_complete","pending_external_followups","pending_external_followups_generation",+ "task_management_ci_idle_skips",+ "task_management_ci_wait_checks",# 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 throughdiff --git a/products/tasks/backend/temporal/task_management/activities/pending_followups.py b/products/tasks/backend/temporal/task_management/activities/pending_followups.pyindex 8b75a13e469b..0653e49b356b 100644--- a/products/tasks/backend/temporal/task_management/activities/pending_followups.py+++ b/products/tasks/backend/temporal/task_management/activities/pending_followups.py@@ -27,6 +27,8 @@ from products.tasks.backend.temporal.observability import log_activity_executionPENDING_FOLLOWUPS_STATE_KEY = "pending_external_followups"PENDING_FOLLOWUPS_GENERATION_STATE_KEY = "pending_external_followups_generation"+CI_IDLE_SKIPS_STATE_KEY = "task_management_ci_idle_skips"+CI_WAIT_CHECKS_STATE_KEY = "task_management_ci_wait_checks"TASK_RUN_NOT_FOUND_ERROR_TYPE = "PendingFollowupsTaskRunNotFound"@@ -39,11 +41,13 @@ class PersistPendingFollowupsInput:followups: list[dict[str, Any]]-@dataclass+@dataclass(frozen=False)class PersistPendingFollowupsV2Input:run_id: strfollowups: list[dict[str, Any]]generation: int+ ci_idle_skips: int | None = None+ ci_wait_checks: int | None = None@dataclass@@ -51,11 +55,13 @@ class ReadPendingFollowupsInput:run_id: str-@dataclass+@dataclass(frozen=False)class ReadPendingFollowupsResult:"""Pending followups read from state. Empty list when nothing is queued."""followups: list[dict[str, Any]]+ ci_idle_skips: int = 0+ ci_wait_checks: int = 0@activity.defn@@ -94,6 +100,10 @@ def persist_pending_followups_v2(input: PersistPendingFollowupsV2Input) -> None:if isinstance(current_generation, int) and current_generation >= input.generation:returnstate[PENDING_FOLLOWUPS_GENERATION_STATE_KEY] = input.generation+ if input.ci_idle_skips is not None:+ state[CI_IDLE_SKIPS_STATE_KEY] = input.ci_idle_skips+ if input.ci_wait_checks is not None:+ state[CI_WAIT_CHECKS_STATE_KEY] = input.ci_wait_checksif input.followups:state[PENDING_FOLLOWUPS_STATE_KEY] = input.followupselse:@@ -133,10 +143,16 @@ def read_pending_followups(input: ReadPendingFollowupsInput) -> ReadPendingFolloexcept TaskRun.DoesNotExist:return ReadPendingFollowupsResult(followups=[])state = task_run.state or {}+ ci_idle_skips = state.get(CI_IDLE_SKIPS_STATE_KEY, 0)+ if type(ci_idle_skips) is not int or ci_idle_skips < 0:+ ci_idle_skips = 0+ ci_wait_checks = state.get(CI_WAIT_CHECKS_STATE_KEY, 0)+ if type(ci_wait_checks) is not int or ci_wait_checks < 0:+ ci_wait_checks = 0value = state.get(PENDING_FOLLOWUPS_STATE_KEY)if not isinstance(value, list):- return ReadPendingFollowupsResult(followups=[])+ return ReadPendingFollowupsResult(followups=[], ci_idle_skips=ci_idle_skips, ci_wait_checks=ci_wait_checks)# Drop entries that don't deserialize cleanly — better to lose a# malformed item than to crash startup over a stale state shape.valid = [item for item in value if isinstance(item, dict)]- return ReadPendingFollowupsResult(followups=valid)+ return ReadPendingFollowupsResult(followups=valid, ci_idle_skips=ci_idle_skips, ci_wait_checks=ci_wait_checks)diff --git a/products/tasks/backend/temporal/task_management/activities/tests/test_pending_followups.py b/products/tasks/backend/temporal/task_management/activities/tests/test_pending_followups.pyindex c48c0fab7264..fae43ab9bc05 100644--- a/products/tasks/backend/temporal/task_management/activities/tests/test_pending_followups.py+++ b/products/tasks/backend/temporal/task_management/activities/tests/test_pending_followups.py@@ -6,6 +6,8 @@ from asgiref.sync import async_to_syncfrom temporalio.exceptions import ApplicationErrorfrom products.tasks.backend.temporal.task_management.activities.pending_followups import (+ CI_IDLE_SKIPS_STATE_KEY,+ CI_WAIT_CHECKS_STATE_KEY,PENDING_FOLLOWUPS_GENERATION_STATE_KEY,PENDING_FOLLOWUPS_STATE_KEY,TASK_RUN_NOT_FOUND_ERROR_TYPE,@@ -82,6 +84,8 @@ class TestPersistPendingFollowups:run_id=run_id,followups=followups,generation=generation,+ ci_idle_skips=generation,+ ci_wait_checks=generation,),)async_to_sync(activity_environment.run)(@@ -92,6 +96,11 @@ class TestPersistPendingFollowups:test_task_run.refresh_from_db()assert test_task_run.state[PENDING_FOLLOWUPS_STATE_KEY] == completeassert test_task_run.state[PENDING_FOLLOWUPS_GENERATION_STATE_KEY] == 2+ restored = async_to_sync(activity_environment.run)(+ read_pending_followups, ReadPendingFollowupsInput(run_id=run_id)+ )+ assert restored.ci_idle_skips == 2+ assert restored.ci_wait_checks == 2def test_missing_task_run_is_non_retryable(self, activity_environment):with pytest.raises(ApplicationError) as exc_info:@@ -123,13 +132,22 @@ class TestReadPendingFollowups:assert result.followups == payload- def test_returns_empty_when_key_missing(self, activity_environment, test_task_run):+ @pytest.mark.parametrize("ci_idle_skips", [None, 2, "invalid", -1, True])+ def test_returns_empty_when_key_missing(self, activity_environment, test_task_run, ci_idle_skips):+ if ci_idle_skips is not None:+ test_task_run.state = {+ CI_IDLE_SKIPS_STATE_KEY: ci_idle_skips,+ CI_WAIT_CHECKS_STATE_KEY: ci_idle_skips,+ }+ test_task_run.save(update_fields=["state"])result = async_to_sync(activity_environment.run)(read_pending_followups,ReadPendingFollowupsInput(run_id=str(test_task_run.id)),)assert result.followups == []+ assert result.ci_idle_skips == (2 if ci_idle_skips == 2 else 0)+ assert result.ci_wait_checks == (2 if ci_idle_skips == 2 else 0)def test_returns_empty_when_task_run_missing(self, activity_environment):result = async_to_sync(activity_environment.run)(diff --git a/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.py b/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.pyindex fe905647914a..ec9228349613 100644--- a/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.py+++ b/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.py@@ -1,3 +1,4 @@+from dataclasses import replacefrom datetime import UTC, datetime, timedeltaimport pytest@@ -10,6 +11,7 @@ from products.tasks.backend.temporal.constants import (DEFAULT_CI_MESSAGE,HEARTBEAT_DEBOUNCE,MAX_ACK_RETRIES,+ MAX_CI_IDLE_SKIPS,MAX_CI_REPETITIONS,SEND_STEER_SIGNAL,STEERING_PROTOCOL_VERSION,@@ -18,7 +20,9 @@ from products.tasks.backend.temporal.execute_sandbox.workflow import PARENT_ATTAfrom products.tasks.backend.temporal.process_task.activities.get_pr_context import GetPrContextOutput, get_pr_contextfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextfrom products.tasks.backend.temporal.task_management import workflow as task_management_workflow_module+from products.tasks.backend.temporal.task_management.activities.pending_followups import ReadPendingFollowupsResultfrom products.tasks.backend.temporal.task_management.workflow import (+ MAX_CI_WAIT_CHECKS,MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES,ChildAck,ChildCompletion,@@ -284,6 +288,38 @@ class TestCIFollowUpEnabled:class TestShouldRunCIFollowUp:+ @pytest.mark.parametrize("patched", [True, False])+ @pytest.mark.parametrize("queued", [True, False])+ async def test_pending_or_queued_pr_waits_without_using_idle_budget(+ self, monkeypatch, silent_workflow_logger, patched: bool, queued: bool+ ) -> None:+ workflow = TaskManagementWorkflow()+ workflow._context = _build_context()+ workflow._pr_fingerprint = "fp-1"+ monkeypatch.setattr(task_management_workflow_module.workflow, "in_workflow", lambda: True)+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "patched",+ lambda patch_id: patched if patch_id == task_management_workflow_module._PATCH_ID_CI_WAIT else True,+ )+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "execute_activity",+ AsyncMock(+ return_value=GetPrContextOutput(+ pr_url="https://github.com/example/repo/pull/1",+ pr_state="open",+ fingerprint="fp-1",+ ci_status="pending" if not queued else "failing",+ merge_queue_push_would_eject=queued,+ )+ ),+ )++ assert await workflow._should_run_ci_follow_up() == (+ CIFollowUpDecision.WAIT if patched else CIFollowUpDecision.SKIP+ )+async def test_returns_no_pr_when_pr_context_missing(self, monkeypatch):workflow = TaskManagementWorkflow()workflow._context = _build_context()@@ -297,21 +333,27 @@ class TestShouldRunCIFollowUp:decision = await workflow._should_run_ci_follow_up()assert decision is CIFollowUpDecision.NO_PR- async def test_returns_skip_when_pr_closed(self, monkeypatch, silent_workflow_logger):+ @pytest.mark.parametrize("pr_state", ["closed", "merged"])+ @pytest.mark.parametrize("patched", [True, False])+ async def test_closed_pr_stops_polling_only_for_patched_histories(+ self, monkeypatch, silent_workflow_logger, pr_state, patched+ ):+ monkeypatch.setattr(task_management_workflow_module.workflow, "in_workflow", lambda: True)+ monkeypatch.setattr(task_management_workflow_module.workflow, "patched", lambda _: patched)workflow = TaskManagementWorkflow()workflow._context = _build_context()async def fake_execute_activity(activity_fn, *args, **kwargs):return GetPrContextOutput(pr_url="https://github.com/org/repo/pull/1",- pr_state="closed",+ pr_state=pr_state,fingerprint="closed-fp",)monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", fake_execute_activity)decision = await workflow._should_run_ci_follow_up()- assert decision is CIFollowUpDecision.SKIP+ assert decision is (CIFollowUpDecision.TERMINAL if patched else CIFollowUpDecision.SKIP)@pytest.mark.parametrize("ci_status,changes_requested,expected_decision,expected_fingerprint",@@ -319,14 +361,12 @@ class TestShouldRunCIFollowUp:# Actionable changes fire.("failing", False, CIFollowUpDecision.FIRE, "fp-1"),("passing", True, CIFollowUpDecision.FIRE, "fp-1"),+ ("pending", True, CIFollowUpDecision.FIRE, "fp-1"),# Non-actionable changes persist the fingerprint but stay quiet —# waking the agent here produced "nothing to report" Slack spam.- # Pending needs no deferral: the settled state hashes differently- # (CI status and head SHA are both in the fingerprint), so it still- # registers as a change on a later tick.("passing", False, CIFollowUpDecision.SKIP, "fp-1"),("none", False, CIFollowUpDecision.SKIP, "fp-1"),- ("pending", False, CIFollowUpDecision.SKIP, "fp-1"),+ ("pending", False, CIFollowUpDecision.WAIT, "fp-1"),],)async def test_fingerprint_change_fires_only_when_actionable(@@ -422,12 +462,76 @@ class TestShouldRunCIFollowUp:class TestMaybeDispatchCIFollowUp:+ @pytest.mark.parametrize("patched", [True, False])+ @pytest.mark.parametrize("mode", ["background", "interactive"])+ @pytest.mark.parametrize("wait_checks", [2, MAX_CI_WAIT_CHECKS])+ async def test_idle_polling_is_bounded_and_wait_preserves_budget(+ self, monkeypatch, fixed_now, silent_workflow_logger, patched: bool, mode: str, wait_checks: int+ ) -> None:+ workflow = TaskManagementWorkflow()+ workflow._context = _build_context()+ workflow.context.state = {"mode": mode}+ workflow._run_id = "run-id"+ monkeypatch.setattr(task_management_workflow_module.workflow, "in_workflow", lambda: True)+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "patched",+ lambda patch_id: (+ patched+ if patch_id+ in (+ task_management_workflow_module._PATCH_ID_CI_IDLE_SKIP_CAP,+ task_management_workflow_module._PATCH_ID_CI_WAIT_CAP,+ )+ else True+ ),+ )+ pr_context = GetPrContextOutput(+ pr_url="https://github.com/example/repo/pull/1",+ pr_state="open",+ fingerprint="fp-1",+ ci_status="passing",+ )+ execute_activity = AsyncMock(return_value=pr_context)+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", execute_activity)++ await workflow._maybe_dispatch_ci_follow_up()+ assert workflow._ci_follow_up_enabled()+ for check in range(wait_checks):+ execute_activity.return_value = replace(+ pr_context, ci_status="pending", merge_queue_push_would_eject=bool(check % 2)+ )+ await workflow._maybe_dispatch_ci_follow_up()+ assert workflow._ci_follow_up_enabled() is (not patched or check + 1 < MAX_CI_WAIT_CHECKS)++ assert workflow._ci_wait_checks == (wait_checks if patched else 0)+ assert workflow._ci_idle_skips == (1 if patched and mode == "background" else 0)+ if patched and wait_checks == MAX_CI_WAIT_CHECKS:+ persisted = execute_activity.await_args_list[-1].args[1]+ assert persisted.ci_wait_checks == MAX_CI_WAIT_CHECKS+ return++ execute_activity.return_value = pr_context+ await workflow._maybe_dispatch_ci_follow_up()++ capped = patched and mode == "background"+ assert workflow._ci_follow_up_enabled() is not capped+ assert workflow._ci_idle_skips == (MAX_CI_IDLE_SKIPS if capped else 0)+ assert workflow._ci_repetitions == 0+ assert workflow._last_active_time == fixed_now.now+ if capped:+ persisted = execute_activity.await_args_list[-1].args[1]+ assert persisted.ci_idle_skips == MAX_CI_IDLE_SKIPS+async def test_fire_dispatches_and_increments_repetitions(self, monkeypatch, fixed_now):# `_dispatch_ci_follow_up` increments repetitions, sets last_active so# _wait_for_ci_follow_up sleeps a full window, and forwards via the# signal-child-followup machinery.workflow = TaskManagementWorkflow()workflow._context = _build_context(ci_prompt="custom prompt")+ workflow._ci_idle_skips = 1+ workflow._ci_wait_checks = 1+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", AsyncMock())workflow._run_id = "run-id"workflow._sandbox_workflow_id = "sandbox-wf"@@ -438,6 +542,8 @@ class TestMaybeDispatchCIFollowUp:await workflow._maybe_dispatch_ci_follow_up()assert workflow._ci_repetitions == 1+ assert workflow._ci_idle_skips == 0+ assert workflow._ci_wait_checks == 0assert workflow._last_active_time == fixed_now.nowsignal_mock.assert_awaited_once_with(message="custom prompt", artifact_ids=[], source="ci")@@ -454,14 +560,15 @@ class TestMaybeDispatchCIFollowUp:signal_mock.assert_awaited_once_with(message=DEFAULT_CI_MESSAGE, artifact_ids=[], source="ci")- async def test_no_pr_disables_ci_loop(self, monkeypatch, silent_workflow_logger):+ @pytest.mark.parametrize("decision", [CIFollowUpDecision.NO_PR, CIFollowUpDecision.TERMINAL])+ async def test_terminal_decision_disables_ci_loop(self, monkeypatch, silent_workflow_logger, decision):# No PR → there will never be one; we have to disable the loop entirely# or the CI timer branch would keep waking up the orchestrator.workflow = TaskManagementWorkflow()workflow._context = _build_context()workflow._run_id = "run-id"- monkeypatch.setattr(workflow, "_should_run_ci_follow_up", AsyncMock(return_value=CIFollowUpDecision.NO_PR))+ monkeypatch.setattr(workflow, "_should_run_ci_follow_up", AsyncMock(return_value=decision))signal_mock = AsyncMock()monkeypatch.setattr(workflow, "_signal_child_followup", signal_mock)@@ -479,6 +586,7 @@ class TestMaybeDispatchCIFollowUp:workflow._context = _build_context()workflow._run_id = "run-id"+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", AsyncMock())monkeypatch.setattr(workflow, "_should_run_ci_follow_up", AsyncMock(return_value=CIFollowUpDecision.SKIP))signal_mock = AsyncMock()monkeypatch.setattr(workflow, "_signal_child_followup", signal_mock)@@ -499,6 +607,8 @@ class TestDrainExternalSignals:workflow._run_id = "run-id"workflow._sandbox_workflow_id = "sandbox-wf"workflow._sandbox_alive = True # sandbox running → no re-bootstrap+ workflow._ci_idle_skips = MAX_CI_IDLE_SKIPS+ workflow._ci_wait_checks = MAX_CI_WAIT_CHECKSworkflow._pending_external_followups.extend([PendingExternalFollowup(message="m1", artifact_ids=[], source="user"),@@ -517,6 +627,8 @@ class TestDrainExternalSignals:await workflow._drain_external_signals()assert call_order == ["followup:m1", "followup:m2", "complete:completed"]+ assert workflow._ci_idle_skips == 0+ assert workflow._ci_wait_checks == 0assert workflow._pending_external_followups == []assert workflow._pending_external_complete is None@@ -822,6 +934,8 @@ class TestDrainExternalSignals:workflow._run_id = "run-id"workflow._sandbox_workflow_id = "sandbox-wf"workflow._sandbox_alive = True+ workflow._ci_idle_skips = MAX_CI_IDLE_SKIPS+ workflow._ci_wait_checks = MAX_CI_WAIT_CHECKSworkflow._pending_external_followups.extend([PendingExternalFollowup(@@ -869,6 +983,8 @@ class TestDrainExternalSignals:await workflow._drain_external_signals()assert workflow._sandbox_alive is False+ assert workflow._ci_idle_skips == 0+ assert workflow._ci_wait_checks == 0assert workflow._pending_ack_slots == {}assert workflow._pending_external_followups == [PendingExternalFollowup(@@ -1737,6 +1853,8 @@ class TestSandboxSessionCompletionReset:workflow._sandbox_alive = Trueworkflow._child_completion = ChildCompletion(success=True, error=None, sandbox_id="sb-1", timed_out=False)workflow._ci_repetitions = 2+ workflow._ci_idle_skips = 1+ workflow._ci_wait_checks = 1workflow._pr_fingerprint = "fp-1"workflow._heartbeat_received = Trueworkflow._last_active_time = fixed_now.now@@ -1748,6 +1866,8 @@ class TestSandboxSessionCompletionReset:assert workflow._child_completion is Noneassert workflow._sandbox_alive is Falseassert workflow._ci_repetitions == 0+ assert workflow._ci_idle_skips == 0+ assert workflow._ci_wait_checks == 0assert workflow._pr_fingerprint is Noneassert workflow._heartbeat_received is Falseassert workflow._last_active_time is None@@ -1845,6 +1965,31 @@ class TestSandboxSessionCompletionReset:class TestPendingFollowupPersistence:+ @pytest.mark.parametrize("patched", [True, False])+ @pytest.mark.parametrize("wait_cap", [False, True])+ async def test_restart_preserves_ci_caps_with_no_pending_followups(+ self, monkeypatch, silent_workflow_logger, patched: bool, wait_cap: bool+ ) -> None:+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._context = _build_context()+ monkeypatch.setattr(task_management_workflow_module.workflow, "in_workflow", lambda: True)+ monkeypatch.setattr(task_management_workflow_module.workflow, "patched", lambda _: patched)+ execute_activity = AsyncMock(+ return_value=ReadPendingFollowupsResult(+ followups=[],+ ci_idle_skips=0 if wait_cap else MAX_CI_IDLE_SKIPS,+ ci_wait_checks=MAX_CI_WAIT_CHECKS if wait_cap else 0,+ )+ )+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", execute_activity)++ await workflow._restore_pending_followups()++ assert workflow._ci_follow_up_enabled() is not patched+ assert await workflow._persist_pending_followups()+ assert execute_activity.await_count == 1+async def test_restore_pending_seeds_in_memory_queue(self, monkeypatch, silent_workflow_logger):# An orchestrator that restarts must rebuild its queue from# TaskRun.state so user messages that landed against the previousdiff --git a/products/tasks/backend/temporal/task_management/workflow.py b/products/tasks/backend/temporal/task_management/workflow.pyindex a55f84fb06d0..8411ae742977 100644--- a/products/tasks/backend/temporal/task_management/workflow.py+++ b/products/tasks/backend/temporal/task_management/workflow.py@@ -19,6 +19,7 @@ from products.tasks.backend.temporal.constants import (DEFAULT_CI_MESSAGE,HEARTBEAT_DEBOUNCE,MAX_ACK_RETRIES,+ MAX_CI_IDLE_SKIPS,MAX_CI_REPETITIONS,SEND_STEER_SIGNAL,STEERING_PROTOCOL_QUERY,@@ -88,6 +89,11 @@ _PATCH_ID_ACCEPTED_ACK_RESETS_REPLACEMENT_BUDGET = "tasks-task-management-accept_PATCH_ID_DURABLE_REPLACEMENT_BUDGET_PERSISTENCE = "tasks-task-management-durable-replacement-budget-persistence"_PATCH_ID_TERMINAL_PENDING_FOLLOWUP_BARRIER = "tasks-task-management-terminal-pending-followup-barrier"_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS = "tasks-task-management-generation-safe-pending-followups"+_PATCH_ID_CI_TERMINAL_PR = "tasks-task-management-ci-terminal-pr"+_PATCH_ID_CI_WAIT = "tasks-task-management-ci-wait"+_PATCH_ID_CI_IDLE_SKIP_CAP = "tasks-task-management-ci-idle-skip-cap"+_PATCH_ID_CI_WAIT_CAP = "tasks-task-management-ci-wait-cap"+MAX_CI_WAIT_CHECKS = 96_CHILD_SIGNAL_TERMINAL_ERROR_TYPES = {"ExternalWorkflowExecutionNotFound","NamespaceNotFound",@@ -204,6 +210,8 @@ class CIFollowUpDecision(StrEnum):FIRE = "fire"SKIP = "skip"NO_PR = "no_pr"+ TERMINAL = "terminal"+ WAIT = "wait"@temporalio.workflow.defn(name="task-management")@@ -244,6 +252,8 @@ class TaskManagementWorkflow(PostHogWorkflow):# already-empty queue still triggers a persist call).self._last_persisted_followups: list[dict[str, Any]] = []self._last_persistence_generation: int = 0+ self._last_persisted_ci_idle_skips: int = 0+ self._last_persisted_ci_wait_checks: int = 0self._persist_pending_followups_on_exit: bool = False# Sandbox-side state.@@ -267,6 +277,8 @@ class TaskManagementWorkflow(PostHogWorkflow):self._heartbeat_received: bool = Falseself._last_active_time: Optional[datetime] = Noneself._ci_repetitions: int = 0+ self._ci_idle_skips: int = 0+ self._ci_wait_checks: int = 0self._pr_fingerprint: Optional[str] = None# Last observed unresolved review-thread count. Starting at 0 means# feedback posted before the first poll still reads as new.@@ -615,6 +627,14 @@ class TaskManagementWorkflow(PostHogWorkflow):def _ci_follow_up_enabled(self) -> bool:if not self._context:return False+ if (+ self.context.mode != "interactive"+ and self._ci_idle_skips >= MAX_CI_IDLE_SKIPS+ and _patch_enabled(_PATCH_ID_CI_IDLE_SKIP_CAP)+ ):+ return False+ if self._ci_wait_checks >= MAX_CI_WAIT_CHECKS and _patch_enabled(_PATCH_ID_CI_WAIT_CAP):+ return Falsereturn bool(self._context.create_pr and self._context.pr_loop_enabled and self._ci_repetitions < MAX_CI_REPETITIONS)@@ -657,6 +677,8 @@ class TaskManagementWorkflow(PostHogWorkflow):)if delivered is False:return+ self._ci_idle_skips = 0+ self._ci_wait_checks = 0# The persisted queue is the orchestrator's recovery buffer — keep# it in sync after every drain so a restart sees an accurate picture# rather than re-delivering work we already forwarded.@@ -830,6 +852,8 @@ class TaskManagementWorkflow(PostHogWorkflow):self._sandbox_alive = Falseself._child_steering_protocol_version = 0self._ci_repetitions = 0+ self._ci_idle_skips = 0+ self._ci_wait_checks = 0self._pr_fingerprint = Noneself._heartbeat_received = Falseself._last_active_time = None@@ -887,6 +911,8 @@ class TaskManagementWorkflow(PostHogWorkflow):self._sandbox_alive = Falseself._child_steering_protocol_version = 0self._ci_repetitions = 0+ self._ci_idle_skips = 0+ self._ci_wait_checks = 0self._pr_fingerprint = Noneself._pr_unresolved_threads = 0self._heartbeat_received = False@@ -910,6 +936,12 @@ class TaskManagementWorkflow(PostHogWorkflow):"task_management_restore_pending_failed", extra={"run_id": self._run_id, "error": str(e)})return+ if _patch_enabled(_PATCH_ID_CI_IDLE_SKIP_CAP):+ self._ci_idle_skips = result.ci_idle_skips+ self._last_persisted_ci_idle_skips = result.ci_idle_skips+ if _patch_enabled(_PATCH_ID_CI_WAIT_CAP):+ self._ci_wait_checks = result.ci_wait_checks+ self._last_persisted_ci_wait_checks = result.ci_wait_checksif not result.followups:returnfor item in result.followups:@@ -953,16 +985,30 @@ class TaskManagementWorkflow(PostHogWorkflow):if self._run_id is None:return Falsepayload = [asdict(f) for f in self._pending_external_followups]- if payload == self._last_persisted_followups:+ persist_ci_idle_skips = _patch_enabled(_PATCH_ID_CI_IDLE_SKIP_CAP)+ persist_ci_wait_checks = _patch_enabled(_PATCH_ID_CI_WAIT_CAP)+ ci_idle_skips = self._ci_idle_skips+ ci_wait_checks = self._ci_wait_checks+ if (+ payload == self._last_persisted_followups+ and (not persist_ci_idle_skips or ci_idle_skips == self._last_persisted_ci_idle_skips)+ and (not persist_ci_wait_checks or ci_wait_checks == self._last_persisted_ci_wait_checks)+ ):return Truetry:- if _patch_enabled(_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS):+ if (+ _patch_enabled(_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS)+ or persist_ci_idle_skips+ or persist_ci_wait_checks+ ):await workflow.execute_activity(persist_pending_followups_v2,PersistPendingFollowupsV2Input(run_id=self._run_id,followups=payload,generation=self._new_persistence_generation(),+ ci_idle_skips=ci_idle_skips if persist_ci_idle_skips else None,+ ci_wait_checks=ci_wait_checks if persist_ci_wait_checks else None,),start_to_close_timeout=timedelta(seconds=30),retry_policy=RetryPolicy(maximum_attempts=3),@@ -975,6 +1021,10 @@ class TaskManagementWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=3),)self._last_persisted_followups = payload+ if persist_ci_idle_skips:+ self._last_persisted_ci_idle_skips = ci_idle_skips+ if persist_ci_wait_checks:+ self._last_persisted_ci_wait_checks = ci_wait_checksreturn Trueexcept Exception as e:workflow.logger.warning(@@ -994,13 +1044,23 @@ class TaskManagementWorkflow(PostHogWorkflow):raise RuntimeError("Cannot persist pending follow-ups without a run id")while True:payload = [asdict(followup) for followup in self._pending_external_followups]- if _patch_enabled(_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS):+ persist_ci_idle_skips = _patch_enabled(_PATCH_ID_CI_IDLE_SKIP_CAP)+ persist_ci_wait_checks = _patch_enabled(_PATCH_ID_CI_WAIT_CAP)+ ci_idle_skips = self._ci_idle_skips+ ci_wait_checks = self._ci_wait_checks+ if (+ _patch_enabled(_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS)+ or persist_ci_idle_skips+ or persist_ci_wait_checks+ ):await workflow.execute_activity(persist_pending_followups_v2,PersistPendingFollowupsV2Input(run_id=self._run_id,followups=payload,generation=self._new_persistence_generation(),+ ci_idle_skips=ci_idle_skips if persist_ci_idle_skips else None,+ ci_wait_checks=ci_wait_checks if persist_ci_wait_checks else None,),schedule_to_close_timeout=timedelta(minutes=5),start_to_close_timeout=timedelta(seconds=30),@@ -1017,6 +1077,10 @@ class TaskManagementWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=0),)self._last_persisted_followups = payload+ if persist_ci_idle_skips:+ self._last_persisted_ci_idle_skips = ci_idle_skips+ if persist_ci_wait_checks:+ self._last_persisted_ci_wait_checks = ci_wait_checksif payload == [asdict(followup) for followup in self._pending_external_followups]:return@@ -1234,12 +1298,24 @@ class TaskManagementWorkflow(PostHogWorkflow):# CI timer branch drops out of the wait set.self._ci_repetitions = MAX_CI_REPETITIONSworkflow.logger.info("task_management_ci_loop_stopped_no_pr", extra={"run_id": self._run_id})- case CIFollowUpDecision.SKIP:+ case CIFollowUpDecision.TERMINAL:+ self._ci_repetitions = MAX_CI_REPETITIONS+ case CIFollowUpDecision.SKIP | CIFollowUpDecision.WAIT:# Bound the next get_pr_context call to +CI_FOLLOW_UP_DELAY.# Mirrors process_task: without this, the next iteration# returns immediately whenever last_active_time is older than# the delay and the workflow tight-loops GET /repos/.../pulls.self._last_active_time = workflow.now()+ if (+ decision == CIFollowUpDecision.SKIP+ and self.context.mode != "interactive"+ and _patch_enabled(_PATCH_ID_CI_IDLE_SKIP_CAP)+ ):+ self._ci_idle_skips += 1+ await self._persist_pending_followups()+ elif decision == CIFollowUpDecision.WAIT and _patch_enabled(_PATCH_ID_CI_WAIT_CAP):+ self._ci_wait_checks += 1+ await self._persist_pending_followups()case _:raise ValueError(f"Unknown CIFollowUpDecision: {decision}")@@ -1256,18 +1332,23 @@ class TaskManagementWorkflow(PostHogWorkflow):workflow.logger.info("task_management_ci_skipped_pr_closed", extra={"run_id": self._run_id, "pr_url": pr_context.pr_url})- return CIFollowUpDecision.SKIP+ return CIFollowUpDecision.TERMINAL if _patch_enabled(_PATCH_ID_CI_TERMINAL_PR) else CIFollowUpDecision.SKIPif pr_context.merge_queue_push_would_eject and workflow.patched(_PATCH_ID_MERGE_QUEUE_SKIP):workflow.logger.info("task_management_ci_skipped_pr_in_merge_queue",extra={"run_id": self._run_id, "pr_url": pr_context.pr_url},)- return CIFollowUpDecision.SKIP+ return CIFollowUpDecision.WAIT if _patch_enabled(_PATCH_ID_CI_WAIT) else CIFollowUpDecision.SKIPfingerprint_changed = self._pr_fingerprint != pr_context.fingerprint+ idle = (+ CIFollowUpDecision.WAIT+ if pr_context.ci_status == "pending" and _patch_enabled(_PATCH_ID_CI_WAIT)+ else CIFollowUpDecision.SKIP+ )if not ci_follow_up_actionable_gate():# Legacy replay path: any fingerprint change fires; feedback is not consulted.if not fingerprint_changed:- return CIFollowUpDecision.SKIP+ return idleself._pr_fingerprint = pr_context.fingerprintreturn CIFollowUpDecision.FIRE# New unresolved review threads are feedback for the agent, and comparing@@ -1279,7 +1360,7 @@ class TaskManagementWorkflow(PostHogWorkflow):workflow.logger.info("task_management_ci_skipped_pr_unchanged", extra={"run_id": self._run_id, "pr_url": pr_context.pr_url})- return CIFollowUpDecision.SKIP+ return idleself._pr_fingerprint = pr_context.fingerprintfire = (fingerprint_changed and is_pr_actionable(pr_context)) or new_feedbackworkflow.logger.info(@@ -1295,13 +1376,17 @@ class TaskManagementWorkflow(PostHogWorkflow):"repetitions": self._ci_repetitions,},)- return CIFollowUpDecision.FIRE if fire else CIFollowUpDecision.SKIP+ return CIFollowUpDecision.FIRE if fire else idleasync def _dispatch_ci_follow_up(self) -> None:self._ci_repetitions += 1+ self._ci_idle_skips = 0+ self._ci_wait_checks = 0ci_message = (self._context.ci_prompt if self._context else None) or DEFAULT_CI_MESSAGEself._last_active_time = workflow.now()await self._signal_child_followup(message=ci_message, artifact_ids=[], source=FOLLOWUP_SOURCE_CI)+ if _patch_enabled(_PATCH_ID_CI_IDLE_SKIP_CAP) or _patch_enabled(_PATCH_ID_CI_WAIT_CAP):+ await self._persist_pending_followups()# ------------------------------------------------------------------# Activities used directly by the parentdiff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex d40b9f536ee1..622267d8fd9b 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -6850,6 +6850,8 @@ class TestTaskRunAPI(BaseTaskAPITest):"pending_dispatch": {"workflow_id_prefix": "review-real", "create_pr": True},"pending_external_followups": pending_external_followups,"pending_external_followups_generation": 7,+ "task_management_ci_idle_skips": 1,+ "task_management_ci_wait_checks": 10,"sandbox_gone": False,"ai_stage": "research","ai_agent_name": "signals-scout-errors",@@ -6930,6 +6932,8 @@ class TestTaskRunAPI(BaseTaskAPITest):}],"pending_external_followups_generation": 999,+ "task_management_ci_idle_skips": 0,+ "task_management_ci_wait_checks": 0,"timed_out_inactivity": True,"timed_out_wall_clock": True,"sandbox_gone": True,@@ -7002,6 +7006,8 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["pending_dispatch"] == {"workflow_id_prefix": "review-real", "create_pr": True}assert run.state["pending_external_followups"] == pending_external_followupsassert run.state["pending_external_followups_generation"] == 7+ assert run.state["task_management_ci_idle_skips"] == 1+ assert run.state["task_management_ci_wait_checks"] == 10assert "timed_out_inactivity" not in run.state # caller cannot forge a timeout reasonassert "timed_out_wall_clock" not in run.stateassert run.state["sandbox_gone"] is False@@ -7059,6 +7065,8 @@ class TestTaskRunAPI(BaseTaskAPITest):"pending_dispatch","pending_external_followups","pending_external_followups_generation",+ "task_management_ci_idle_skips",+ "task_management_ci_wait_checks","sandbox_gone","runtime_adapter","provider",@@ -7109,6 +7117,8 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["pending_dispatch"] == {"workflow_id_prefix": "review-real", "create_pr": True}assert run.state["pending_external_followups"] == pending_external_followupsassert run.state["pending_external_followups_generation"] == 7+ assert run.state["task_management_ci_idle_skips"] == 1+ assert run.state["task_management_ci_wait_checks"] == 10assert 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@@ -7136,13 +7146,22 @@ class TestTaskRunAPI(BaseTaskAPITest):response = self.client.patch(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",- {"state_append": {"systemPrompt": "Caller-controlled instructions", "scratch": "ok"}},+ {+ "state_append": {+ "systemPrompt": "Caller-controlled instructions",+ "task_management_ci_idle_skips": 0,+ "task_management_ci_wait_checks": 0,+ "scratch": "ok",+ }+ },format="json",)self.assertEqual(response.status_code, status.HTTP_200_OK)run.refresh_from_db()assert run.state["systemPrompt"] == system_promptassert run.state["scratch"] == ["ok"]+ assert run.state["task_management_ci_idle_skips"] == 1+ assert run.state["task_management_ci_wait_checks"] == 10@patch("products.tasks.backend.facade.api.signal_workflow_completion")def test_update_run_status_to_completed_signals_workflow(self, mock_signal):