: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
"""Resolve implementation PR URLs linked to signal reports."""
import re
from collections.abc import Callable, Sequence
from dataclasses import replace
from datetime import datetime
from typing import TYPE_CHECKING, Any, Literal, TypeVar
from uuid import NAMESPACE_URL, uuid5
from django.contrib.postgres.expressions import ArraySubquery
from django.db.models import F, Lookup, Q, QuerySet
import structlog
from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
from posthog.egress.limiter.policies import Priority
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration
from products.signals.backend.github_actor import github_mention_for_user
from products.signals.backend.models import (
SignalActorKind,
SignalReport,
SignalReportArtefact,
SignalReportAssignment,
SignalReportPullRequest,
SignalReportTask,
)
from products.signals.backend.report_lifecycle import report_status_filter
from products.signals.backend.report_urls import ReportLinkSource, build_report_url
from products.signals.backend.task_run_artefacts import (
NON_PR_BEARING_TASK_RUN_TYPES,
SIGNALS_PRODUCT,
TASK_RUN_TYPE_DISCUSSION,
TASK_RUN_TYPE_IMPLEMENTATION,
)
from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
_LinkModel = TypeVar("_LinkModel", SignalReportArtefact, SignalReportAssignment, SignalReportTask)
if TYPE_CHECKING:
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.models.sql.compiler import SQLCompiler
from posthog.models.user import User
# A report in one of these statuses is finished with its pull request. Anything else still holds
# it open — a status this list doesn't know about keeps the PR, which is the safe direction.
_FINISHED_REPORT_STATUSES = frozenset(
{
SignalReport.Status.RESOLVED,
SignalReport.Status.CLOSED,
SignalReport.Status.SUPPRESSED,
SignalReport.Status.DELETED,
}
)
_PULL_REQUEST_URL_BODY = (
r"[A-Za-z][A-Za-z0-9+.-]*://(www\.)?github\.com/+[^/?#]+/+[^/?#]+/+pull/+[+-]?[ \t\r\n\f\v]*[0-9]+"
)
_PULL_REQUEST_URL_PATTERN = rf"^{_PULL_REQUEST_URL_BODY}([/?#].*)?$"
_PULL_REQUEST_URL_ARRAY_PATTERN = rf'"{_PULL_REQUEST_URL_BODY}([/?#][^"]*)?"'
_PR_BEARING_LEGACY_TASK_RELATIONSHIPS = (TASK_RUN_TYPE_IMPLEMENTATION, TASK_RUN_TYPE_DISCUSSION)
class _EqualsAny(Lookup):
"""`lhs = ANY(rhs)`, the SQL form an `ArraySubquery` needs on the right side."""
def as_sql(self, compiler: SQLCompiler, connection: BaseDatabaseWrapper) -> tuple[str, tuple[Any, ...]]:
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
return f"{lhs} = ANY({rhs})", (*lhs_params, *rhs_params)
def implementation_pr_report_filter(
*, team_id: int, active_only: bool = False, report_ids: Sequence[Any] | None = None
) -> Q:
"""Matches the reports with an implementation PR.
`report_ids` narrows every link subquery to those reports, so a caller that asks about a few
reports does not scan the team's links and PR-bearing task runs. The answer for those reports
is the same either way.
"""
# Every branch is a team-scoped subquery on the report id. A join through `assignment` or
# `pull_request` lets the planner scan every team's rows before it applies the team scope.
def for_reports(queryset: QuerySet[_LinkModel]) -> QuerySet[_LinkModel]:
return queryset if report_ids is None else queryset.filter(report_id__in=report_ids)
assignments = for_reports(
SignalReportAssignment.all_teams.filter(team_id=team_id, pr_url__regex=_PULL_REQUEST_URL_PATTERN)
)
pull_requests = SignalReportPullRequest.objects.for_team(team_id).filter(url__regex=_PULL_REQUEST_URL_PATTERN)
task_conditions = [
pr_bearing_task_run_filter(),
Q(output__pr_url__regex=_PULL_REQUEST_URL_PATTERN) | Q(output__pr_urls__regex=_PULL_REQUEST_URL_ARRAY_PATTERN),
]
if report_ids is not None:
pull_requests = pull_requests.filter(
id__in=SignalReportArtefact.objects.filter(
team_id=team_id, type=SignalReportArtefact.ArtefactType.PULL_REQUEST, report_id__in=report_ids
).values("pull_request_id")
)
task_conditions.append(
Q(task_id__in=for_reports(SignalReportArtefact.objects.filter(team_id=team_id)).values("task_id"))
| Q(task_id__in=for_reports(SignalReportTask.objects.filter(team_id=team_id)).values("task_id"))
| Q(
task_id__in=for_reports(SignalReportAssignment.all_teams.filter(team_id=team_id)).values(
"actor_task_id"
)
)
)
task_ids = tasks_facade.task_ids_with_pr_url_subquery(team_id, *task_conditions)
task_run_artefacts = (
for_reports(
SignalReportArtefact.objects.filter(
team_id=team_id,
type=SignalReportArtefact.ArtefactType.TASK_RUN,
task_id__in=task_ids,
content__regex=rf'"product"\s*:\s*"{SIGNALS_PRODUCT}"',
)
)
.exclude(content__regex=rf'"type"\s*:\s*"({"|".join(sorted(NON_PR_BEARING_TASK_RUN_TYPES))})"')
.values("report_id")
)
legacy_tasks = for_reports(
SignalReportTask.objects.filter(
team_id=team_id,
task_id__in=task_ids,
relationship__in=_PR_BEARING_LEGACY_TASK_RELATIONSHIPS,
)
).values("report_id")
assignment_tasks = for_reports(
SignalReportAssignment.all_teams.filter(
team_id=team_id,
actor_task_id__in=task_ids,
)
).values("report_id")
if active_only:
active_states = [
SignalReportAssignment.PrState.UNKNOWN,
SignalReportAssignment.PrState.DRAFT,
SignalReportAssignment.PrState.OPEN,
]
assignments = assignments.filter(
Q(pr_merged=False) & (Q(pr_state__isnull=True) | Q(pr_state="") | Q(pr_state__in=active_states))
)
pull_requests = pull_requests.filter(state__in=active_states)
# `pull_request_id IN (subquery)` keeps the cross-team merge join. Only the array form makes
# Postgres probe `signals_artefact_pr_report_idx` with this team's PR ids.
pull_request_links = for_reports(
SignalReportArtefact.objects.filter(
_EqualsAny(F("pull_request_id"), ArraySubquery(pull_requests.values("id"))),
team_id=team_id,
type=SignalReportArtefact.ArtefactType.PULL_REQUEST,
)
).values("report_id")
return (
Q(id__in=assignments.values("report_id"))
| Q(id__in=pull_request_links)
| Q(id__in=task_run_artefacts)
| Q(id__in=legacy_tasks)
| Q(id__in=assignment_tasks)
)
@frozen
class ImplementationPr:
"""The implementation PR surfaced for a report and its latest known state."""
url: str
merged: bool
state: str = SignalReportAssignment.PrState.UNKNOWN
review_decision: str | None = None
merged_at: datetime | None = None
task_id: str | None = None
actor_kind: str | None = None
id: str | None = None
claim_id: str | None = None
attached_at: datetime | None = None
attached_by_user: "User | None" = None
agent_name: str | None = None
def fetch_implementation_prs_for_reports(
report_ids: list[str], *, team_id: int, using: str | None = None
) -> dict[str, list[ImplementationPr]]:
"""Pull requests per report. Pass `using="default"` when the answer decides whether work starts
or a report closes, so a replica's lag cannot read a just-attached pull request as absent."""
if not report_ids:
return {}
reports = SignalReport.objects.using(using) if using else SignalReport.objects
artefacts = SignalReportArtefact.objects.using(using) if using else SignalReportArtefact.objects
report_ids = [str(pk) for pk in reports.filter(team_id=team_id, id__in=report_ids).values_list("id", flat=True)]
if not report_ids:
return {}
result: dict[str, list[ImplementationPr]] = {}
seen: set[tuple[str, str]] = set()
links = (
artefacts.filter(
team_id=team_id,
report_id__in=report_ids,
pull_request__isnull=False,
type=SignalReportArtefact.ArtefactType.PULL_REQUEST,
)
.select_related("pull_request", "created_by")
.order_by("created_at", "id")
)
for link in links:
linked_pr = link.pull_request
if linked_pr is None or linked_pr.team_id != link.team_id:
continue
key = (str(link.report_id), str(linked_pr.id))
if key in seen:
continue
seen.add(key)
result.setdefault(str(link.report_id), []).append(
ImplementationPr(
id=str(linked_pr.id),
url=linked_pr.url,
state=linked_pr.state,
review_decision=linked_pr.review_decision,
merged_at=linked_pr.merged_at,
merged=linked_pr.state == "merged",
task_id=str(link.task_id) if link.task_id else None,
actor_kind=link.actor_kind,
claim_id=str(link.claim_id) if link.claim_id else None,
attached_at=link.created_at,
attached_by_user=link.created_by,
agent_name=link.actor_agent,
)
)
assignments = list(
SignalReportAssignment.objects.for_team(team_id).filter(report_id__in=report_ids).select_related("actor_user")
)
runs = SignalReport.associated_task_runs_for_reports(
report_ids=report_ids, team_id=team_id, product=SIGNALS_PRODUCT
)
tasks_by_report = {
report_id: {
str(run.task_id)
for run in report_runs
if run.type not in NON_PR_BEARING_TASK_RUN_TYPES and not run.type.startswith("scout:")
}
for report_id, report_runs in runs.items()
}
for assignment in assignments:
report_id = str(assignment.report_id)
if assignment.pr_url:
result.setdefault(report_id, []).append(
ImplementationPr(
url=assignment.pr_url,
state="merged" if assignment.pr_merged else assignment.pr_state or "unknown",
merged=assignment.pr_merged,
task_id=str(assignment.actor_task_id) if assignment.actor_task_id else None,
actor_kind=assignment.actor_kind,
attached_by_user=assignment.actor_user,
agent_name=assignment.actor_agent,
)
)
if assignment.actor_task_id:
tasks_by_report.setdefault(report_id, set()).add(str(assignment.actor_task_id))
task_prs = tasks_facade.get_pull_requests_for_tasks(
team_id, set().union(*tasks_by_report.values()) if tasks_by_report else set(), pr_bearing_task_run_filter()
)
for report_id, task_ids in tasks_by_report.items():
for task_id in sorted(task_ids):
for task_pr in task_prs.get(task_id, []):
state = task_pr.state if task_pr.state in SignalReportPullRequest.State.values else "unknown"
result.setdefault(report_id, []).append(
ImplementationPr(
url=task_pr.url,
state=state,
merged=state == "merged",
task_id=task_id,
actor_kind=SignalActorKind.TASK,
)
)
combined: dict[str, list[ImplementationPr]] = {}
for report_id, prs in result.items():
identities: set[tuple[str, int]] = set()
for pr in prs:
parsed = GitHubIntegrationBase.parse_pull_request_url(pr.url)
if parsed is None:
continue
identity = (parsed.repository.lower(), parsed.number)
if identity in identities:
continue
identities.add(identity)
if pr.id is None:
pr = replace(pr, id=str(uuid5(NAMESPACE_URL, f"signals:{team_id}:{identity[0]}:{identity[1]}")))
combined.setdefault(report_id, []).append(pr)
return combined
def pull_request_matches_id(pr: ImplementationPr, requested_id: str, team_id: int) -> bool:
if pr.id == requested_id:
return True
parsed = GitHubIntegrationBase.parse_pull_request_url(pr.url)
return parsed is not None and requested_id == str(
uuid5(NAMESPACE_URL, f"signals:{team_id}:{parsed.repository.lower()}:{parsed.number}")
)
def primary_pull_request(prs: list[ImplementationPr]) -> ImplementationPr:
return min(prs, key=lambda pr: ({"merged": 1, "closed": 2}.get(pr.state, 0), pr.url.lower()))
def fetch_implementation_pr_state_for_reports(report_ids: list[str], *, team_id: int) -> dict[str, ImplementationPr]:
# Older clients show one PR. Prefer unfinished work so one merged stack layer cannot hide it.
return {
report_id: primary_pull_request(prs)
for report_id, prs in fetch_implementation_prs_for_reports(report_ids, team_id=team_id).items()
}
def pr_bearing_task_run_filter() -> Q:
return Q(state__ai_stage__isnull=True) | (
~Q(state__ai_stage__in=sorted(NON_PR_BEARING_TASK_RUN_TYPES)) & ~Q(state__ai_stage__startswith="scout:")
)
def fetch_implementation_pr_urls_for_reports(report_ids: list[str], *, team_id: int) -> dict[str, str]:
return {
report_id: pr.url
for report_id, pr in fetch_implementation_pr_state_for_reports(report_ids, team_id=team_id).items()
}
def report_ids_for_implementation_pr(*, team_id: int, repository: str, pr_number: int) -> list[str]:
# The webhook reaches every team on the installation. A team without reports must not pay for
# the regex scan over its task runs below.
if not SignalReport.objects.filter(team_id=team_id).exists():
return []
# Narrow by task output before resolving reports so webhooks do not scan the whole inbox.
owner, repo = repository.split("/", 1)
url_body = rf'[^:"]+://(www\.)?github\.com/+{re.escape(owner)}/+{re.escape(repo)}/+pull/+0*{pr_number}'
url_pattern = rf"^{url_body}([/?#]|$)"
array_url_pattern = rf'"{url_body}([/?#"]|$)'
task_ids = list(
tasks_facade.task_ids_with_pr_url_subquery(
team_id,
pr_bearing_task_run_filter(),
Q(output__pr_url__iregex=url_pattern) | Q(output__pr_urls__iregex=array_url_pattern),
).values_list("task_id", flat=True)
)
# One `OR` over joins to every link table defeats the indexes, so each path is its own lookup.
candidate_querysets = [
# The array form, as in `implementation_pr_report_filter`, so Postgres probes the artefact index.
SignalReportArtefact.objects.filter(
_EqualsAny(
F("pull_request_id"),
ArraySubquery(
SignalReportPullRequest.objects.for_team(team_id)
.filter(repository__iexact=repository, number=pr_number)
.values("id")
),
),
team_id=team_id,
).values("report_id"),
SignalReportAssignment.all_teams.filter(
team_id=team_id, repository__iexact=repository, pr_number=pr_number
).values("report_id"),
]
if task_ids:
candidate_querysets.extend(SignalReport.report_ids_for_task_ids(task_ids, team_id=team_id))
candidate_ids = {str(row["report_id"]) for queryset in candidate_querysets for row in queryset}
prs = fetch_implementation_prs_for_reports(sorted(candidate_ids), team_id=team_id)
return [
report_id
for report_id, report_prs in prs.items()
if any(
(parsed := GitHubIntegrationBase.parse_pull_request_url(pr.url)) is not None
and parsed.repository.lower() == repository.lower()
and parsed.number == pr_number
for pr in report_prs
)
]
def implementation_pr_needed_by_another_report(*, team_id: int, report_id: str, pr_url: str) -> bool:
"""Whether an unfinished report other than ``report_id`` still links this pull request.
One pull request can back several reports. Closing it for one dismissal would close the 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. No retry can change the answer while the other report runs, so
a caller that reports per-PR outcomes records this as a skip rather than a failure.
"""
parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
if parsed is None:
return False
return (
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(id=report_id)
.exclude(report_status_filter(_FINISHED_REPORT_STATUSES, team_id=team_id))
.exists()
)
PrCloseReason = Literal["suppressed", "snoozed", "resolved", "superseded"]
_SUPERSEDED_COMMENT = (
"Closing this PR because later research changed the fix. "
"PostHog completed the replacement implementation: {replacement}.\n\n"
"The replacement explains what changed. If this PR should remain open, reopen it and review "
"the linked report before changing the replacement PRs."
)
_SUPERSEDED_COMMENT_NO_URL = (
"🔕 Closing this PR because more research changed what the fix should be. "
"The report it came from is still open, and a new PR replaces this one.\n\n"
"If this PR was still the right fix, reopen it."
)
def _pr_close_comment(
reason: PrCloseReason, *, report_link: str, actor_mention: str | None, replacement_pr_url: str | None = None
) -> str:
"""What the PR says about its own close.
Left on the PR before it closes, so anyone reading the PR sees why it closed, who decided it,
and how to undo it. The close itself goes out under the team's GitHub App, so this comment is
the only place the person behind it can appear.
"""
if reason == "superseded":
return (
_SUPERSEDED_COMMENT.format(replacement=replacement_pr_url)
if replacement_pr_url
else _SUPERSEDED_COMMENT_NO_URL
)
if reason == "resolved":
opening = (
f"🔕 Closing this PR because {actor_mention} resolved the {report_link} without it."
if actor_mention
else f"🔕 Closing this PR because the {report_link} was resolved without it."
)
return f"{opening}\n\nIf that wasn't intended, reopen this PR."
opening = (
f"🔕 Closing this PR because {actor_mention} {reason} the {report_link}."
if actor_mention
else f"🔕 Closing this PR because the {report_link} was {reason}."
)
return f"{opening}\n\nIf that wasn't intended, restore the report in PostHog and reopen this PR."
def _close_implementation_pr(
team_id: int,
report_id: str,
*,
reason: PrCloseReason = "suppressed",
pr: ImplementationPr,
actor_user_id: int | None = None,
replacement_pr_url: str | None = None,
expected_head_sha: str | None = None,
comment_marker: str | None = None,
before_close: Callable[[], bool] | None = None,
priority: Priority = Priority.CRITICAL,
) -> bool | None:
"""Best-effort: comment on and close the GitHub PR attached to this report.
Called when a report is suppressed, snoozed, or resolved without its PR — the open PR shouldn't linger. Only acts on a PR
that is still open: an already-closed or merged PR is left untouched (no comment, no close), so
we never leave a confusing "closing this PR" note on a PR that shipped months ago. Leaves an
explanatory comment, then closes the PR. Returns True when closed, None when no close is
needed, and False on failure. Batch rate limits propagate so scheduled delivery can back off.
"""
try:
if not SignalReport.objects.filter(id=report_id, team_id=team_id).exists():
return False
if pr.actor_kind not in {SignalActorKind.TASK, SignalActorKind.SYSTEM}:
logger.info(
"close_implementation_pr_untrusted_actor",
report_id=str(report_id),
actor_kind=pr.actor_kind,
)
return None
pr_url = pr.url
parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
if parsed is None:
logger.warning("close_implementation_pr_unparseable_url", report_id=str(report_id), pr_url=pr_url)
return False
from products.signals.backend.report_assignments import update_assignments_for_pull_request
if implementation_pr_needed_by_another_report(team_id=team_id, report_id=report_id, pr_url=pr_url):
logger.info(
"close_implementation_pr_still_used_by_another_report",
report_id=str(report_id),
pr_url=pr_url,
)
return None
github = GitHubIntegration.first_for_team_repository(
team_id, parsed.repository, source="signals_implementation_pr", priority=priority
)
if github is None:
logger.info(
"close_implementation_pr_no_integration", report_id=str(report_id), repository=parsed.repository
)
return False
# Only comment on and close a PR that's still open. A merged PR reports state "closed" with
# merged=True, and an already-closed PR reports state "closed" — in either case there's
# nothing to close, and leaving a comment would just be noise. If the state can't be
# confirmed, skip rather than risk commenting on a PR that already shipped.
pr_status = github.get_pull_request(parsed.repository, parsed.number)
if not pr_status.get("success"):
logger.warning(
"close_implementation_pr_status_fetch_failed",
report_id=str(report_id),
pr_url=pr_url,
error=pr_status.get("error"),
status_code=pr_status.get("status_code"),
)
return False
if pr_status.get("merged") or pr_status.get("state") == "closed":
update_assignments_for_pull_request(
team_ids=[team_id],
repository=parsed.repository,
pr_number=parsed.number,
pr_state="merged" if pr_status.get("merged") else "closed",
)
if pr_status.get("state") != "open" or pr_status.get("merged"):
logger.info(
"close_implementation_pr_not_open",
report_id=str(report_id),
pr_url=pr_url,
state=pr_status.get("state"),
merged=pr_status.get("merged"),
)
return None if pr_status.get("state") == "closed" or pr_status.get("merged") else False
if expected_head_sha is not None and pr_status.get("head_sha") != expected_head_sha:
return False
comment = _pr_close_comment(
reason,
report_link=f"[linked PostHog report]({build_report_url(team_id, report_id, ReportLinkSource.GITHUB_PR)})",
actor_mention=github_mention_for_user(actor_user_id),
replacement_pr_url=replacement_pr_url,
)
already_commented = False
if comment_marker:
found = github.has_pull_request_comment(parsed.repository, parsed.number, comment_marker)
if found is None:
return False
already_commented = found
comment += f"\n\n{comment_marker}"
if not already_commented:
comment_outcome = github.comment_on_pull_request(parsed.repository, parsed.number, comment)
if not comment_outcome.get("success"):
logger.warning(
"close_implementation_pr_comment_failed",
report_id=str(report_id),
pr_url=pr_url,
error=comment_outcome.get("error"),
status_code=comment_outcome.get("status_code"),
)
if comment_marker:
return False
if before_close is not None and not before_close():
return False
outcome = github.close_pull_request(parsed.repository, parsed.number)
if not outcome.get("success"):
logger.warning(
"close_implementation_pr_failed",
report_id=str(report_id),
pr_url=pr_url,
error=outcome.get("error"),
status_code=outcome.get("status_code"),
)
return False
# Closing a merged pull request is a no-op that still reports success, so a merge that landed
# during the round trip must keep its state. A merge is terminal: no later webhook would
# correct a downgrade here.
update_assignments_for_pull_request(
team_ids=[team_id],
repository=parsed.repository,
pr_number=parsed.number,
pr_state="closed",
)
return True
except (GitHubEgressBudgetExhausted, GitHubRateLimitError):
if priority == Priority.BATCH:
raise
return False
except Exception:
logger.exception("close_implementation_pr_unexpected_error", report_id=str(report_id))
return False
def close_implementation_pr_for_report(
team_id: int,
report_id: str,
*,
reason: PrCloseReason = "suppressed",
actor_user_id: int | None = None,
pr_url: str | None = None,
replacement_pr_url: str | None = None,
comment_marker: str | None = None,
before_close: Callable[[], bool] | None = None,
priority: Priority = Priority.CRITICAL,
require_all: bool = False,
) -> bool:
try:
if not SignalReport.objects.filter(team_id=team_id, id=report_id).exists():
return False
closed = False
failed = False
for pr in fetch_implementation_prs_for_reports([str(report_id)], team_id=team_id).get(str(report_id), []):
if pr_url is not None and pr.url != pr_url:
continue
outcome = _close_implementation_pr(
team_id,
report_id,
reason=reason,
pr=pr,
actor_user_id=actor_user_id,
replacement_pr_url=replacement_pr_url,
comment_marker=comment_marker,
before_close=before_close,
priority=priority,
)
closed = outcome is True or closed
failed = outcome is False or failed
return not failed if require_all else closed
except (GitHubEgressBudgetExhausted, GitHubRateLimitError):
if priority == Priority.BATCH:
raise
return False
except Exception:
logger.exception("close_implementation_pr_lookup_failed", report_id=str(report_id))
return False