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(engineering-analytics): ignore fork PRs in run attribution (#73969)

Raúl Negrón-Otero9499f1ca31f5
diff --git a/products/engineering_analytics/AGENTS.md b/products/engineering_analytics/AGENTS.md
index 381f78e014cd..f0e3f0be6198 100644
--- a/products/engineering_analytics/AGENTS.md
+++ b/products/engineering_analytics/AGENTS.md
@@ -10,3 +10,7 @@ The decision most often re-derived wrong: **CI ↔ PR linkage is by PR number (t
A head-SHA join silently drops every push but the latest, because the `github_pull_requests` snapshot keeps only the current head.
See SPEC §6 (Locked decisions).
head SHA is a per-commit precision key only; `head_branch` is the capture-time / fork fallback.
+
+The one sanctioned exception, so you don't "fix" it back: `commit_pr_number` joins a default-branch run's `head_sha` to a **merged** PR's `merge_commit_sha`.
+That is a different key from the banned one: terminal and immutable after merge, one commit per PR, so it drops nothing.
+It stays correct only while gated on `merged_at` (open PRs carry a throwaway test-merge SHA) and deduped to one row per SHA (a raw join fans a run row out and multiplies downstream counts).
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index df866f45627f..45e8cf762459 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -108,7 +108,7 @@ They are non-materialized: the rendered SQL is persisted per team and re-synced
- The per-job-attempt history with commit attribution, for green/red boundary analysis ("master went red at SHA X, authored by Y, via PR Z").
- Column order is the locked contract (it fixes the UNION ALL order and the saved-query schema): append, never reorder.
-- Two PR keys, by design (§6): `pr_number` is the run's `pull_requests` association (0 when absent: master pushes, fork PRs); `commit_pr_number` is parsed from the head commit's squash-merge suffix, which is how a master push gets PR attribution at all.
+- Two PR keys, by design (§6): `pr_number` is the run's `pull_requests` association (0 when absent: master pushes, fork PRs); `commit_pr_number` resolves the merged PR that produced the head commit, which is how a master push gets PR attribution at all.
- Commit attribution joins the raw runs table on `run_id` alone, never `run_attempt`: the runs snapshot upserts by id so only the newest attempt's row exists, and attribution is attempt-invariant (a re-run is the same commit).
#### `engineering_analytics_ci_failures`
@@ -126,6 +126,9 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- `head_branch` is the capture-time / pre-PR / fork fallback (fork runs have an empty association). Branches are reused, so branch-keyed reads must be time-bounded.
- `head_sha` is per-commit precision only, and always the webhook head SHA, never the ephemeral `refs/pull/N/merge` SHA.
- Attribution is a possibly-empty, possibly-multi set (a run ↔ PR is 0..N); the read layer credits a run to the first PR in its association.
+ - **Only association entries whose `base.repo.id` is the run's own `repository.id` count.** GitHub lists every PR in the fork network sharing the run's head SHA, so a default-branch push arrives carrying downstream forks' "sync from upstream" PRs; reading the first entry unfiltered attributed those runs to a stranger's PR number under our own owner/name.
+ - `commit_pr_number` is the complementary key and the only PR attribution a default-branch push has. It resolves through the merged PR's `merge_commit_sha` (the commit GitHub records at merge _is_ the run's `head_sha`), and falls back to the head commit's `(#NNNN)` squash-merge suffix when the PR snapshot can't serve it: a repo with no `pull_requests` endpoint synced, or a PR row not landed yet. Consumers read `pr_number` first and fall back to `commit_pr_number`; both are defined once in the `workflow_runs` builder.
+ - **The `merge_commit_sha` lookup is not the head-SHA join banned above.** That ban is about resolving a run through a PR's _current head_, which the snapshot overwrites on every push. `merge_commit_sha` on a **merged** PR is terminal: written once at merge, one commit per PR, so it drops nothing. It must be gated on `merged_at`, because GitHub also fills it on an open PR with the throwaway commit from a test merge. The index is deduped to one row per SHA, because a raw join on a non-unique key fans one run row into several and multiplies every downstream count.
- **Warehouse columns are strings + Nullable JSON; the builders parse and `ifNull`-guard.** Timestamps parse via `parseDateTimeBestEffort`; Nullable columns unwrap before any array function (ClickHouse rejects an Array inside a Nullable). `source_schema.py` mirrors the real landed types so seed and tests exercise the real path; violating this 500'd every endpoint on real data while idealized fixtures stayed green.
- **The warehouse views are managed data, not code registration.** "No global HogQL views" locks out `Database.create_for` (core importing the product, every team's per-query hot path). A per-team `DataWarehouseSavedQuery`, synced only for qualifying teams, reopens nothing: it exists so cost and CI history are queryable by insights, subscriptions, and `execute-sql`.
- **CI Signals use immutable evidence.** Flaky checks require job rows from `github_workflow_jobs` showing a failed attempt followed by a successful later attempt for the same `(run_id, job)`. The run snapshot alone cannot prove this transition. Broken-default-branch detection reads GitHub's reported `repository.default_branch` and gates on the rate over runs that reached a verdict (cancelled and skipped runs decide nothing). Duration comparisons require enough successful samples because the percentiles exclude failed and cancelled runs. All three conditions carry a week-stable `source_id`, and the coordinator records each emitted key in `SignalEmissionRecord` so an hourly sweep doesn't re-emit the same standing condition within its week. For broken-default-branch that means one signal per week per workflow, accepting that a distinct second breakage of the same workflow inside one week dedupes into the first rather than minting a signal (and a ledger row) per completed run.
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 951fec98fe10..88a58d01ce08 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -310,6 +310,11 @@ class WorkflowRunDetail:
run_attempt: int
# Attributed pull request number, or 0 when unattributed.
pr_number: int
+ # The PR whose merge produced this run's head commit: the merged PR whose merge commit is this
+ # head SHA, falling back to the commit subject's `(#NNNN)` suffix. None when neither resolves.
+ # This is the only PR attribution a default-branch push has, since its `pull_requests`
+ # association is empty by then, so consumers read `pr_number` first and fall back to this (SPEC §6).
+ commit_pr_number: int | None
@dataclass(frozen=True)
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index f7566840d241..adf512c05305 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -90,7 +90,12 @@ class CuratedGitHubSource:
"""Curated workflow-runs ``SELECT``, parenthesised for use as a subquery. ``started_floor``
adds the raw-string scan floor — callers must register {run_started_floor} (see
run_started_floor_constant)."""
- return f"({workflow_runs.build_query(self._tables.workflow_runs, started_floor=started_floor)})"
+ query = workflow_runs.build_query(
+ self._tables.workflow_runs,
+ pull_requests_table=self._tables.pull_requests,
+ started_floor=started_floor,
+ )
+ return f"({query})"
def jobs_source(self) -> str | None:
"""Curated workflow-jobs ``SELECT`` subquery, or None when the optional jobs table isn't synced."""
diff --git a/products/engineering_analytics/backend/logic/queries/_run_detail.py b/products/engineering_analytics/backend/logic/queries/_run_detail.py
index 28e63ee0355e..c01152d94307 100644
--- a/products/engineering_analytics/backend/logic/queries/_run_detail.py
+++ b/products/engineering_analytics/backend/logic/queries/_run_detail.py
@@ -12,7 +12,7 @@ from products.engineering_analytics.backend.facade.contracts import RepoRef, Wor
# The run columns every run-detail query selects, in order — kept in lockstep with the unpacking below.
RUN_DETAIL_COLUMNS = """
id, workflow_name, head_sha, head_branch, status, conclusion,
- run_started_at, updated_at, duration_seconds, run_attempt, pr_number,
+ run_started_at, updated_at, duration_seconds, run_attempt, pr_number, commit_pr_number,
repo_owner, repo_name
"""
@@ -30,6 +30,7 @@ def to_run_detail(row: tuple[Any, ...]) -> WorkflowRunDetail:
duration_seconds,
run_attempt,
pr_number,
+ commit_pr_number,
repo_owner,
repo_name,
) = row
@@ -48,4 +49,5 @@ def to_run_detail(row: tuple[Any, ...]) -> WorkflowRunDetail:
duration_seconds=int(duration_seconds) if duration_seconds is not None else None,
run_attempt=int(run_attempt) if run_attempt is not None else 1,
pr_number=int(pr_number) if pr_number is not None else 0,
+ commit_pr_number=int(commit_pr_number) if commit_pr_number is not None else None,
)
diff --git a/products/engineering_analytics/backend/logic/queries/pr_runs.py b/products/engineering_analytics/backend/logic/queries/pr_runs.py
index 35f0d11d735c..35b7ef78caff 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_runs.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_runs.py
@@ -4,10 +4,12 @@ Unlike ``pr_lifecycle`` (which scopes to the PR's current head SHA), this return
to the PR — so the detail page can show CI across all of the PR's pushes, grouped by commit. Newest run
first. Run-level only.
-Attribution is the curated ``pr_number``, i.e. the FIRST PR in a run's ``pull_requests`` association
-(see ``views/workflow_runs.py``). A run that lists this PR only in a later slot — uncommon: one head
-commit tied to several open PRs — is credited to its first PR instead and won't appear here. That's the
-same deliberate v1 simplification the rollup uses; it's a friction signal, not billing.
+Attribution is the curated ``pr_number``, i.e. the first entry of a run's ``pull_requests``
+association whose base repo is the run's own (see ``views/workflow_runs.py``; the fork network's
+PRs share the head SHA and are skipped). A run that lists this PR only in a later own-repo slot is
+credited to its first such PR instead and won't appear here. That case is uncommon because it needs
+one head commit tied to several of this repo's open PRs, and it's the same deliberate v1
+simplification the rollup uses; it's a friction signal, not billing.
"""
from posthog.hogql import ast
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index 477645395c5d..dc3a28132aa9 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -147,24 +147,42 @@ def resolve_github_tables(
raise GitHubSourceNotConnectedError()
-def resolve_job_cost_source_pairs(team: Team) -> list[tuple[str, str]]:
- """``(jobs_table, runs_table)`` for every synced repo with BOTH the jobs and runs endpoints.
-
- Used to build the exposed per-job cost view, which unions across all of a team's qualifying
- repos. Unlike ``resolve_github_tables`` (which needs pull_requests + workflow_runs and returns
- one repo), this needs workflow_jobs + workflow_runs and returns all of them — the cost view has
- no PR dependency and shouldn't collapse a team's repos to one. A multi-repo source contributes
- one pair per repo, so the view stays complete when one source syncs several repos. Userless
- (the view sync runs in a system/Temporal context); team scoping is the boundary.
+@dataclass(frozen=True)
+class JobSourceTables:
+ """One qualifying repo's job-level warehouse tables, for the exposed per-job views."""
+
+ workflow_jobs: str
+ workflow_runs: str
+ # Optional: these views qualify on jobs + runs alone, so a repo can reach them with no PR
+ # snapshot. Consumers that enrich from it (default-branch PR attribution) degrade without it.
+ pull_requests: str | None = None
+
+
+def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:
+ """Job-level tables for every synced repo with BOTH the jobs and runs endpoints.
+
+ Used to build the exposed per-job views (cost, CI job history, CI failures), which union across
+ all of a team's qualifying repos. Unlike ``resolve_github_tables`` (which needs pull_requests +
+ workflow_runs and returns one repo), this needs workflow_jobs + workflow_runs and returns all of
+ them, because those views shouldn't collapse a team's repos to one over a PR dependency they
+ only partly have. A multi-repo source contributes one entry per repo, so the views stay complete when
+ one source syncs several repos. Userless (the view sync runs in a system/Temporal context);
+ team scoping is the boundary.
"""
- pairs: list[tuple[str, str]] = []
+ resolved: list[JobSourceTables] = []
for source in _github_sources(team):
for tables in _synced_tables_by_repo(team=team, source=source).values():
runs = tables.get(WORKFLOW_RUNS_SCHEMA)
jobs = tables.get(WORKFLOW_JOBS_SCHEMA)
if runs and jobs:
- pairs.append((jobs, runs))
- return pairs
+ resolved.append(
+ JobSourceTables(
+ workflow_jobs=jobs,
+ workflow_runs=runs,
+ pull_requests=tables.get(PULL_REQUESTS_SCHEMA),
+ )
+ )
+ return resolved
# Listing the team's connected sources is its own concern (no curated read handle): it threads the
diff --git a/products/engineering_analytics/backend/logic/views/ci_failures.py b/products/engineering_analytics/backend/logic/views/ci_failures.py
index 82a2a8542ea0..9f4c9accd32a 100644
--- a/products/engineering_analytics/backend/logic/views/ci_failures.py
+++ b/products/engineering_analytics/backend/logic/views/ci_failures.py
@@ -29,7 +29,7 @@ from typing import TYPE_CHECKING
from posthog.hogql.database.models import DateTimeDatabaseField, FieldOrTable, IntegerDatabaseField, StringDatabaseField
from products.engineering_analytics.backend.logic.job_logs.constants import CI_LOGS_SERVICE_NAME
-from products.engineering_analytics.backend.logic.sources import resolve_job_cost_source_pairs
+from products.engineering_analytics.backend.logic.sources import resolve_job_source_tables
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -111,9 +111,9 @@ def build_query() -> str:
def build_team_view(team: "Team") -> str | None:
"""The view body, or None when the team has no qualifying GitHub source.
- Gated on the same ``resolve_job_cost_source_pairs`` condition as ``ci_job_history`` so the two
+ Gated on the same ``resolve_job_source_tables`` condition as ``ci_job_history`` so the two
views always appear together — a team without a synced GitHub jobs/runs source gets neither.
"""
- if not resolve_job_cost_source_pairs(team):
+ if not resolve_job_source_tables(team):
return None
return build_query()
diff --git a/products/engineering_analytics/backend/logic/views/ci_job_history.py b/products/engineering_analytics/backend/logic/views/ci_job_history.py
index eae004f14b82..e416dde58db1 100644
--- a/products/engineering_analytics/backend/logic/views/ci_job_history.py
+++ b/products/engineering_analytics/backend/logic/views/ci_job_history.py
@@ -16,17 +16,18 @@ never dropped when its run row is missing. ClickHouse fills the unmatched run si
defaults (empty repo/sha, ``pr_number`` 0), not NULL — HogQL doesn't set ``join_use_nulls`` — so a
missing run reads as empty attribution rather than a real repo.
-Commit attribution comes from the run's ``head_commit`` Nullable-JSON column, which the shared
-``workflow_runs`` builder deliberately does not surface (other embedders — cost, health, PR list —
-don't need it, and the builder stays lean). Rather than widen the shared builder, this module reads
-the commit fields through its own minimal projection over the raw runs table and LEFT JOINs it on
-``run_id`` — the ``head_commit`` JSON is ``ifNull``-unwrapped before ``JSONExtractString``
-because a Nullable column can't feed the extractor.
+The commit's author and message come from the run's ``head_commit`` Nullable-JSON column, which the
+shared ``workflow_runs`` builder deliberately does not surface (only this view needs the strings,
+and every other embedder — cost, health, PR list — pays for the width). Rather than widen the shared
+builder, this module reads those fields through its own minimal projection over the raw runs table
+and LEFT JOINs it on ``run_id`` — the ``head_commit`` JSON is ``ifNull``-unwrapped before
+``JSONExtractString`` because a Nullable column can't feed the extractor.
Two PR keys, by design: ``pr_number`` is the runs builder's association-derived number (0 when the
-run has no ``pull_requests`` association — pushes to master, fork PRs), and ``commit_pr_number`` is
-parsed from the squash-merge message's ``(#NNNN)`` suffix. The latter is how a master push run gets
-PR attribution at all, since its ``pull_requests`` association is empty (SPEC §6).
+run has no own-repo ``pull_requests`` association — pushes to master, fork PRs), and
+``commit_pr_number`` resolves the merged PR that produced the head commit. The latter is how a
+master push run gets PR attribution at all, since its association is empty (SPEC §6). Both come
+straight off the runs builder, which defines each key once for every consumer.
``created_at_raw`` is the unparsed jobs ``created_at`` string riding alongside the parsed
``created_at``. Consumers windowing this view pair their precise ``created_at`` bound with a coarse
@@ -43,7 +44,7 @@ from typing import TYPE_CHECKING
from posthog.hogql.database.models import DateTimeDatabaseField, FieldOrTable, IntegerDatabaseField, StringDatabaseField
-from products.engineering_analytics.backend.logic.sources import resolve_job_cost_source_pairs
+from products.engineering_analytics.backend.logic.sources import resolve_job_source_tables
from products.engineering_analytics.backend.logic.views import workflow_jobs, workflow_runs
if TYPE_CHECKING:
@@ -102,71 +103,46 @@ def _head_commit_query(runs_table: str) -> str:
"""
-def build_query(*, jobs_table: str, runs_table: str) -> str:
+def build_query(*, jobs_table: str, runs_table: str, pull_requests_table: str | None = None) -> str:
"""The per-job-attempt history SELECT for one GitHub source: curated jobs LEFT JOIN curated runs,
plus the run's commit attribution.
- Two layers so ``commit_pr_number`` can be derived from ``commit_message``: the inner join layer
- projects the raw columns (including ``commit_message`` from the head-commit projection), and the
- outer layer extracts the squash-merge PR number off that projected column — a same-SELECT alias
- can't feed another expression, so the extraction lives one level up.
+ ``pull_requests_table`` is what lets the runs builder resolve ``commit_pr_number`` through the
+ merged PR's ``merge_commit_sha`` instead of the head commit's message. It is optional because
+ this view qualifies on jobs + runs alone (see ``resolve_job_source_tables``), so a repo can
+ reach it without a PR snapshot; without one, attribution falls back to the message suffix.
"""
jobs = workflow_jobs.build_query(jobs_table)
- runs = workflow_runs.build_query(runs_table)
+ runs = workflow_runs.build_query(runs_table, pull_requests_table=pull_requests_table)
head_commits = _head_commit_query(runs_table)
return f"""
SELECT
- repo_owner,
- repo_name,
- workflow_name,
- job_name,
- run_id,
- run_attempt,
- head_branch,
- head_sha,
- status,
- conclusion,
- created_at,
- created_at_raw,
- started_at,
- completed_at,
- duration_seconds,
- pr_number,
- commit_author_name,
- commit_author_email,
- commit_message,
- -- Anchored to a line end ((?m) — the squash title): an unanchored match would take the
- -- FIRST (#N) in the message, misattributing reverts ('Revert "x (#A)" (#B)') to the
- -- reverted PR instead of the reverting one.
- accurateCastOrNull(regexpExtract(commit_message, '(?m)[(]#([0-9]+)[)]$'), 'Int64') AS commit_pr_number
- FROM (
- SELECT
- r.repo_owner AS repo_owner,
- r.repo_name AS repo_name,
- j.workflow_name AS workflow_name,
- j.name AS job_name,
- j.run_id AS run_id,
- j.run_attempt AS run_attempt,
- j.head_branch AS head_branch,
- r.head_sha AS head_sha,
- j.status AS status,
- j.conclusion AS conclusion,
- j.created_at AS created_at,
- j.created_at_raw AS created_at_raw,
- j.started_at AS started_at,
- j.completed_at AS completed_at,
- j.duration_seconds AS duration_seconds,
- -- The runs builder emits 0 for a run with no PR association; keep that semantic (a
- -- LEFT-JOIN miss also reads 0 — type default). commit_pr_number is the push-run fallback.
- r.pr_number AS pr_number,
- hc.commit_author_name AS commit_author_name,
- hc.commit_author_email AS commit_author_email,
- hc.commit_message AS commit_message
- FROM ({jobs}) AS j
- LEFT JOIN ({runs}) AS r ON j.run_id = r.id
- LEFT JOIN ({head_commits}) AS hc ON j.run_id = hc.run_id
- )
+ r.repo_owner AS repo_owner,
+ r.repo_name AS repo_name,
+ j.workflow_name AS workflow_name,
+ j.name AS job_name,
+ j.run_id AS run_id,
+ j.run_attempt AS run_attempt,
+ j.head_branch AS head_branch,
+ r.head_sha AS head_sha,
+ j.status AS status,
+ j.conclusion AS conclusion,
+ j.created_at AS created_at,
+ j.created_at_raw AS created_at_raw,
+ j.started_at AS started_at,
+ j.completed_at AS completed_at,
+ j.duration_seconds AS duration_seconds,
+ -- The runs builder emits 0 for a run with no PR association; keep that semantic (a
+ -- LEFT-JOIN miss also reads 0 — type default). commit_pr_number is the push-run fallback.
+ r.pr_number AS pr_number,
+ hc.commit_author_name AS commit_author_name,
+ hc.commit_author_email AS commit_author_email,
+ hc.commit_message AS commit_message,
+ r.commit_pr_number AS commit_pr_number
+ FROM ({jobs}) AS j
+ LEFT JOIN ({runs}) AS r ON j.run_id = r.id
+ LEFT JOIN ({head_commits}) AS hc ON j.run_id = hc.run_id
"""
@@ -174,10 +150,17 @@ def build_team_view(team: "Team") -> str | None:
"""The full view body for a team: every GitHub source with both runs and jobs synced, unioned.
None when the team has no qualifying source (no view is created). Gated on the same
- ``resolve_job_cost_source_pairs`` condition as ``job_costs`` so the exposed views stay coherent.
+ ``resolve_job_source_tables`` condition as ``job_costs`` so the exposed views stay coherent.
"""
- pairs = resolve_job_cost_source_pairs(team)
- if not pairs:
+ sources = resolve_job_source_tables(team)
+ if not sources:
return None
- selects = [build_query(jobs_table=jobs_table, runs_table=runs_table) for jobs_table, runs_table in pairs]
+ selects = [
+ build_query(
+ jobs_table=source.workflow_jobs,
+ runs_table=source.workflow_runs,
+ pull_requests_table=source.pull_requests,
+ )
+ for source in sources
+ ]
return "\nUNION ALL\n".join(selects)
diff --git a/products/engineering_analytics/backend/logic/views/job_costs.py b/products/engineering_analytics/backend/logic/views/job_costs.py
index 47cb361b5c3c..19e13fc855fd 100644
--- a/products/engineering_analytics/backend/logic/views/job_costs.py
+++ b/products/engineering_analytics/backend/logic/views/job_costs.py
@@ -35,7 +35,7 @@ from products.engineering_analytics.backend.logic.cost import (
render_provider,
render_vcpu,
)
-from products.engineering_analytics.backend.logic.sources import resolve_job_cost_source_pairs
+from products.engineering_analytics.backend.logic.sources import resolve_job_source_tables
from products.engineering_analytics.backend.logic.views import workflow_jobs, workflow_runs
if TYPE_CHECKING:
@@ -224,8 +224,8 @@ def build_team_view(team: "Team") -> str | None:
None when the team has no qualifying source (no view is created). One view over all sources so
the exposed name stays stable regardless of how many GitHub sources a team connects.
"""
- pairs = resolve_job_cost_source_pairs(team)
- if not pairs:
+ sources = resolve_job_source_tables(team)
+ if not sources:
return None
- selects = [build_query(jobs_table=jobs_table, runs_table=runs_table) for jobs_table, runs_table in pairs]
+ selects = [build_query(jobs_table=source.workflow_jobs, runs_table=source.workflow_runs) for source in sources]
return "\nUNION ALL\n".join(selects)
diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.py
index 621423b21ca2..346d90863ff2 100644
--- a/products/engineering_analytics/backend/logic/views/source_schema.py
+++ b/products/engineering_analytics/backend/logic/views/source_schema.py
@@ -30,6 +30,10 @@ PULL_REQUESTS_COLUMNS: dict[str, dict[str, str]] = {
"updated_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
"merged_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
"closed_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+ # The commit the merge produced on the base branch: the key that resolves a default-branch push
+ # run back to the PR that landed it. GitHub also populates it on OPEN PRs, where it is a
+ # throwaway test-merge SHA, so every read of it must gate on the PR being merged.
+ "merge_commit_sha": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
"user": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
"head": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
"base": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
diff --git a/products/engineering_analytics/backend/logic/views/workflow_runs.py b/products/engineering_analytics/backend/logic/views/workflow_runs.py
index c7e444e2f162..3a580d3cbce9 100644
--- a/products/engineering_analytics/backend/logic/views/workflow_runs.py
+++ b/products/engineering_analytics/backend/logic/views/workflow_runs.py
@@ -10,13 +10,37 @@ re-runs. The source table name is resolved per-team and passed in (see
``logic.sources``); it is never hardcoded, because a warehouse table's name carries
the user-chosen source prefix.
-``pr_number`` is the FIRST entry of the run's ``pull_requests`` association. Two cases:
-a run with no association (fork PRs, and pushes to a branch with no open PR) extracts
-``0`` (filtered out of the rollup, which only counts ``pr_number > 0``); a run shared
-across more than one PR (uncommon — one head tied to multiple open PRs) is credited to
-its first PR only, not fanned out across all of them. That's a deliberate v1
-simplification: the rollup is an approximate friction signal (pushes / re-runs), not
-billing.
+``pr_number`` is the first entry of the run's ``pull_requests`` association **whose base repo
+is this run's own repo**. That filter is load-bearing, not defensive: GitHub populates the
+association with every PR in the fork network whose head SHA matches the run, so a push to
+``PostHog/posthog:master`` arrives carrying the downstream forks' open "sync from upstream"
+PRs (``Mu-L/posthog-1#1379``, ``em3ndez/posthog#3``, ...). Taking the first entry unfiltered
+credited ~14% of runs to a stranger's PR number, and — since the number was then paired with
+this repo's owner/name — linked it to an unrelated PR of ours. Only an entry whose
+``base.repo.id`` equals the run's ``repository.id`` describes a PR this run actually ran for.
+
+Two cases still extract ``0``: a run with no own-repo association (fork PRs, and pushes to a
+branch with no open PR), which is filtered out of the rollup (it only counts ``pr_number > 0``);
+and a run shared across more than one of our PRs (uncommon — one head tied to multiple open PRs),
+which is credited to its first PR only, not fanned out across all of them. That's a deliberate v1
+simplification: the rollup is an approximate friction signal (pushes / re-runs), not billing.
+
+``commit_pr_number`` is the complementary key: it is how a push run gets PR attribution at all,
+since a merged commit on the default branch has no association of its own. Consumers prefer
+``pr_number`` and fall back to this (SPEC §6, "two PR keys, by design"); ``ci_job_history``
+exposes both under these names.
+
+It resolves in two steps. The authoritative one is a join to the PR snapshot on
+``merge_commit_sha``: the commit GitHub records when a PR merges *is* this run's ``head_sha``, so
+the merged PR that produced the commit is a lookup rather than an inference. The head commit's
+squash-merge ``(#NNNN)`` suffix is the fallback, for the two cases the join cannot serve: a repo
+whose ``pull_requests`` endpoint isn't synced (``pull_requests_table=None``), and a commit whose PR
+row hasn't landed in the snapshot yet. Measured over 30 days of ``PostHog/posthog`` default-branch
+runs, the join agreed with the suffix on all 122,743 runs the suffix resolved and attributed 35
+more that it could not (a merge-commit landing whose subject carries no ``(#NNNN)``).
+
+This is *not* the head-SHA join SPEC §6 locks out; see that entry for why a **merged** PR's
+``merge_commit_sha`` is a terminal key rather than the mutable current head the ban is about.
The real GitHub source lands timestamps as **strings** and ``repository`` /
``pull_requests`` as **Nullable** JSON, so this builder runs in two layers: an inner
@@ -40,14 +64,58 @@ Every query module embeds this ``SELECT`` as a subquery (see ``_curated``);
nothing registers it as a global HogQL view.
"""
+# The run's PR association, narrowed to PRs based in the run's OWN repo (see module docstring).
+# ``> 0`` guards the both-missing case: JSONExtractInt yields 0 for an absent key, so a malformed
+# entry would otherwise "match" a run whose ``repository`` JSON never landed.
+_OWN_REPO_PR = """arrayFirst(
+ p -> JSONExtractInt(p, 'base', 'repo', 'id') > 0
+ AND JSONExtractInt(p, 'base', 'repo', 'id') = ifNull(JSONExtractInt(repository, 'id'), 0),
+ JSONExtractArrayRaw(ifNull(pull_requests, '[]'))
+ )"""
+
+# The squash-merge PR number off the head commit's subject: the fallback when the merge-commit
+# join can't resolve the run (see module docstring). Anchored to a line end ((?m), the squash
+# title): an unanchored match would take the FIRST (#N) in the message, misattributing reverts
+# ('Revert "x (#A)" (#B)') to the reverted PR instead of the reverting one.
+_MESSAGE_PR_NUMBER = (
+ "accurateCastOrNull("
+ "regexpExtract(JSONExtractString(ifNull(head_commit, '{}'), 'message'), '(?m)[(]#([0-9]+)[)]$'), 'Int64')"
+)
+
+
+def _merged_pr_index(pull_requests_table: str) -> str:
+ """Merged PRs keyed by the commit their merge produced: the default-branch attribution lookup.
+
+ Deduped to one row per SHA: a LEFT JOIN on a non-unique key fans one run row out into several,
+ which would silently multiply every count built on this builder. ``min`` breaks the tie
+ deterministically rather than correctly, which is the honest trade. GitHub reuses a merge SHA
+ only for PRs that landed together, and one SHA in all of ``PostHog/posthog`` carries three.
+ """
+ return f"""
+ SELECT
+ merge_commit_sha,
+ min(number) AS merged_pr_number
+ FROM {pull_requests_table}
+ WHERE ifNull(merged_at, '') != '' AND ifNull(merge_commit_sha, '') != ''
+ GROUP BY merge_commit_sha
+ """
+
-def build_query(table_name: str, *, started_floor: bool = False) -> str:
+def build_query(table_name: str, *, pull_requests_table: str | None = None, started_floor: bool = False) -> str:
# The raw floor must live in its OWN innermost SELECT, not the parsing SELECT below: that SELECT
# aliases parseDateTimeBestEffort(run_started_at) AS run_started_at, and ClickHouse alias resolution
# would make a WHERE there compare the parsed DateTime against the string. Keep it on the raw column.
table_source = (
f"(SELECT * FROM {table_name} WHERE run_started_at >= {{run_started_floor}})" if started_floor else table_name
)
+ if pull_requests_table:
+ merge_join = f"LEFT JOIN ({_merged_pr_index(pull_requests_table)}) AS pr ON run.head_sha = pr.merge_commit_sha"
+ # An unmatched LEFT JOIN fills the Int with 0, not NULL (HogQL doesn't set `join_use_nulls`),
+ # so `nullIf` is what lets the message fallback fire on a miss instead of reading PR 0.
+ commit_pr_number = "coalesce(nullIf(pr.merged_pr_number, 0), message_pr_number)"
+ else:
+ merge_join = ""
+ commit_pr_number = "message_pr_number"
return f"""
SELECT
id,
@@ -62,6 +130,7 @@ def build_query(table_name: str, *, started_floor: bool = False) -> str:
run_attempt,
default_branch,
pr_number,
+ {commit_pr_number} AS commit_pr_number,
if(status = 'completed', dateDiff('second', run_started_at, updated_at), NULL) AS duration_seconds,
arrayElement(repo_parts, 1) AS repo_owner,
arrayElement(repo_parts, 2) AS repo_name
@@ -74,12 +143,14 @@ def build_query(table_name: str, *, started_floor: bool = False) -> str:
status,
conclusion,
run_attempt,
- JSONExtractInt(arrayElement(JSONExtractArrayRaw(ifNull(pull_requests, '[]')), 1), 'number') AS pr_number,
+ JSONExtractInt({_OWN_REPO_PR}, 'number') AS pr_number,
+ {_MESSAGE_PR_NUMBER} AS message_pr_number,
splitByChar('/', ifNull(JSONExtractString(repository, 'full_name'), '')) AS repo_parts,
ifNull(JSONExtractString(repository, 'default_branch'), '') AS default_branch,
parseDateTimeBestEffort(run_started_at) AS run_started_at,
parseDateTimeBestEffort(updated_at) AS updated_at,
parseDateTimeBestEffort(created_at) AS created_at
FROM {table_source}
- )
+ ) AS run
+ {merge_join}
"""
diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
index 1efcd8e56ebd..b048552e3603 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -26,6 +26,8 @@ Usage:
import csv
import json
+import zlib
+from collections.abc import Sequence
from datetime import datetime, timedelta
from io import StringIO
from pathlib import Path
@@ -85,7 +87,8 @@ DEFAULT_PREFIX = "eng_analytics_seed"
def _flatten_pr(pr: dict[str, Any]) -> dict[str, Any]:
return {
- **{key: pr[key] for key in PULL_REQUESTS_COLUMNS if key not in ("user", "head", "base", "labels", "draft")},
+ # .get() tolerates a pre-existing fixture captured before merge_commit_sha was kept.
+ **{key: pr.get(key) for key in PULL_REQUESTS_COLUMNS if key not in ("user", "head", "base", "labels", "draft")},
"draft": int(bool(pr["draft"])),
"user": json.dumps(pr["user"]),
"head": json.dumps(pr["head"]),
@@ -94,14 +97,29 @@ def _flatten_pr(pr: dict[str, Any]) -> dict[str, Any]:
}
+def _synthetic_repo_id(full_name: str) -> int:
+ """A stable stand-in for GitHub's numeric repo id, derived from ``owner/name``."""
+ return zlib.crc32(full_name.encode())
+
+
def _flatten_run(run: dict[str, Any]) -> dict[str, Any]:
json_keys = ("repository", "pull_requests", "head_commit")
scalar_keys = [key for key in WORKFLOW_RUNS_COLUMNS if key not in json_keys]
+ # A run is attributed to a PR only when the PR's base repo id equals the run's own — that's what
+ # keeps the fork network's PRs out (see logic/views/workflow_runs). Snapshots captured before
+ # those ids were kept, and the synthetic demo rows below, carry neither, so stamp both ends with
+ # one synthetic id rather than seeding data that attributes nothing.
+ repository = {**run["repository"]}
+ repository.setdefault("id", _synthetic_repo_id(repository["full_name"]))
+ associations = [
+ {**pr, "base": {"repo": {"id": pr.get("base", {}).get("repo", {}).get("id", repository["id"])}}}
+ for pr in run.get("pull_requests") or []
+ ]
return {
# .get() tolerates a pre-existing fixture captured before run_attempt / pull_requests were added.
**{key: run.get(key) for key in scalar_keys},
- "repository": json.dumps(run["repository"]),
- "pull_requests": json.dumps(run.get("pull_requests", [])),
+ "repository": json.dumps(repository),
+ "pull_requests": json.dumps(associations),
"head_commit": json.dumps(run.get("head_commit", {})),
}
@@ -217,9 +235,15 @@ _MASTER_WORKFLOWS = ("Backend CI", "Frontend CI", "Rust CI", "E2E Tests", "Lint"
# Co-windowed with the merge spread: a day with merges but no seeded job cost would chart as $0/merge.
_MASTER_DAYS = _MERGE_SPREAD_DAYS
_MASTER_COMMITS_PER_DAY = 18
+# Each master push carries a downstream fork's open "sync from upstream" PR, because that is what
+# GitHub really sends: the association lists every PR in the fork network sharing the run's head SHA.
+# Seeding it keeps the demo honest about what a master run is never attributable by, which is the
+# association (SPEC §6, "two PR keys").
+_FORK_REPO_ID = 778592526
+_FORK_PR_NUMBER = 1379
-def _demo_master_commits(anchor: datetime) -> list[dict[str, Any]]:
+def _demo_master_commits(anchor: datetime, merged_prs: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
def iso(dt: datetime) -> str:
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -231,6 +255,22 @@ def _demo_master_commits(anchor: datetime) -> list[dict[str, Any]]:
age_minutes = (total - 1 - commit_index) * spacing_minutes + (commit_index * 37) % 90
commit_time = anchor - timedelta(minutes=age_minutes)
sha = f"aa57e2{commit_index:04d}" + "e" * 30
+ # Cite a PR that is really in the seeded snapshot, so following the run's PR link lands on a
+ # PR page instead of dead-ending on "may not exist in the connected GitHub source". Cycling
+ # through the merged set is enough: the demo needs the link to resolve, not a faithful
+ # commit-to-merge history.
+ pr = merged_prs[commit_index % len(merged_prs)] if merged_prs else None
+ subject = f"feat: seeded master commit {commit_index}"
+ if pr is not None:
+ # The first commit to cite a PR owns its merge commit, so that run resolves through the
+ # merge_commit_sha join; later citations reuse the number and exercise the message
+ # fallback. Every tenth join-backed commit drops the (#NNNN) suffix too, seeding the
+ # merge-commit landing that only the join can attribute.
+ joins_via_merge_sha = not pr.get("merge_commit_sha")
+ if joins_via_merge_sha:
+ pr["merge_commit_sha"] = sha
+ if not (joins_via_merge_sha and commit_index % 10 == 3):
+ subject += f" (#{pr['number']})"
red_commit = commit_index % 9 == 4 # an occasional broken master push
cancelled_commit = commit_index % 17 == 9 # a rare all-cancelled push (neutral dot)
for wf_index, workflow in enumerate(_MASTER_WORKFLOWS):
@@ -259,7 +299,11 @@ def _demo_master_commits(anchor: datetime) -> list[dict[str, Any]]:
"updated_at": iso(start) if running else iso(start + duration),
"run_attempt": 1,
"repository": {"full_name": "PostHog/posthog"},
- "pull_requests": [],
+ "pull_requests": [{"number": _FORK_PR_NUMBER, "base": {"repo": {"id": _FORK_REPO_ID}}}],
+ "head_commit": {
+ "message": subject,
+ "author": {"name": "PostHog Bot", "email": "[email protected]"},
+ },
}
)
return demo_runs
@@ -889,7 +933,10 @@ class Command(BaseCommand):
# scheduled/re-triggered runs span days, which pins the scatter's Y axis at 100h+ and crushes
# every real duration to the baseline. PR-branch rows stay untouched.
runs = [run for run in runs if run.get("head_branch") != "master"]
- runs.extend(_demo_master_commits(_fixture_anchor(prs, runs)))
+ # Passed as the PR rows, not just their numbers: seeding master stamps each cited PR's
+ # merge_commit_sha with the commit it landed, which is what the attribution join reads.
+ merged_prs = [pr for pr in prs if pr.get("merged_at")]
+ runs.extend(_demo_master_commits(_fixture_anchor(prs, runs), merged_prs))
# Always normalize timestamps to a ClickHouse-friendly format; rebasing is optional.
shift = timedelta(0) if options["keep_dates"] else self._rebase_delta(prs, runs)
diff --git a/products/engineering_analytics/backend/presentation/serializers/workflows.py b/products/engineering_analytics/backend/presentation/serializers/workflows.py
index b1d2756700fc..c081e11c7e02 100644
--- a/products/engineering_analytics/backend/presentation/serializers/workflows.py
+++ b/products/engineering_analytics/backend/presentation/serializers/workflows.py
@@ -55,7 +55,17 @@ class WorkflowRunDetailSerializer(DataclassSerializer):
"allow_null": True,
},
"run_attempt": {"help_text": "Re-run attempt number; 1 for the first attempt."},
- "pr_number": {"help_text": "Attributed pull request number, or 0 when unattributed."},
+ "pr_number": {
+ "help_text": "Pull request this run ran for, from the run's own-repo PR association; "
+ "0 when unattributed (a default-branch push, or a fork PR)."
+ },
+ "commit_pr_number": {
+ "help_text": "Pull request whose merge produced this run's head commit, resolved through the "
+ "merged pull request's merge commit and falling back to the commit subject's '(#NNNN)' suffix. "
+ "Null when neither resolves. The only PR attribution a default-branch push has: read pr_number "
+ "first and fall back to this.",
+ "allow_null": True,
+ },
}
diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.py
index 8522674c2409..6885ead60969 100644
--- a/products/engineering_analytics/backend/tests/_github_fixtures.py
+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py
@@ -1,5 +1,7 @@
"""GitHub source and warehouse-table fixtures shared across this product's test files."""
+import json
+import zlib
import tempfile
from pathlib import Path
from typing import Any
@@ -82,6 +84,26 @@ def connect_github_source_without_data(
return GitHubTables(pull_requests=pr_table.name, workflow_runs=run_table.name, repository=repository)
+def repo_id(full_name: str) -> int:
+ """A stable synthetic GitHub repo id for a fixture repo — distinct per ``owner/name``."""
+ return zlib.crc32(full_name.encode())
+
+
+def pr_association_entry(number: int, *, base_repo: str = "PostHog/posthog") -> dict[str, Any]:
+ """One entry of a run's ``pull_requests`` association, shaped like the real webhook payload.
+
+ ``base.repo.id`` is what the curated builder matches against the run's own ``repository.id`` to
+ ignore the fork network's PRs. Pass ``base_repo`` to forge an entry based in a *different* repo —
+ that's what a default-branch push really lands, and the builder must skip it.
+ """
+ return {"number": number, "base": {"repo": {"id": repo_id(base_repo)}}}
+
+
+def pr_association(*numbers: int, base_repo: str = "PostHog/posthog") -> str:
+ """A run's ``pull_requests`` association over one base repo, serialized as the column lands it."""
+ return json.dumps([pr_association_entry(number, base_repo=base_repo) for number in numbers])
+
+
def _user(login: str) -> str:
return f'{{"login": "{login}", "avatar_url": "https://avatars/{login}"}}'
@@ -102,6 +124,7 @@ def _pr_row(
created_at: str,
*,
merged_at: str | None = None,
+ merge_commit_sha: str | None = None,
head_sha: str = "",
head_ref: str = "",
base_ref: str = "",
@@ -118,6 +141,7 @@ def _pr_row(
"updated_at": merged_at or created_at,
"merged_at": merged_at,
"closed_at": merged_at,
+ "merge_commit_sha": merge_commit_sha,
"user": _user(login),
"head": f'{{"sha": "{head_sha}", "ref": "{head_ref}"}}',
"base": _base(full_name, base_ref),
@@ -138,6 +162,7 @@ def _run_row(
run_attempt: int = 1,
pr_number: int | None = None,
head_branch: str = "main",
+ commit_message: str | None = None,
) -> dict[str, Any]:
return {
"id": run_id,
@@ -152,8 +177,9 @@ def _run_row(
"run_attempt": run_attempt,
# Mirror the real Nullable(String) column: an unassociated run lands NULL, not "[]",
# so the builder's ifNull(pull_requests, '[]') guard is exercised on the real path.
- "pull_requests": f'[{{"number": {pr_number}}}]' if pr_number is not None else None,
- "repository": f'{{"full_name": "{full_name}"}}',
+ "pull_requests": pr_association(pr_number, base_repo=full_name) if pr_number is not None else None,
+ "repository": json.dumps({"full_name": full_name, "id": repo_id(full_name)}),
+ "head_commit": json.dumps({"message": commit_message}) if commit_message is not None else None,
}
diff --git a/products/engineering_analytics/backend/tests/test_ci_failure_logs.py b/products/engineering_analytics/backend/tests/test_ci_failure_logs.py
index 38754d7a4278..a1af650af357 100644
--- a/products/engineering_analytics/backend/tests/test_ci_failure_logs.py
+++ b/products/engineering_analytics/backend/tests/test_ci_failure_logs.py
@@ -20,6 +20,7 @@ def _run(run_id: int) -> WorkflowRunDetail:
duration_seconds=None,
run_attempt=1,
pr_number=5,
+ commit_pr_number=None,
)
diff --git a/products/engineering_analytics/backend/tests/test_ci_signals.py b/products/engineering_analytics/backend/tests/test_ci_signals.py
index cddb9bfd1f94..98c62962b5cb 100644
--- a/products/engineering_analytics/backend/tests/test_ci_signals.py
+++ b/products/engineering_analytics/backend/tests/test_ci_signals.py
@@ -50,6 +50,7 @@ from products.engineering_analytics.backend.logic.signals.detectors import (
)
from products.engineering_analytics.backend.logic.sources import GitHubTables
from products.engineering_analytics.backend.logic.views.source_schema import (
+ PULL_REQUESTS_COLUMNS,
WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
@@ -573,11 +574,19 @@ class TestCISignalDetectors(ClickhouseTestMixin, BaseTest):
source=source,
credential=credential,
)
- # pull_requests is never read by these detectors; reuse the runs table so for_team isn't needed.
+ # These detectors read no PR data, but the curated run source joins the PR snapshot for
+ # default-branch attribution, so it needs a real table of that shape. An empty one suffices.
+ prs_table, _source, _credential = self._seed_table(
+ [],
+ table_name="github_pull_requests",
+ columns=PULL_REQUESTS_COLUMNS,
+ source=source,
+ credential=credential,
+ )
return CuratedGitHubSource(
team=self.team,
tables=GitHubTables(
- pull_requests=table.name,
+ pull_requests=prs_table.name,
workflow_runs=table.name,
workflow_jobs=jobs_table.name if jobs_table else None,
),
diff --git a/products/engineering_analytics/backend/tests/test_ci_views.py b/products/engineering_analytics/backend/tests/test_ci_views.py
index c4d0a1aebc49..2462d57a93b4 100644
--- a/products/engineering_analytics/backend/tests/test_ci_views.py
+++ b/products/engineering_analytics/backend/tests/test_ci_views.py
@@ -19,6 +19,7 @@ from products.engineering_analytics.backend.logic.views.source_schema import (
WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
+from products.engineering_analytics.backend.tests._github_fixtures import pr_association_entry, repo_id
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
from products.warehouse_sources.backend.test.utils import create_data_warehouse_table_from_csv
@@ -28,6 +29,7 @@ GITHUB_SOURCE_PREFIX = "myprefix"
_BASE = "2026-01-01 10:00:00"
_LATER = "2026-01-01 10:10:00"
+_REPO = "PostHog/posthog"
def _job_row(job_id: int, run_id: int, name: str) -> dict[str, Any]:
@@ -52,7 +54,12 @@ def _job_row(job_id: int, run_id: int, name: str) -> dict[str, Any]:
def _run_row(
- run_id: int, head_sha: str, pull_requests: list[dict], head_commit: dict, run_attempt: int = 1
+ run_id: int,
+ head_sha: str,
+ pr_numbers: list[int],
+ head_commit: dict,
+ run_attempt: int = 1,
+ fork_pr_numbers: tuple[int, ...] = (),
) -> dict[str, Any]:
return {
"id": run_id,
@@ -65,8 +72,11 @@ def _run_row(
"run_started_at": _BASE,
"updated_at": _LATER,
"run_attempt": run_attempt,
- "pull_requests": json.dumps(pull_requests),
- "repository": json.dumps({"full_name": "PostHog/posthog"}),
+ "pull_requests": json.dumps(
+ [pr_association_entry(number, base_repo="Mu-L/posthog-1") for number in fork_pr_numbers]
+ + [pr_association_entry(number, base_repo=_REPO) for number in pr_numbers]
+ ),
+ "repository": json.dumps({"full_name": _REPO, "id": repo_id(_REPO)}),
"head_commit": json.dumps(head_commit),
}
@@ -118,7 +128,7 @@ class TestCIJobHistoryView(ClickhouseTestMixin, BaseTest):
_run_row(
100,
head_sha="runsha100",
- pull_requests=[{"number": 5}],
+ pr_numbers=[5],
head_commit={
"author": {"name": "Alice", "email": "[email protected]"},
"message": "fix(ci): thing (#4242)",
@@ -129,15 +139,18 @@ class TestCIJobHistoryView(ClickhouseTestMixin, BaseTest):
_run_row(
200,
head_sha="runsha200",
- pull_requests=[],
+ pr_numbers=[],
head_commit={"author": {"name": "Bob"}, "message": "chore: no pr suffix"},
),
- # A revert: the message carries the reverted PR's (#N) inside quotes AND the revert
- # PR's own suffix — the anchored extraction must attribute the reverting PR.
+ # The real master-push shape: GitHub attaches the fork network's PRs (same head SHA,
+ # foreign base repo), which must NOT become pr_number — the commit suffix is the only
+ # attribution. Also a revert, so the reverted PR's (#N) sits inside the quoted title
+ # alongside the revert PR's own suffix and the anchored extraction must pick the latter.
_run_row(
300,
head_sha="runsha300",
- pull_requests=[],
+ pr_numbers=[],
+ fork_pr_numbers=(1379, 3),
head_commit={
"author": {"name": "Carol"},
"message": 'Revert "feat(ci): thing (#4242)" (#4300)\n\nThis reverts commit abc.',
@@ -148,7 +161,7 @@ class TestCIJobHistoryView(ClickhouseTestMixin, BaseTest):
_run_row(
400,
head_sha="runsha400",
- pull_requests=[],
+ pr_numbers=[],
head_commit={"author": {"name": "Dave"}, "message": "fix: rerun me"},
run_attempt=2,
),
@@ -194,8 +207,10 @@ class TestCIJobHistoryView(ClickhouseTestMixin, BaseTest):
assert value("job-b", "commit_message") == "chore: no pr suffix"
# Revert commit: two (#N) occurrences — the anchored extraction must credit the reverting
- # PR (#4300), never the reverted one quoted in the title (#4242).
+ # PR (#4300), never the reverted one quoted in the title (#4242). Its run also carries the
+ # fork network's PRs; crediting one of those to this repo is the bug pr_number 0 guards.
assert value("job-d", "commit_pr_number") == 4300
+ assert value("job-d", "pr_number") == 0
# Unjoined run: the LEFT JOIN keeps the job attempt (an INNER join would drop it — the guard
# here). ClickHouse fills the unmatched run side with type defaults, so attribution is empty
@@ -219,7 +234,7 @@ class TestCIJobHistoryView(ClickhouseTestMixin, BaseTest):
runs_table = self._create_table(
"github_workflow_runs",
WORKFLOW_RUNS_COLUMNS,
- [_run_row(100, head_sha="s", pull_requests=[{"number": 1}], head_commit={"message": "m"})],
+ [_run_row(100, head_sha="s", pr_numbers=[1], head_commit={"message": "m"})],
)
query = ci_job_history.build_query(jobs_table=jobs_table, runs_table=runs_table)
unioned = "\nUNION ALL\n".join([query, query])
diff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.py
index f57f24f0a21b..601350572d40 100644
--- a/products/engineering_analytics/backend/tests/test_logic_sources.py
+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py
@@ -13,9 +13,10 @@ from products.engineering_analytics.backend.logic.sources import (
WORKFLOW_JOBS_SCHEMA,
WORKFLOW_RUNS_SCHEMA,
GitHubTables,
+ JobSourceTables,
list_github_sources,
resolve_github_tables,
- resolve_job_cost_source_pairs,
+ resolve_job_source_tables,
)
from products.engineering_analytics.backend.logic.views.source_schema import (
PULL_REQUESTS_COLUMNS,
@@ -429,10 +430,19 @@ class TestMultiRepoGitHubResolution(BaseTest):
"posthog/other": [(WORKFLOW_RUNS_SCHEMA, True)],
},
)
- pairs = resolve_job_cost_source_pairs(self.team)
- assert set(pairs) == {
- ("costgithub_posthog_posthog_workflow_jobs", "costgithub_posthog_posthog_workflow_runs"),
- ("costgithub_posthog_posthog_com_workflow_jobs", "costgithub_posthog_posthog_com_workflow_runs"),
+ # pull_requests stays None here: these views qualify on jobs + runs, so a repo reaches them
+ # with no PR snapshot and the run builder's PR attribution degrades to the message suffix.
+ assert set(resolve_job_source_tables(self.team)) == {
+ JobSourceTables(
+ workflow_jobs="costgithub_posthog_posthog_workflow_jobs",
+ workflow_runs="costgithub_posthog_posthog_workflow_runs",
+ pull_requests=None,
+ ),
+ JobSourceTables(
+ workflow_jobs="costgithub_posthog_posthog_com_workflow_jobs",
+ workflow_runs="costgithub_posthog_posthog_com_workflow_runs",
+ pull_requests=None,
+ ),
}
def test_picker_lists_one_entry_per_configured_repo(self) -> None:
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 711184e36dfd..7e58b73289c3 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -163,6 +163,7 @@ def _workflow_run() -> contracts.WorkflowRunDetail:
duration_seconds=120,
run_attempt=2,
pr_number=42,
+ commit_pr_number=None,
)
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index 4bafafad67d9..54f57cda15ec 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -1,3 +1,4 @@
+import json
from typing import Any
from posthog.test.base import BaseTest, ClickhouseTestMixin
@@ -18,6 +19,9 @@ from products.engineering_analytics.backend.tests._github_fixtures import (
_run_row,
create_github_source,
create_github_warehouse_table,
+ pr_association,
+ pr_association_entry,
+ repo_id,
)
from ee.models.rbac.access_control import AccessControl
@@ -167,13 +171,132 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
raw = (
"(SELECT 1 AS id, 'CI' AS name, 'sha1' AS head_sha, 'main' AS head_branch, 'completed' AS status, "
"'success' AS conclusion, 1 AS run_attempt, nullIf('', '') AS pull_requests, "
- f"'{repo_json}' AS repository, "
+ f"'{repo_json}' AS repository, nullIf('', '') AS head_commit, "
"'2026-01-20 10:00:00' AS run_started_at, '2026-01-20 10:30:00' AS updated_at, "
"'2026-01-20 10:00:00' AS created_at)"
)
rows = self._select(f"SELECT pr_number, repo_owner, repo_name FROM ({workflow_runs.build_query(raw)}) AS r")
assert rows[0] == (0, "PostHog", "posthog")
+ def test_workflow_runs_view_attributes_only_own_repo_prs_and_falls_back_to_the_merge_commit(self) -> None:
+ # GitHub's pull_requests association lists every PR in the fork network sharing the run's
+ # head SHA, so a push to our default branch arrives carrying downstream forks' "sync from
+ # upstream" PRs. Taking the first entry unfiltered credited those runs to a stranger's PR
+ # number under our own owner/name. Only a base.repo.id matching the run's repository.id is
+ # ours; a push's real attribution is the (#NNNN) squash-merge suffix instead.
+ own, fork = "PostHog/posthog", "Mu-L/posthog-1"
+ cases: list[tuple[str, str | None, str | None, int, int | None]] = [
+ # (head_branch, pull_requests, commit message, expected pr_number, expected commit_pr_number)
+ ("pr-branch", pr_association(42, base_repo=own), "feat: wip", 42, None),
+ # The real master-push shape: only foreign entries, so nothing is ours.
+ ("master", pr_association(1379, 3, base_repo=fork), "feat: thing (#73832)", 0, 73832),
+ # A foreign entry listed FIRST must not shadow ours — position is what the old code used.
+ (
+ "pr-branch",
+ json.dumps([pr_association_entry(1379, base_repo=fork), pr_association_entry(42, base_repo=own)]),
+ "feat: wip",
+ 42,
+ None,
+ ),
+ ("master", None, "chore: direct push", 0, None),
+ ]
+ rows = [
+ {
+ "id": 5000 + index,
+ "name": "CI",
+ "head_sha": f"sha{index}",
+ "head_branch": head_branch,
+ "status": "completed",
+ "conclusion": "success",
+ "created_at": "2026-01-20 10:00:00",
+ "run_started_at": "2026-01-20 10:00:00",
+ "updated_at": "2026-01-20 10:30:00",
+ "run_attempt": 1,
+ "pull_requests": association,
+ "repository": json.dumps({"full_name": own, "id": repo_id(own)}),
+ "head_commit": json.dumps({"message": message}),
+ }
+ for index, (head_branch, association, message, _, _) in enumerate(cases)
+ ]
+ table_name = self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, rows)
+
+ results = self._select(
+ f"SELECT id, pr_number, commit_pr_number FROM ({workflow_runs.build_query(table_name)}) AS r ORDER BY id"
+ )
+ assert results == [(5000 + index, pr, commit_pr) for index, (_, _, _, pr, commit_pr) in enumerate(cases)]
+
+ def test_workflow_runs_view_resolves_default_branch_pushes_through_the_merge_commit(self) -> None:
+ # A default-branch push carries no association of its own, so commit_pr_number is the only
+ # attribution it gets. The merged PR's merge_commit_sha IS that run's head SHA, which
+ # resolves landings the (#NNNN) message suffix can't, but it must be read only off a
+ # MERGED PR, since GitHub fills it on an open one with a throwaway test-merge commit.
+ own = "PostHog/posthog"
+ cases: list[tuple[str, str, int | None]] = [
+ # (head_sha, commit message, expected commit_pr_number)
+ # The case only the join serves: a merge-commit landing, no (#NNNN) in the subject.
+ ("shaA", "fix: regenerate generated types", 101),
+ # An open PR's merge_commit_sha is a test merge, not a landing, so it must not attribute.
+ ("shaB", "chore: direct push", None),
+ # Join miss (no PR row for this SHA) still falls back to the message suffix.
+ ("shaC", "feat: thing (#103)", 103),
+ # Several merged PRs sharing one merge commit stay ONE run row, not one per PR.
+ ("shaD", "feat: stacked landing (#104)", 104),
+ ]
+ prs = [
+ _pr_row(
+ 101,
+ "alice",
+ "closed",
+ 0,
+ "2026-01-19 09:00:00",
+ merged_at="2026-01-20 09:00:00",
+ merge_commit_sha="shaA",
+ ),
+ _pr_row(102, "bob", "open", 0, "2026-01-19 09:00:00", merge_commit_sha="shaB"),
+ _pr_row(
+ 104,
+ "carol",
+ "closed",
+ 0,
+ "2026-01-19 09:00:00",
+ merged_at="2026-01-20 09:00:00",
+ merge_commit_sha="shaD",
+ ),
+ _pr_row(
+ 105,
+ "dave",
+ "closed",
+ 0,
+ "2026-01-19 09:00:00",
+ merged_at="2026-01-20 09:00:00",
+ merge_commit_sha="shaD",
+ ),
+ ]
+ runs = [
+ {
+ "id": 6000 + index,
+ "name": "CI",
+ "head_sha": head_sha,
+ "head_branch": "master",
+ "status": "completed",
+ "conclusion": "success",
+ "created_at": "2026-01-20 10:00:00",
+ "run_started_at": "2026-01-20 10:00:00",
+ "updated_at": "2026-01-20 10:30:00",
+ "run_attempt": 1,
+ "pull_requests": None,
+ "repository": json.dumps({"full_name": own, "id": repo_id(own)}),
+ "head_commit": json.dumps({"message": message}),
+ }
+ for index, (head_sha, message, _) in enumerate(cases)
+ ]
+ prs_table = self._create_table("github_pull_requests", PULL_REQUESTS_COLUMNS, prs)
+ runs_table = self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, runs)
+
+ query = workflow_runs.build_query(runs_table, pull_requests_table=prs_table)
+ results = self._select(f"SELECT id, commit_pr_number FROM ({query}) AS r ORDER BY id")
+ assert results == [(6000 + index, expected) for index, (_, _, expected) in enumerate(cases)]
+
def test_workflow_runs_view_tolerates_all_nullable_columns(self) -> None:
# Prod lands every column Nullable, so a single run can carry NULL across timestamps,
# repository, pull_requests and run_attempt at once (e.g. a barely-started run). Driven
diff --git a/products/engineering_analytics/fixtures/fetch.py b/products/engineering_analytics/fixtures/fetch.py
index 99e5669bd9ea..9c5e2380170e 100644
--- a/products/engineering_analytics/fixtures/fetch.py
+++ b/products/engineering_analytics/fixtures/fetch.py
@@ -28,7 +28,19 @@ from typing import Any
FIXTURE_DIR = Path(__file__).parent
# Only the fields the curated query builders in backend/logic/views read.
-PR_FIELDS = ("id", "number", "title", "state", "draft", "created_at", "updated_at", "merged_at", "closed_at")
+PR_FIELDS = (
+ "id",
+ "number",
+ "title",
+ "state",
+ "draft",
+ "created_at",
+ "updated_at",
+ "merged_at",
+ "closed_at",
+ # Keyed on by the runs builder to attribute a default-branch push to the PR that landed it.
+ "merge_commit_sha",
+)
RUN_FIELDS = (
"id",
"name",
@@ -68,9 +80,24 @@ def trim_pr(pr: dict[str, Any]) -> dict[str, Any]:
def trim_run(run: dict[str, Any]) -> dict[str, Any]:
trimmed: dict[str, Any] = {field: run[field] for field in RUN_FIELDS}
- trimmed["repository"] = {"full_name": run["repository"]["full_name"]}
- # The PR-list push / re-run rollup attributes runs to a PR via this association.
- trimmed["pull_requests"] = [{"number": pr["number"]} for pr in (run.get("pull_requests") or [])]
+ trimmed["repository"] = {"full_name": run["repository"]["full_name"], "id": run["repository"]["id"]}
+ # The PR-list push / re-run rollup attributes runs to a PR via this association. `base.repo.id`
+ # is load-bearing, not decoration: GitHub lists every PR in the fork network sharing the run's
+ # head SHA, and the curated builder keeps only the entries based in this repo.
+ trimmed["pull_requests"] = [
+ {"number": pr["number"], "base": {"repo": {"id": pr["base"]["repo"]["id"]}}}
+ for pr in (run.get("pull_requests") or [])
+ ]
+ # A default-branch push has no association at all — its squash-merge subject is the only PR
+ # attribution it has, and the author fields back the ci_job_history view.
+ head_commit = run.get("head_commit") or {}
+ trimmed["head_commit"] = {
+ "message": head_commit.get("message", ""),
+ "author": {
+ "name": (head_commit.get("author") or {}).get("name", ""),
+ "email": (head_commit.get("author") or {}).get("email", ""),
+ },
+ }
return trimmed
diff --git a/products/engineering_analytics/frontend/components/runTables.test.tsx b/products/engineering_analytics/frontend/components/runTables.test.tsx
index 4a50877c777e..43f380a04a80 100644
--- a/products/engineering_analytics/frontend/components/runTables.test.tsx
+++ b/products/engineering_analytics/frontend/components/runTables.test.tsx
@@ -1,16 +1,33 @@
-import { formatCost } from './runTables'
+import { formatCost, runPrNumber } from './runTables'
-describe('formatCost', () => {
- it.each([
- [null, '—'],
- [0, '$0.00'],
- // Sub-cent positives must not read as free — a short self-hosted job at the reference rate.
- [0.004, '<$0.01'],
- [0.009, '<$0.01'],
- [0.01, '$0.01'],
- [0.38, '$0.38'],
- [12.5, '$12.50'],
- ])('formats %p as %p', (usd, expected) => {
- expect(formatCost(usd)).toBe(expected)
+describe('runTables', () => {
+ describe('formatCost', () => {
+ it.each([
+ [null, '—'],
+ [0, '$0.00'],
+ // Sub-cent positives must not read as free: a short self-hosted job at the reference rate.
+ [0.004, '<$0.01'],
+ [0.009, '<$0.01'],
+ [0.01, '$0.01'],
+ [0.38, '$0.38'],
+ [12.5, '$12.50'],
+ ])('formats %p as %p', (usd, expected) => {
+ expect(formatCost(usd)).toBe(expected)
+ })
+ })
+
+ describe('runPrNumber', () => {
+ // Both inputs signal "unattributed" differently: pr_number arrives as 0 (ClickHouse fills an
+ // unmatched join with the type default, never NULL) while commit_pr_number arrives as null.
+ // Collapsing that to `prNumber ?? commitPrNumber` would link every unattributed run to #0.
+ it.each([
+ ['association wins', 10, null, 10],
+ ['association preferred over the merge commit', 10, 74028, 10],
+ ['default-branch push falls back to the merge commit', 0, 74028, 74028],
+ ['unattributed reads as no PR, not #0', 0, null, null],
+ ['a zero merge-commit number is absent too', 0, 0, null],
+ ])('%s', (_name, prNumber, commitPrNumber, expected) => {
+ expect(runPrNumber(prNumber, commitPrNumber)).toBe(expected)
+ })
})
})
diff --git a/products/engineering_analytics/frontend/components/runTables.tsx b/products/engineering_analytics/frontend/components/runTables.tsx
index b2b241735d96..d63cb2a874c8 100644
--- a/products/engineering_analytics/frontend/components/runTables.tsx
+++ b/products/engineering_analytics/frontend/components/runTables.tsx
@@ -32,6 +32,20 @@ export function StatusDot({ conclusion }: { conclusion: string | null }): JSX.El
)
}
+/**
+ * The PR to show for a run, or null when it has none.
+ *
+ * A run that ran *for* a PR carries `pr_number`. A default-branch push has no PR association by the
+ * time it runs, so its only attribution is the PR whose merge produced the head commit: the
+ * backend's `commit_pr_number`. Prefer the direct association; fall back to the merge.
+ */
+export function runPrNumber(prNumber: number | null, commitPrNumber: number | null): number | null {
+ if (prNumber != null && prNumber > 0) {
+ return prNumber
+ }
+ return commitPrNumber != null && commitPrNumber > 0 ? commitPrNumber : null
+}
+
export function formatCost(usd: number | null): string {
if (usd == null) {
return '—'
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 2716b47d43c0..59414b099806 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -535,8 +535,13 @@ export interface WorkflowRunDetailApi {
duration_seconds: number | null
/** Re-run attempt number; 1 for the first attempt. */
run_attempt: number
- /** Attributed pull request number, or 0 when unattributed. */
+ /** Pull request this run ran for, from the run's own-repo PR association; 0 when unattributed (a default-branch push, or a fork PR). */
pr_number: number
+ /**
+ * Pull request whose merge produced this run's head commit, resolved through the merged pull request's merge commit and falling back to the commit subject's '(#NNNN)' suffix. Null when neither resolves. The only PR attribution a default-branch push has: read pr_number first and fall back to this.
+ * @nullable
+ */
+ commit_pr_number: number | null
}
export interface CIStatusRollupApi {
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
index 36578b302d53..3d2f33ebf1be 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
@@ -18,7 +18,7 @@ import { EntityHeader, VerdictPill } from '../components/EntityHeader'
import { FailureLogGroups } from '../components/FailureLogs'
import { GroupedJobsTable } from '../components/GroupedJobsTable'
import { MetricTile } from '../components/MetricTile'
-import { formatCost, formatMinutes } from '../components/runTables'
+import { formatCost, formatMinutes, runPrNumber } from '../components/runTables'
import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
import { githubCommitUrl, githubRunUrl } from '../lib/github'
import { isDecisiveFailure } from '../lib/lifecycle'
@@ -64,10 +64,11 @@ export function WorkflowRunDetailScene(): JSX.Element {
const githubUrl = run ? githubRunUrl(run.repo.owner, run.repo.name, run.id) : null
const verdict = run ? verdictTag(run.conclusion) : null
+ const prNumber = run ? runPrNumber(run.pr_number, run.commit_pr_number) : null
const prUrl =
- run && run.pr_number > 0
+ prNumber != null && run
? withScope(
- urls.engineeringAnalyticsPullRequest(run.repo.owner, run.repo.name, run.pr_number),
+ urls.engineeringAnalyticsPullRequest(run.repo.owner, run.repo.name, prNumber),
searchParams,
sourceId
)
@@ -190,7 +191,7 @@ export function WorkflowRunDetailScene(): JSX.Element {
{prUrl && (
<>
<span>· pull request</span>
- <Link to={prUrl}>#{run.pr_number}</Link>
+ <Link to={prUrl}>#{prNumber}</Link>
</>
)}
{run.run_attempt > 1 && <span>· attempt {run.run_attempt}</span>}
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
index 61d1ce10c07b..3bd55cd6d022 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
@@ -198,7 +198,7 @@ export function WorkflowRunsScene(): JSX.Element {
key: 'pr',
width: 80,
render: (_, run) =>
- run.prNumber > 0 ? (
+ run.prNumber != null ? (
<Link
to={withScope(
urls.engineeringAnalyticsPullRequest(run.repoOwner, run.repoName, run.prNumber),
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index eb272bab0efe..c9642a0ee4f3 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -706,6 +706,7 @@ describe('engineeringAnalyticsLogic', () => {
duration_seconds: 300,
run_attempt: 1,
pr_number: 10,
+ commit_pr_number: null,
...overrides,
})
const groups = groupRunsByCommit([
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
index 7c68c0d9c45c..ade5c95a7a16 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
@@ -7,6 +7,7 @@ import { urls } from 'scenes/urls'
import { Breadcrumb } from '~/types'
import type { ActivityRun } from '../components/RunActivityChart'
+import { runPrNumber } from '../components/runTables'
import {
engineeringAnalyticsJobAggregates,
engineeringAnalyticsWorkflowJobs,
@@ -40,7 +41,8 @@ export interface WorkflowRunRow {
id: number
headBranch: string | null
headSha: string
- prNumber: number
+ /** The PR to link, already resolved from the run's association or its merge commit. */
+ prNumber: number | null
repoOwner: string
repoName: string
}
@@ -357,7 +359,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
id: run.id,
headBranch: run.head_branch,
headSha: run.head_sha,
- prNumber: run.pr_number,
+ prNumber: runPrNumber(run.pr_number, run.commit_pr_number),
repoOwner: run.repo.owner,
repoName: run.repo.name,
})),
diff --git a/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
index 417e5e04664b..3a0050523882 100644
--- a/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
+++ b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
@@ -23,8 +23,8 @@ Two warehouse views are the substrate (both non-materialized — always current,
pre-fingerprinted (`fingerprint` = test id + digit/hex-normalized error). Group by `fingerprint`
to get first/last seen, occurrence count, and branch spread.
- **`engineering_analytics_ci_job_history`** — one row per job attempt with `conclusion` AND commit
- attribution: `head_sha`, `commit_author_name`, `commit_message`, `commit_pr_number` (parsed from
- the squash-merge suffix — the only PR attribution a master push run has). This is where greens
+ attribution: `head_sha`, `commit_author_name`, `commit_message`, `commit_pr_number` (the merged PR
+ that produced the commit, the only PR attribution a master push run has). This is where greens
live; the logs are failure-only, so every "when did it turn red / green again" question must come
from here, never from the logs.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6ce10ab669d9..0d1970328379 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -71229,8 +71229,13 @@ export namespace Schemas {
duration_seconds: number | null;
/** Re-run attempt number; 1 for the first attempt. */
run_attempt: number;
- /** Attributed pull request number, or 0 when unattributed. */
+ /** Pull request this run ran for, from the run's own-repo PR association; 0 when unattributed (a default-branch push, or a fork PR). */
pr_number: number;
+ /**
+ * Pull request whose merge produced this run's head commit, resolved through the merged pull request's merge commit and falling back to the commit subject's '(#NNNN)' suffix. Null when neither resolves. The only PR attribution a default-branch push has: read pr_number first and fall back to this.
+ * @nullable
+ */
+ commit_pr_number: number | null;
}
export interface WorkflowRunnerCost {