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(signals): restore task-backed pr lifecycle handling (#95554)

Mikayla Thompsona295f97f60ed
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
new file mode 100644
index 000000000000..6ef95a2591cb
--- /dev/null
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -0,0 +1,29 @@
+# Signals implementation PR lifecycle
+
+Report PR lookups use `fetch_implementation_pr_state_for_reports` in
+`products/signals/backend/implementation_pr.py`. A non-empty assignment PR takes
+precedence. Otherwise, lookup falls back to associated task-run artefacts and
+legacy `SignalReportTask` links, or the assignment's task when it has no PR.
+Implementation associations take precedence over other PR-bearing associations.
+Research, repository-selection, and scout runs do not supply implementation PRs.
+
+List/detail responses, PR checks and review actions, dismissal, and webhook
+handling use this selection. Reverse lookup first narrows candidates by PR
+identity and task output, then runs the same resolver so a superseded task PR
+cannot override an explicit assignment PR.
+
+GitHub webhooks remain scoped to teams connected to the installation. For a
+matching task-backed report without an assignment PR, they populate the PR
+metadata while preserving any existing claim. Merges resolve matching reports;
+unmerged closes suppress them, except reports already resolved. PR-driven
+transitions do not enqueue another GitHub close.
+
+Dismissal, snoozing, and manual resolution can close a task-backed fallback PR.
+An explicit assignment PR still requires a task or system actor for automatic
+closure. The shared-PR guard checks both assignment and task-backed links, and
+keeps the PR open while another unfinished report uses it. GitHub must confirm
+the PR is open and unmerged before PostHog comments or closes it.
+
+Fallback reads do not require a data migration. This does not replay webhook
+events that were missed before the fix; those reports need a subsequent event
+or explicit reconciliation.
diff --git a/products/signals/AGENT_REMEDIATION_PLAN.md b/products/signals/AGENT_REMEDIATION_PLAN.md
index 2a1b5ac0a787..8c40caacf1fa 100644
--- a/products/signals/AGENT_REMEDIATION_PLAN.md
+++ b/products/signals/AGENT_REMEDIATION_PLAN.md
@@ -47,9 +47,9 @@ PRs from unconnected repositories are allowed. Their state is `unknown`, they ar
GitHub webhook matching is scoped by the teams associated with the installation, then matched by normalized repository and PR number. A matching merge or close transitions every unresolved report attached to that PR.
-Internal implementation tasks claim their report when they start. When a PR-bearing task run records a PR, the signals receiver copies it into the assignment without requiring the task to call the public claim API. Existing task-backed PRs remain readable as a compatibility fallback when an assignment has no PR; assignment data always wins.
+Internal implementation tasks claim their report when they start. When a PR-bearing task run records a PR, the signals receiver copies it into the assignment without requiring the task to call the public claim API. Existing task-backed PRs remain a compatibility fallback for reads, PR actions, dismissal, and webhook handling when an assignment has no PR; a non-empty assignment PR always wins. See [PR lifecycle](../../docs/internal/signals-pr-lifecycle.md).
-Resolving a report never requires a PR. Manual resolution keeps the existing behavior: `fixed_outside_posthog` describes a fix without a PR, and `pr_merged` describes a merged PR that did not resolve the report automatically. A direct resolve or suppression closes an attached open PR only when the current assignment actor is `task` or `system` and PostHog can access it. PRs owned by users or external agents are not modified.
+Resolving a report never requires a PR. Manual resolution keeps the existing behavior: `fixed_outside_posthog` describes a fix without a PR, and `pr_merged` describes a merged PR that did not resolve the report automatically. A direct resolve or suppression closes an attached open PR only when its assignment actor is `task` or `system`, or the PR comes from the task-backed fallback, and PostHog can access it. Explicit PRs owned by users or external agents are not modified. A PR stays open while another unfinished report uses it through either source.
## Derived work state
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index 8950a8850dff..b28d04a45ce1 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -1,5 +1,6 @@
"""Resolve implementation PR URLs linked to signal reports."""
+import re
from typing import Literal, cast
from django.db.models import Q
@@ -34,23 +35,24 @@ class ImplementationPr:
url: str
merged: bool
state: str = SignalReportAssignment.PrState.UNKNOWN
+ task_id: str | None = None
+ actor_kind: str | None = None
def fetch_implementation_pr_state_for_reports(report_ids: list[str]) -> dict[str, ImplementationPr]:
"""Return assignment PRs first, falling back to existing task-backed PRs."""
if not report_ids:
return {}
+ assignments = list(SignalReportAssignment.all_teams.filter(report_id__in=report_ids))
result = {
str(assignment.report_id): ImplementationPr(
url=assignment.pr_url,
merged=assignment.pr_merged,
state=assignment.pr_state or SignalReportAssignment.PrState.UNKNOWN,
+ actor_kind=assignment.actor_kind,
)
- for assignment in SignalReportAssignment.all_teams.filter(
- report_id__in=report_ids,
- pr_url__isnull=False,
- ).exclude(pr_url="")
- if assignment.pr_url is not None
+ for assignment in assignments
+ if assignment.pr_url
}
missing_report_ids = [str(report_id) for report_id in report_ids if str(report_id) not in result]
@@ -67,9 +69,14 @@ def fetch_implementation_pr_state_for_reports(report_ids: list[str]) -> dict[str
for run in sorted(runs, key=lambda run: run.type != TASK_RUN_TYPE_IMPLEMENTATION)
if run.type not in NON_PR_BEARING_TASK_RUN_TYPES
]
+ pairs.extend(
+ (str(assignment.report_id), str(assignment.actor_task_id))
+ for assignment in assignments
+ if not assignment.pr_url and assignment.actor_kind == SignalActorKind.TASK and assignment.actor_task_id
+ )
task_ids = [task_id for _, task_id in pairs]
- pr_url_by_task = tasks_facade.get_latest_pr_url_by_task(task_ids)
- merged_task_ids = tasks_facade.get_merged_pr_task_ids(task_ids)
+ pr_url_by_task = tasks_facade.get_latest_pr_url_by_task(task_ids, pr_bearing_task_run_filter())
+ merged_task_ids = tasks_facade.get_merged_pr_task_ids(task_ids, pr_bearing_task_run_filter())
for report_id, task_id in pairs:
pr_url = pr_url_by_task.get(task_id)
if pr_url and report_id not in result:
@@ -78,6 +85,8 @@ def fetch_implementation_pr_state_for_reports(report_ids: list[str]) -> dict[str
url=pr_url,
merged=merged,
state=SignalReportAssignment.PrState.MERGED if merged else SignalReportAssignment.PrState.UNKNOWN,
+ task_id=task_id,
+ actor_kind=SignalActorKind.TASK,
)
return result
@@ -89,10 +98,32 @@ def pr_bearing_task_run_filter() -> Q:
def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str, str]:
- """PR URL stored on each report assignment, when available."""
return {report_id: pr.url for report_id, pr in fetch_implementation_pr_state_for_reports(report_ids).items()}
+def report_ids_for_implementation_pr(*, team_id: int, repository: str, pr_number: int) -> list[str]:
+ # Narrow by task output before resolving reports so webhooks do not scan the whole inbox.
+ owner, repo = repository.split("/", 1)
+ url_pattern = rf"^[^:]+://(www\.)?github\.com/+{re.escape(owner)}/+{re.escape(repo)}/+pull/+0*{pr_number}([/?#]|$)"
+ task_ids = tasks_facade.task_ids_with_pr_url_subquery(
+ team_id, pr_bearing_task_run_filter(), Q(output__pr_url__iregex=url_pattern)
+ )
+ candidates = SignalReport.objects.filter(team_id=team_id).filter(
+ Q(assignment__repository__iexact=repository, assignment__pr_number=pr_number)
+ | SignalReport.reports_for_task_ids_filter(task_ids, team_id=team_id)
+ )
+ prs = fetch_implementation_pr_state_for_reports(
+ [str(report_id) for report_id in candidates.values_list("id", flat=True)]
+ )
+ return [
+ report_id
+ for report_id, pr in prs.items()
+ if (parsed := GitHubIntegrationBase.parse_pull_request_url(pr.url)) is not None
+ and parsed.repository.lower() == repository.lower()
+ and parsed.number == pr_number
+ ]
+
+
PrCloseReason = Literal["suppressed", "snoozed", "resolved"]
# Left on the PR before it's closed, so anyone looking at the PR sees why it was closed and how to undo it.
@@ -127,20 +158,19 @@ def close_implementation_pr_for_report(
must succeed regardless.
"""
try:
- assignment = SignalReportAssignment.all_teams.filter(
- report_id=report_id,
- report__team_id=team_id,
- ).first()
- if assignment is None or not assignment.pr_url:
+ if not SignalReport.objects.filter(id=report_id, team_id=team_id).exists():
+ return False
+ pr = fetch_implementation_pr_state_for_reports([str(report_id)]).get(str(report_id))
+ if pr is None:
return False
- if assignment.actor_kind not in {SignalActorKind.TASK, SignalActorKind.SYSTEM}:
+ if pr.actor_kind not in {SignalActorKind.TASK, SignalActorKind.SYSTEM}:
logger.info(
"close_implementation_pr_untrusted_actor",
report_id=str(report_id),
- actor_kind=assignment.actor_kind,
+ actor_kind=pr.actor_kind,
)
return False
- pr_url = assignment.pr_url
+ pr_url = pr.url
parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
if parsed is None:
@@ -161,13 +191,14 @@ def close_implementation_pr_for_report(
# work the others still depend on, and the close webhook would then suppress them too, so
# only the last report still using it closes it.
still_used_elsewhere = (
- SignalReportAssignment.all_teams.filter(
- report__team_id=team_id,
- repository=parsed.repository.lower(),
- pr_number=parsed.number,
+ SignalReport.objects.filter(
+ team_id=team_id,
+ id__in=report_ids_for_implementation_pr(
+ team_id=team_id, repository=parsed.repository, pr_number=parsed.number
+ ),
)
- .exclude(report_id=report_id)
- .exclude(report__status__in=_FINISHED_REPORT_STATUSES)
+ .exclude(id=report_id)
+ .exclude(status__in=_FINISHED_REPORT_STATUSES)
.exists()
)
if still_used_elsewhere:
diff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.py
index 37c78f93d962..81a883471e55 100644
--- a/products/signals/backend/report_assignments.py
+++ b/products/signals/backend/report_assignments.py
@@ -411,24 +411,58 @@ def update_assignments_for_pull_request(
pr_number: int,
pr_state: str,
) -> int:
- """Apply a scoped GitHub webhook state to every report linked to the PR."""
+ from products.signals.backend.implementation_pr import (
+ fetch_implementation_pr_state_for_reports,
+ report_ids_for_implementation_pr,
+ )
+
if not team_ids:
return 0
normalized_repository = repository.lower()
+ report_ids = [
+ report_id
+ for team_id in team_ids
+ for report_id in report_ids_for_implementation_pr(team_id=team_id, repository=repository, pr_number=pr_number)
+ ]
updated = 0
with transaction.atomic():
- assignments = list(
- SignalReportAssignment.all_teams.select_for_update()
- .select_related("report")
- .filter(report__team_id__in=team_ids, repository=normalized_repository, pr_number=pr_number)
+ reports = list(
+ # nosemgrep: idor-lookup-without-team - The verified webhook installation scopes this cross-team lookup through team_id__in.
+ SignalReport.objects.select_for_update().filter(team_id__in=team_ids, id__in=report_ids).order_by("id")
)
- for assignment in assignments:
+ assignments = {
+ assignment.report_id: assignment
+ for assignment in SignalReportAssignment.all_teams.select_for_update().filter(
+ team_id__in=team_ids, report_id__in=report_ids
+ )
+ }
+ prs = fetch_implementation_pr_state_for_reports([str(report.id) for report in reports])
+ for report in reports:
+ pr = prs.get(str(report.id))
+ parsed = GitHubIntegrationBase.parse_pull_request_url(pr.url) if pr else None
+ if (
+ pr is None
+ or parsed is None
+ or parsed.repository.lower() != normalized_repository
+ or parsed.number != pr_number
+ ):
+ continue
+ assignment = assignments.get(report.id)
+ if assignment is None:
+ assignment = SignalReportAssignment(team_id=report.team_id, report_id=report.id)
+ if pr.task_id:
+ _set_actor(assignment, ArtefactAttribution.from_task(pr.task_id))
+ missing_pr = not assignment.pr_url
+ if missing_pr:
+ assignment.pr_url = pr.url
+ assignment.repository = normalized_repository
+ assignment.pr_number = pr_number
merged = pr_state == SignalReportAssignment.PrState.MERGED
changed = assignment.pr_state != pr_state or assignment.pr_merged != merged
assignment.pr_state = pr_state
assignment.pr_merged = merged
- if changed:
- assignment.save(update_fields=["pr_state", "pr_merged", "updated_at"])
- _apply_pr_report_state(assignment.report, pr_state)
+ if changed or missing_pr or assignment._state.adding:
+ assignment.save()
+ _apply_pr_report_state(report, pr_state)
updated += 1
return updated
diff --git a/products/signals/backend/test/test_dismissal_pr_close.py b/products/signals/backend/test/test_dismissal_pr_close.py
index 11c4c0554275..a9505d738051 100644
--- a/products/signals/backend/test/test_dismissal_pr_close.py
+++ b/products/signals/backend/test/test_dismissal_pr_close.py
@@ -8,9 +8,10 @@ from parameterized import parameterized
from posthog.models.team.team import Team
from products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report
-from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportAssignment
+from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportAssignment, SignalReportTask
from products.signals.backend.report_assignments import update_assignments_for_pull_request
from products.signals.backend.tasks import close_dismissed_report_pr
+from products.tasks.backend.models import Task, TaskRun
_PR_URL = "https://github.com/PostHog/posthog/pull/123"
@@ -147,6 +148,11 @@ class TestCloseDismissedReportPrTask(BaseTest):
class TestCloseImplementationPrForReport(BaseTest):
+ def _link_task_pr(self, report: SignalReport, pr_url: str = _PR_URL) -> None:
+ task = Task.objects.create(team=report.team, title="Implementation", description="Fix a bug")
+ TaskRun.objects.create(team=report.team, task=task, output={"pr_url": pr_url})
+ SignalReportTask.objects.create(team=report.team, report=report, task=task, relationship="implementation")
+
def setUp(self):
super().setUp()
self.report = SignalReport.objects.create(
@@ -173,6 +179,7 @@ class TestCloseImplementationPrForReport(BaseTest):
]
)
def test_does_not_touch_pr_without_trusted_claim_actor(self, _name: str, actor_kind: str | None):
+ self._link_task_pr(self.report, "https://github.com/PostHog/posthog/pull/456")
self.assignment.actor_kind = actor_kind
self.assignment.save(update_fields=["actor_kind", "updated_at"])
@@ -200,12 +207,23 @@ class TestCloseImplementationPrForReport(BaseTest):
@parameterized.expand(
[
- ("suppressed", "suppressed"),
- ("snoozed", "snoozed"),
- ("resolved", "resolved"),
+ ("suppressed", "suppressed", "assignment"),
+ ("snoozed", "snoozed", "assignment"),
+ ("resolved", "resolved", "assignment"),
+ ("legacy_suppressed", "suppressed", "legacy"),
+ ("legacy_snoozed", "snoozed", "legacy"),
+ ("legacy_resolved", "resolved", "legacy"),
+ ("claim_without_pr", "suppressed", "claim"),
]
)
- def test_comments_on_and_closes_linked_pr(self, _name: str, reason: PrCloseReason):
+ def test_comments_on_and_closes_linked_pr(self, _name: str, reason: PrCloseReason, source: str):
+ if source != "assignment":
+ self.assignment.delete()
+ self._link_task_pr(self.report)
+ if source == "claim":
+ SignalReportAssignment.objects.for_team(self.team.id).create(
+ team=self.team, report=self.report, actor_kind=SignalActorKind.AGENT, actor_agent="test-agent"
+ )
github = MagicMock()
github.get_pull_request.return_value = {"success": True, "state": "open", "merged": False}
github.comment_on_pull_request.return_value = {"success": True}
@@ -220,9 +238,10 @@ class TestCloseImplementationPrForReport(BaseTest):
comment_body = github.comment_on_pull_request.call_args.args[2]
assert reason in comment_body
github.close_pull_request.assert_called_once_with("PostHog/posthog", 123)
- self.assignment.refresh_from_db()
- assert self.assignment.pr_state == SignalReportAssignment.PrState.CLOSED
- assert self.assignment.pr_merged is False
+ if source == "assignment":
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_state == SignalReportAssignment.PrState.CLOSED
+ assert self.assignment.pr_merged is False
def test_returns_false_and_skips_github_without_linked_pr(self):
self.assignment.pr_url = None
@@ -248,7 +267,11 @@ class TestCloseImplementationPrForReport(BaseTest):
self.assignment.refresh_from_db()
assert self.assignment.pr_state == SignalReportAssignment.PrState.OPEN
- def test_does_not_close_a_report_pr_from_another_team(self):
+ @parameterized.expand([("assignment",), ("legacy",)])
+ def test_does_not_close_a_report_pr_from_another_team(self, source: str):
+ if source == "legacy":
+ self.assignment.delete()
+ self._link_task_pr(self.report)
other_team = Team.objects.create(organization=self.organization, name="Other team")
with patch(
@@ -257,8 +280,10 @@ class TestCloseImplementationPrForReport(BaseTest):
assert close_implementation_pr_for_report(other_team.id, str(self.report.id)) is False
mock_resolve.assert_not_called()
- self.assignment.refresh_from_db()
- assert self.assignment.pr_state == SignalReportAssignment.PrState.OPEN
+
+ if source == "assignment":
+ self.assignment.refresh_from_db()
+ assert self.assignment.pr_state == SignalReportAssignment.PrState.OPEN
def _other_report_sharing_the_pr(self, report_status: str) -> SignalReport:
other_report = SignalReport.objects.create(
@@ -277,8 +302,12 @@ class TestCloseImplementationPrForReport(BaseTest):
)
return other_report
- def test_does_not_close_a_pr_another_live_report_still_uses(self):
- self._other_report_sharing_the_pr(SignalReport.Status.READY)
+ @parameterized.expand([("assignment",), ("legacy",)])
+ def test_does_not_close_a_pr_another_live_report_still_uses(self, source: str):
+ other_report = self._other_report_sharing_the_pr(SignalReport.Status.READY)
+ if source == "legacy":
+ SignalReportAssignment.objects.for_team(self.team.id).filter(report=other_report).delete()
+ self._link_task_pr(other_report)
with patch(
"products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository"
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index b5d129c47d24..20e7edc035a0 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -753,7 +753,8 @@ class TestSignalReportListAPI(APIBaseTest):
assert response.json()["implementation_pr_url"] == "https://github.com/org/repo/pull/42"
assert response.json()["implementation_pr_state"] == SignalReportAssignment.PrState.OPEN
- def test_task_run_pr_is_used_as_fallback_when_assignment_has_no_pr(self):
+ @parameterized.expand([("missing",), ("empty",), ("task_only",)])
+ def test_task_run_pr_is_used_as_fallback_when_assignment_has_no_pr(self, source: str):
Task = apps.get_model("tasks", "Task")
TaskRun = apps.get_model("tasks", "TaskRun")
report = self._create_report()
@@ -775,12 +776,29 @@ class TestSignalReportListAPI(APIBaseTest):
task_id=str(task.id),
relationship=TASK_RUN_TYPE_IMPLEMENTATION,
)
+ if source == "missing":
+ SignalReportAssignment.objects.for_team(self.team.id).filter(report=report).delete()
+ elif source == "empty":
+ SignalReportAssignment.objects.for_team(self.team.id).filter(report=report).update(pr_url="")
+ else:
+ SignalReportTask.objects.filter(report=report).delete()
+ SignalReportArtefact.objects.filter(report=report, type="task_run").delete()
+
+ TaskRun.objects.create(
+ team=self.team,
+ task=task,
+ state={"ai_stage": "research"},
+ output={"pr_url": "https://github.com/org/repo/pull/99", "pr_merged": True},
+ )
row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
assert row["implementation_pr_url"] == "https://github.com/org/repo/pull/7"
assert row["implementation_pr_state"] == SignalReportAssignment.PrState.UNKNOWN
assert row["work_state"] == "in_review"
+ detail = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/").json()
+ assert detail["implementation_pr_url"] == row["implementation_pr_url"]
+ assert detail["implementation_pr_merged"] is False
with_pr = self.client.get(self._list_url(has_implementation_pr="true"))
assert str(report.id) in {item["id"] for item in with_pr.json()["results"]}
@@ -2888,8 +2906,20 @@ class TestSignalReportPrEndpoints(APIBaseTest):
assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
- def test_pr_checks_success_returns_checks(self):
+ @parameterized.expand([("assignment",), ("legacy",), ("claim",)])
+ def test_pr_checks_success_returns_checks(self, source: str):
report = self._create_report()
+ if source != "assignment":
+ SignalReportAssignment.objects.for_team(self.team.id).filter(report=report).delete()
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ task = Task.objects.create(team=self.team, title="Implementation", description="Fix a bug")
+ TaskRun.objects.create(
+ team=self.team, task=task, output={"pr_url": "https://github.com/PostHog/posthog/pull/7"}
+ )
+ SignalReportTask.objects.create(team=self.team, report=report, task=task, relationship="implementation")
+ if source == "claim":
+ SignalReportAssignment.objects.for_team(self.team.id).create(team=self.team, report=report)
github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()
self.addCleanup(patch.stopall)
checks = [{"name": "unit", "status": "completed", "conclusion": "success", "url": "https://gh/1"}]
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 3e48ef8f30d6..a7ab37f2ce69 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -2994,12 +2994,10 @@ class SignalReportViewSet(
def _resolve_report_pr_reference(self, report: SignalReport) -> tuple[str, int] | None:
"""Resolve a report's implementation PR to ``(owner/repo, pr_number)``, or None if it has none
(or the stored URL isn't a parseable GitHub PR URL)."""
- assignment = getattr(report, "assignment", None)
- if assignment is None or not assignment.pr_url:
+ pr = fetch_implementation_pr_state_for_reports([str(report.id)]).get(str(report.id))
+ if pr is None:
return None
- if assignment.repository and assignment.pr_number:
- return assignment.repository, assignment.pr_number
- parsed = GitHubIntegration.parse_pull_request_url(assignment.pr_url)
+ parsed = GitHubIntegration.parse_pull_request_url(pr.url)
if parsed is None:
return None
return parsed.repository, parsed.number
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 71cd911a1ffd..2040344582d7 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -955,13 +955,13 @@ def get_tasks_by_ids(task_ids: Iterable[str | UUID], team_ids: Iterable[int]) ->
return [_task_to_dto(task) for task in Task.objects.filter(id__in=ids, team_id__in=teams)]
-def get_latest_pr_url_by_task(task_ids: Iterable[str | UUID]) -> dict[str, str]:
+def get_latest_pr_url_by_task(task_ids: Iterable[str | UUID], *conditions: Q) -> dict[str, str]:
"""Latest non-empty ``output.pr_url`` per task, for the supplied task ids."""
ids = [str(t) for t in task_ids]
if not ids:
return {}
rows = (
- TaskRun.objects.filter(task_id__in=ids, output__pr_url__isnull=False)
+ TaskRun.objects.filter(*conditions, task_id__in=ids, output__pr_url__isnull=False)
.exclude(output__pr_url="")
.order_by("task_id", "-created_at", "-id")
.annotate(output_pr_url_text=KeyTextTransform("pr_url", "output"))
@@ -1020,7 +1020,7 @@ def latest_task_run_pr_merged_subquery(*conditions: Q, **task_run_filter) -> Sub
)
-def get_merged_pr_task_ids(task_ids: Iterable[str | UUID]) -> set[str]:
+def get_merged_pr_task_ids(task_ids: Iterable[str | UUID], *conditions: Q) -> set[str]:
"""Of the supplied tasks, those whose latest PR-bearing run has a webhook-attested merged PR.
Batched counterpart to ``latest_task_run_pr_merged_subquery``, matching ``get_latest_pr_url_by_task``
@@ -1030,7 +1030,7 @@ def get_merged_pr_task_ids(task_ids: Iterable[str | UUID]) -> set[str]:
if not ids:
return set()
rows = (
- TaskRun.objects.filter(task_id__in=ids, output__pr_url__isnull=False)
+ TaskRun.objects.filter(*conditions, task_id__in=ids, output__pr_url__isnull=False)
.exclude(output__pr_url="")
.order_by("task_id", "-created_at", "-id")
.annotate(output_pr_merged_flag=KeyTextTransform("pr_merged", "output"))
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index 90e8c4e650af..7b30d5cb60f2 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -21,7 +21,8 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.user_integration import UserIntegration
-from products.signals.backend.models import SignalReport, SignalReportAssignment
+from products.signals.backend.implementation_pr import fetch_implementation_pr_state_for_reports
+from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportAssignment, SignalReportTask
from products.tasks.backend.facade.api import find_signal_implementation_run
from products.tasks.backend.models import Task, TaskRun, TaskThreadMessage
from products.tasks.backend.webhooks import (
@@ -1161,6 +1162,49 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
pr_state=SignalReportAssignment.PrState.OPEN,
)
+ def _link_task_pr(self, report: SignalReport, pr_url: str, relationship: str = "implementation") -> TaskRun:
+ task = Task.objects.create(team=report.team, title="Implementation", description="Fix a bug")
+ run = TaskRun.objects.create(team=report.team, task=task, output={"pr_url": pr_url})
+ SignalReportTask.objects.create(team=report.team, report=report, task=task, relationship=relationship)
+ return run
+
+ @parameterized.expand(
+ [
+ ("legacy_merge", True, None, "implementation", SignalReport.Status.RESOLVED),
+ ("legacy_close", False, None, "implementation", SignalReport.Status.SUPPRESSED),
+ ("claim_merge", True, SignalActorKind.AGENT, "implementation", SignalReport.Status.RESOLVED),
+ ("claim_close", False, SignalActorKind.AGENT, "implementation", SignalReport.Status.SUPPRESSED),
+ ("research", True, None, "research", SignalReport.Status.READY),
+ ]
+ )
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_pr_event_falls_back_to_task_links(
+ self, _name, merged, actor_kind, relationship, expected_status, _mock_capture, mock_get_secret
+ ):
+ mock_get_secret.return_value = self.webhook_secret
+ self.assignment.delete()
+ self._link_task_pr(self.report, "https://www.github.com/PostHog/posthog/pull/42/", relationship)
+ if actor_kind:
+ SignalReportAssignment.objects.for_team(self.team.id).create(
+ team=self.team, report=self.report, actor_kind=actor_kind, actor_agent="test-agent"
+ )
+
+ with patch("products.signals.backend.receivers.close_dismissed_report_pr") as close_task:
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self._post_pr_webhook(action="closed", merged=merged)
+
+ self.assertEqual(response.status_code, 200)
+ self.report.refresh_from_db()
+ self.assertEqual(self.report.status, expected_status)
+ close_task.delay.assert_not_called()
+ if relationship == "implementation":
+ assignment = SignalReportAssignment.objects.for_team(self.team.id).get(report=self.report)
+ self.assertEqual(assignment.actor_kind, actor_kind or SignalActorKind.TASK)
+ pr = fetch_implementation_pr_state_for_reports([str(self.report.id)])[str(self.report.id)]
+ self.assertEqual(pr.state, "merged" if merged else "closed")
+ self.assertIs(pr.merged, merged)
+
def _post_pr_webhook(self, action: str, merged: bool, pr_url: str = "https://github.com/posthog/posthog/pull/42"):
payload = {
"action": action,
@@ -1278,6 +1322,9 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
pr_number=self.assignment.pr_number,
pr_state=SignalReportAssignment.PrState.OPEN,
)
+ legacy_report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY)
+ assert self.assignment.pr_url is not None
+ self._link_task_pr(legacy_report, self.assignment.pr_url)
response = self._post_pr_webhook(action="closed", merged=merged)
@@ -1292,11 +1339,15 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
self.assertEqual(second_assignment.pr_state, expected_pr_state)
self.assertIs(self.assignment.pr_merged, merged)
self.assertIs(second_assignment.pr_merged, merged)
+ legacy_report.refresh_from_db()
+ self.assertEqual(legacy_report.status, expected_status)
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_event_does_not_transition_assignment_for_another_pr(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
+ assert self.assignment.pr_url is not None
+ self._link_task_pr(self.report, self.assignment.pr_url)
self.assignment.pr_url = "https://github.com/posthog/posthog/pull/99"
self.assignment.pr_number = 99
self.assignment.save(update_fields=["pr_url", "pr_number", "updated_at"])
@@ -1330,6 +1381,9 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
pr_number=self.assignment.pr_number,
pr_state=SignalReportAssignment.PrState.OPEN,
)
+ legacy_other_report = SignalReport.objects.create(team=other_team, status=SignalReport.Status.READY)
+ assert self.assignment.pr_url is not None
+ self._link_task_pr(legacy_other_report, self.assignment.pr_url)
response = self._post_pr_webhook(action="closed", merged=True)
@@ -1342,6 +1396,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
self.assertEqual(self.assignment.pr_state, SignalReportAssignment.PrState.MERGED)
self.assertEqual(other_report.status, SignalReport.Status.READY)
self.assertEqual(other_assignment.pr_state, SignalReportAssignment.PrState.OPEN)
+ legacy_other_report.refresh_from_db()
+ self.assertEqual(legacy_other_report.status, SignalReport.Status.READY)
@parameterized.expand(
[