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(eng-analytics): stop counting merge-queue artifacts as work (#77530)

Raúl Negrón-Otero27cfd63fbc05
diff --git a/products/engineering_analytics/AGENTS.md b/products/engineering_analytics/AGENTS.md
index f0e3f0be6198..c5c2b1ffa851 100644
--- a/products/engineering_analytics/AGENTS.md
+++ b/products/engineering_analytics/AGENTS.md
@@ -11,6 +11,12 @@ A head-SHA join silently drops every push but the latest, because the `github_pu
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).
+Two sanctioned exceptions, so you don't "fix" either back:
+
+1. `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).
+2. A **merge-queue gate run** takes its `pr_number` from its own branch name (`trunk-merge/pr-<n>/…`), not from its `pull_requests` association.
+ The association is present but names the throwaway PR the queue opened, not the PR being landed.
+ The branch name is immutable for the branch's life and names exactly one PR, so it carries none of the ambiguity the head-SHA ban is about.
+ Defined once in `logic/merge_queue.py`; see SPEC §6.
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 93938ddc98a9..80d0e3957c82 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -103,12 +103,13 @@ They are non-materialized: the rendered SQL is persisted per team and re-synced
- Grain: one row per job attempt (a retry appears once per attempt; correct for cost). Jobs whose run row is missing keep NULL attribution rather than being dropped.
- NULL cost is disambiguated by `provider` (non-billable: github-hosted, non-Linux, unclassifiable) vs `completed_at` (unsettled). A queued job is never shown as `$0.00`.
- Cost is defined once, in `logic/cost.py`, rendered to HogQL; a ClickHouse-backed parity test asserts the view equals the Python model. The endpoint cost queries read the same rendered SELECT (via `_curated.job_cost_source()`), so there is no second cost path to drift.
+- `is_merge_queue` splits merge-queue gate spend from the rest without anyone re-deriving what a gate branch is. Both this view and `ci_job_history` carry it, so neither answers "what does the queue cost" by pattern-matching a branch name.
#### `engineering_analytics_ci_job_history`
- 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` resolves the merged PR that produced the head commit, 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), or the PR a merge-queue gate branch was landing when `is_merge_queue`; `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`
@@ -129,6 +130,11 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- **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.
+- **Merge-queue gate branches are CI artifacts, not work — defined once in `logic/merge_queue.py`.** A merge queue (Trunk's `/trunk merge`, GitHub's native queue) lands a PR by pushing a throwaway branch with that PR's commits rebased onto trunk, running the full suite there, and merging only if it stays green. GitHub records that branch as a pull request, so on this repo a third of PR rows and ~13% of CI spend belong to gate attempts.
+ - Gate PRs are dropped in the `pull_requests` builder. They carry no diff, never merge, and no PR surface can act on one, so they are not the bot/draft case (which stays a per-read default so bot-impact analysis can still see bots).
+ - A gate run's `pr_number` resolves through its branch (`trunk-merge/pr-<n>/…`), not its `pull_requests` association — the association names the throwaway PR. This is not the head-SHA join banned above: the branch name is immutable for the branch's life and names exactly one PR. `ci_job_history.is_merge_queue` keeps the two populations separable. The same resolution runs over the CI test spans, where the emitter stamps the gate PR from the webhook payload and would otherwise make one test failing across N merge attempts read as N distinct PRs in every blast-radius count.
+ - A failure on a gate branch that never reached trunk classifies as `blocking_merge_queue`, not `pr_only`: the commit had already passed the PR's own CI, which is the semantic-conflict class the queue exists to catch.
+ - A queue that batched several PRs onto one gate branch would break the one-PR assumption; that needs a new branch shape in `merge_queue.py`, not a new rule at each call site.
- **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 c0301b6d9ce7..b1114563810d 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -117,6 +117,10 @@ class BrokenTestState(StrEnum):
- ``breaking_master``: has failed on the default branch and that job's latest completed run
is still red — trunk is broken by this right now.
+ - ``blocking_merge_queue``: failed on a merge-queue gate branch and never on the default
+ branch — it stopped a merge on a commit that had already passed the PR's own CI, which is
+ the semantic-conflict class a merge queue exists to catch. Trunk is still green, so this
+ ranks below ``breaking_master``, but it is holding up landings right now.
- ``novel_burst``: first seen within the last day and already spreading across several PR
branches, not on the default branch yet — a new failure catching on.
- ``potentially_resolved``: hit the default branch but that job's latest run is green again —
@@ -127,6 +131,7 @@ class BrokenTestState(StrEnum):
"""
BREAKING_MASTER = "breaking_master"
+ BLOCKING_MERGE_QUEUE = "blocking_merge_queue"
NOVEL_BURST = "novel_burst"
POTENTIALLY_RESOLVED = "potentially_resolved"
FLAKY = "flaky"
diff --git a/products/engineering_analytics/backend/logic/merge_queue.py b/products/engineering_analytics/backend/logic/merge_queue.py
new file mode 100644
index 000000000000..a4c3a583eefe
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/merge_queue.py
@@ -0,0 +1,107 @@
+"""Merge-queue branches: telling a CI gate artifact apart from real work.
+
+A merge queue lands a pull request by pushing a throwaway branch carrying that PR's commits
+rebased onto the current default branch, running the full suite there, and merging only if it
+stays green. GitHub sees the gate branch as an ordinary pull request, so the warehouse snapshot
+gains one extra draft PR per merge attempt and one extra full CI fan-out — associated to *that*
+PR, not the one being landed.
+
+Left alone, every PR surface counts gate artifacts as work: the attention list fills with bot
+drafts that no human can act on, the open-PR and failing-CI cards over-count, and a PR's cost
+card omits the gate run its own merge paid for. This module is where the product knows the
+difference, defined once (SPEC §3).
+
+Two shapes are recognized, both of which name their source PR in the branch:
+
+- Trunk: ``trunk-merge/pr-<number>/<uuid>``, and the ``-bisection`` suffix variant Trunk pushes
+ while bisecting a flaky failure.
+- GitHub's native queue: ``gh-readonly-queue/<base-branch>/pr-<number>-<sha>``.
+
+The branch name is the attribution key on purpose. It is immutable for the branch's life and
+names exactly one PR, so it carries none of the ambiguity SPEC §6 bans the head-SHA join for: a
+gate branch's head SHA is a rebase that exists nowhere else, and its own ``pull_requests``
+association points at the throwaway PR rather than the real one.
+
+**The shape alone is not enough, because branch names are contributor-controlled.** On a public
+repo anyone can open a PR from a branch called ``trunk-merge/pr-123/anything``; on the shape alone
+we would drop their PR from every surface and re-key its runs, jobs and cost onto PR 123. So every
+destructive use pairs the shape with an identity the pusher cannot set: GitHub stamps ``actor`` on
+a run and ``user`` on a PR, and a real gate artifact carries a queue bot in both. Measured over two
+months of ``PostHog/posthog``: 51,052 gate-shaped runs, all with ``actor`` = ``trunk-io[bot]``, none
+from a fork — so requiring it costs nothing today and closes the spoof.
+
+A queue that batched several PRs onto one gate branch would break the one-PR assumption. Neither
+shape above does — batching would need a new shape here, not a new rule at each call site.
+"""
+
+# Both shapes carry the source PR as a ``pr-<number>`` segment; the trailing separator ('/' before
+# Trunk's uuid, '-' before GitHub's sha) is what ends the digit run. ``[0-9]`` rather than ``\d``
+# keeps the pattern backslash-free, so it survives embedding in a HogQL string literal unescaped.
+_SOURCE_PR_PATTERN = "^(?:trunk-merge/|gh-readonly-queue/[^/]+/)pr-([0-9]+)[/-]"
+
+# The identities a real merge queue acts as. GitHub's native queue pushes gate branches without
+# opening a PR, so only Trunk needs an entry today.
+MERGE_QUEUE_BOT_HANDLES: frozenset[str] = frozenset({"trunk-io[bot]"})
+
+
+# Both helpers ``ifNull`` their input, and that is load-bearing rather than defensive: a branch or
+# actor column can read NULL rather than '' (the CI spans hold theirs in a map, NULL for a run that
+# predates the stamp), and NULL into regexpExtract poisons the whole expression. `WHERE NOT <NULL>`
+# drops the row and `if(<NULL>, a, b)` returns NULL instead of the fallback, so an unstamped column
+# would silently delete data rather than fail a filter.
+def _source_pr_string(branch_column: str) -> str:
+ return f"regexpExtract(ifNull({branch_column}, ''), '{_SOURCE_PR_PATTERN}')"
+
+
+def _pushed_by_queue(actor_column: str) -> str:
+ handles = ", ".join(f"'{handle}'" for handle in sorted(MERGE_QUEUE_BOT_HANDLES))
+ return f"ifNull({actor_column}, '') IN ({handles})"
+
+
+def looks_like_merge_queue_branch_expr(branch_column: str) -> str:
+ """HogQL predicate on the branch **shape alone** — no identity corroboration.
+
+ Only for reads where a false positive cannot drop or re-key anything, i.e. where the worst case
+ is one miscounted row. The failure-lines view (Logs) carries no actor to corroborate against, and
+ its gate-branch count only feeds a classifier verdict, so it uses this. Anything that decides
+ what a row *is* must use ``merge_queue_branch_expr`` instead — see the module docstring on why
+ the shape is contributor-controlled.
+ """
+ return f"{_source_pr_string(branch_column)} != ''"
+
+
+def source_pr_string_expr(branch_column: str, *, queue_actor_column: str) -> str:
+ """HogQL: the PR number a corroborated gate branch is landing, as a string; '' otherwise.
+
+ The string flavor exists for the CI-span reads, where ``pr_number`` is a resource attribute
+ (a String) and '' is already that layer's "unattributed" sentinel.
+
+ ``queue_actor_column`` is required, not optional, so no caller can take the branch name's word
+ for it: the identity that owns the artifact (a run's ``actor``, a PR's ``user``, a span's
+ ``ci.actor``). A non-queue identity yields '' — the same "not a gate branch" answer as a
+ non-matching name.
+ """
+ return f"if({_pushed_by_queue(queue_actor_column)}, {_source_pr_string(branch_column)}, '')"
+
+
+def source_pr_number_expr(branch_column: str, *, queue_actor_column: str) -> str:
+ """HogQL: the PR number a corroborated gate branch is landing, 0 otherwise.
+
+ 0 rather than NULL to match the runs builder's existing "no attribution" sentinel for
+ ``pr_number``, so the two compose with a plain comparison instead of a null-guard.
+ """
+ string_expr = source_pr_string_expr(branch_column, queue_actor_column=queue_actor_column)
+ return f"ifNull(accurateCastOrNull({string_expr}, 'Int64'), 0)"
+
+
+def merge_queue_branch_expr(branch_column: str, *, queue_actor_column: str) -> str:
+ """HogQL predicate: is this a merge-queue gate branch, pushed by the queue?
+
+ Defined as "we resolved a source PR from it" rather than a cheaper prefix test, so recognizing a
+ gate branch and attributing one can never disagree. A prefix test would classify a branch the
+ pattern cannot resolve (a queue shape we don't know yet, a base branch containing a slash), and
+ that disagreement is destructive in one direction: the PR row is dropped from the curated source
+ while its runs keep pointing at it. Failing to recognize an exotic shape only leaves us the
+ cleanup we have today; misrecognizing one loses data.
+ """
+ return f"{source_pr_number_expr(branch_column, queue_actor_column=queue_actor_column)} > 0"
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index ca32e2b5abad..5cb9ee05b23d 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -240,6 +240,12 @@ class CuratedGitHubSource:
(CI triggers), ``rerun_cycles`` the runs that were a 2nd+ attempt. Fork-PR runs have no
association (``pr_number = 0``) and are excluded.
+ Merge-queue gate runs are excluded too, even though the runs builder credits them to the PR
+ they were landing. This rollup measures what the *author* did to the PR, and a gate branch's
+ head SHA is a rebase the queue made — counting it would report a push nobody made, once per
+ merge attempt. Cost and CI-health surfaces keep the gate run; they measure spend and outcomes,
+ not authoring activity.
+
Keyed on ``(repo_owner, repo_name, pr_number)``, not ``pr_number`` alone: PR numbers
restart per repository, so the PR-list join is qualified by repo to stay correct — as
repo-safe as the head-SHA join in ``ci_rollup_cte``. A resolved source is a single repo
@@ -256,7 +262,7 @@ class CuratedGitHubSource:
count(DISTINCT head_sha) AS pushes,
countIf(run_attempt > 1) AS rerun_cycles
FROM runs AS r
- WHERE pr_number > 0
+ WHERE pr_number > 0 AND NOT is_merge_queue
GROUP BY repo_owner, repo_name, pr_number
)
"""
diff --git a/products/engineering_analytics/backend/logic/queries/_test_spans.py b/products/engineering_analytics/backend/logic/queries/_test_spans.py
index 45a6357ba56f..e7283a3bac7d 100644
--- a/products/engineering_analytics/backend/logic/queries/_test_spans.py
+++ b/products/engineering_analytics/backend/logic/queries/_test_spans.py
@@ -29,6 +29,16 @@ from datetime import datetime
from posthog.hogql import ast
+from products.engineering_analytics.backend.logic.merge_queue import source_pr_string_expr
+
+# On a merge-queue gate run the emitter stamps ``ci.pr_number`` from the webhook payload, which names
+# the throwaway PR the queue opened rather than the PR being landed. Every blast-radius read here
+# counts distinct PRs, so left alone one test failing across N merge attempts looks like N separate
+# PRs hitting it — the branch is what names the real one (see ``logic.merge_queue``).
+_SPAN_PR_NUMBER = source_pr_string_expr(
+ "resource_attributes['ci.branch']", queue_actor_column="resource_attributes['ci.actor']"
+)
+
# Only test spans carry test.outcome (job-root and setup spans don't), and only these
# outcomes are flaky signal. Plain 'skipped' spans never reach any aggregation; 'passed'
# spans are read only from re-run attempts (the scan's recovery arm), where they are the
@@ -118,21 +128,32 @@ def run_evidence(*, bounded: bool) -> str:
``bounded`` adds the upper time bound; some callers scan to now.
"""
- scan = _SCAN.replace("__DATE_TO__", " AND timestamp <= {date_to}" if bounded else "")
- return _RUN_EVIDENCE.replace("__SPAN_SCAN__", scan)
+ return _RUN_EVIDENCE.replace("__SPAN_SCAN__", _scan(bounded=bounded))
+
+
+def _scan(*, bounded: bool) -> str:
+ """The span scan with every ``__``-token substituted — the only way to obtain this SQL.
+
+ An unsubstituted token is not a parse error you would notice, it is a silently wrong query, so
+ every render goes through here rather than each caller remembering the list. The ``{...}`` names
+ that remain are real HogQL placeholders, bound by ``scan_placeholders``.
+ """
+ return _SCAN_TEMPLATE.replace("__DATE_TO__", " AND timestamp <= {date_to}" if bounded else "").replace(
+ "__QUEUE_PR__", _SPAN_PR_NUMBER
+ )
# Scans [scan_from, date_to?]; `is_current` splits rows at {date_from} so a caller scanning
# an extra prior window (scan_from < date_from) gets the current/prior split for free. A
# caller without a prior window passes scan_from = date_from and ignores the column.
-_SCAN = """
+_SCAN_TEMPLATE = """
SELECT
if(attributes['test.runner'] = 'jest' OR service_name = 'ci-frontend', 'jest', 'pytest') AS runner,
name AS nodeid,
attributes['test.selector'] AS selector,
attributes['test.outcome'] AS outcome,
coalesce(nullIf(attributes['test.owner_team'], ''), {unowned_team}) AS owner_team,
- resource_attributes['ci.pr_number'] AS pr_number,
+ if(__QUEUE_PR__ != '', __QUEUE_PR__, resource_attributes['ci.pr_number']) AS pr_number,
resource_attributes['ci.branch'] AS branch,
-- The emitter always stamps ci.run_id; the trace_id fallback (one trace per job) keeps an
-- unstamped span from merging every execution of its test into one phantom run.
diff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
index 84e4209f9a56..1025f6f91be9 100644
--- a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
@@ -120,5 +120,9 @@ def run_scope_filter_clause(
# query_default_branch resolves per-repo, not reused here because it costs an extra query.
# The cost queries pass the cost source's columns; there pr_number is 0→NULL normalized, so
# "attributed" becomes ``c.pr_number IS NOT NULL`` rather than ``> 0``.
+ # Merge-queue gate runs stay in this scope on purpose: a gate run is CI the PR paid for on
+ # its way to landing, and the runs builder already credits it to that PR rather than to the
+ # throwaway PR the queue opened. ``is_merge_queue`` splits the two populations, on the cost
+ # view and the job-history view alike.
return f"AND {branch_column} NOT IN ('master', 'main') AND {attributed_predicate}"
return ""
diff --git a/products/engineering_analytics/backend/logic/queries/broken_tests.py b/products/engineering_analytics/backend/logic/queries/broken_tests.py
index 27a94e1aa14d..2e6208a2db01 100644
--- a/products/engineering_analytics/backend/logic/queries/broken_tests.py
+++ b/products/engineering_analytics/backend/logic/queries/broken_tests.py
@@ -22,6 +22,12 @@ the Python classifier never does timezone-sensitive datetime math on the returne
by name (the log record's ``job_name`` vs the warehouse job ``name``). When the job-level source
isn't synced there is no job status at all, so those fingerprints fall through to ``flaky`` /
``pr_only`` — the panel degrades rather than misreports.
+
+``blocking_merge_queue`` needs neither: it reads only the failure lines' branches. A merge queue
+runs the full suite on a gate branch carrying the PR rebased onto trunk, so a failure there is on a
+commit the PR's own CI already passed. Without this verdict a gate-only failure ranks by its branch
+spread like any other — ``pr_only`` for a single merge attempt, ``flaky`` or ``novel_burst`` across
+several — which buries the one failure class the queue was installed to surface.
"""
from datetime import datetime, timedelta
@@ -36,6 +42,7 @@ from products.engineering_analytics.backend.facade.contracts import (
BrokenTestsResult,
BrokenTestState,
)
+from products.engineering_analytics.backend.logic.merge_queue import looks_like_merge_queue_branch_expr
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.views import ci_failures
@@ -54,10 +61,11 @@ _FLAKY_MIN_SPAN_HOURS = 24 # ...and recurring over more than a day
# Sort rank: lowest surfaces first (breaking master on top, PR-only last).
_SEVERITY: dict[BrokenTestState, int] = {
BrokenTestState.BREAKING_MASTER: 0,
- BrokenTestState.NOVEL_BURST: 1,
- BrokenTestState.POTENTIALLY_RESOLVED: 2,
- BrokenTestState.FLAKY: 3,
- BrokenTestState.PR_ONLY: 4,
+ BrokenTestState.BLOCKING_MERGE_QUEUE: 1,
+ BrokenTestState.NOVEL_BURST: 2,
+ BrokenTestState.POTENTIALLY_RESOLVED: 3,
+ BrokenTestState.FLAKY: 4,
+ BrokenTestState.PR_ONLY: 5,
}
# Fingerprint aggregation over the failure-lines view. ``age_hours`` / ``span_hours`` /
@@ -81,6 +89,8 @@ _FINGERPRINTS_SELECT = """
count() AS occurrences,
uniqExactIf(branch, branch != '') AS branches,
countIf(branch IN {default_branches}) AS master_hits,
+ countIf(__MERGE_QUEUE_BRANCH__) AS merge_queue_hits,
+ countIf(branch != '' AND branch NOT IN {default_branches} AND NOT __MERGE_QUEUE_BRANCH__) AS pr_branch_hits,
-- Aliased away from `repo`: HogQL binds a WHERE identifier to a matching SELECT alias, so
-- `any(repo) AS repo` would make the `lower(repo)` filter below resolve to this aggregate and
-- 500 with "aggregate function found in WHERE". Keep the alias distinct from the filtered column.
@@ -92,7 +102,7 @@ _FINGERPRINTS_SELECT = """
FROM __FAILURES_SOURCE__
WHERE timestamp >= {date_from} AND lower(repo) = lower({repository})
GROUP BY fingerprint
- ORDER BY master_hits DESC, branches DESC, last_seen DESC
+ ORDER BY master_hits DESC, merge_queue_hits DESC, branches DESC, last_seen DESC
LIMIT {limit_plus_one}
"""
@@ -136,6 +146,8 @@ _MASTER_JOBS_SELECT = """
def _classify(
*,
master_hits: int,
+ merge_queue_hits: int,
+ pr_branch_hits: int,
age_hours: int,
span_hours: int,
branches: int,
@@ -160,6 +172,13 @@ def _classify(
# Breaking trunk right now: hit the default branch and that job's latest run is still red.
if master_hits > 0 and master_red:
return BrokenTestState.BREAKING_MASTER
+ # Stopped a merge on a commit that had already passed the PR's own CI — the semantic conflict the
+ # queue exists to catch. Gated on failing *only* there: the queue re-runs the full suite on every
+ # merge attempt, so an ordinary flake picks up gate hits by sheer breadth. Requiring no trunk and
+ # no PR-branch failures keeps this the "passed everywhere else, died at the gate" signal instead
+ # of a second home for flakes, which stay ranked by the shape they actually have.
+ if merge_queue_hits > 0 and master_hits == 0 and pr_branch_hits == 0:
+ return BrokenTestState.BLOCKING_MERGE_QUEUE
# New today and already spreading across branches, but not on trunk yet.
if age_hours < _NOVEL_BURST_MAX_AGE_HOURS and branches >= _NOVEL_BURST_MIN_BRANCHES and master_hits == 0:
return BrokenTestState.NOVEL_BURST
@@ -202,6 +221,11 @@ def query_broken_tests(
)
failures_source = f"({ci_failures.build_query()})"
+ # Shape-only: the failure-lines view carries no actor to corroborate against, and a false
+ # positive here can only mis-rank one fingerprint — it drops and re-keys nothing.
+ fingerprints_sql = _FINGERPRINTS_SELECT.replace(
+ "__MERGE_QUEUE_BRANCH__", looks_like_merge_queue_branch_expr("branch")
+ ).replace("__FAILURES_SOURCE__", failures_source)
logs_placeholders: dict[str, ast.Expr] = {
"default_branches": ast.Constant(value=_DEFAULT_BRANCHES),
"repository": ast.Constant(value=repository),
@@ -211,7 +235,7 @@ def query_broken_tests(
}
fingerprint_rows = (
curated.run(
- _FINGERPRINTS_SELECT.replace("__FAILURES_SOURCE__", failures_source),
+ fingerprints_sql,
query_type="engineering_analytics.broken_tests_fingerprints",
placeholders=logs_placeholders,
workload=Workload.LOGS,
@@ -278,6 +302,8 @@ def query_broken_tests(
occurrences,
branches,
master_hits,
+ merge_queue_hits,
+ pr_branch_hits,
repo,
latest_run_id,
latest_branch,
@@ -287,6 +313,8 @@ def query_broken_tests(
latest_conclusion, latest_completed_age = master_by_key.get((workflow_name, job_name), (None, None))
state = _classify(
master_hits=master_hits,
+ merge_queue_hits=merge_queue_hits,
+ pr_branch_hits=pr_branch_hits,
age_hours=age_hours,
span_hours=span_hours,
branches=branches,
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
index 6d106398f73b..8097f82822c8 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_list.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
@@ -82,6 +82,10 @@ _READY_JOIN = "LEFT JOIN ready_by_pr AS re ON re.pr_number = pr.number"
# round red and any not-yet-completed run marks it pending. Wall time is the round's earliest run
# start to its latest completed run end (``updated_at`` is the end time the duration column uses).
#
+# Merge-queue gate runs are excluded for the same reason as ``runs_by_pr`` (see its docstring), and
+# for one specific to here: they are the newest rounds a PR has, since they happen at merge time, so
+# leaving them in would push the author's real pushes out of the capped window below.
+#
# ``LIMIT __PUSH_HISTORY_LIMIT__ BY (repo_owner, repo_name, pr_number)`` bounds the scan to the most
# recent N pushes per PR *in ClickHouse* (rows are ordered newest-first, so the cap keeps the newest),
# rather than fetching every push and slicing in Python — a PR with hundreds of pushes never ships more
@@ -102,7 +106,7 @@ _PUSH_HISTORY_SELECT = """
argMax(status, run_started_at) AS s,
argMax(conclusion, run_started_at) AS c
FROM __RUNS_SOURCE__ AS r
- WHERE pr_number IN {pr_numbers}
+ WHERE pr_number IN {pr_numbers} AND NOT is_merge_queue
GROUP BY repo_owner, repo_name, pr_number, head_sha, workflow_name
)
GROUP BY repo_owner, repo_name, pr_number, head_sha
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 e416dde58db1..80f183e7b965 100644
--- a/products/engineering_analytics/backend/logic/views/ci_job_history.py
+++ b/products/engineering_analytics/backend/logic/views/ci_job_history.py
@@ -27,7 +27,9 @@ Two PR keys, by design: ``pr_number`` is the runs builder's association-derived
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.
+straight off the runs builder, which defines each key once for every consumer. On a merge-queue
+gate run ``pr_number`` is the PR the queue was landing rather than an association, and
+``is_merge_queue`` is what tells the two apart.
``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
@@ -42,7 +44,13 @@ Nothing here is registered as a global HogQL view; it is provisioned per-team as
from typing import TYPE_CHECKING
-from posthog.hogql.database.models import DateTimeDatabaseField, FieldOrTable, IntegerDatabaseField, StringDatabaseField
+from posthog.hogql.database.models import (
+ BooleanDatabaseField,
+ DateTimeDatabaseField,
+ FieldOrTable,
+ IntegerDatabaseField,
+ StringDatabaseField,
+)
from products.engineering_analytics.backend.logic.sources import resolve_job_source_tables
from products.engineering_analytics.backend.logic.views import workflow_jobs, workflow_runs
@@ -79,6 +87,7 @@ FIELDS: dict[str, FieldOrTable] = {
"commit_author_email": StringDatabaseField(name="commit_author_email", nullable=True),
"commit_message": StringDatabaseField(name="commit_message", nullable=True),
"commit_pr_number": IntegerDatabaseField(name="commit_pr_number", nullable=True),
+ "is_merge_queue": BooleanDatabaseField(name="is_merge_queue"),
}
@@ -139,7 +148,10 @@ def build_query(*, jobs_table: str, runs_table: str, pull_requests_table: str |
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
+ r.commit_pr_number AS commit_pr_number,
+ -- The run ran on a merge-queue gate branch, so pr_number above is the PR it was landing
+ -- rather than an association. Without this the two populations are indistinguishable.
+ r.is_merge_queue AS is_merge_queue
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
diff --git a/products/engineering_analytics/backend/logic/views/job_costs.py b/products/engineering_analytics/backend/logic/views/job_costs.py
index 19e13fc855fd..63b0bf6a5c92 100644
--- a/products/engineering_analytics/backend/logic/views/job_costs.py
+++ b/products/engineering_analytics/backend/logic/views/job_costs.py
@@ -18,6 +18,7 @@ non-materialized ``DataWarehouseSavedQuery`` by data_modeling's managed-viewset
from typing import TYPE_CHECKING
from posthog.hogql.database.models import (
+ BooleanDatabaseField,
DateTimeDatabaseField,
FieldOrTable,
FloatDatabaseField,
@@ -73,6 +74,11 @@ FIELDS: dict[str, FieldOrTable] = {
"multiplier": IntegerDatabaseField(name="multiplier", nullable=True),
"billable_seconds": IntegerDatabaseField(name="billable_seconds", nullable=True),
"estimated_cost_usd": FloatDatabaseField(name="estimated_cost_usd", nullable=True),
+ # Non-nullable unlike the attribution columns above, because it is derived rather than read off
+ # the source: an unjoined run reads 0, the same "no" it gives every other run attribute. Exposed
+ # so "what does the merge queue cost" doesn't get answered by re-deriving a gate branch from
+ # head_branch, which would put that definition somewhere other than logic/merge_queue.py.
+ "is_merge_queue": BooleanDatabaseField(name="is_merge_queue"),
}
@@ -147,7 +153,8 @@ def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool =
vcpu,
{render_multiplier("vcpu")} AS multiplier,
{render_billable_seconds("provider", "os", "duration_seconds")} AS billable_seconds,
- {render_estimated_cost_usd("provider", "os", "vcpu", "duration_seconds")} AS estimated_cost_usd{run_columns}
+ {render_estimated_cost_usd("provider", "os", "vcpu", "duration_seconds")} AS estimated_cost_usd,
+ is_merge_queue{run_columns}
FROM (
SELECT
repo_owner,
@@ -166,6 +173,7 @@ def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool =
completed_at,
queue_seconds,
duration_seconds,
+ is_merge_queue,
{render_provider("depot_label", "hosted_label")} AS provider,
{render_os("depot_label", "hosted_label")} AS os,
{render_vcpu("depot_label", "hosted_label")} AS vcpu{run_columns}
@@ -187,6 +195,7 @@ def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool =
completed_at,
queue_seconds,
duration_seconds,
+ is_merge_queue,
{render_depot_label("labels_arr")} AS depot_label,
{render_hosted_label("labels_arr")} AS hosted_label{run_columns}
FROM (
@@ -209,6 +218,7 @@ def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool =
j.completed_at AS completed_at,
j.queue_seconds AS queue_seconds,
j.duration_seconds AS duration_seconds,
+ r.is_merge_queue AS is_merge_queue,
{labels_array} AS labels_arr{inner_run_columns}
FROM ({jobs}) AS j
LEFT JOIN ({runs}) AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt
diff --git a/products/engineering_analytics/backend/logic/views/pull_requests.py b/products/engineering_analytics/backend/logic/views/pull_requests.py
index 836eb17001c5..6ba8a2e01c3d 100644
--- a/products/engineering_analytics/backend/logic/views/pull_requests.py
+++ b/products/engineering_analytics/backend/logic/views/pull_requests.py
@@ -11,6 +11,16 @@ is user-chosen. Every query module embeds this ``SELECT`` as a subquery (see
``_curated``) rather than re-deriving the columns from JSON; nothing registers it as a
global HogQL view, so the product stays off the per-query catalog hot path.
+Merge-queue gate branches are filtered out here (see ``logic.merge_queue``). A queue opens a
+draft PR per merge attempt — a third of this repo's PR rows — and those are CI artifacts, not
+units of work: they carry no diff of their own, never merge, and no PR surface can act on one.
+The filter pairs the branch shape with the PR's author, because a branch name is contributor-
+controlled: on the shape alone, opening a PR from a branch named ``trunk-merge/pr-123/x`` would
+delete it from every surface here.
+Dropping them at the builder is deliberately unlike the bot/draft rule, which stays a per-read
+default so bot-impact analysis can still see bots (SPEC §6). Nothing is lost for attribution:
+the gate branch's *runs* stay in the runs substrate, re-keyed to the PR they were landing.
+
The real GitHub source lands timestamps as **strings** and the nested objects
(``user`` / ``head`` / ``base`` / ``labels``) as **Nullable** JSON, so this builder
runs in two layers: an inner SELECT parses each timestamp with
@@ -21,6 +31,8 @@ identity, labels and the duration off those parsed columns. Splitting the layers
avoids referencing a same-SELECT alias as another expression's input.
"""
+from products.engineering_analytics.backend.logic.merge_queue import merge_queue_branch_expr
+
# Bots whose handle does not carry GitHub's automatic ``[bot]`` suffix. Kept
# deliberately small; per-team configuration is deferred.
KNOWN_BOT_HANDLES: frozenset[str] = frozenset(
@@ -85,4 +97,5 @@ def build_query(table_name: str) -> str:
parseDateTimeBestEffort(closed_at) AS closed_at
FROM {table_name}
)
+ WHERE NOT {merge_queue_branch_expr("head_branch", queue_actor_column="author_handle")}
"""
diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.py
index 13df230885eb..6d46d2f740c3 100644
--- a/products/engineering_analytics/backend/logic/views/source_schema.py
+++ b/products/engineering_analytics/backend/logic/views/source_schema.py
@@ -57,6 +57,10 @@ WORKFLOW_RUNS_COLUMNS: dict[str, dict[str, str]] = {
# attribution the ci_job_history view extracts; a push run's PR number rides its squash-merge
# message when the pull_requests association is empty (master pushes). Nullable like every column.
"head_commit": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+ # The account GitHub recorded as triggering the run, verbatim as JSON. GitHub sets it; whoever
+ # pushed the branch cannot, which is what makes it the corroboration a merge-queue gate branch
+ # is checked against before its name is trusted for attribution (see logic/merge_queue.py).
+ "actor": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
}
# Contract for the incoming ``github_workflow_jobs`` warehouse source (job-level CI: queue
diff --git a/products/engineering_analytics/backend/logic/views/workflow_runs.py b/products/engineering_analytics/backend/logic/views/workflow_runs.py
index 3a580d3cbce9..037b3b47df32 100644
--- a/products/engineering_analytics/backend/logic/views/workflow_runs.py
+++ b/products/engineering_analytics/backend/logic/views/workflow_runs.py
@@ -25,6 +25,26 @@ and a run shared across more than one of our PRs (uncommon — one head tied to
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.
+A merge-queue gate run is the one case where the association is present but wrong for the product's
+purpose: it points at the throwaway PR the queue opened, not the PR being landed. The gate branch
+names its source PR (``trunk-merge/pr-77271/...``), so ``pr_number`` resolves through the branch
+whenever it is one, and ``is_merge_queue`` marks those rows for consumers that need the two
+populations apart. Without this a PR's cost card omits the full-suite run its own merge paid for —
+~13% of this repo's CI spend — while it lands on a PR no surface shows. See ``logic.merge_queue``
+for the branch shapes and why the branch name is a sound key here.
+
+**The rule for a new ``pr_number`` consumer**, since crediting the gate run is right for most reads
+and wrong for a few. Ask what the number is being counted *for*:
+
+- Measuring **CI** — cost, duration, pass rate, which runs ran, which failures to read — include gate
+ runs. That work happened, the PR caused it, and excluding it under-reports what landing cost.
+- Measuring **what the author did** — pushes, re-run cycles, push history — exclude them with
+ ``NOT is_merge_queue``. A gate branch's head SHA is a rebase the queue made, so counting it reports
+ activity nobody performed, once per merge attempt.
+
+Only ``runs_by_pr`` (``_curated``) and the push-history scan (``pull_request_list``) are in the second
+group today. Getting this wrong is silent: the numbers stay plausible and just drift up.
+
``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``
@@ -64,6 +84,12 @@ Every query module embeds this ``SELECT`` as a subquery (see ``_curated``);
nothing registers it as a global HogQL view.
"""
+from products.engineering_analytics.backend.logic.merge_queue import source_pr_number_expr
+
+# The source PR of a merge-queue gate branch, corroborated against the run's actor so a
+# contributor-named branch can't re-key someone else's runs onto their PR (see logic.merge_queue).
+_MERGE_QUEUE_PR_NUMBER = source_pr_number_expr("head_branch", queue_actor_column="JSONExtractString(actor, 'login')")
+
# 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.
@@ -129,7 +155,10 @@ def build_query(table_name: str, *, pull_requests_table: str | None = None, star
created_at,
run_attempt,
default_branch,
- pr_number,
+ merge_queue_pr_number > 0 AS is_merge_queue,
+ -- A gate run's own association names the throwaway PR the queue opened; the branch names
+ -- the PR being landed, which is the one every surface asks about.
+ if(merge_queue_pr_number > 0, merge_queue_pr_number, association_pr_number) AS 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,
@@ -143,7 +172,12 @@ def build_query(table_name: str, *, pull_requests_table: str | None = None, star
status,
conclusion,
run_attempt,
- JSONExtractInt({_OWN_REPO_PR}, 'number') AS pr_number,
+ JSONExtractInt({_OWN_REPO_PR}, 'number') AS association_pr_number,
+ -- ``actor`` is read inline, not via an alias: an alias defined later in this same
+ -- SELECT is not reliably resolvable as another expression's input (see the two-layer
+ -- note above). It is the account GitHub recorded as triggering the run, which whoever
+ -- pushed the branch cannot set — that is what makes it usable as corroboration.
+ {_MERGE_QUEUE_PR_NUMBER} AS merge_queue_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,
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 29bec1667d61..8ae07a474ede 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -105,7 +105,7 @@ def _synthetic_repo_id(full_name: str) -> int:
def _flatten_run(run: dict[str, Any]) -> dict[str, Any]:
- json_keys = ("repository", "pull_requests", "head_commit")
+ json_keys = ("repository", "pull_requests", "head_commit", "actor")
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
@@ -123,6 +123,9 @@ def _flatten_run(run: dict[str, Any]) -> dict[str, Any]:
"repository": json.dumps(repository),
"pull_requests": json.dumps(associations),
"head_commit": json.dumps(run.get("head_commit", {})),
+ # Snapshots captured before actor was kept land '{}', which reads as "not the merge queue" —
+ # the safe answer, since the branch parse it gates only ever adds attribution.
+ "actor": json.dumps(run.get("actor") or {}),
}
diff --git a/products/engineering_analytics/backend/presentation/serializers/suite_health.py b/products/engineering_analytics/backend/presentation/serializers/suite_health.py
index d9e42c47ab97..5af4bfcba341 100644
--- a/products/engineering_analytics/backend/presentation/serializers/suite_health.py
+++ b/products/engineering_analytics/backend/presentation/serializers/suite_health.py
@@ -98,9 +98,10 @@ class BrokenTestRowSerializer(DataclassSerializer):
"repo": {"help_text": "'owner/name' repository the failure belongs to."},
"state": {
"help_text": "The classifier's verdict on how this failure is behaving right now: "
- "'breaking_master' (failing on trunk, latest trunk run still red), 'novel_burst' (new within a "
- "day and spreading across branches, not on trunk yet), 'potentially_resolved' (hit trunk but "
- "trunk is green again), 'flaky' (sporadic across branches over more than a day), or 'pr_only' "
+ "'breaking_master' (failing on trunk, latest trunk run still red), 'blocking_merge_queue' (stopped "
+ "a merge on a commit that already passed the PR's own CI, trunk still green), 'novel_burst' (new "
+ "within a day and spreading across branches, not on trunk yet), 'potentially_resolved' (hit trunk "
+ "but trunk is green again), 'flaky' (sporadic across branches over more than a day), or 'pr_only' "
"(confined to one branch — one PR's own problem).",
},
"first_seen": {"help_text": "Earliest failure line for this fingerprint in the analysis window."},
diff --git a/products/engineering_analytics/backend/presentation/views/suite_health.py b/products/engineering_analytics/backend/presentation/views/suite_health.py
index bf7d6833042d..29d590574c48 100644
--- a/products/engineering_analytics/backend/presentation/views/suite_health.py
+++ b/products/engineering_analytics/backend/presentation/views/suite_health.py
@@ -120,8 +120,11 @@ class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):
description=(
"The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct "
"failures (by test id + normalized error signature) and classified by how each is behaving right "
- "now — breaking trunk, a new failure spreading across branches, probably-resolved, flaky, or one "
- "PR's own problem — ranked with the most urgent first. Also returns breaking_master_jobs, the "
+ "now — breaking trunk, blocking the merge queue, a new failure spreading across branches, "
+ "probably-resolved, flaky, or one PR's own problem — ranked with the most urgent first. A "
+ "blocking_merge_queue row is a failure on a merge-queue gate branch that never hit trunk: the "
+ "commit had already passed the PR's own CI, so it is the semantic conflict the queue exists to "
+ "catch, and it is holding up landings. Also returns breaking_master_jobs, the "
"default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I "
"care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. "
"Fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and "
diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.py
index 55e795cc8e2a..4290dd845d50 100644
--- a/products/engineering_analytics/backend/tests/_github_fixtures.py
+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py
@@ -192,6 +192,7 @@ def _run_row(
pr_number: int | None = None,
head_branch: str = "main",
commit_message: str | None = None,
+ actor: str = "alice",
) -> dict[str, Any]:
return {
"id": run_id,
@@ -209,6 +210,7 @@ def _run_row(
"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,
+ "actor": json.dumps({"login": actor}),
}
diff --git a/products/engineering_analytics/backend/tests/_logic_helpers.py b/products/engineering_analytics/backend/tests/_logic_helpers.py
index 63acf3708def..c2b51d2fbaaa 100644
--- a/products/engineering_analytics/backend/tests/_logic_helpers.py
+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py
@@ -211,5 +211,19 @@ class _EndpointsWarehouseMixin(_WarehouseMixin):
_run_row(
2003, "Deploy", "sha10b", "completed", "success", _ago(1), _ago(1), pr_number=10, run_attempt=2
),
+ # PR 10 queued to merge: the gate run is credited to PR 10 (its branch names it) but
+ # its head SHA is a rebase the queue made, so it must not read as a third push.
+ _run_row(
+ 2004,
+ "Deploy",
+ "sha10queue",
+ "completed",
+ "success",
+ _ago(1),
+ _ago(1),
+ pr_number=9001,
+ head_branch="trunk-merge/pr-10/cabec75e-5181-4429-aea5-0501a52d0688",
+ actor="trunk-io[bot]",
+ ),
],
)
diff --git a/products/engineering_analytics/backend/tests/test_broken_tests.py b/products/engineering_analytics/backend/tests/test_broken_tests.py
index f4a909101fee..654e9ffd90f1 100644
--- a/products/engineering_analytics/backend/tests/test_broken_tests.py
+++ b/products/engineering_analytics/backend/tests/test_broken_tests.py
@@ -24,36 +24,59 @@ from products.engineering_analytics.backend.logic.sources import GitHubTables
# Ages are seconds-ago-from-now (smaller = more recent). last_master_hit_age is the fingerprint's most
# recent trunk failure; latest_completed_age is the matched job's newest completed run.
@pytest.mark.parametrize(
- "master_hits,age_hours,span_hours,branches,latest_conclusion,last_master_hit_age,latest_completed_age,expected",
+ "master_hits,queue_hits,pr_hits,age_hours,span_hours,branches,latest_conclusion,last_master_hit_age,latest_completed_age,expected",
[
# Breaking trunk: hit master and that job's latest run is still red — highest priority.
- (3, 5, 48, 5, "failure", 100, 50, BrokenTestState.BREAKING_MASTER),
- (1, 40, 100, 2, "timed_out", 100, 50, BrokenTestState.BREAKING_MASTER),
+ (3, 0, 5, 5, 48, 5, "failure", 100, 50, BrokenTestState.BREAKING_MASTER),
+ (1, 0, 2, 40, 100, 2, "timed_out", 100, 50, BrokenTestState.BREAKING_MASTER),
# Breaking wins even when the row also looks novel (fresh + spreading).
- (3, 5, 5, 4, "failure", 100, 50, BrokenTestState.BREAKING_MASTER),
+ (3, 0, 4, 5, 5, 4, "failure", 100, 50, BrokenTestState.BREAKING_MASTER),
+ # Trunk breakage outranks a merge-queue hit: a broadly-failing test fails on gate branches
+ # too, and must still classify by its trunk behavior.
+ (3, 4, 5, 5, 48, 5, "failure", 100, 50, BrokenTestState.BREAKING_MASTER),
+ # Gate-only: failed at the gate and nowhere else, so the commit had already passed the PR's
+ # own CI. A single gate branch would otherwise read as pr_only, the lowest signal.
+ (0, 1, 0, 5, 2, 1, None, 0, None, BrokenTestState.BLOCKING_MERGE_QUEUE),
+ # Across several merge attempts it would read as novel_burst instead — still the wrong shape.
+ (0, 3, 0, 5, 5, 4, None, 0, None, BrokenTestState.BLOCKING_MERGE_QUEUE),
+ # But a test that also fails on ordinary PR branches is a flake that happened to hit the gate
+ # by breadth, not a conflict with trunk — it keeps the shape it actually has.
+ (0, 1, 6, 100, 48, 3, None, 0, None, BrokenTestState.FLAKY),
+ (0, 1, 6, 5, 5, 4, None, 0, None, BrokenTestState.NOVEL_BURST),
# Novel burst: fresh (<24h), spread across >=3 branches, never on trunk.
- (0, 5, 5, 4, None, 0, None, BrokenTestState.NOVEL_BURST),
+ (0, 0, 5, 5, 5, 4, None, 0, None, BrokenTestState.NOVEL_BURST),
# Hit trunk but the green run finished AFTER the last failure (100 < 1000) — a real recovery.
- (2, 40, 100, 3, "success", 1000, 100, BrokenTestState.POTENTIALLY_RESOLVED),
+ (2, 0, 3, 40, 100, 3, "success", 1000, 100, BrokenTestState.POTENTIALLY_RESOLVED),
# Green but STALE: the green predates the last trunk failure (1000 > 100), so the warehouse is
# just lagging the fresher logs — not resolved, falls through to flaky.
- (2, 40, 100, 3, "success", 100, 1000, BrokenTestState.FLAKY),
+ (2, 0, 3, 40, 100, 3, "success", 100, 1000, BrokenTestState.FLAKY),
# Flaky: sporadic across >=2 branches over more than a day, not on trunk.
- (0, 100, 48, 3, None, 0, None, BrokenTestState.FLAKY),
+ (0, 0, 5, 100, 48, 3, None, 0, None, BrokenTestState.FLAKY),
# Degradation: hit trunk but no job status (source unsynced) — falls through, not misreported.
- (3, 100, 48, 3, None, 100, None, BrokenTestState.FLAKY),
+ (3, 0, 5, 100, 48, 3, None, 100, None, BrokenTestState.FLAKY),
# PR-only: one branch, recent, short span — the lowest signal.
- (0, 5, 2, 1, None, 0, None, BrokenTestState.PR_ONLY),
+ (0, 0, 2, 5, 2, 1, None, 0, None, BrokenTestState.PR_ONLY),
# Not novel (only 2 branches) and not flaky (span within a day) → PR-only.
- (0, 5, 10, 2, None, 0, None, BrokenTestState.PR_ONLY),
+ (0, 0, 3, 5, 10, 2, None, 0, None, BrokenTestState.PR_ONLY),
],
)
def test_classify_states(
- master_hits, age_hours, span_hours, branches, latest_conclusion, last_master_hit_age, latest_completed_age, expected
+ master_hits,
+ queue_hits,
+ pr_hits,
+ age_hours,
+ span_hours,
+ branches,
+ latest_conclusion,
+ last_master_hit_age,
+ latest_completed_age,
+ expected,
):
assert (
_classify(
master_hits=master_hits,
+ merge_queue_hits=queue_hits,
+ pr_branch_hits=pr_hits,
age_hours=age_hours,
span_hours=span_hours,
branches=branches,
@@ -96,6 +119,8 @@ def _fp_row(
age=100,
span=48,
last_master_hit_age=500,
+ merge_queue_hits=0,
+ pr_branch_hits=1,
):
# Column order mirrors _FINGERPRINTS_SELECT (workflow_name + last_master_hit_age appended last).
return (
@@ -110,6 +135,8 @@ def _fp_row(
10,
branches,
master_hits,
+ merge_queue_hits,
+ pr_branch_hits,
"PostHog/posthog",
latest_run_id,
"some-branch",
diff --git a/products/engineering_analytics/backend/tests/test_job_costs.py b/products/engineering_analytics/backend/tests/test_job_costs.py
index b262e6cc65c2..e22bd141ae10 100644
--- a/products/engineering_analytics/backend/tests/test_job_costs.py
+++ b/products/engineering_analytics/backend/tests/test_job_costs.py
@@ -119,6 +119,20 @@ class TestJobCostsViewParity(ClickhouseTestMixin, BaseTest):
self.addCleanup(cleanup)
return table.name
+ def test_exposed_view_columns_match_the_field_contract(self) -> None:
+ # The view body projects its column list through four nested SELECTs. Appending to FIELDS but
+ # missing a layer yields a query that still runs and silently drops the column from the
+ # exposed view, so assert the two agree — the same guard ci_job_history has.
+ jobs_table = self._create_table("github_workflow_jobs", WORKFLOW_JOBS_COLUMNS, [_job_row(0, *_MATRIX[0][1:])])
+ runs_table = self._create_table(
+ "github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [dict.fromkeys(WORKFLOW_RUNS_COLUMNS)]
+ )
+ query = job_costs.build_query(jobs_table=jobs_table, runs_table=runs_table)
+ columns = execute_hogql_query(
+ query=f"SELECT * FROM ({query})", team=self.team, query_type="engineering_analytics.test"
+ ).columns
+ assert columns == list(job_costs.FIELDS)
+
def test_view_matches_python_cost_model(self) -> None:
jobs_table = self._create_table(
"github_workflow_jobs",
diff --git a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py b/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
index 1698813903bb..ad4043ad10d6 100644
--- a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
+++ b/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
@@ -294,7 +294,10 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
assert by_number[13].author.is_bot is True # '[bot]' suffix branch
assert by_number[16].author.is_bot is True # KNOWN_BOT_HANDLES allowlist branch
# pushes = distinct head SHAs across runs attributed to the PR; rerun_cycles = 2nd+ attempts.
+ # PR 10 also has a merge-queue gate run credited to it. That run is CI the PR paid for, but
+ # its head SHA is a rebase the queue made, so it must not inflate the author's push count.
assert (by_number[10].pushes, by_number[10].rerun_cycles) == (2, 1)
+ assert {sample.head_sha for sample in by_number[10].push_history} == {"sha10", "sha10b"}
assert (by_number[11].pushes, by_number[11].rerun_cycles) == (1, 0)
assert by_number[12].pushes == 0 # no runs attributed to this PR
assert by_number[10].estimated_cost_usd is None # no jobs source seeded here → no cost figure
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index 54f57cda15ec..a255785b0637 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -91,6 +91,25 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
),
_pr_row(11, "dependabot[bot]", "closed", 0, "2026-01-11 10:00:00", merged_at="2026-01-11 12:00:00"),
_pr_row(12, "charlie", "open", 1, "2026-01-08 10:00:00"),
+ _pr_row(
+ 13,
+ "trunk-io[bot]",
+ "open",
+ 1,
+ "2026-01-13 10:00:00",
+ head_ref="trunk-merge/pr-10/cabec75e-5181-4429-aea5-0501a52d0688",
+ ),
+ # Same branch shape, ordinary author: branch names are contributor-controlled, so
+ # dropping on the shape alone would let anyone delete their own PR from every surface
+ # here (or someone else's runs onto a PR of their choosing).
+ _pr_row(
+ 14,
+ "mallory",
+ "open",
+ 0,
+ "2026-01-14 10:00:00",
+ head_ref="trunk-merge/pr-10/deadbeef-0000-0000-0000-000000000000",
+ ),
],
)
@@ -119,6 +138,11 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
assert by_number[12][6] == "open"
assert by_number[12][7] == 1
assert by_number[12][9] is None
+ # A merge-queue gate branch is a CI artifact, not a PR — dropped here so no PR surface
+ # (list, cards, medians) has to remember to exclude it. Only when the queue bot authored it:
+ # PR 14 wears the same branch shape but a human's name, and must survive.
+ assert 13 not in by_number
+ assert 14 in by_number
def test_workflow_runs_view_maps_columns(self) -> None:
table_name = self._create_table(
@@ -128,18 +152,52 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
_run_row(2001, "CI", "sha1", "completed", "success", "2026-01-20 10:00:00", "2026-01-20 10:30:00"),
_run_row(2002, "CI", "sha2", "completed", "failure", "2026-01-22 10:00:00", "2026-01-22 10:45:00"),
_run_row(2003, "Deploy", "sha3", "in_progress", None, "2026-01-25 10:00:00", "2026-01-25 10:05:00"),
+ _run_row(
+ 2004,
+ "CI",
+ "sha4",
+ "completed",
+ "success",
+ "2026-01-26 10:00:00",
+ "2026-01-26 10:20:00",
+ # A gate run's own association names the throwaway PR the queue opened (9001);
+ # the branch names the PR being landed (44), which is the one every surface asks
+ # about. Reading the association here loses the gate run from that PR's rollup
+ # and cost, and files it under a PR no surface shows.
+ pr_number=9001,
+ head_branch="trunk-merge/pr-44/cabec75e-5181-4429-aea5-0501a52d0688",
+ actor="trunk-io[bot]",
+ ),
+ # Same branch shape, ordinary actor. Branch names are contributor-controlled, so on
+ # the shape alone this would re-key a stranger's runs and CI cost onto PR 44.
+ _run_row(
+ 2005,
+ "CI",
+ "sha5",
+ "completed",
+ "success",
+ "2026-01-27 10:00:00",
+ "2026-01-27 10:20:00",
+ pr_number=9002,
+ head_branch="trunk-merge/pr-44/deadbeef-0000-0000-0000-000000000000",
+ actor="mallory",
+ ),
],
)
rows = self._select(
- "SELECT workflow_name, status, conclusion, duration_seconds, repo_owner, repo_name "
+ "SELECT workflow_name, status, conclusion, duration_seconds, repo_owner, repo_name, "
+ "pr_number, is_merge_queue "
f"FROM ({workflow_runs.build_query(table_name)}) AS r ORDER BY id"
)
# completed runs carry a duration; in-progress run has null duration and null conclusion
- assert rows[0] == ("CI", "completed", "success", 1800, "PostHog", "posthog")
+ assert rows[0][:6] == ("CI", "completed", "success", 1800, "PostHog", "posthog")
assert rows[1][3] == 2700
- assert rows[2] == ("Deploy", "in_progress", None, None, "PostHog", "posthog")
+ assert rows[2][:6] == ("Deploy", "in_progress", None, None, "PostHog", "posthog")
+ assert rows[3][6:] == (44, 1)
+ # Spoofed shape without the queue actor: attribution stays on the run's own association.
+ assert rows[4][6:] == (9002, 0)
def test_pull_requests_view_handles_null_user(self) -> None:
# The real source lands user as Nullable(String), NULL for a PR by a deleted GitHub account.
@@ -163,20 +221,24 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
def test_workflow_runs_view_handles_null_pull_requests(self) -> None:
# The real source lands pull_requests as Nullable(String), so it can be NULL (a run with no
# PR association). The builder's ifNull(pull_requests, '[]') guard must carry that NULL to
- # pr_number = 0 (unattributed), never letting JSONExtractArrayRaw see a Nullable. Driven
- # through an inline constant source (nullIf('', '') is a typed NULL) so it exercises the
- # guard whether or not object storage is available — unlike the table-backed tests, which
- # skip without it.
+ # pr_number = 0 (unattributed), never letting JSONExtractArrayRaw see a Nullable. ``actor``
+ # is Nullable the same way, and it gates the merge-queue branch parse — a NULL there must
+ # read as "not the queue", not poison the whole expression to NULL. Driven through an inline
+ # constant source (nullIf('', '') is a typed NULL) so it exercises the guards whether or not
+ # object storage is available — unlike the table-backed tests, which skip without it.
repo_json = '{"full_name": "PostHog/posthog"}'
raw = (
- "(SELECT 1 AS id, 'CI' AS name, 'sha1' AS head_sha, 'main' AS head_branch, 'completed' AS status, "
+ "(SELECT 1 AS id, 'CI' AS name, 'sha1' AS head_sha, "
+ "'trunk-merge/pr-44/cabec75e' AS head_branch, 'completed' AS status, "
"'success' AS conclusion, 1 AS run_attempt, nullIf('', '') AS pull_requests, "
- f"'{repo_json}' AS repository, nullIf('', '') AS head_commit, "
+ f"'{repo_json}' AS repository, nullIf('', '') AS head_commit, nullIf('', '') AS actor, "
"'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")
+ rows = self._select(
+ f"SELECT pr_number, repo_owner, repo_name, is_merge_queue FROM ({workflow_runs.build_query(raw)}) AS r"
+ )
+ assert rows[0] == (0, "PostHog", "posthog", 0)
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
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 4c8cd753b189..ea07a9f9aae8 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -27,6 +27,7 @@ export interface WorkflowCostApi {
/**
* * `breaking_master` - BREAKING_MASTER
+ * * `blocking_merge_queue` - BLOCKING_MERGE_QUEUE
* * `novel_burst` - NOVEL_BURST
* * `potentially_resolved` - POTENTIALLY_RESOLVED
* * `flaky` - FLAKY
@@ -36,6 +37,7 @@ export type BrokenTestRowStateEnumApi = (typeof BrokenTestRowStateEnumApi)[keyof
export const BrokenTestRowStateEnumApi = {
BreakingMaster: 'breaking_master',
+ BlockingMergeQueue: 'blocking_merge_queue',
NovelBurst: 'novel_burst',
PotentiallyResolved: 'potentially_resolved',
Flaky: 'flaky',
@@ -53,9 +55,10 @@ export interface BrokenTestRowApi {
job_name: string
/** 'owner/name' repository the failure belongs to. */
repo: string
- /** The classifier's verdict on how this failure is behaving right now: 'breaking_master' (failing on trunk, latest trunk run still red), 'novel_burst' (new within a day and spreading across branches, not on trunk yet), 'potentially_resolved' (hit trunk but trunk is green again), 'flaky' (sporadic across branches over more than a day), or 'pr_only' (confined to one branch — one PR's own problem).
+ /** The classifier's verdict on how this failure is behaving right now: 'breaking_master' (failing on trunk, latest trunk run still red), 'blocking_merge_queue' (stopped a merge on a commit that already passed the PR's own CI, trunk still green), 'novel_burst' (new within a day and spreading across branches, not on trunk yet), 'potentially_resolved' (hit trunk but trunk is green again), 'flaky' (sporadic across branches over more than a day), or 'pr_only' (confined to one branch — one PR's own problem).
*
* * `breaking_master` - BREAKING_MASTER
+ * * `blocking_merge_queue` - BLOCKING_MERGE_QUEUE
* * `novel_burst` - NOVEL_BURST
* * `potentially_resolved` - POTENTIALLY_RESOLVED
* * `flaky` - FLAKY
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 3b47ecef2f4c..8c8da30388ac 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -118,7 +118,7 @@ export const getEngineeringAnalyticsBrokenTestsUrl = (
}
/**
- * The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct failures (by test id + normalized error signature) and classified by how each is behaving right now — breaking trunk, a new failure spreading across branches, probably-resolved, flaky, or one PR's own problem — ranked with the most urgent first. Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. Fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported.
+ * The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct failures (by test id + normalized error signature) and classified by how each is behaving right now — breaking trunk, blocking the merge queue, a new failure spreading across branches, probably-resolved, flaky, or one PR's own problem — ranked with the most urgent first. A blocking_merge_queue row is a failure on a merge-queue gate branch that never hit trunk: the commit had already passed the PR's own CI, so it is the semantic conflict the queue exists to catch, and it is holding up landings. Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. Fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported.
*/
export const engineeringAnalyticsBrokenTests = async (
projectId: string,
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index 06233120d5cc..5d15e8a0bbfb 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -27,12 +27,14 @@ tools:
error signature) and classified by how each is behaving right now, most urgent first. Reach for this to
answer "what CI failures should I care about right now": it is the triage counterpart to the test-health
queue (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on
- the default branch and that job's latest run is still red, so trunk is broken now), novel_burst (first seen
- within a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but
- that job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only
- (confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs
- whose latest run is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines.
- Caveats: fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the
+ the default branch and that job's latest run is still red, so trunk is broken now), blocking_merge_queue
+ (failing only on merge-queue gate branches, so it stopped a merge on a commit that had already passed the
+ PR's own CI — the conflict-with-trunk class the queue exists to catch), novel_burst (first seen within a day
+ and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but that job is
+ green again), flaky (sporadic across two or more branches over more than a day), or pr_only (confined to one
+ branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs whose latest run
+ is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines. Caveats:
+ fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the
breaking/resolved distinction needs the job-level source synced — without it those failures fall through to
flaky/pr_only rather than being misreported. Counts are absolute, never rates (passing runs aren't in this
data).
diff --git a/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
index 3a0050523882..fa5502180e0f 100644
--- a/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
+++ b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
@@ -35,13 +35,19 @@ Copy-ready SQL for every step is in [references/investigation-queries.md](./refe
For "what CI failures should I care about right now" (before you have a specific test in hand), the
`engineering-analytics-broken-tests` MCP tool does the shape classification below across _all_ live
failures at once: it groups the last 2 days of failures by fingerprint and labels each
-`breaking_master` / `novel_burst` / `potentially_resolved` / `flaky` / `pr_only`, most urgent first,
-plus `breaking_master_jobs` (default-branch jobs whose latest run is red). Use it as the triage entry
-point, then drop into the per-failure workflow below to reach a culprit. It is the automated
-counterpart to fingerprinting by hand; the manual queries stay the way to pin a specific failure to a
-boundary and author.
+`breaking_master` / `blocking_merge_queue` / `novel_burst` / `potentially_resolved` / `flaky` /
+`pr_only`, most urgent first, plus `breaking_master_jobs` (default-branch jobs whose latest run is
+red). Use it as the triage entry point, then drop into the per-failure workflow below to reach a
+culprit. It is the automated counterpart to fingerprinting by hand; the manual queries stay the way
+to pin a specific failure to a boundary and author.
-## The three failure shapes
+`blocking_merge_queue` is the one shape the manual table below does not cover, because it looks like
+a single-branch failure and is not. The merge queue runs the full suite on a gate branch
+(`trunk-merge/pr-<n>/…`) carrying the PR rebased onto trunk, so a failure there is on a commit that
+already passed the PR's own CI: a conflict with what landed in between, not that PR's own bug. Read
+it as "this stopped a merge", and diff the PR against trunk rather than reading the PR alone.
+
+## The four failure shapes
Fingerprint the failure first (query 1 in the references), then read its shape — the classification
falls out of three columns:
@@ -49,6 +55,7 @@ falls out of three columns:
| Shape | Reading | Next step |
| --------------------------------------- | ------------------------------- | ---------------------------------------------------- |
| 1 branch, any window | That PR's own problem | Read its failure lines; done |
+| 1 `trunk-merge/pr-<n>/…` gate branch | Conflict with what landed since | Diff the PR against trunk, not the PR alone |
| Many branches, dense burst, hits master | Trunk break (master is/was red) | Boundary query → culprit (below) |
| Many branches, sporadic over days/weeks | Flaky | Corroborate with `engineering-analytics-flaky-tests` |
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index fd34ed25fe8a..1ff84504d6be 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2789,7 +2789,7 @@
}
},
"engineering-analytics-broken-tests": {
- "description": "Live CI failures over the last 2 days, grouped into distinct failures (by failing test id + a normalized error signature) and classified by how each is behaving right now, most urgent first. Reach for this to answer \"what CI failures should I care about right now\": it is the triage counterpart to the test-health queue (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on the default branch and that job's latest run is still red, so trunk is broken now), novel_burst (first seen within a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but that job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only (confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines. Caveats: fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported. Counts are absolute, never rates (passing runs aren't in this data).",
+ "description": "Live CI failures over the last 2 days, grouped into distinct failures (by failing test id + a normalized error signature) and classified by how each is behaving right now, most urgent first. Reach for this to answer \"what CI failures should I care about right now\": it is the triage counterpart to the test-health queue (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on the default branch and that job's latest run is still red, so trunk is broken now), blocking_merge_queue (failing only on merge-queue gate branches, so it stopped a merge on a commit that had already passed the PR's own CI — the conflict-with-trunk class the queue exists to catch), novel_burst (first seen within a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but that job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only (confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines. Caveats: fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported. Counts are absolute, never rates (passing runs aren't in this data).",
"category": "Engineering analytics",
"feature": "engineering_analytics",
"summary": "Broken tests triage",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index bbada233f93a..ffb69d296cb0 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2818,7 +2818,7 @@
}
},
"engineering-analytics-broken-tests": {
- "description": "Live CI failures over the last 2 days, grouped into distinct failures (by failing test id + a normalized error signature) and classified by how each is behaving right now, most urgent first. Reach for this to answer \"what CI failures should I care about right now\": it is the triage counterpart to the test-health queue (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on the default branch and that job's latest run is still red, so trunk is broken now), novel_burst (first seen within a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but that job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only (confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines. Caveats: fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported. Counts are absolute, never rates (passing runs aren't in this data).",
+ "description": "Live CI failures over the last 2 days, grouped into distinct failures (by failing test id + a normalized error signature) and classified by how each is behaving right now, most urgent first. Reach for this to answer \"what CI failures should I care about right now\": it is the triage counterpart to the test-health queue (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on the default branch and that job's latest run is still red, so trunk is broken now), blocking_merge_queue (failing only on merge-queue gate branches, so it stopped a merge on a commit that had already passed the PR's own CI — the conflict-with-trunk class the queue exists to catch), novel_burst (first seen within a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but that job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only (confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines. Caveats: fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported. Counts are absolute, never rates (passing runs aren't in this data).",
"category": "Engineering analytics",
"feature": "engineering_analytics",
"summary": "Broken tests triage",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e9bd17cfe964..de9f0fd02047 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12418,6 +12418,7 @@ export namespace Schemas {
/**
* * `breaking_master` - BREAKING_MASTER
+ * * `blocking_merge_queue` - BLOCKING_MERGE_QUEUE
* * `novel_burst` - NOVEL_BURST
* * `potentially_resolved` - POTENTIALLY_RESOLVED
* * `flaky` - FLAKY
@@ -12428,6 +12429,7 @@ export namespace Schemas {
export const BrokenTestRowStateEnum = {
BreakingMaster: 'breaking_master',
+ BlockingMergeQueue: 'blocking_merge_queue',
NovelBurst: 'novel_burst',
PotentiallyResolved: 'potentially_resolved',
Flaky: 'flaky',
@@ -12445,9 +12447,10 @@ export namespace Schemas {
job_name: string;
/** 'owner/name' repository the failure belongs to. */
repo: string;
- /** The classifier's verdict on how this failure is behaving right now: 'breaking_master' (failing on trunk, latest trunk run still red), 'novel_burst' (new within a day and spreading across branches, not on trunk yet), 'potentially_resolved' (hit trunk but trunk is green again), 'flaky' (sporadic across branches over more than a day), or 'pr_only' (confined to one branch — one PR's own problem).
+ /** The classifier's verdict on how this failure is behaving right now: 'breaking_master' (failing on trunk, latest trunk run still red), 'blocking_merge_queue' (stopped a merge on a commit that already passed the PR's own CI, trunk still green), 'novel_burst' (new within a day and spreading across branches, not on trunk yet), 'potentially_resolved' (hit trunk but trunk is green again), 'flaky' (sporadic across branches over more than a day), or 'pr_only' (confined to one branch — one PR's own problem).
*
* * `breaking_master` - BREAKING_MASTER
+ * * `blocking_merge_queue` - BLOCKING_MERGE_QUEUE
* * `novel_burst` - NOVEL_BURST
* * `potentially_resolved` - POTENTIALLY_RESOLVED
* * `flaky` - FLAKY
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index 25d324a1774b..7b68f44fea7c 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -9,7 +9,7 @@
import * as zod from 'zod'
/**
- * The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct failures (by test id + normalized error signature) and classified by how each is behaving right now — breaking trunk, a new failure spreading across branches, probably-resolved, flaky, or one PR's own problem — ranked with the most urgent first. Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. Fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported.
+ * The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct failures (by test id + normalized error signature) and classified by how each is behaving right now — breaking trunk, blocking the merge queue, a new failure spreading across branches, probably-resolved, flaky, or one PR's own problem — ranked with the most urgent first. A blocking_merge_queue row is a failure on a merge-queue gate branch that never hit trunk: the commit had already passed the PR's own CI, so it is the semantic conflict the queue exists to catch, and it is holding up landings. Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. Fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported.
*/
export const EngineeringAnalyticsBrokenTestsParams = /* @__PURE__ */ zod.object({
project_id: zod