: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): reconcile late pull request attachments (#109254)
Georgiy Tarasov5051c773a392
diff --git a/products/signals/backend/facade/github.py b/products/signals/backend/facade/github.pyindex 791fd2a8e7c2..0f24473c6056 100644--- a/products/signals/backend/facade/github.py+++ b/products/signals/backend/facade/github.py@@ -1,5 +1,7 @@"""Signals' GitHub identity and report-assignment integration."""+from datetime import datetime+from django.utils.dateparse import parse_datetimeimport structlog@@ -12,6 +14,14 @@ from products.signals.backend.report_generation.resolve_reviewers import resolvelogger = structlog.get_logger(__name__)+def reconcile_pull_request_state(+ *, team_id: int, repository: str, pr_number: int, pr_state: str, merged_at: datetime | None+) -> None:+ update_assignments_for_pull_request(+ team_ids=[team_id], repository=repository, pr_number=pr_number, pr_state=pr_state, merged_at=merged_at+ )++def resolve_github_login_distinct_id(login: str, team_id: int) -> str | None:user = resolve_org_github_login_to_users(team_id, [login]).get(login.strip().lower())return str(user.distinct_id) if user is not None else Nonediff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 3618501ae14a..fa700e909dbd 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -2650,6 +2650,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(# controller write arbitrary text into the agent's user-level instructions file."agent_instructions","wizard_config",+ "reconciled_pr_merge_url","wizard_head_branch","use_modal_directory_resume_snapshots","use_modal_vm_sandbox",@@ -3199,6 +3200,9 @@ def update_task_run(from products.tasks.backend.logic.services.loop_runs import ( # noqa: PLC0415 (keep temporalio off the api import path)handle_loop_run_terminal,)+ from products.tasks.backend.logic.services.pr_reconciliation import ( # noqa: PLC0415 - avoids the facade/webhook import cycle+ PullRequestReconciler,+ )from products.tasks.backend.metrics import ( # noqa: PLC0415 — keep prometheus deps off the api import pathobserve_agent_turn_failed,observe_prewarmed_unused_if_never_activated,@@ -3255,6 +3259,7 @@ def update_task_run(or only_if_non_terminalor only_if_not_startedor "status" in validated_data+ or "branch" in validated_data):run = TaskRun.objects.select_for_update().get(pk=run.pk)if only_if_not_started and run.status != TaskRun.Status.NOT_STARTED:@@ -3264,6 +3269,8 @@ def update_task_run(transaction.on_commit(lambda: resume_workflow_step_for_run(run))return _task_run_detail_to_dto(run, user_id=user_id)old_status = run.status+ old_output = run.output+ old_branch = run.branchold_pr_url = (run.output or {}).get("pr_url") if isinstance(run.output, dict) else Noneold_commit_head = _commit_push_head_sha(run.output)@@ -3335,6 +3342,7 @@ def update_task_run(update_fields.add("updated_at")run.save(update_fields=list(update_fields))+ PullRequestReconciler.schedule(run, previous_output=old_output, previous_branch=old_branch)run.publish_stream_state_event()# Only on the actual transition: a repeat PATCH with the same terminal status, or an@@ -3433,16 +3441,23 @@ def set_task_run_output(run_id: str | UUID, task_id: str | UUID, team_id: int, *, output: dict, user_id: int | None = None) -> contracts.TaskRunDetailDTO | None:"""Persist a run's output. Completes the run for structured-output tasks; posts Slack PR update."""+ from products.tasks.backend.logic.services.pr_reconciliation import ( # noqa: PLC0415 - avoids the facade/webhook import cycle+ PullRequestReconciler,+ )+run = _get_visible_run(run_id, task_id, team_id)if run is None:return Nonetask = run.task# Preserve PR facts a webhook may have written concurrently: this assignment is wholesale,# so a bare `= output` would drop output.pr_url recorded out of band.- existing = run.output if isinstance(run.output, dict) else {}- merged = merge_pr_output(existing, output)- run.output = _apply_caller_output(existing, output, merged)- run.save(update_fields=["output", "updated_at"])+ with transaction.atomic():+ run = TaskRun.objects.select_for_update().get(pk=run.pk, team_id=team_id)+ existing = run.output if isinstance(run.output, dict) else {}+ merged = merge_pr_output(existing, output)+ run.output = _apply_caller_output(existing, output, merged)+ run.save(update_fields=["output", "updated_at"])+ PullRequestReconciler.schedule(run, previous_output=existing, previous_branch=run.branch)_refresh_self_driving_quota_for_pr(run, existing.get("pr_url"))if task.json_schema and not (run.state or {}).get("caller_ends_run"):signal_workflow_completion(run.id, TaskRun.Status.COMPLETED, None)diff --git a/products/tasks/backend/logic/services/pr_reconciliation.py b/products/tasks/backend/logic/services/pr_reconciliation.pynew file mode 100644index 000000000000..bfc859d44c78--- /dev/null+++ b/products/tasks/backend/logic/services/pr_reconciliation.py@@ -0,0 +1,214 @@+from datetime import datetime+from typing import Literal++from django.db import transaction+from django.utils.dateparse import parse_datetime++import structlog++from posthog.dataclasses import frozen+from posthog.egress.limiter.policies import Priority+from posthog.models.github_integration_base import (+ GitHubIntegrationBase,+ GitHubIntegrationError,+ _is_safe_github_repo_path,+)+from posthog.models.integration import GitHubIntegration+from posthog.models.organization import OrganizationMembership+from posthog.models.user_integration import UserGitHubIntegration++from products.signals.backend.facade.github import reconcile_pull_request_state+from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.pr_urls import read_head_branches, read_pr_urls+from products.tasks.backend.webhooks import _run_repository_filter, _task_run_scope_team_ids, find_task_run++logger = structlog.get_logger(__name__)+++@frozen+class PullRequestSnapshot:+ url: str+ head_branch: str+ head_repository: str+ state: Literal["open", "draft", "closed", "merged"]+ merged_at: datetime | None++ @classmethod+ def from_github(cls, response: dict[str, object]) -> "PullRequestSnapshot | None":+ url, branch, repository = response.get("url"), response.get("head_branch"), response.get("head_repository")+ if not all(isinstance(value, str) and value for value in (url, branch, repository)):+ return None+ if response.get("state") not in {"open", "closed"}:+ return None+ assert isinstance(url, str) and isinstance(branch, str) and isinstance(repository, str)+ state: Literal["open", "draft", "closed", "merged"] = "open"+ if response.get("merged") is True:+ state = "merged"+ elif response.get("state") == "closed":+ state = "closed"+ elif response.get("draft") is True:+ state = "draft"+ merged_at = response.get("merged_at")+ return cls(+ url=url,+ head_branch=branch,+ head_repository=repository,+ state=state,+ merged_at=parse_datetime(merged_at) if isinstance(merged_at, str) else None,+ )+++class PullRequestReconciler:+ @staticmethod+ def schedule(run: TaskRun, *, previous_output: object, previous_branch: str | None) -> None:+ from products.tasks.backend.tasks.tasks import ( # noqa: PLC0415 - avoids the facade/task import cycle+ reconcile_task_run_pull_request,+ )++ state = run.state if isinstance(run.state, dict) else {}+ verified = state.get("verified_pr_urls") or []+ metadata_changed = run.branch != previous_branch or read_head_branches(run.output) != read_head_branches(+ previous_output+ )+ previous_urls = read_pr_urls(previous_output)+ for url in read_pr_urls(run.output):+ if url in verified or (url in previous_urls and not metadata_changed):+ continue+ if GitHubIntegrationBase.parse_pull_request_url(url) is None:+ continue++ def enqueue(pr_url: str = url) -> None:+ try:+ reconcile_task_run_pull_request.delay(team_id=run.team_id, run_id=str(run.id), pr_url=pr_url)+ except Exception:+ logger.exception("task_pr_reconciliation_enqueue_failed", run_id=str(run.id))++ transaction.on_commit(enqueue)++ def __init__(self, *, team_id: int, run_id: str, pr_url: str) -> None:+ self.team_id = team_id+ self.run_id = run_id+ self.pr_url = pr_url++ def _log(self, outcome: str) -> None:+ logger.info("task_pr_reconciliation", team_id=self.team_id, run_id=self.run_id, outcome=outcome)++ def _eligible(self, run: TaskRun) -> bool:+ state = run.state if isinstance(run.state, dict) else {}+ return (+ not run.task.deleted+ and run.task.origin_product != Task.OriginProduct.REVIEW_HOG+ and self.pr_url in read_pr_urls(run.output)+ and self.pr_url not in (state.get("verified_pr_urls") or [])+ )++ @staticmethod+ def _github(run: TaskRun) -> GitHubIntegrationBase | None:+ integration = run.task.github_integration+ if integration is not None and integration.team_id == run.team_id and integration.kind == "github":+ return GitHubIntegration(integration, source="task_pr_reconciliation", priority=Priority.BATCH)+ personal = run.task.github_user_integration+ if (+ personal is not None+ and personal.kind == "github"+ and personal.user_id == run.task.created_by_id+ and OrganizationMembership.objects.filter(+ user_id=personal.user_id, organization_id=run.team.organization_id+ ).exists()+ ):+ return UserGitHubIntegration(personal, source="task_pr_reconciliation", priority=Priority.BATCH)+ return None++ def reconcile(self) -> None:+ parsed = GitHubIntegrationBase.parse_pull_request_url(self.pr_url)+ if (+ parsed is None+ or not _is_safe_github_repo_path(parsed.repository)+ or self.pr_url != f"https://github.com/{parsed.repository}/pull/{parsed.number}"+ ):+ self._log("invalid_url")+ return+ runs = TaskRun.objects.using("default").filter(team_id=self.team_id, id=self.run_id)+ run = (+ runs.filter(_run_repository_filter(parsed.repository))+ .select_related("task__github_integration", "task__github_user_integration", "team")+ .first()+ )+ if run is None or not self._eligible(run):+ self._log("ineligible")+ return+ github = self._github(run)+ if github is None:+ self._log("missing_integration")+ return+ scope = _task_run_scope_team_ids({"installation": {"id": github.github_installation_id}})+ if self.team_id not in scope:+ self._log("outside_installation_scope")+ return+ try:+ response = github.get_pull_request(parsed.repository, parsed.number)+ except GitHubIntegrationError as error:+ if error.status_code in {401, 403, 404}:+ self._log("inaccessible")+ return+ raise+ if not response.get("success"):+ if response.get("status_code") in {401, 403, 404, 422}:+ self._log("inaccessible")+ return+ status_code = response.get("status_code")+ raise GitHubIntegrationError(+ "Could not fetch PR for reconciliation",+ status_code=status_code if isinstance(status_code, int) else None,+ )+ snapshot = PullRequestSnapshot.from_github(response)+ if (+ snapshot is None+ or snapshot.url != self.pr_url+ or snapshot.head_repository.lower() != parsed.repository.lower()+ ):+ self._log("pr_mismatch")+ return+ with transaction.atomic():+ locked = runs.select_for_update(of=("self",)).select_related("task").first()+ if locked is None or not self._eligible(locked):+ self._log("superseded")+ return+ if (+ locked.task.github_integration_id != run.task.github_integration_id+ or locked.task.github_user_integration_id != run.task.github_user_integration_id+ or self._github(locked) is None+ ):+ self._log("integration_changed")+ return+ matched = find_task_run(+ pr_url=self.pr_url, branch=snapshot.head_branch, repository=parsed.repository, team_ids=scope+ )+ if matched is None or matched.id != locked.id:+ self._log("different_run")+ return+ state = locked.state if isinstance(locked.state, dict) else {}+ verified = state.get("verified_pr_urls")+ locked.state = {+ **state,+ "verified_pr_urls": [*(verified if isinstance(verified, list) else []), self.pr_url],+ }+ output = locked.output if isinstance(locked.output, dict) else {}+ if output.get("pr_url") == self.pr_url:+ locked.output = {+ **output,+ "pr_state": snapshot.state,+ "pr_merged": snapshot.state == "merged",+ }+ if snapshot.state == "merged" and "wizard_config" in state:+ locked.state["reconciled_pr_merge_url"] = self.pr_url+ # Output receivers must retry report linking after verification, even if the URL is unchanged.+ locked.save(update_fields=["state", "output", "updated_at"])+ reconcile_pull_request_state(+ team_id=self.team_id,+ repository=parsed.repository,+ pr_number=parsed.number,+ pr_state=snapshot.state,+ merged_at=snapshot.merged_at,+ )+ self._log("verified")diff --git a/products/tasks/backend/tasks/tasks.py b/products/tasks/backend/tasks/tasks.pyindex b2d521d74398..61d3d4946e86 100644--- a/products/tasks/backend/tasks/tasks.py+++ b/products/tasks/backend/tasks/tasks.py@@ -1,7 +1,17 @@from datetime import datetimefrom uuid import UUID+from django.db import OperationalError+from celery import shared_task+from celery.app.task import Task as CeleryTask+from requests.exceptions import (+ ConnectionError as RequestsConnectionError,+ Timeout as RequestsTimeout,+)++from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.models.github_integration_base import GitHubIntegrationErrorfrom products.tasks.backend.facade.api import record_comment_activityfrom products.tasks.backend.logic.services.comment_slack_dm import send_comment_slack_dms@@ -10,6 +20,36 @@ from products.tasks.backend.logic.services.workflow_step_resume import resume_wofrom products.tasks.backend.logic.stream.budget_steer import BudgetSteerCapture, BudgetSteerProperties+@shared_task(ignore_result=True, bind=True, max_retries=5)+def reconcile_task_run_pull_request(self: CeleryTask, *, team_id: int, run_id: str, pr_url: str) -> None:+ from products.tasks.backend.logic.services.pr_reconciliation import ( # noqa: PLC0415 - avoids the facade/task import cycle+ PullRequestReconciler,+ )++ try:+ PullRequestReconciler(team_id=team_id, run_id=run_id, pr_url=pr_url).reconcile()+ except (+ GitHubIntegrationError,+ GitHubRateLimitError,+ GitHubEgressBudgetExhausted,+ RequestsConnectionError,+ RequestsTimeout,+ OperationalError,+ ) as error:+ if (+ isinstance(error, GitHubIntegrationError)+ and error.status_code is not None+ and 400 <= error.status_code < 500+ and error.status_code not in {408, 429}+ ):+ raise+ countdown = min(60 * 2**self.request.retries, 900)+ retry_after = getattr(error, "retry_after", None)+ if isinstance(retry_after, (int, float)):+ countdown = max(countdown, retry_after)+ raise self.retry(exc=error, countdown=countdown)++@shared_task(ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=5, acks_late=True)def capture_budget_steer(*, team_id: int, event_uuid: str, timestamp: str, properties: BudgetSteerProperties) -> None:BudgetSteerCapture.capture(team_id, event_uuid, timestamp, properties)diff --git a/products/tasks/backend/tests/test_pr_reconciliation.py b/products/tasks/backend/tests/test_pr_reconciliation.pynew file mode 100644index 000000000000..26643e924e96--- /dev/null+++ b/products/tasks/backend/tests/test_pr_reconciliation.py@@ -0,0 +1,390 @@+from itertools import product++from unittest.mock import MagicMock, patch++from django.db import transaction+from django.test import TestCase++from celery.exceptions import Retry+from parameterized import parameterized+from requests.exceptions import (+ ConnectionError as RequestsConnectionError,+ Timeout as RequestsTimeout,+)++from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.models import Organization, OrganizationMembership, Team, User+from posthog.models.github_integration_base import GitHubIntegrationError+from posthog.models.integration import Integration+from posthog.models.user_integration import UserIntegration++from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequest+from products.tasks.backend.facade.api import set_task_run_output, update_task_run+from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.tasks.tasks import reconcile_task_run_pull_request+from products.tasks.backend.webhooks import handle_pull_request_event+++class TestPullRequestReconciliation(TestCase):+ def setUp(self) -> None:+ self.organization = Organization.objects.create(name="Example organization")+ self.team = Team.objects.create(organization=self.organization)+ self.user = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)+ self.integration = Integration.objects.create(team=self.team, kind="github", integration_id="707070")+ self.report = SignalReport.objects.create(team=self.team, title="Improve widget navigation", status="ready")+ self.task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="Improve widget navigation",+ repository="example/widgets",+ github_integration=self.integration,+ signal_report=self.report,+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )+ SignalReportArtefact.objects.create(+ team=self.team, report=self.report, task=self.task, type="task_run", content="{}"+ )+ self.task_run = TaskRun.objects.create(team=self.team, task=self.task, branch="feature/navigation", output={})+ self.url = "https://github.com/example/widgets/pull/17"+ self.snapshot: dict[str, object] = {+ "success": True,+ "url": self.url,+ "head_branch": self.task_run.branch,+ "head_repository": self.task.repository,+ "state": "open",+ "draft": False,+ "merged": False,+ }+ self.fetch = self._patch("posthog.models.github_integration_base.GitHubIntegrationBase.get_pull_request")+ self.fetch.return_value = self.snapshot+ self.enqueue = self._patch("products.tasks.backend.tasks.tasks.reconcile_task_run_pull_request.delay")+ self.link = self._patch("products.signals.backend.tasks.link_report_tracker_issues.delay")+ self.analytics = self._patch("posthog.github.pull_request_events.posthoganalytics.capture")+ self._patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled").return_value = False+ self._patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")+ self._patch("products.tasks.backend.models.TaskRun.publish_stream_event")+ self._patch("products.tasks.backend.models.TaskRun.emit_progress_event")+ self._patch("products.signals.backend.tasks.refresh_pull_request_review_decision.delay")++ def _patch(self, target: str) -> MagicMock:+ patcher = patch(target)+ mocked = patcher.start()+ self.addCleanup(patcher.stop)+ return mocked++ def _write(self, writer: str = "patch", *, secondary: bool = False) -> None:+ output = (+ {"pr_url": "https://github.com/example/widgets/pull/16", "pr_urls": [self.url]}+ if secondary+ else {"pr_url": self.url}+ )+ with self.captureOnCommitCallbacks(execute=True):+ if writer == "patch":+ update_task_run(self.task_run.id, self.task.id, self.team.id, validated_data={"output": output})+ else:+ set_task_run_output(self.task_run.id, self.task.id, self.team.id, output=output)++ def _reconcile(self) -> None:+ with self.captureOnCommitCallbacks(execute=True):+ reconcile_task_run_pull_request.run(team_id=self.team.id, run_id=str(self.task_run.id), pr_url=self.url)++ def _webhook(self, *, merged: bool = False) -> None:+ with self.captureOnCommitCallbacks(execute=True):+ handle_pull_request_event(+ {+ "action": "closed" if merged else "opened",+ "installation": {"id": 707070},+ "repository": {"full_name": "example/widgets"},+ "pull_request": {+ "number": 17,+ "html_url": self.url,+ "state": "closed" if merged else "open",+ "merged": merged,+ "head": {"ref": "feature/navigation", "repo": {"full_name": "example/widgets"}},+ },+ }+ )++ @parameterized.expand(list(product(("patch", "set_output"), (False, True), (False, True))))+ def test_arrival_orders_restore_report_linking(self, writer: str, webhook_first: bool, secondary: bool) -> None:+ if webhook_first:+ self._webhook()+ self._write(writer, secondary=secondary)+ self.link.reset_mock()+ if not webhook_first:+ self._webhook()+ captures = self.analytics.call_count+ self._reconcile()+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertIn(self.url, self.task_run.state["verified_pr_urls"])+ self.assertTrue(SignalReportArtefact.objects.filter(report=self.report, type="pull_request").exists())+ self.link.assert_any_call(team_id=self.team.id, task_id=str(self.task.id), pr_url=self.url)+ self.assertEqual(self.analytics.call_count, captures)+ self.assertEqual(+ self.task_run.output["pr_url"], self.url if not secondary else "https://github.com/example/widgets/pull/16"+ )+ calls = self.link.call_count+ self._reconcile()+ self.assertEqual(self.link.call_count, calls)++ @parameterized.expand(list(product(("open", "draft", "closed", "merged"), (False, True))))+ def test_reconciles_current_status(self, state: str, secondary: bool) -> None:+ self._write(secondary=secondary)+ self.snapshot.update(+ state="closed" if state in {"closed", "merged"} else "open",+ draft=state == "draft",+ merged=state == "merged",+ )+ self._reconcile()+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ if secondary:+ self.assertNotIn("pr_state", self.task_run.output)+ self.assertNotIn("pr_merged", self.task_run.output)+ else:+ self.assertEqual(self.task_run.output["pr_state"], state)+ self.assertEqual(self.task_run.output["pr_merged"], state == "merged")+ pr = SignalReportPullRequest.objects.for_team(self.team.id).get(number=17)+ self.assertEqual(pr.state, state)++ @parameterized.expand(+ [+ ("fork",),+ ("branch",),+ ("url",),+ ("repository",),+ ("reviewhog",),+ ("deleted",),+ ("removed_url",),+ ("missing_integration",),+ ("stronger_match",),+ ]+ )+ def test_rejects_ineligible_attachment(self, reason: str) -> None:+ self._write()+ if reason == "fork":+ self.snapshot["head_repository"] = "another/widgets"+ elif reason == "branch":+ self.snapshot["head_branch"] = "another-branch"+ elif reason == "url":+ self.snapshot["url"] = "https://github.com/example/widgets/pull/18"+ elif reason == "repository":+ Task.objects.filter(id=self.task.id).update(repository="example/other")+ elif reason == "reviewhog":+ Task.objects.filter(id=self.task.id).update(origin_product=Task.OriginProduct.REVIEW_HOG)+ elif reason == "deleted":+ Task.objects.filter(id=self.task.id).update(deleted=True)+ elif reason == "removed_url":+ TaskRun.objects.filter(id=self.task_run.id).update(output={})+ elif reason == "missing_integration":+ Task.objects.filter(id=self.task.id).update(github_integration=None)+ elif reason == "stronger_match":+ TaskRun.objects.create(team=self.team, task=self.task, state={"verified_pr_urls": [self.url]})+ self.link.reset_mock()+ self._reconcile()+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertNotIn(self.url, (self.task_run.state or {}).get("verified_pr_urls", []))+ self.link.assert_not_called()++ def test_webhook_wins_while_fetch_is_in_flight(self) -> None:+ self._write()++ def fetch(repository: str, number: int) -> dict[str, object]:+ self._webhook(merged=True)+ return self.snapshot++ self.fetch.side_effect = fetch+ self._reconcile()+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertEqual(self.task_run.output["pr_state"], "merged")+ self.assertTrue(self.task_run.output["pr_merged"])++ def test_rechecks_branch_after_fetch(self) -> None:+ self._write()++ def fetch(repository: str, number: int) -> dict[str, object]:+ TaskRun.objects.filter(id=self.task_run.id).update(branch="another-branch")+ return self.snapshot++ self.fetch.side_effect = fetch+ self._reconcile()+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertNotIn("verified_pr_urls", self.task_run.state)++ def test_branch_arriving_after_url_schedules_reconciliation(self) -> None:+ TaskRun.objects.filter(id=self.task_run.id).update(branch=None)+ self._write()+ self._reconcile()+ self.enqueue.reset_mock()+ with self.captureOnCommitCallbacks(execute=True):+ update_task_run(+ self.task_run.id, self.task.id, self.team.id, validated_data={"branch": "feature/navigation"}+ )+ self.enqueue.assert_called_once_with(team_id=self.team.id, run_id=str(self.task_run.id), pr_url=self.url)+ self._reconcile()+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertIn(self.url, self.task_run.state["verified_pr_urls"])++ def test_rollback_does_not_enqueue(self) -> None:+ with self.captureOnCommitCallbacks(execute=True):+ with transaction.atomic():+ update_task_run(+ self.task_run.id, self.task.id, self.team.id, validated_data={"output": {"pr_url": self.url}}+ )+ transaction.set_rollback(True)+ self.enqueue.assert_not_called()++ def test_personal_integration(self) -> None:+ personal = UserIntegration.objects.create(user=self.user, kind="github", integration_id="808080")+ Task.objects.filter(id=self.task.id).update(github_integration=None, github_user_integration=personal)+ self._write()+ self._reconcile()+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertIn(self.url, self.task_run.state["verified_pr_urls"])++ def _attempt(self, retries: int) -> None:+ reconcile_task_run_pull_request.push_request(+ retries=retries,+ called_directly=False,+ is_eager=False,+ args=(),+ kwargs={"team_id": self.team.id, "run_id": str(self.task_run.id), "pr_url": self.url},+ )+ try:+ self._reconcile()+ finally:+ reconcile_task_run_pull_request.pop_request()++ @parameterized.expand(+ [+ ("server", GitHubIntegrationError("server unavailable"), 0),+ ("rate_limit", GitHubRateLimitError("rate limited", retry_after=1200), 1200),+ ("budget", GitHubEgressBudgetExhausted("budget exhausted"), 0),+ ("connection", RequestsConnectionError("connection unavailable"), 0),+ ("timeout", RequestsTimeout("request timed out"), 0),+ ]+ )+ def test_retries_transient_errors(self, _name: str, error: Exception, retry_after: int) -> None:+ self._write()+ self.fetch.side_effect = error+ with patch.object(reconcile_task_run_pull_request, "apply_async") as publish:+ for attempt, delay in enumerate([60, 120, 240, 480, 900]):+ with self.assertRaises(Retry):+ self._attempt(attempt)+ self.assertEqual(publish.call_count, attempt + 1)+ self.assertEqual(publish.call_args.kwargs["countdown"], max(delay, retry_after))+ self.assertEqual(publish.call_args.kwargs["retries"], attempt + 1)+ with self.assertRaises(type(error)):+ self._attempt(5)+ self.assertEqual(publish.call_count, 5)+ self.assertEqual(self.fetch.call_count, 6)+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertNotIn("verified_pr_urls", self.task_run.state)++ def test_retry_recovers_after_transient_failure(self) -> None:+ self._write()+ self.fetch.side_effect = [+ {"success": False, "status_code": 503},+ GitHubRateLimitError("rate limited", retry_after=180),+ self.snapshot,+ ]+ self.link.reset_mock()+ with patch.object(reconcile_task_run_pull_request, "apply_async") as publish:+ for attempt, delay in enumerate([60, 180]):+ with self.assertRaises(Retry):+ self._attempt(attempt)+ self.assertEqual(publish.call_args.kwargs["countdown"], delay)+ self._attempt(2)+ self.assertEqual(publish.call_count, 2)+ self.task_run.refresh_from_db()+ self.assertIn(self.url, self.task_run.state["verified_pr_urls"])+ self.link.assert_called_once_with(team_id=self.team.id, task_id=str(self.task.id), pr_url=self.url)++ @parameterized.expand(+ [+ ("programming_error", TypeError("invalid snapshot")),+ ("missing_row", TaskRun.DoesNotExist()),+ ("bad_request", GitHubIntegrationError("bad request", status_code=400)),+ ]+ )+ def test_deterministic_errors_do_not_retry(self, _name: str, error: Exception) -> None:+ self._write()+ if _name == "bad_request":+ self.fetch.return_value = {"success": False, "status_code": 400}+ else:+ self.fetch.side_effect = error+ with patch.object(reconcile_task_run_pull_request, "apply_async") as publish:+ with self.assertRaises(type(error)):+ self._attempt(0)+ publish.assert_not_called()+ self.fetch.assert_called_once()++ def test_repeated_output_does_not_enqueue(self) -> None:+ self._write()+ self.enqueue.reset_mock()+ self._write()+ self.enqueue.assert_not_called()++ def test_reconciled_merge_leaves_wizard_completion_to_webhook(self) -> None:+ TaskRun.objects.filter(id=self.task_run.id).update(+ state={"wizard_config": {}}, status=TaskRun.Status.IN_PROGRESS+ )+ self._write()+ self.snapshot.update(state="closed", merged=True)+ with patch("products.tasks.backend.webhooks.signal_workflow_completion") as signal:+ self._reconcile()+ signal.assert_not_called()+ self._webhook(merged=True)+ self._webhook(merged=True)+ signal.assert_called_once_with(self.task_run.id, TaskRun.Status.COMPLETED, None)+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertNotIn("reconciled_pr_merge_url", self.task_run.state)++ @parameterized.expand([("invalid_url",), ("inaccessible",), ("other_team",), ("foreign_personal_integration",)])+ def test_does_not_use_unavailable_pr_access(self, reason: str) -> None:+ self._write()+ if reason == "invalid_url":+ self.url = "https://example.com/example/widgets/pull/17"+ elif reason == "inaccessible":+ self.fetch.return_value = {"success": False, "status_code": 404}+ elif reason == "other_team":+ self.team = Team.objects.create(organization=self.organization)+ else:+ other_user = User.objects.create(email="[email protected]")+ personal = UserIntegration.objects.create(user=other_user, kind="github", integration_id="808080")+ Task.objects.filter(id=self.task.id).update(github_integration=None, github_user_integration=personal)+ self._reconcile()+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertNotIn("verified_pr_urls", self.task_run.state)+ if reason != "inaccessible":+ self.fetch.assert_not_called()++ def test_failed_enqueue_preserves_output_write(self) -> None:+ self.enqueue.side_effect = ConnectionError("queue unavailable")+ self._write()+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertEqual(self.task_run.output["pr_url"], self.url)++ def test_output_cannot_forge_reconciliation_state(self) -> None:+ with self.captureOnCommitCallbacks(execute=True):+ update_task_run(+ self.task_run.id,+ self.task.id,+ self.team.id,+ validated_data={"state": {"reconciled_pr_merge_url": self.url, "verified_pr_urls": [self.url]}},+ )+ self.task_run.refresh_from_db()+ assert isinstance(self.task_run.output, dict)+ self.assertNotIn("reconciled_pr_merge_url", self.task_run.state)+ self.assertNotIn("verified_pr_urls", self.task_run.state)diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex c90bd3aaf21b..e2ad26a0c1c6 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -403,7 +403,9 @@ def _append_run_pr_url(task_run: TaskRun, pr_url: str) -> bool:)locked.state = {**state, "verified_pr_urls": verified_pr_urls}if pr_url in read_pr_urls(locked.output):- locked.save(update_fields=["state", "updated_at"])+ if not isinstance(existing_verified, list) or pr_url not in existing_verified:+ # Restart report linking when its earlier attempt ran before verification.+ locked.save(update_fields=["state", "output", "updated_at"])task_run.state = locked.statetask_run.output = locked.outputreturn False@@ -438,6 +440,16 @@ def _record_run_pr_merged(task_run: TaskRun) -> None:APIs expose."""if not _record_run_output_field(task_run, "pr_merged", True, "github_pr_webhook_record_pr_merged_failed"):+ # A snapshot can record the merge before the webhook performs wizard lifecycle actions.+ pr_url = (task_run.output or {}).get("pr_url")+ if pr_url and (task_run.state or {}).get("reconciled_pr_merge_url") == pr_url:+ with transaction.atomic():+ locked = TaskRun.objects.select_for_update().get(id=task_run.id, team_id=task_run.team_id)+ if (locked.state or {}).get("reconciled_pr_merge_url") != pr_url:+ return+ locked.state = {key: value for key, value in locked.state.items() if key != "reconciled_pr_merge_url"}+ locked.save(update_fields=["state", "updated_at"])+ _complete_wizard_run_on_merge(locked)return# Publish-only (no append_log), same rationale and failure tolerance as _record_run_pr_url.try: