:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(eng-analytics): centralize gate attempts (#102963)
Raúl Negrón-Otero6037bd8a37ad
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex fdb51dcdde42..9572b7c634c5 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -142,6 +142,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke- 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.+ - Every gate metric and timeline reads the same per-PR attempt rollup. Bisection probes fold into their parent attempt, probes started after merge do not affect landing metrics, and attempts before the seven-day gate lookback do not appear.- 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.- **Depot bills from the first step, not from `started_at` — the cost model uses a billed clock.** GitHub stamps a job's `started_at` the moment Depot accepts it; the machine then boots before "Set up job" runs, and Depot bills only the time after the job started running. The gap is tens of seconds per job (the other end, last step -> `completed_at`, is negligible), a few percent of billed minutes at scale. So `billed_elapsed = duration_seconds - provisioning_seconds` (clamped >= 0).- `provisioning_seconds` (the curated jobs builder) is `started_at` -> the first `steps` entry's `started_at`, and NULL when the `steps` payload is missing or empty. NULL subtracts nothing: an under-correction is honest, an over-correction is not.@@ -158,7 +159,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke- **HogQL only for analytics data.** No raw ClickHouse.- **No product Postgres DB.** Analytics data lives in the warehouse / ClickHouse; any product-config model goes on the main DB as a team-scoped model (`TeamScopedRootMixin`), never a separate DB.- **No author leaderboards or per-developer performance rankings; individual comparison is allowed.** The surveillance risk is turning developer figures into an ordered population or a performance scorecard. It is not an engineer inspecting their own friction, and not a comparison with a colleague they already know. Author figures may therefore be read one author at a time, and compared deliberately with another author, a GitHub team, or the repository. The product must not rank, sort, score or enumerate authors by delivery or CI/PR figures, and a team view must never break its aggregate down into a per-member ranking. The delivery reads (`delivery_summary`, `pull_request_timelines`) take exactly one scope (one author, one GitHub team, or one pull request, defined once in `logic/delivery_scope.py`) and give repository context. `delivery_comparison` gives explicit comparison context: one author's ready-to-merge medians next to the aggregate of the relevant teams and the repository, and next to another author's figures when the person asking named that author. It does not discover, order or return a population of authors. Review pace differs a lot between teams, so the repository median alone cannot say whether an author's wait is normal for the work they do. The read picks the teams from the author's own memberships by one fixed rule, defined once in the logic layer: the teams the pull request in focus asked to review, else the team asked by the most of the author's pull requests, counting each pull request once per team and only requests made in the window, else every team the author is in. Each picked team gets its own row, and teams are never pooled. What a pull request asked comes from its immutable `review_requested` issue events, never from the pull request snapshot, which drops a request once the team reviews. Without those events the rule falls through to every team the author is in. A team scope matches authors through the `team_members` snapshot and matches nothing when it isn't synced. The team page passes its owning team straight through as that scope: an ownership file's team name is already the GitHub org team slug, which `hogli owners:lint --live` validates against the org on every ownership change, so no mapping sits between the two vocabularies. The author page is reached from PR-row author links, and a colleague's page may be opened directly; `author_workflow_costs` and the delivery reads stay UI-only (MCP `enabled: false`).-- **A pull request timeline is replayed from immutable timestamps, defined once in `logic/pr_timeline.py`.** Run and job attempts, reviews and merge-queue gate runs become change points, and the state between two points follows one precedence: merge queue, out of the queue (open PRs, Trunk's current state), red checks, running checks, review state. A red stretch is labelled by what turned it green (a re-run of the same commit, the same job failing on the default branch within 12 hours, a later push), which is evidence about the cause, not proof of it. Every merge-queue state collapses into one span because the warehouse keeps no queue history. An author or team list reads CI from 30 days before the window at the earliest, so an older open pull request's timeline starts there; a single pull request is replayed whole.+- **A pull request timeline is replayed from immutable timestamps, defined once in `logic/pr_timeline.py`.** Run and job attempts, reviews and merge-queue gate runs become change points, and the state between two points follows one precedence: merge queue, out of the queue (open PRs, Trunk's current state), red checks, running checks, review state. A red stretch is labelled by what turned it green (a re-run of the same commit, the same job failing on the default branch within 12 hours, a later push), which is evidence about the cause, not proof of it. Every merge-queue state collapses into one span because the warehouse keeps no queue history. An author or team list reads CI from 30 days before the window at the earliest, so an older open pull request's timeline starts there. A single pull request replays its full CI history, while its merge-queue evidence uses the shared seven-day gate lookback.- **Bot detection, defined once:** `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist; per-team config deferred.- **Bots and drafts excluded by default** in throughput / cycle-time reads; first-class in bot-impact analysis, so never strip them at the substrate.- **Time to merge** = `open_to_merge_seconds` = `merged_at - created_at`, coarse (draft + ready combined). The precise companion is `ready_to_merge_seconds` = `merged_at` minus the last observed `ready_for_review` issue event (only the last draft/ready switch counts; a draft can't merge), falling back to `created_at` for a merged PR verifiably never drafted (no transition rows and its whole open-to-merge span inside the observed issue-event window, so the transitions can't merely be unsynced). NULL means "not observed", never zero: GitHub caps the issue-events history walk, so coverage grows forward from the first sync.diff --git a/products/engineering_analytics/backend/logic/merge_queue.py b/products/engineering_analytics/backend/logic/merge_queue.pyindex 2e59c1b311a6..a264a7dc8a0a 100644--- a/products/engineering_analytics/backend/logic/merge_queue.py+++ b/products/engineering_analytics/backend/logic/merge_queue.py@@ -34,7 +34,9 @@ A queue that batched several PRs onto one gate branch would break the one-PR assshape above does — batching would need a new shape here, not a new rule at each call site."""-from datetime import timedelta+from datetime import datetime, timedelta++from posthog.dataclasses import frozen# 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``@@ -52,6 +54,16 @@ MERGE_QUEUE_BOT_HANDLES: frozenset[str] = frozenset({"trunk-io[bot]"})GATE_RUN_LOOKBACK = timedelta(days=7)+@frozen+class GateAttempt:+ """One merge-queue attempt for a pull request, with bisection probes folded into their parent."""++ attempt: str+ started_at: datetime+ completed_at: datetime | None+ failed: bool++# 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>`@@ -131,3 +143,30 @@ def gate_attempt_expr(branch_column: str) -> str:``-bisection`` suffix collapsed, so a flake-bisection probe groups with the attempt itinvestigates instead of counting as an attempt of its own."""return f"replaceRegexpOne({branch_column}, '-bisection$', '')"+++def gate_attempts_sql(+ *,+ runs_source: str,+ pull_requests_source: str,+ pull_request_filter: str,+ decisive_failure_conclusions_sql: str,+) -> str:+ """One row per merge-queue attempt, bounded before grouping so post-merge probes cannot change it."""+ return f"""+ SELECT+ r.pr_number AS pr_number,+ {gate_attempt_expr("r.head_branch")} AS attempt,+ min(r.run_started_at) AS started_at,+ max(r.updated_at) AS completed_at,+ countIf(r.status != 'completed' OR r.updated_at IS NULL) AS unfinished,+ max(r.status = 'completed' AND r.conclusion IN ({decisive_failure_conclusions_sql})) AS failed,+ any(pr.merged_at) AS merged_at+ FROM {runs_source} AS r+ INNER JOIN {pull_requests_source} AS pr ON pr.number = r.pr_number+ WHERE r.is_merge_queue+ AND r.run_started_at >= {{gate_from}}+ AND (pr.merged_at IS NULL OR r.run_started_at <= pr.merged_at)+ AND ({pull_request_filter})+ GROUP BY r.pr_number, attempt+ """diff --git a/products/engineering_analytics/backend/logic/pr_timeline.py b/products/engineering_analytics/backend/logic/pr_timeline.pyindex 5e82890a6887..ac2688533de0 100644--- a/products/engineering_analytics/backend/logic/pr_timeline.py+++ b/products/engineering_analytics/backend/logic/pr_timeline.py@@ -33,6 +33,7 @@ from products.engineering_analytics.backend.facade.contracts import (PRTimelineSegment,PRTimelineSegmentKind,)+from products.engineering_analytics.backend.logic.merge_queue import GateAttemptfrom products.engineering_analytics.backend.logic.queries.master_failures import strip_shard_suffixfrom products.engineering_analytics.backend.logic.views.reviews import APPROVED_STATE, CHANGES_REQUESTED_STATE@@ -62,15 +63,6 @@ class RunAttempt:failed_jobs: tuple[str, ...]-@frozen-class GateAttempt:- """One merge-queue attempt for the PR: the gate branch's runs, bisection probes folded in."""-- started_at: datetime- # None while any of the attempt's runs is still running.- completed_at: datetime | None--@frozenclass ReviewVerdict:reviewer: strdiff --git a/products/engineering_analytics/backend/logic/queries/delivery_summary.py b/products/engineering_analytics/backend/logic/queries/delivery_summary.pyindex cd63b40c4189..15d6bd0b9673 100644--- a/products/engineering_analytics/backend/logic/queries/delivery_summary.py+++ b/products/engineering_analytics/backend/logic/queries/delivery_summary.py@@ -25,7 +25,7 @@ from products.engineering_analytics.backend.facade.contracts import ()from products.engineering_analytics.backend.logic.cost import PRCostAggregatefrom products.engineering_analytics.backend.logic.delivery_scope import CI_LOOKBACK, DeliveryScope, SummaryScope-from products.engineering_analytics.backend.logic.merge_queue import GATE_RUN_LOOKBACK, gate_attempt_expr+from products.engineering_analytics.backend.logic.merge_queue import GATE_RUN_LOOKBACK, GateAttempt, gate_attempts_sqlfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries._workflow_filters import (DECISIVE_FAILURE_CONCLUSIONS_SQL,@@ -84,24 +84,6 @@ _PUSHES_SELECT = f"""LIMIT {UNPAGED_SCAN_LIMIT}"""-_GATE_ATTEMPTS_SELECT = f"""- SELECT- r.pr_number AS pr_number,- __GATE_ATTEMPT__ AS attempt,- min(r.run_started_at) AS started_at,- max(r.status = 'completed' AND r.conclusion IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})) AS failed- FROM __RUNS_SOURCE__ AS r- WHERE r.is_merge_queue AND r.pr_number IN {{pr_numbers}} AND r.run_started_at >= {{gate_from}}- GROUP BY pr_number, attempt- LIMIT {UNPAGED_SCAN_LIMIT}-"""---@dataclass(frozen=True, kw_only=True)-class _GateAttempt:- started_at: datetime- failed: bool-@dataclass(frozen=True, kw_only=True)class MergedPRFacts:@@ -113,7 +95,7 @@ class MergedPRFacts:ready_to_merge_seconds: int | Noneapproved_at: list[datetime]pushed_at: list[datetime]- gate_attempts: list[_GateAttempt]+ gate_attempts: list[GateAttempt]cost: PRCostAggregate | None@property@@ -138,11 +120,6 @@ class MergedPRFacts:def pushes(self) -> int:return sum(1 for at in self.pushed_at if at <= self.merged_at)- @property- def landing_gate_attempts(self) -> list[_GateAttempt]:- # Bisection probes after the merge are not attempts to land it.- return [gate for gate in self.gate_attempts if gate.started_at <= self.merged_at]-def quantile(values: list[float], q: float) -> float | None:"""Linear-interpolation quantile (numpy's default), None over an empty list."""@@ -261,15 +238,15 @@ def _pushes_after_approval(facts: list[MergedPRFacts]) -> float | None:def _queue_attempts(facts: list[MergedPRFacts]) -> float | None:- counts = [len(f.landing_gate_attempts) for f in facts if f.landing_gate_attempts]+ counts = [len(f.gate_attempts) for f in facts if f.gate_attempts]return statistics.fmean(counts) if counts else Nonedef _failed_queue_share(facts: list[MergedPRFacts]) -> float | None:- queued = [f for f in facts if f.landing_gate_attempts]+ queued = [f for f in facts if f.gate_attempts]if not queued:return None- return sum(1 for f in queued if any(gate.failed for gate in f.landing_gate_attempts)) / len(queued)+ return sum(1 for f in queued if any(gate.failed for gate in f.gate_attempts)) / len(queued)def scope_repo_figure(@@ -392,7 +369,7 @@ def _merged_facts(*,approved_at: list[datetime],pushed_at: list[datetime] | None = None,- gate_attempts: list[_GateAttempt] | None = None,+ gate_attempts: list[GateAttempt] | None = None,cost: PRCostAggregate | None = None,) -> MergedPRFacts:return MergedPRFacts(@@ -446,9 +423,13 @@ def _query_merged_facts(gate_from = date_from - GATE_RUN_LOOKBACKgates_response = curated.run(- _GATE_ATTEMPTS_SELECT.replace("__RUNS_SOURCE__", runs_source).replace(- "__GATE_ATTEMPT__", gate_attempt_expr("r.head_branch")- ),+ gate_attempts_sql(+ runs_source=runs_source,+ pull_requests_source=curated.pr_source(),+ pull_request_filter="pr.number IN {pr_numbers} AND pr.merged_at IS NOT NULL",+ decisive_failure_conclusions_sql=DECISIVE_FAILURE_CONCLUSIONS_SQL,+ )+ + f"\nLIMIT {UNPAGED_SCAN_LIMIT}",query_type="engineering_analytics.delivery_summary_gate_attempts",placeholders={"pr_numbers": numbers,@@ -456,10 +437,17 @@ def _query_merged_facts("run_started_floor": run_started_floor_constant(gate_from),},)- gates: dict[int, list[_GateAttempt]] = defaultdict(list)- for number, _attempt, started_at, failed in gates_response.results or []:+ gates: dict[int, list[GateAttempt]] = defaultdict(list)+ for number, attempt, started_at, completed_at, unfinished, failed, _merged_at in gates_response.results or []:if started_at is not None:- gates[int(number)].append(_GateAttempt(started_at=started_at, failed=bool(failed)))+ gates[int(number)].append(+ GateAttempt(+ started_at=started_at,+ completed_at=None if unfinished else completed_at,+ attempt=attempt or "",+ failed=bool(failed),+ )+ )# A resolved source is one repository's tables, so dropping the owner and name cannot collide two# pull requests. The timelines read keeps the full key, because it shows the repository per row.diff --git a/products/engineering_analytics/backend/logic/queries/merge_queue_overview.py b/products/engineering_analytics/backend/logic/queries/merge_queue_overview.pyindex 64dcb9903724..9fbf8e6c4fa0 100644--- a/products/engineering_analytics/backend/logic/queries/merge_queue_overview.py+++ b/products/engineering_analytics/backend/logic/queries/merge_queue_overview.py@@ -16,7 +16,7 @@ from datetime import datetimefrom posthog.hogql import ast-from products.engineering_analytics.backend.logic.merge_queue import GATE_RUN_LOOKBACK, gate_attempt_expr+from products.engineering_analytics.backend.logic.merge_queue import GATE_RUN_LOOKBACK, gate_attempts_sqlfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_floatfrom products.engineering_analytics.backend.logic.queries._workflow_filters import (DECISIVE_FAILURE_CONCLUSIONS_SQL,@@ -24,12 +24,12 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters imporun_started_floor_constant,window_pair_predicates,)+from products.engineering_analytics.backend.logic.views.trunk_merge_queue import TRUNK_OUT_OF_QUEUE_STATES-# Three layers so no SELECT reads an alias it defines: the inner select groups gate runs per source-# PR, the middle names the per-PR measure, the outer splits the current and previous windows on-# merge time. ``r.run_started_at <= merged_at`` keeps post-merge bisection runs out of both the-# first-gate anchor and the attempt count; a cancelled gate run counts as an attempt but not a-# failure (an attempt evicted by a neighbor's failure is not this PR's failure).+# Three layers so no SELECT reads an alias it defines: the inner select groups attempts per source+# PR, the middle names the per-PR measure, and the outer splits the current and previous windows on+# merge time. A cancelled gate run counts as an attempt but not a failure (an attempt evicted by a+# neighbor's failure is not this PR's failure)._MERGE_QUEUE_SELECT = """SELECTcountIf(__CUR__) AS merged_cur,@@ -57,19 +57,13 @@ _MERGE_QUEUE_SELECT = """had_failed_gateFROM (SELECT- r.pr_number AS pr_number,- any(pr.merged_at) AS merged_at,- min(r.run_started_at) AS first_gate_started_at,- count(DISTINCT __GATE_ATTEMPT__) AS attempts,- max(r.status = 'completed' AND r.conclusion IN (__DECISIVE_FAILURES__)) AS had_failed_gate- FROM __RUNS_SOURCE__ AS r- INNER JOIN __PR_SOURCE__ AS pr ON pr.number = r.pr_number- WHERE r.is_merge_queue- AND r.run_started_at >= {gate_from}- AND pr.merged_at IS NOT NULL- AND r.run_started_at <= pr.merged_at- AND pr.merged_at >= {prev_from} __DATE_TO_MERGED__- GROUP BY r.pr_number+ pr_number,+ any(merged_at) AS merged_at,+ min(started_at) AS first_gate_started_at,+ count() AS attempts,+ max(failed) AS had_failed_gate+ FROM (__GATE_ATTEMPTS__)+ GROUP BY pr_number))"""@@ -131,8 +125,8 @@ _TRUNK_OUTCOMES_SELECT = """FROM (SELECTstate_changed_at,- state IN ('merged', 'failed', 'cancelled') AS concluded,- state IN ('failed', 'cancelled') AS failed_or_cancelled,+ state IN (__CONCLUDED_STATES__) AS concluded,+ state IN (__OUT_OF_QUEUE_STATES__) AS failed_or_cancelled,skip_the_lineFROM __TRUNK_SOURCE__WHERE state_changed_at >= {prev_from} __DATE_TO_CHANGED__@@ -180,11 +174,15 @@ def query_merge_queue_trunk_outcomes("prev_from": ast.Constant(value=prev_from),}date_to_changed_clause = date_to_filter_clause(date_to, placeholders, column="state_changed_at")+ out_of_queue_states = ", ".join(f"'{state}'" for state in sorted(TRUNK_OUT_OF_QUEUE_STATES))+ concluded_states = f"'merged', {out_of_queue_states}"sql = (_TRUNK_OUTCOMES_SELECT.replace("__CUR__", cur).replace("__PREV__", prev).replace("__TRUNK_SOURCE__", source).replace("__DATE_TO_CHANGED__", date_to_changed_clause)+ .replace("__CONCLUDED_STATES__", concluded_states)+ .replace("__OUT_OF_QUEUE_STATES__", out_of_queue_states))response = curated.run(sql, query_type="engineering_analytics.merge_queue_trunk_outcomes", placeholders=placeholders@@ -208,9 +206,8 @@ def query_merge_queue_overview() -> MergeQueueWindowStats:"""Merge-queue landing stats for [date_from, date_to] and [prev_from, date_from], one scan.- The population keys on ``merged_at`` like every merge median; gate runs are scanned from- ``prev_from - GATE_RUN_LOOKBACK`` so a merge near the previous window's start keeps its early- attempts.+ The population keys on ``merged_at`` like every merge median. Each comparison window applies+ ``GATE_RUN_LOOKBACK`` from its own start, while the shared source scan begins at the earlier floor."""gate_from = prev_from - GATE_RUN_LOOKBACKwindows = window_pair_predicates("merged_at", date_to=date_to)@@ -218,17 +215,23 @@ def query_merge_queue_overview("date_from": ast.Constant(value=date_from),"prev_from": ast.Constant(value=prev_from),"gate_from": ast.Constant(value=gate_from),+ "current_gate_from": ast.Constant(value=date_from - GATE_RUN_LOOKBACK),"run_started_floor": run_started_floor_constant(gate_from),}date_to_merged_clause = date_to_filter_clause(date_to, placeholders, column="pr.merged_at")+ gate_attempts = gate_attempts_sql(+ runs_source=curated.run_source(started_floor=True),+ pull_requests_source=curated.pr_source(),+ pull_request_filter="""pr.merged_at IS NOT NULL AND (+ (pr.merged_at >= {date_from} __DATE_TO_MERGED__ AND r.run_started_at >= {current_gate_from})+ OR (pr.merged_at >= {prev_from} AND pr.merged_at < {date_from})+ )""",+ decisive_failure_conclusions_sql=DECISIVE_FAILURE_CONCLUSIONS_SQL,+ ).replace("__DATE_TO_MERGED__", date_to_merged_clause)sql = (_MERGE_QUEUE_SELECT.replace("__CUR__", windows.current).replace("__PREV__", windows.previous)- .replace("__RUNS_SOURCE__", curated.run_source(started_floor=True))- .replace("__PR_SOURCE__", curated.pr_source())- .replace("__GATE_ATTEMPT__", gate_attempt_expr("r.head_branch"))- .replace("__DATE_TO_MERGED__", date_to_merged_clause)- .replace("__DECISIVE_FAILURES__", DECISIVE_FAILURE_CONCLUSIONS_SQL)+ .replace("__GATE_ATTEMPTS__", gate_attempts))response = curated.run(sql, query_type="engineering_analytics.merge_queue_overview", placeholders=placeholders)if not response.results:diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.pyindex 1ba2ccd8015d..ae5f93748028 100644--- a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py+++ b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py@@ -23,9 +23,8 @@ from products.engineering_analytics.backend.facade.contracts import (RepoRef,)from products.engineering_analytics.backend.logic.delivery_scope import CI_LOOKBACK, DeliveryScope-from products.engineering_analytics.backend.logic.merge_queue import gate_attempt_expr+from products.engineering_analytics.backend.logic.merge_queue import GATE_RUN_LOOKBACK, GateAttempt, gate_attempts_sqlfrom products.engineering_analytics.backend.logic.pr_timeline import (- GateAttempt,MasterFailureIndex,PRTimelineBuilder,PRTimelineInput,@@ -43,12 +42,10 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impo)from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_costsfrom products.engineering_analytics.backend.logic.views import issue_events+from products.engineering_analytics.backend.logic.views.trunk_merge_queue import TRUNK_OUT_OF_QUEUE_STATES_LIMIT = 200-# Trunk states that mean the entry left the queue without landing.-_OUT_OF_QUEUE_STATES = frozenset({"failed", "cancelled"})-# A list scope shows what is still open plus what merged in the window; closed-unmerged work is not# listed. A single pull request is shown whatever its state._LIST_WINDOW = "(pr.state = 'open' OR (pr.merged_at >= {date_from} __DATE_TO__))"@@ -87,8 +84,8 @@ _REVIEWS_SELECT = f"""LIMIT {UNPAGED_SCAN_LIMIT}"""-# Skipped runs add no red or running time, and _GATE_ATTEMPTS_SELECT reads gate runs. Leaving both out-# keeps this list under UNPAGED_SCAN_LIMIT.+# Skipped runs add no red or running time, and the shared gate-attempt read handles queue runs. Leaving+# both out keeps this list under UNPAGED_SCAN_LIMIT._RUNS_SELECT = f"""SELECTid, pr_number, workflow_name, head_sha, status, conclusion, run_started_at, updated_at, run_attempt, created_at@@ -98,19 +95,6 @@ _RUNS_SELECT = f"""LIMIT {UNPAGED_SCAN_LIMIT}"""-# One row per merge-queue attempt: the queue runs several workflows for each attempt.-_GATE_ATTEMPTS_SELECT = f"""- SELECT- pr_number,- min(run_started_at) AS started_at,- max(updated_at) AS completed_at,- countIf(status != 'completed' OR updated_at IS NULL) AS unfinished- FROM __RUNS_SOURCE__ AS r- WHERE pr_number IN {{pr_numbers}} AND run_started_at >= {{run_from}} AND is_merge_queue- GROUP BY pr_number, __GATE_ATTEMPT__- LIMIT {UNPAGED_SCAN_LIMIT}-"""-# One row per run attempt. Re-run copies are GitHub's re-listing of jobs that never ran again, so# they would stretch an attempt back to the previous attempt's start._JOB_ATTEMPTS_SELECT = f"""@@ -203,7 +187,7 @@ class PullRequestTimelinesQuery:ready_at = self._query_ready_at(pr_numbers, run_from)reviews = self._query_reviews(pr_numbers)attempts = self._query_run_attempts(pr_numbers, run_from)- gates = self._query_gate_attempts(pr_numbers, run_from)+ gates = self._query_gate_attempts(pr_numbers)default_branch = next((row[9] for row in prs if row[9]), "")master_failures = self._query_master_failures(attempts, default_branch, run_from)out_of_queue = self._query_out_of_queue(pr_numbers)@@ -415,19 +399,33 @@ class PullRequestTimelinesQuery:)return attempts- def _query_gate_attempts(self, pr_numbers: list[int], run_from: datetime) -> dict[int, list[GateAttempt]]:+ def _query_gate_attempts(self, pr_numbers: list[int]) -> dict[int, list[GateAttempt]]:+ gate_from = self._date_from - GATE_RUN_LOOKBACKgates_response = self._curated.run(- _GATE_ATTEMPTS_SELECT.replace("__RUNS_SOURCE__", self._curated.run_source(started_floor=True)).replace(- "__GATE_ATTEMPT__", gate_attempt_expr("r.head_branch")- ),+ gate_attempts_sql(+ runs_source=self._curated.run_source(started_floor=True),+ pull_requests_source=self._curated.pr_source(),+ pull_request_filter="pr.number IN {pr_numbers}",+ decisive_failure_conclusions_sql=DECISIVE_FAILURE_CONCLUSIONS_SQL,+ )+ + f"\nLIMIT {UNPAGED_SCAN_LIMIT}",query_type="engineering_analytics.pull_request_timelines_gate_attempts",- placeholders=self._runs_placeholders(pr_numbers, run_from),+ placeholders={+ "pr_numbers": ast.Constant(value=pr_numbers),+ "gate_from": ast.Constant(value=gate_from),+ "run_started_floor": run_started_floor_constant(gate_from),+ },)gates: dict[int, list[GateAttempt]] = defaultdict(list)- for number, started_at, completed_at, unfinished in gates_response.results or []:+ for number, attempt, started_at, completed_at, unfinished, failed, _merged_at in gates_response.results or []:if started_at is not None:gates[int(number)].append(- GateAttempt(started_at=started_at, completed_at=None if unfinished else completed_at)+ GateAttempt(+ started_at=started_at,+ completed_at=None if unfinished else completed_at,+ attempt=attempt or "",+ failed=bool(failed),+ ))return gates@@ -502,7 +500,7 @@ class PullRequestTimelinesQuery:query_type="engineering_analytics.pull_request_timelines_trunk_state",placeholders={"pr_numbers": ast.Constant(value=pr_numbers)},)- return {int(number) for number, state in response.results or [] if state in _OUT_OF_QUEUE_STATES}+ return {int(number) for number, state in response.results or [] if state in TRUNK_OUT_OF_QUEUE_STATES}def query_pull_request_timelines(diff --git a/products/engineering_analytics/backend/logic/views/trunk_merge_queue.py b/products/engineering_analytics/backend/logic/views/trunk_merge_queue.pyindex a5176deb481d..96d8a7bddaf1 100644--- a/products/engineering_analytics/backend/logic/views/trunk_merge_queue.py+++ b/products/engineering_analytics/backend/logic/views/trunk_merge_queue.py@@ -1,5 +1,7 @@"""Curated view over the Trunk merge-queue snapshot (``TRUNK_MERGE_QUEUE_COLUMNS``)."""+TRUNK_OUT_OF_QUEUE_STATES = frozenset({"failed", "cancelled"})+def build_query(table: str) -> str:"""Curated SELECT over a synced Trunk merge-queue table: parsed last-transition time, thediff --git a/products/engineering_analytics/backend/tests/test_delivery.py b/products/engineering_analytics/backend/tests/test_delivery.pyindex b7aee64a2309..894a86f5757e 100644--- a/products/engineering_analytics/backend/tests/test_delivery.py+++ b/products/engineering_analytics/backend/tests/test_delivery.py@@ -16,8 +16,8 @@ from products.engineering_analytics.backend.facade.contracts import (from products.engineering_analytics.backend.logic.census import CENSUS_EVENTfrom products.engineering_analytics.backend.logic.comparison_teams import choose_comparison_teamsfrom products.engineering_analytics.backend.logic.delivery_scope import CI_LOOKBACK, DeliveryScope, SummaryScope+from products.engineering_analytics.backend.logic.merge_queue import GateAttemptfrom products.engineering_analytics.backend.logic.pr_timeline import (- GateAttempt,MasterFailureIndex,PRTimelineBuilder,PRTimelineInput,@@ -35,6 +35,7 @@ from products.engineering_analytics.backend.logic.queries.delivery_summary imporquery_delivery_summary,scope_repo_figure,)+from products.engineering_analytics.backend.logic.queries.merge_queue_overview import query_merge_queue_overviewfrom products.engineering_analytics.backend.logic.queries.pull_request_timelines import query_pull_request_timelinesfrom products.engineering_analytics.backend.logic.views.source_schema import (DEPLOYMENT_STATUSES_COLUMNS,@@ -200,7 +201,7 @@ class TestPRTimelineBuilder(SimpleTestCase):ReviewVerdict(reviewer="ada", state="COMMENTED", submitted_at=_at(3)),ReviewVerdict(reviewer="ada", state="APPROVED", submitted_at=_at(6)),],- gates=[GateAttempt(started_at=_at(7), completed_at=_at(8))],+ gates=[GateAttempt(attempt="gate-1", started_at=_at(7), completed_at=_at(8), failed=False)],),[],[@@ -232,7 +233,7 @@ class TestPRTimelineBuilder(SimpleTestCase):10,[_attempt("a", 0, 1)],reviews=[ReviewVerdict(reviewer="ada", state="APPROVED", submitted_at=_at(1))],- gates=[GateAttempt(started_at=_at(2), completed_at=_at(3))],+ gates=[GateAttempt(attempt="gate-1", started_at=_at(2), completed_at=_at(3), failed=False)],is_open=True,trunk_out=True,),@@ -250,7 +251,7 @@ class TestPRTimelineBuilder(SimpleTestCase):10,[_attempt("a", 0, 1)],reviews=[ReviewVerdict(reviewer="ada", state="APPROVED", submitted_at=_at(1))],- gates=[GateAttempt(started_at=_at(2), completed_at=_at(3))],+ gates=[GateAttempt(attempt="gate-1", started_at=_at(2), completed_at=_at(3), failed=False)],is_merged=False,),[],@@ -511,6 +512,8 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):red_start, red_end = _ago_offset_with_duration(2, 0, 3600)fix_start, fix_end = _ago_offset_with_duration(2, 8 * 3600, 3600)gate_start, gate_end = _ago_offset_with_duration(2, 20 * 3600, 3600)+ post_merge_probe_start, post_merge_probe_end = _ago_offset_with_duration(1, 3600, 3600)+ old_gate_start, old_gate_end = _ago_offset_with_duration(20, 0, 3600)self._create_table("github_workflow_runs",WORKFLOW_RUNS_COLUMNS,@@ -530,6 +533,30 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):actor="trunk-io[bot]",),_run_row(3004, "CI", "sha22", "completed", "success", _ago(2), _ago(2), pr_number=22),+ _run_row(+ 3005,+ "CI",+ "sha21probe",+ "completed",+ "failure",+ post_merge_probe_start,+ post_merge_probe_end,+ pr_number=9002,+ head_branch="trunk-merge/pr-21/cabec75e-5181-4429-aea5-0501a52d0688-bisection",+ actor="trunk-io[bot]",+ ),+ _run_row(+ 3006,+ "CI",+ "sha26queue",+ "completed",+ "failure",+ old_gate_start,+ old_gate_end,+ pr_number=9003,+ head_branch="trunk-merge/pr-26/old",+ actor="trunk-io[bot]",+ ),],)@@ -537,10 +564,9 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):def test_summary_compares_scope_with_repo_and_flags_missing_sources(self, _name: str, scope: SummaryScope) -> None:self._seed()curated = CuratedGitHubSource.for_team(self.team)+ date_from = datetime.now(tz=UTC) - timedelta(days=7)- summary = query_delivery_summary(- curated=curated, scope=scope, date_from=datetime.now(tz=UTC) - timedelta(days=7), date_to=None- )+ summary = query_delivery_summary(curated=curated, scope=scope, date_from=date_from, date_to=None)assert (summary.opened_pr_count, summary.merged_pr_count, summary.open_pr_count, summary.draft_pr_count) == (3,@@ -557,6 +583,15 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):assert summary.median_ready_to_merge_seconds.repo == (86400 + 3 * 86400) / 2assert summary.pushes_after_approval_per_merged_pr.scope == 1assert summary.merge_queue_attempts_per_merged_pr.scope == 1+ assert summary.failed_merge_queue_share.scope == 0+ overview = query_merge_queue_overview(+ curated=curated,+ date_from=date_from,+ date_to=None,+ prev_from=date_from - timedelta(days=7),+ )+ assert overview.avg_attempts_per_merge == summary.merge_queue_attempts_per_merged_pr.scope+ assert overview.failed_gate_merge_share == summary.failed_merge_queue_share.scopeassert summary.push_count == 2assert summary.cost_per_merged_pr_usd.scope is Noneassert summary.lead_time.deploy_data_available is False