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): hold the pr follow-up loop while trunk tests the pr (#105311)

Julian Bezbf954a20c907
diff --git a/products/tasks/backend/temporal/babysit_pr/snapshot.py b/products/tasks/backend/temporal/babysit_pr/snapshot.py
index 7f7aa2e7c0a0..11ca4f3b4fa8 100644
--- a/products/tasks/backend/temporal/babysit_pr/snapshot.py
+++ b/products/tasks/backend/temporal/babysit_pr/snapshot.py
@@ -54,6 +54,7 @@ class PRSnapshot:
review_decision: str | None = None
review_threads_complete: bool = False
head_ref: str = ""
+ merge_queue_push_would_eject: bool = False
@property
def can_mark_ready(self) -> bool:
@@ -86,6 +87,7 @@ class PRSnapshot:
review_decision=raw.get("review_decision"),
review_threads_complete=raw.get("review_threads_complete") is True,
head_ref=raw.get("head_ref") or "",
+ merge_queue_push_would_eject=raw.get("merge_queue_push_would_eject") is True,
failing_checks=[
FailingCheck(key=check["key"], details_url=check.get("details_url"))
for check in raw.get("failing_checks") or []
diff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py b/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py
index 3c6cc4f73b63..5a1dc024c0d7 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py
@@ -19,6 +19,7 @@ from products.tasks.backend.temporal.process_task.activities.get_pr_context impo
DEFAULT_GITHUB_RATE_LIMIT_BACKOFF_SECONDS,
get_github_integration,
get_user_github_integration,
+ merge_queue_push_would_eject,
)
@@ -66,6 +67,9 @@ def get_pr_babysit_snapshot(input: GetPrBabysitSnapshotInput) -> PRSnapshot | No
try:
raw = github_integration.get_pull_request_babysit_snapshot(pr_url)
+ # A closed PR ends the loop anyway, so a failed queue read must not fail its last tick.
+ if raw.get("success") and raw.get("state") not in ("closed", "merged"):
+ raw["merge_queue_push_would_eject"] = merge_queue_push_would_eject(github_integration, pr_url)
except (GitHubRateLimitError, GitHubEgressBudgetExhausted) as e:
retry_after = getattr(e, "retry_after", None) or DEFAULT_GITHUB_RATE_LIMIT_BACKOFF_SECONDS
raise GitHubRateLimitedError(
diff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py
index e34ddd8a1468..c1dc59b1e73b 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py
@@ -28,7 +28,7 @@ class GetPrContextInput:
context: TaskProcessingContext
-@dataclass
+@dataclass(frozen=True)
class GetPrContextOutput:
pr_url: str
pr_state: str
@@ -37,6 +37,7 @@ class GetPrContextOutput:
ci_status: str = "none"
changes_requested: bool = False
unresolved_threads: int = 0
+ merge_queue_push_would_eject: bool = False
def is_pr_actionable(pr: GetPrContextOutput) -> bool:
@@ -79,6 +80,19 @@ def compute_pr_fingerprint(pr: dict[str, Any]) -> str:
return hashlib.sha256(fingerprint_source.encode()).hexdigest()
+def merge_queue_push_would_eject(github_integration: GitHubIntegration | UserGitHubIntegration, pr_url: str) -> bool:
+ """Whether a push now removes the PR from the Trunk merge queue and resets the PRs testing behind it.
+
+ A submitted PR that still waits for branch protection reads False, because a fix push is what
+ it waits for.
+ """
+ ref = github_integration.parse_pull_request_url(pr_url)
+ if ref is None:
+ return False
+ state = github_integration.get_pull_request_merge_queue_state(ref.repository, ref.number)
+ return state is not None and state.push_would_eject
+
+
def get_github_integration(github_integration_id: int) -> GitHubIntegration:
integration = Integration.objects.get(id=github_integration_id)
github_integration = GitHubIntegration(integration)
@@ -140,6 +154,9 @@ def get_pr_context(input: GetPrContextInput) -> GetPrContextOutput | None:
if not pull_request.get("success"):
return None
fingerprint = compute_pr_fingerprint(pull_request)
+ push_would_eject = pull_request.get("state") not in ("closed", "merged") and merge_queue_push_would_eject(
+ github_integration, pr_url
+ )
except (GitHubRateLimitError, GitHubEgressBudgetExhausted) as e:
# A GitHub rate limit (its own 429) or our egress budget shedding the call is a
# normal, recoverable condition — not a fault. Keep it retryable but skip error
@@ -193,4 +210,5 @@ def get_pr_context(input: GetPrContextInput) -> GetPrContextOutput | None:
ci_status=pull_request.get("ci_status", "none"),
changes_requested=pull_request.get("review_decision") == "changes_requested",
unresolved_threads=pull_request.get("unresolved_threads", 0),
+ merge_queue_push_would_eject=push_would_eject,
)
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_babysit_snapshot.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_babysit_snapshot.py
index d196fe988b29..3d4353baa733 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_babysit_snapshot.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_babysit_snapshot.py
@@ -7,6 +7,8 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
+from posthog.github.merge_queue import MergeQueueState
+from posthog.models.github_integration_base import GitHubIntegrationBase
from products.tasks.backend.exceptions import GitHubRateLimitedError, ProcessTaskTransientError
from products.tasks.backend.temporal.babysit_pr.snapshot import BODY_EXCERPT_MAX_CHARS, PRSnapshot
@@ -92,6 +94,8 @@ class TestGetPrBabysitSnapshotActivity:
def _integration_returning(self, raw: dict) -> MagicMock:
integration = MagicMock()
integration.get_pull_request_babysit_snapshot.return_value = raw
+ integration.parse_pull_request_url = GitHubIntegrationBase.parse_pull_request_url
+ integration.get_pull_request_merge_queue_state.return_value = None
return integration
@pytest.mark.django_db
@@ -134,9 +138,9 @@ class TestGetPrBabysitSnapshotActivity:
}
ctx = self._ctx(run_id=str(test_task_run.id))
- with patch(
- f"{GET_PR_BABYSIT_SNAPSHOT_MODULE}.get_github_integration", return_value=self._integration_returning(raw)
- ):
+ integration = self._integration_returning(raw)
+ integration.get_pull_request_merge_queue_state.return_value = MergeQueueState.TESTING
+ with patch(f"{GET_PR_BABYSIT_SNAPSHOT_MODULE}.get_github_integration", return_value=integration):
snapshot = self._run(ctx)
assert snapshot is not None
@@ -151,6 +155,20 @@ class TestGetPrBabysitSnapshotActivity:
assert thread.body_excerpt == "rename this"
comment = snapshot.comments[0]
assert (comment.id, comment.body_excerpt) == ("M1", "3 nits")
+ assert snapshot.merge_queue_push_would_eject is True
+
+ @pytest.mark.django_db
+ def test_merged_pr_skips_the_queue_read(self, test_task_run):
+ test_task_run.output = {"pr_url": PR_URL}
+ test_task_run.save(update_fields=["output"])
+
+ integration = self._integration_returning({"success": True, "url": PR_URL, "state": "merged"})
+ integration.get_pull_request_merge_queue_state.side_effect = RuntimeError("comments unavailable")
+ with patch(f"{GET_PR_BABYSIT_SNAPSHOT_MODULE}.get_github_integration", return_value=integration):
+ snapshot = self._run(self._ctx(run_id=str(test_task_run.id)))
+
+ assert snapshot is not None
+ assert snapshot.is_terminal
@pytest.mark.django_db
def test_raises_transient_error_when_github_call_raises(self, test_task_run):
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 10a376953064..31bdfdafe314 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
@@ -300,6 +300,22 @@ class TestBabysitFollowUpDecision:
assert await wf._should_run_ci_follow_up() is expected_decision
+ @pytest.mark.parametrize(
+ "patch_recorded,expected_decision",
+ [
+ (True, CIFollowUpDecision.SKIP),
+ (False, CIFollowUpDecision.FIRE),
+ ],
+ )
+ async def test_merge_queue_skip_follows_the_patch_marker(self, monkeypatch, patch_recorded, expected_decision):
+ wf = _babysit_workflow()
+ _patch_snapshot(
+ monkeypatch, _babysit_snapshot(failing_checks=[BABYSIT_CHECK], merge_queue_push_would_eject=True)
+ )
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: patch_recorded)
+
+ assert await wf._should_run_ci_follow_up() is expected_decision
+
async def test_dispatched_check_is_silenced_until_a_new_head(self, monkeypatch):
wf = _babysit_workflow()
sent = _capture_dispatched_messages(monkeypatch)
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index d4166c752adc..8ed9bc305750 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -437,6 +437,9 @@ _PATCH_ID_FOLLOWUP_FAILURE_KEEPS_RUN = "tasks-followup-failure-keeps-run"
_PATCH_ID_DEV_STACK_PREVIEW = "tasks-dev-stack-preview"
_PATCH_ID_PROGRESS_EMIT_NONBLOCKING = "progress-emit-nonblocking-2026-09"
+# A new activity worker can record the merge queue flag as true while an old workflow worker
+# ignores it and dispatches, so replay takes the skip only where the marker was recorded.
+_PATCH_ID_MERGE_QUEUE_SKIP = "tasks-merge-queue-skip-2026-09"
_PENDING_PROGRESS_FLUSH_SECONDS = 15.0
@@ -990,6 +993,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):
},
)
return CIFollowUpDecision.SKIP
+ if pr_context.merge_queue_push_would_eject and workflow.patched(_PATCH_ID_MERGE_QUEUE_SKIP):
+ workflow.logger.info(
+ "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
fingerprint_changed = self._pr_fingerprint != pr_context.fingerprint
if not ci_follow_up_actionable_gate():
# Legacy replay path: any fingerprint change fires; feedback is not consulted.
@@ -1113,6 +1122,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):
label = "PR merged" if snapshot.pr_state == "merged" else "PR closed"
await self._emit_progress("ci", "completed", label, "setup")
return CIFollowUpDecision.TERMINAL
+ if snapshot.merge_queue_push_would_eject and workflow.patched(_PATCH_ID_MERGE_QUEUE_SKIP):
+ # The journal stays untouched, so the feedback waits for the next tick after the PR
+ # leaves the queue instead of being marked handled.
+ workflow.logger.info(
+ "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
attention = self._babysit_journal.attention(snapshot)
if attention.is_empty:
if (
diff --git a/products/tasks/backend/temporal/task_management/workflow.py b/products/tasks/backend/temporal/task_management/workflow.py
index 3982b67286b9..a55f84fb06d0 100644
--- a/products/tasks/backend/temporal/task_management/workflow.py
+++ b/products/tasks/backend/temporal/task_management/workflow.py
@@ -79,6 +79,7 @@ _PATCH_ID_ACK_BEFORE_COMPLETION = "tasks-task-management-ack-before-completion"
_PATCH_ID_ACK_BEFORE_COMPLETION_SANDBOX_GENERATION = "tasks-task-management-ack-before-completion-sandbox-generation"
_PATCH_ID_CLOSED_CHILD_FOLLOWUP_RECOVERY = "tasks-task-management-closed-child-followup-recovery"
_PATCH_ID_CLOSED_CHILD_COMPLETION_RECOVERY = "tasks-task-management-closed-child-completion-recovery"
+_PATCH_ID_MERGE_QUEUE_SKIP = "tasks-task-management-merge-queue-skip-2026-09"
_PATCH_ID_CLOSED_CHILD_ACK_RETRY_RECOVERY = "tasks-task-management-closed-child-ack-retry-recovery"
_PATCH_ID_CLEAR_STEER_ON_SANDBOX_BOUNDARY = "tasks-task-management-clear-steer-on-sandbox-boundary"
_PATCH_ID_BOUNDED_SANDBOX_REPLACEMENT_RECOVERY = "tasks-task-management-bounded-sandbox-replacement-recovery"
@@ -1256,6 +1257,12 @@ class TaskManagementWorkflow(PostHogWorkflow):
"task_management_ci_skipped_pr_closed", extra={"run_id": self._run_id, "pr_url": pr_context.pr_url}
)
return CIFollowUpDecision.SKIP
+ if 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
fingerprint_changed = self._pr_fingerprint != pr_context.fingerprint
if not ci_follow_up_actionable_gate():
# Legacy replay path: any fingerprint change fires; feedback is not consulted.