: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(engineering-analytics): scope PR-list CI rollups to visible PRs (#90973)
Paul D'Ambraa680e2da3c41
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex d1f8aab8fdc2..1b606b74db63 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -311,12 +311,25 @@ class CuratedGitHubSource:"""return f"runs AS {self.run_source()}"+ def _pr_scope_cte(self, pr_scope_where: str) -> str:+ """CTE: the number and head SHA of PRs matching ``pr_scope_where`` (a predicate over+ unqualified curated PR columns), read once and shared by both runs rollups below —+ the same one-scan-per-query reasoning as ``runs_cte``, applied to the PR source.++ The runs rollups only ever join back to PRs the consuming query keeps, so they+ prefilter the runs scan to this set. Unscoped, they aggregate the team's whole+ run history — millions of ``(head_sha, workflow)`` groups on a busy repo — and+ the query runs out of memory before the join discards almost all of it.+ """+ return f"pr_scope AS (SELECT number, head_sha FROM {self.pr_source()} AS scope_pr WHERE {pr_scope_where})"+def ci_rollup_cte(self) -> str:"""CTE collapsing each head SHA's workflow runs into pass/fail/pending counts.Takes the latest run per ``(head_sha, workflow_name)`` via ``argMax`` (a PR's CI statusis its newest run per workflow), then aggregates per SHA. Reads the shared ``runs`` CTE- (see ``runs_cte``); ``head_sha`` is the only link between a PR and its CI.+ (see ``runs_cte``); ``head_sha`` is the only link between a PR and its CI. Scoped to the+ ``pr_scope`` CTE the composing query adds (see ``_pr_scope_cte``)."""return f"""ci_rollup AS (@@ -338,23 +351,30 @@ class CuratedGitHubSource:argMax(status, run_started_at) AS s,argMax(conclusion, run_started_at) AS cFROM runs AS r+ WHERE head_sha IN (SELECT head_sha FROM pr_scope)GROUP BY head_sha, workflow_name)GROUP BY head_sha)"""- def pr_rollup_query(self, select: str) -> str:+ def pr_rollup_query(self, select: str, *, pr_scope_where: str) -> str:"""Compose a pull-requests query that reads ``FROM __PR_SOURCE__ AS pr LEFT JOIN ci_rollup``.- Prefixes ``select`` with the CI rollup CTE and fills its ``__PR_SOURCE__`` placeholder- with the curated pull-requests source — the two steps the cards and PR-list queries always- do together.+ Prefixes ``select`` with the ``pr_scope`` and CI rollup CTEs and fills its+ ``__PR_SOURCE__`` placeholder with the curated pull-requests source — the steps the+ cards and PR-list queries always do together. ``pr_scope_where`` must keep every PR the+ ``select`` reads CI for (it prunes the rollup scan, see ``_pr_scope_cte``); a PR outside+ it joins as if it had no runs."""- return self._compose_pr_query([self.runs_cte(), self.ci_rollup_cte()], select)+ return self._compose_pr_query(+ [self.runs_cte(), self._pr_scope_cte(pr_scope_where), self.ci_rollup_cte()], select+ )def runs_by_pr_cte(self) -> str:- """CTE: per-PR activity from the workflow runs attributed to each PR.+ """CTE: per-PR activity from the workflow runs attributed to each PR. Scoped to the+ ``pr_scope`` CTE the composing query adds (see ``_pr_scope_cte``); the scope is a+ prefilter — the repo-qualified join below still decides correctness.A run records the PR(s) it ran for in ``pull_requests``; the curated run source surfacesthe first as ``pr_number``. ``pushes`` counts the distinct head SHAs that triggered CI@@ -384,14 +404,21 @@ class CuratedGitHubSource:countIf(run_attempt > 1) AS rerun_cyclesFROM runs AS rWHERE pr_number > 0 AND NOT is_merge_queue+ AND pr_number IN (SELECT number FROM pr_scope)GROUP BY repo_owner, repo_name, pr_number)"""- def pr_list_rollup_query(self, select: str) -> str:+ def pr_list_rollup_query(self, select: str, *, pr_scope_where: str) -> str:"""``pr_rollup_query`` plus the per-PR runs rollup and, when it is observable, the- ``ready_by_pr`` rollup ``ready_to_merge_sql`` reads."""- ctes = [self.runs_cte(), self.ci_rollup_cte(), self.runs_by_pr_cte()]+ ``ready_by_pr`` rollup ``ready_to_merge_sql`` reads. ``pr_scope_where`` scopes both+ runs rollups via the shared ``pr_scope`` CTE (see ``pr_rollup_query``)."""+ ctes = [+ self.runs_cte(),+ self._pr_scope_cte(pr_scope_where),+ self.ci_rollup_cte(),+ self.runs_by_pr_cte(),+ ]ready_cte = self.ready_to_merge_sql().cteif ready_cte:ctes.append(ready_cte)diff --git a/products/engineering_analytics/backend/logic/queries/ci_cards.py b/products/engineering_analytics/backend/logic/queries/ci_cards.pyindex 63569eaa5435..ebcbf52d6290 100644--- a/products/engineering_analytics/backend/logic/queries/ci_cards.py+++ b/products/engineering_analytics/backend/logic/queries/ci_cards.py@@ -10,21 +10,29 @@ from products.engineering_analytics.backend.logic.queries._curated import Curate_EMPTY = CICardSummary(open_prs=0, repos=0, stuck=0, failing_ci=0)-_SELECT = """+# Every _SELECT metric below is gated on this, and it also scopes the rollup CTEs to the+# same PRs (see query_ci_cards) — one definition so the two can never drift apart.+_OPEN = "state = 'open'"++_SELECT = f"""SELECT- countIf(pr.state = 'open') AS open_prs,- count(DISTINCT if(pr.state = 'open', concat(pr.repo_owner, '/', pr.repo_name), NULL)) AS repos,+ countIf(pr.{_OPEN}) AS open_prs,+ count(DISTINCT if(pr.{_OPEN}, concat(pr.repo_owner, '/', pr.repo_name), NULL)) AS repos,countIf(- pr.state = 'open' AND NOT pr.is_draft AND NOT pr.is_bot AND pr.created_at < now() - INTERVAL 7 DAY+ pr.{_OPEN} AND NOT pr.is_draft AND NOT pr.is_bot AND pr.created_at < now() - INTERVAL 7 DAY) AS stuck,- countIf(pr.state = 'open' AND coalesce(ci.failing, 0) > 0) AS failing_ci+ countIf(pr.{_OPEN} AND coalesce(ci.failing, 0) > 0) AS failing_ciFROM __PR_SOURCE__ AS prLEFT JOIN ci_rollup AS ci ON ci.head_sha = pr.head_sha"""def query_ci_cards(*, curated: CuratedGitHubSource) -> CICardSummary:- response = curated.run(curated.pr_rollup_query(_SELECT), query_type="engineering_analytics.ci_cards")+ # Every count only reads CI for open PRs, so the rollup scan is scoped to their head SHAs.+ response = curated.run(+ curated.pr_rollup_query(_SELECT, pr_scope_where=_OPEN),+ query_type="engineering_analytics.ci_cards",+ )if not response.results:return _EMPTYopen_prs, repos, stuck, failing_ci = response.results[0]diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.pyindex 6e9720ed84a2..1403257d983c 100644--- a/products/engineering_analytics/backend/logic/queries/pull_request_list.py+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py@@ -28,6 +28,19 @@ _LIMIT = 1000# Sparkline cap: enough to read a PR's CI history at a glance without bloating a 1000-row page._PUSH_HISTORY_LIMIT = 20++def _visible_prs_where(prefix: str, author: str | None) -> str:+ """The list's row predicate, buildable against the ``pr`` alias (outer WHERE) or+ unqualified curated PR columns (the runs-rollup scope) — one definition so the+ rollup scope can never drift narrower than the rows it must serve."""+ author_clause = f"AND {prefix}author_handle = {{author}}" if author else ""+ return f"""(+ {prefix}state = 'open'+ OR {prefix}merged_at >= {{date_from}}+ OR {prefix}closed_at >= {{date_from}}+ ) {author_clause}"""++_SELECT = f"""SELECTpr.number, pr.title, pr.repo_owner, pr.repo_name,@@ -48,11 +61,7 @@ _SELECT = f"""LEFT JOIN runs_by_pr AS rpON rp.repo_owner = pr.repo_owner AND rp.repo_name = pr.repo_name AND rp.pr_number = pr.number__READY_JOIN__- WHERE (- pr.state = 'open'- OR pr.merged_at >= {{date_from}}- OR pr.closed_at >= {{date_from}}- ) __AUTHOR__+ WHERE __VISIBLE_PRS__ORDER BY pr.created_at DESCLIMIT {_LIMIT + 1}"""@@ -133,18 +142,17 @@ def query_pull_request_list(*, curated: CuratedGitHubSource, date_from: datetime, author: str | None = None) -> PullRequestList:placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}- author_clause = ""if author:- author_clause = "AND pr.author_handle = {author}"placeholders["author"] = ast.Constant(value=author)+ready = curated.ready_to_merge_sql()select = (_SELECT.replace("__READY_TO_MERGE__", f"{ready.expr} AS ready_to_merge_seconds").replace("__READY_JOIN__", ready.join)- .replace("__AUTHOR__", author_clause)+ .replace("__VISIBLE_PRS__", _visible_prs_where("pr.", author)))response = curated.run(- curated.pr_list_rollup_query(select),+ curated.pr_list_rollup_query(select, pr_scope_where=_visible_prs_where("", author)),query_type="engineering_analytics.pull_request_list",placeholders=placeholders,)