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): end background pr watch after two idle ci checks (#108248)

Alessandro Pogliaghieabc70a9c796
diff --git a/products/tasks/backend/temporal/constants.py b/products/tasks/backend/temporal/constants.py
index 1e5004b50525..988f8382883d 100644
--- a/products/tasks/backend/temporal/constants.py
+++ b/products/tasks/backend/temporal/constants.py
@@ -121,6 +121,7 @@ CI_FOLLOW_UP_DELAY = timedelta(minutes=15)
# Upper bound on how many CI rounds the orchestrator will dispatch.
MAX_CI_REPETITIONS = 3
+MAX_CI_IDLE_SKIPS = 2
# Long-lived SSE relay activity timeout. The relay reconnects internally on
# transient failures; this is the outer cap.
diff --git a/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py b/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py
index 31bdfdafe314..793ba9cc5a93 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py
@@ -39,12 +39,9 @@ class TestShouldRunCIFollowUpDecision:
("failing", False, CIFollowUpDecision.FIRE, "fp-1"),
("passing", True, CIFollowUpDecision.FIRE, "fp-1"),
# Non-actionable changes persist the fingerprint but stay quiet.
- # 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(
@@ -291,6 +288,7 @@ class TestBabysitFollowUpDecision:
(_babysit_snapshot(pr_state="merged"), CIFollowUpDecision.TERMINAL),
(_babysit_snapshot(pr_state="closed"), CIFollowUpDecision.TERMINAL),
(_babysit_snapshot(), CIFollowUpDecision.SKIP),
+ (_babysit_snapshot(ci_status="pending"), CIFollowUpDecision.WAIT),
(_babysit_snapshot(failing_checks=[BABYSIT_CHECK]), CIFollowUpDecision.FIRE),
],
)
@@ -303,7 +301,7 @@ class TestBabysitFollowUpDecision:
@pytest.mark.parametrize(
"patch_recorded,expected_decision",
[
- (True, CIFollowUpDecision.SKIP),
+ (True, CIFollowUpDecision.WAIT),
(False, CIFollowUpDecision.FIRE),
],
)
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 fa144d6710e3..deff172ff249 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_followup.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_followup.py
@@ -433,11 +433,12 @@ def _mock_get_pr_context(_input) -> GetPrContextOutput | None:
sequence: list[str] = _pr_context_overrides["sequence"]
idx = min(_pr_context_overrides.get("_call_count", 0), len(sequence) - 1)
_pr_context_overrides["_call_count"] = idx + 1
+ ci_sequence: list[str] = _pr_context_overrides.get("ci_sequence", [ci_status] * len(sequence))
return GetPrContextOutput(
pr_url="https://github.com/org/repo/pull/1",
pr_state="open",
fingerprint=sequence[idx],
- ci_status=ci_status,
+ ci_status=ci_sequence[idx],
)
# Default "changing": unique fingerprint per call so CI follow-up always fires
_pr_context_overrides["_call_count"] = _pr_context_overrides.get("_call_count", 0) + 1
@@ -867,6 +868,64 @@ class TestFollowupGuards:
f"would yield 3. Got {_pr_context_overrides.get('_call_count')}"
)
+ @pytest.mark.parametrize(
+ "mode, pr_context, followup_after, expected_pr_context_calls, expected_followups, expected_timeout_updates",
+ [
+ ("background", {"behavior": "unchanged"}, None, 3, 1, [("completed", None)]),
+ (
+ "background",
+ {"behavior": "sequence", "sequence": ["fp-A", "fp-A", "fp-B", "fp-B", "fp-B", "fp-B"]},
+ None,
+ 5,
+ 2,
+ [("completed", None)],
+ ),
+ (
+ "background",
+ {
+ "behavior": "sequence",
+ "sequence": ["fp-A", "fp-A", "fp-A", "fp-B", "fp-B", "fp-B"],
+ "ci_sequence": ["failing", "pending", "pending", "failing", "failing", "failing"],
+ },
+ None,
+ 6,
+ 2,
+ [("completed", None)],
+ ),
+ ("background", {"behavior": "unchanged"}, timedelta(minutes=50), 5, 2, [("completed", None)]),
+ ("interactive", {"behavior": "unchanged"}, None, 4, 1, []),
+ ],
+ )
+ @pytest.mark.timeout(60, func_only=True)
+ async def test_idle_ci_skips_end_background_pr_watch(
+ self, mode, pr_context, followup_after, expected_pr_context_calls, expected_followups, expected_timeout_updates
+ ):
+ _ci_context_overrides["state"] = {"mode": mode}
+ _pr_context_overrides.update(pr_context)
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ task_queue = f"test-{uuid.uuid4()}"
+ async with _make_worker(env, task_queue):
+ 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),
+ execution_timeout=timedelta(hours=4),
+ )
+ if followup_after is not None:
+ await env.sleep(followup_after.total_seconds())
+ await handle.signal(ProcessTaskWorkflow.send_followup_message, args=["push a fix", []])
+ if mode == "interactive":
+ await env.sleep(CI_FOLLOW_UP_DELAY.total_seconds() * 4 + 60)
+ await handle.signal(ProcessTaskWorkflow.complete_task, args=["completed", None])
+ await handle.result()
+
+ assert _pr_context_overrides.get("_call_count") == expected_pr_context_calls
+ assert len(_ci_followup_calls) == expected_followups
+ assert [(s, e) for s, e, timed_out in _status_updates if timed_out] == expected_timeout_updates
+
@pytest.mark.timeout(60, func_only=True)
async def test_stops_ci_loop_when_no_pr_and_agent_idle(self):
"""When get_pr_context returns None and the agent is idle, the CI loop
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 cd8d523ef4e7..2ad5feefb7ea 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -3478,6 +3478,7 @@ class TestContinueAsNew:
wf._sandbox_url = "https://sandbox.example"
wf._sandbox_connect_token = "tok"
wf._ci_repetitions = 2
+ wf._ci_idle_skips = 1
wf._pr_fingerprint = "fp-1"
wf._pr_progress_emitted = True
wf._ci_resume_snapshot_created = True
@@ -3513,6 +3514,7 @@ class TestContinueAsNew:
restored._restore_resumed_state(rs)
assert restored._ci_repetitions == 2
+ assert restored._ci_idle_skips == 1
assert restored._pr_fingerprint == "fp-1"
assert restored._pr_progress_emitted is True
assert restored._ci_resume_snapshot_created is True
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index e6fe4ddf8082..e5b3686d9c31 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -201,6 +201,7 @@ class ResumedSandboxState:
last_active_time: Optional[str] # ISO8601, or None if never active
# Defaulted so continue_as_new payloads from pre-rollout runs deserialize.
pr_unresolved_threads: int = 0
+ ci_idle_skips: int = 0
dev_stack_preview_enabled: bool = False
babysit_journal: BabysitJournal = field(default_factory=BabysitJournal)
ci_resume_snapshot_created: bool = False
@@ -308,6 +309,7 @@ class TaskEvent(StrEnum):
class CIFollowUpDecision(StrEnum):
FIRE = "fire"
SKIP = "skip"
+ WAIT = "wait"
NO_PR = "no_pr"
TERMINAL = "terminal"
@@ -325,6 +327,7 @@ from products.tasks.backend.temporal.constants import ( # noqa: E402
DEFAULT_CI_MESSAGE,
IN_FLIGHT_TURN_IDLE_TIMEOUT_SECONDS,
INACTIVITY_TIMEOUT,
+ MAX_CI_IDLE_SKIPS,
MAX_CI_REPETITIONS,
PENDING_MESSAGE_FORWARD_TIMEOUT_SECONDS,
RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,
@@ -419,6 +422,7 @@ _PATCH_ID_RUN_LIFECYCLE_BOUNDS = "tasks-run-lifecycle-bounds"
_PATCH_ID_DELIVERED_PR_TIMEOUT_STATUS = "tasks-delivered-pr-timeout-status"
_PATCH_ID_SNAPSHOT_BEFORE_CI_FOLLOW_UP = "tasks-snapshot-before-ci-follow-up"
+_PATCH_ID_CI_IDLE_SKIP_CAP = "tasks-ci-idle-skip-cap"
AGENT_LOST_ERROR_MESSAGE = "The agent stopped before finishing its turn"
@@ -531,6 +535,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._shutting_down: bool = False
self._pending_permission_responses: list[PendingPermissionResponse] = []
self._ci_repetitions: int = 0
+ self._ci_idle_skips: 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.
@@ -666,6 +671,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
async def _dispatch_followup(self, followup: PendingFollowup) -> None:
self._last_active_time = workflow.now()
self._first_user_message_received = True
+ self._ci_idle_skips = 0
if self._should_skip_followup(followup.message, followup.artifact_ids):
workflow.logger.warning(
"empty_followup_skipped",
@@ -884,6 +890,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
and self._context.create_pr
and self._context.pr_loop_enabled
and self._ci_repetitions < MAX_CI_REPETITIONS
+ and self._ci_idle_skips < MAX_CI_IDLE_SKIPS
)
# When CI follow-up is scheduled, the inactivity timer must outlive
# CI_FOLLOW_UP_DELAY. The testing-only `TASKS_INACTIVITY_TIMEOUT_SECONDS`
@@ -1024,12 +1031,13 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"PR is in the merge queue, skipping CI follow-up",
extra={"run_id": self.context.run_id, "pr_url": pr_context.pr_url},
)
- return CIFollowUpDecision.SKIP
+ return CIFollowUpDecision.WAIT
fingerprint_changed = self._pr_fingerprint != pr_context.fingerprint
+ idle = CIFollowUpDecision.WAIT if pr_context.ci_status == "pending" 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 idle
self._pr_fingerprint = pr_context.fingerprint
return CIFollowUpDecision.FIRE
# New unresolved review threads are feedback for the agent, and comparing
@@ -1046,7 +1054,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"pr_state": pr_context.pr_state,
},
)
- return CIFollowUpDecision.SKIP
+ return idle
self._pr_fingerprint = pr_context.fingerprint
fire = (fingerprint_changed and is_pr_actionable(pr_context)) or new_feedback
workflow.logger.info(
@@ -1062,7 +1070,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"fire": fire,
},
)
- return CIFollowUpDecision.FIRE if fire else CIFollowUpDecision.SKIP
+ return CIFollowUpDecision.FIRE if fire else idle
async def _emit_pr_opened_progress(self, pr_url: str) -> None:
# First time we observe a PR: surface "Opened pull request" + "Keeping CI green" so the UI moves
@@ -1155,7 +1163,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"PR is in the merge queue, skipping CI follow-up",
extra={"run_id": self.context.run_id, "pr_url": snapshot.pr_url},
)
- return CIFollowUpDecision.SKIP
+ return CIFollowUpDecision.WAIT
attention = self._babysit_journal.attention(snapshot)
if attention.is_empty:
if (
@@ -1191,7 +1199,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"head_sha": snapshot.head_sha,
},
)
- return CIFollowUpDecision.SKIP
+ return CIFollowUpDecision.WAIT if snapshot.ci_status == "pending" else CIFollowUpDecision.SKIP
self._pending_babysit = _BabysitDispatch(snapshot=snapshot, attention=attention)
workflow.logger.info(
"PR needs attention, dispatching CI follow-up",
@@ -1378,16 +1386,23 @@ class ProcessTaskWorkflow(PostHogWorkflow):
case CIFollowUpDecision.FIRE:
workflow.set_current_details("🔁 Re-checking the PR's CI and nudging the agent.")
self._ci_resume_snapshot_created = False
+ self._ci_idle_skips = 0
await self._dispatch_ci_follow_up()
case CIFollowUpDecision.NO_PR | CIFollowUpDecision.TERMINAL:
# No PR will ever appear — stop the CI loop entirely.
self._ci_repetitions = MAX_CI_REPETITIONS
- case CIFollowUpDecision.SKIP:
+ case CIFollowUpDecision.SKIP | CIFollowUpDecision.WAIT:
# Bound the next get_pr_context call to +CI_FOLLOW_UP_DELAY.
# Without this, _wait_for_ci_follow_up returns immediately
# whenever last_active_time is older than the delay, and the
# workflow tight-loops calling GET /repos/.../pulls/{n}.
self._last_active_time = workflow.now()
+ if (
+ follow_up_result == CIFollowUpDecision.SKIP
+ and self.context.mode != "interactive"
+ and workflow.patched(_PATCH_ID_CI_IDLE_SKIP_CAP)
+ ):
+ self._ci_idle_skips += 1
case _:
raise ValueError(f"Unknown CIFollowUpDecision: {follow_up_result}")
case TaskEvent.SANDBOX_TTL_APPROACHING:
@@ -1955,6 +1970,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
connect_token=self._sandbox_connect_token,
jwt_kid=self._sandbox_jwt_kid,
ci_repetitions=self._ci_repetitions,
+ ci_idle_skips=self._ci_idle_skips,
pr_fingerprint=self._pr_fingerprint,
pr_unresolved_threads=self._pr_unresolved_threads,
babysit_journal=self._babysit_journal,
@@ -2000,6 +2016,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._is_agent_design_enabled = resumed.is_agent_design_enabled
self._dev_stack_preview_enabled = resumed.dev_stack_preview_enabled
self._ci_repetitions = resumed.ci_repetitions
+ self._ci_idle_skips = resumed.ci_idle_skips
self._pr_fingerprint = resumed.pr_fingerprint
self._pr_unresolved_threads = resumed.pr_unresolved_threads
self._babysit_journal = resumed.babysit_journal