: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
feat(eng-analytics): trunk-recorded merge queue outcomes (#86562)
Raúl Negrón-Otero56572ea13c39
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ff45c6adf5ea..992dd6dc201d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6268,6 +6268,10 @@ snapshots:hash: v1.k794b7964.93f0784927beb8f29f7060b98795fc4200dc169ef7f5da3fe255cf5e143c0ff3.-5znSrlummkvLSBLsYSKNzJ3Co4GxMNxsndYCtHeMmsscenes-app-engineering-analytics-repo-overview--repo-overview--light:hash: v1.k794b7964.a7c7a2d6fefcf26234d5cacdbb217130930a6c25070affd05abe74d5bce3be76.20Bs4I2_GIprl6Dj7hDuA7yYpsl0aU8Z37Xv4brbh-4+ scenes-app-engineering-analytics-repo-overview--repo-overview-with-trunk-queue-data--dark:+ hash: v1.k794b7964.4c6c1827581d663bfbb28276e2d73cf182f848f8f39444eba6455fae7f733bd5.OzZ6iginpNb78vCag84FYApu1nGgco-E28S3SxSObh4+ scenes-app-engineering-analytics-repo-overview--repo-overview-with-trunk-queue-data--light:+ hash: v1.k794b7964.f90a953f8439da15f49ebaec140a51e3fc77d27c271bdb39489155262f4c30e0.XBJrnoYWscrDRgpL9YwIWGHoNMse2ZeoaovXPXf4swAscenes-app-engineering-analytics-run-activity-chart--default--dark:hash: v1.k794b7964.7f17c5ac7c6862493f7c4d59e6e3c3146c42e3d7b08908ee1716d387c129ba64.lPsE9KrOSZee9wJq8zjqYnvk09numvEFWOn4mdCOgJEscenes-app-engineering-analytics-run-activity-chart--default--light:diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex d332ee6152b1..fe1575392986 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -1083,8 +1083,7 @@ class RepoOverview:billable_minutes_prev: float | Noneestimated_cost_usd: float | Noneestimated_cost_usd_prev: float | None- # The window's estimated cost divided by its merged-PR count (all authors) — defined here so no- # consumer re-derives the ratio with different guards. None without cost data or merges.+ # estimated_cost_usd / merged_pr_count (all authors). None without cost data or merges.cost_per_merge_usd: float | Nonecost_per_merge_usd_prev: float | None# The slice of billable_minutes spent on merge-queue batch branches, broken out so queue-settings@@ -1116,6 +1115,17 @@ class RepoOverview:# CI-outcome proxy, not the queue's own eviction record.merge_queue_failed_gate_merge_share: float | Nonemerge_queue_failed_gate_merge_share_prev: float | None+ # Trunk-recorded outcomes, present only when the team's TrunkIo warehouse source has the opt-in+ # merge-queue endpoint synced; without it consumers fall back to the failed-gate proxy above.+ # Windowed on each entry's last state change, since Trunk keeps no state history.+ merge_queue_trunk_available: bool+ # Fraction (0-1) of concluded queue entries (merged, failed, or cancelled) that ended failed or+ # cancelled, from the queue's own records.+ merge_queue_failed_or_cancelled_share: float | None+ merge_queue_failed_or_cancelled_share_prev: float | None+ # Queue entries flagged skip-the-line (prioritized past the queue order), whatever state they reached.+ merge_queue_skip_the_line_count: int | None+ merge_queue_skip_the_line_count_prev: int | None# Median wall clock for a push round to settle fully green over the window: the window-level# twin of time_to_green_series, same population and exclusions. None when no fully green rounds.median_time_to_green_seconds: float | Nonediff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 45bdff3416de..19b7066c61e4 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -27,12 +27,17 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.clickhouse.workload import Workloadfrom posthog.models.team import Team-from products.engineering_analytics.backend.logic.sources import GitHubTables, resolve_github_tables+from products.engineering_analytics.backend.logic.sources import (+ GitHubTables,+ resolve_github_tables,+ resolve_trunk_merge_queue_table,+)from products.engineering_analytics.backend.logic.views import (issue_events,job_costs,pull_requests,team_members,+ trunk_merge_queue,workflow_jobs,workflow_runs,)@@ -124,6 +129,8 @@ class CuratedGitHubSource:self._team = teamself._tables = tablesself._user_access_control = user_access_control+ self._trunk_table: str | None = None+ self._trunk_table_resolved = False@propertydef team(self) -> Team:@@ -173,6 +180,18 @@ class CuratedGitHubSource:return Nonereturn f"({workflow_jobs.build_query(self._tables.workflow_jobs)})"+ def trunk_merge_queue_source(self) -> str | None:+ """Curated Trunk merge-queue ``SELECT`` subquery, or None when no TrunkIo source has the+ opt-in merge-queue endpoint synced (the normal state) or the requesting user can't access+ one; either way consumers degrade to the GitHub-derived proxy. Resolved lazily on first+ call and cached, so probing stays as cheap as the sibling sources."""+ if not self._trunk_table_resolved:+ self._trunk_table = resolve_trunk_merge_queue_table(self._team, self._user_access_control)+ self._trunk_table_resolved = True+ if self._trunk_table is None:+ return None+ return f"({trunk_merge_queue.build_query(self._trunk_table)})"+def members_source(self) -> str | None:"""Curated team-membership ``SELECT`` subquery, or None when the optional table isn't synced."""if not self._tables.team_members:diff --git a/products/engineering_analytics/backend/logic/queries/merge_queue_overview.py b/products/engineering_analytics/backend/logic/queries/merge_queue_overview.pyindex 9016a2f67507..1d3e6289d8eb 100644--- a/products/engineering_analytics/backend/logic/queries/merge_queue_overview.py+++ b/products/engineering_analytics/backend/logic/queries/merge_queue_overview.py@@ -7,7 +7,8 @@ branch parsing of its own. The population is merged PRs with atleast one corroborated gate run: all authors, bots included, because these figures measure thequeue's mechanics, not author behavior (the locked bots/drafts recipe governs cycle-time medians,a different question). ``had_failed_gate`` is a CI-outcome proxy for eviction: the queue's own-records are not in the GitHub source.+records are not in the GitHub source. Where a team syncs them (the opt-in Trunk merge-queue+table), ``query_merge_queue_trunk_outcomes`` reads the real verdicts instead."""from dataclasses import dataclass@@ -122,6 +123,86 @@ _EMPTY_STATS = MergeQueueWindowStats()+# Trunk records each entry's terminal state directly, so eviction here is the queue's own verdict+# rather than the CI-outcome proxy above. Windowed on the entry's last state change because Trunk+# keeps no state history, so that approximates conclusion time.+_TRUNK_OUTCOMES_SELECT = """+ SELECT+ countIf(failed_or_cancelled AND __CUR__) / nullIf(countIf(concluded AND __CUR__), 0) AS failed_or_cancelled_share_cur,+ countIf(failed_or_cancelled AND __PREV__) / nullIf(countIf(concluded AND __PREV__), 0) AS failed_or_cancelled_share_prev,+ countIf(skip_the_line AND __CUR__) AS skip_the_line_cur,+ countIf(skip_the_line AND __PREV__) AS skip_the_line_prev+ FROM (+ SELECT+ state_changed_at,+ state IN ('merged', 'failed', 'cancelled') AS concluded,+ state IN ('failed', 'cancelled') AS failed_or_cancelled,+ skip_the_line+ FROM __TRUNK_SOURCE__+ WHERE state_changed_at >= {prev_from} __DATE_TO_CHANGED__+ )+"""+++@dataclass(frozen=True, kw_only=True)+class TrunkQueueOutcomes:+ """Queue outcomes from Trunk's own records, for a window and its previous twin. Everything is+ None when no TrunkIo source has the merge-queue endpoint synced (``available``)."""++ available: bool+ failed_or_cancelled_share: float | None+ failed_or_cancelled_share_prev: float | None+ skip_the_line_count: int | None+ skip_the_line_count_prev: int | None+++_TRUNK_UNAVAILABLE = TrunkQueueOutcomes(+ available=False,+ failed_or_cancelled_share=None,+ failed_or_cancelled_share_prev=None,+ skip_the_line_count=None,+ skip_the_line_count_prev=None,+)+++def query_merge_queue_trunk_outcomes(+ *,+ curated: CuratedGitHubSource,+ date_from: datetime,+ date_to: datetime | None,+ prev_from: datetime,+) -> TrunkQueueOutcomes:+ """Trunk-recorded queue outcomes for [date_from, date_to] and [prev_from, date_from], one scan;+ the unavailable shape when the opt-in Trunk merge-queue table isn't synced."""+ source = curated.trunk_merge_queue_source()+ if source is None:+ return _TRUNK_UNAVAILABLE+ cur = "(state_changed_at >= {date_from}" + (" AND state_changed_at <= {date_to})" if date_to is not None else ")")+ prev = "(state_changed_at >= {prev_from} AND state_changed_at < {date_from})"+ placeholders: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=date_from),+ "prev_from": ast.Constant(value=prev_from),+ }+ date_to_changed_clause = date_to_filter_clause(date_to, placeholders, column="state_changed_at")+ sql = (+ _TRUNK_OUTCOMES_SELECT.replace("__CUR__", cur)+ .replace("__PREV__", prev)+ .replace("__TRUNK_SOURCE__", source)+ .replace("__DATE_TO_CHANGED__", date_to_changed_clause)+ )+ response = curated.run(+ sql, query_type="engineering_analytics.merge_queue_trunk_outcomes", placeholders=placeholders+ )+ unmerged_cur, unmerged_prev, skip_cur, skip_prev = response.results[0] if response.results else (None, None, 0, 0)+ return TrunkQueueOutcomes(+ available=True,+ failed_or_cancelled_share=opt_float(unmerged_cur),+ failed_or_cancelled_share_prev=opt_float(unmerged_prev),+ skip_the_line_count=int(skip_cur or 0),+ skip_the_line_count_prev=int(skip_prev or 0),+ )++def query_merge_queue_overview(*,curated: CuratedGitHubSource,diff --git a/products/engineering_analytics/backend/logic/queries/repo_overview.py b/products/engineering_analytics/backend/logic/queries/repo_overview.pyindex 778a4e2a498c..1235c1a6b7b2 100644--- a/products/engineering_analytics/backend/logic/queries/repo_overview.py+++ b/products/engineering_analytics/backend/logic/queries/repo_overview.py@@ -38,7 +38,10 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters imporun_started_floor_constant,window_pair_predicates,)-from products.engineering_analytics.backend.logic.queries.merge_queue_overview import query_merge_queue_overview+from products.engineering_analytics.backend.logic.queries.merge_queue_overview import (+ query_merge_queue_overview,+ query_merge_queue_trunk_outcomes,+)from products.engineering_analytics.backend.logic.queries.pr_cost import (query_cost_per_merge_series,query_workflow_window_costs_with_prev,@@ -376,6 +379,7 @@ def query_repo_overview(jobs_available = curated.jobs_source() is not Nonequeue = query_merge_queue_overview(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)+ trunk = query_merge_queue_trunk_outcomes(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)time_to_green = query_time_to_green_window(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)@@ -431,6 +435,11 @@ def query_repo_overview(merge_queue_multi_attempt_merge_share_prev=queue.multi_attempt_merge_share_prev,merge_queue_failed_gate_merge_share=queue.failed_gate_merge_share,merge_queue_failed_gate_merge_share_prev=queue.failed_gate_merge_share_prev,+ merge_queue_trunk_available=trunk.available,+ merge_queue_failed_or_cancelled_share=trunk.failed_or_cancelled_share,+ merge_queue_failed_or_cancelled_share_prev=trunk.failed_or_cancelled_share_prev,+ merge_queue_skip_the_line_count=trunk.skip_the_line_count,+ merge_queue_skip_the_line_count_prev=trunk.skip_the_line_count_prev,median_time_to_green_seconds=time_to_green.median_seconds,median_time_to_green_seconds_prev=time_to_green.median_seconds_prev,jobs_available=jobs_available,diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex 2ac9c28b8157..454eab667205 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -193,6 +193,31 @@ def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:return resolved+TRUNK_MERGE_QUEUE_SCHEMA = "MergeQueuePullRequests"+++def resolve_trunk_merge_queue_table(team: Team, user_access_control: "UserAccessControl | None" = None) -> str | None:+ """The synced Trunk merge-queue table's warehouse name, or None.++ The TrunkIo source leaves its merge-queue endpoint unselected by default (it needs a target+ branch the flaky-tests endpoints don't), so absence is the normal state and every consumer+ degrades to the GitHub-derived proxy. Team-level: a Trunk source covers one merge queue, so+ the first synced table (oldest source first, for determinism) wins rather than threading repo+ scope through a source that has none. ``user_access_control`` applies the requesting user's+ per-source warehouse RBAC through the same scope the GitHub resolver uses+ (``_accessible_sources``): a user denied every TrunkIo source resolves None, degrading to the+ proxy exactly like the unsynced state.+ """+ for source in _accessible_sources(team, ExternalDataSourceType.TRUNKIO, user_access_control):+ for schema in _synced_schemas(team=team, source=source):+ if schema.name != TRUNK_MERGE_QUEUE_SCHEMA:+ continue+ table = schema.table+ if table is not None and not table.deleted and _IDENTIFIER.match(table.name):+ return table.name+ return None++# Listing the team's connected sources is its own concern (no curated read handle): it threads the# requesting user's access control so the picker can't enumerate sources the user can't access.def build_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:@@ -275,13 +300,22 @@ def _repo_candidates(*, team: Team, sources: QuerySet[ExternalDataSource]) -> Itdef _github_sources(team: Team, user_access_control: "UserAccessControl | None" = None) -> QuerySet[ExternalDataSource]:"""The team's non-deleted GitHub sources the caller may access, oldest first — the order``resolve_github_tables`` defaults from, so a picker's first entry matches the default source.+ Access scope comes from ``_accessible_sources``, shared with the Trunk resolver.+ """+ return _accessible_sources(team, ExternalDataSourceType.GITHUB, user_access_control)+- ``user_access_control`` applies the requesting user's per-source warehouse RBAC, so neither the- resolver nor the picker can reach a source the user can't access; ``None`` (system/Temporal/CLI- contexts) skips it, leaving team scoping. This is the single place that access scope is decided.+def _accessible_sources(+ team: Team, source_type: ExternalDataSourceType, user_access_control: "UserAccessControl | None"+) -> QuerySet[ExternalDataSource]:+ """The team's non-deleted sources of ``source_type`` the caller may access.++ ``user_access_control`` applies the requesting user's per-source warehouse RBAC, so no resolver+ or picker can reach a source the user can't access; ``None`` (system/Temporal/CLI contexts)+ skips it, leaving team scoping. This is the single place that access scope is decided."""sources = (- ExternalDataSource.objects.filter(team_id=team.pk, source_type=ExternalDataSourceType.GITHUB)+ ExternalDataSource.objects.filter(team_id=team.pk, source_type=source_type).exclude(deleted=True).order_by("created_at", "id"))@@ -353,6 +387,14 @@ def _as_source_uuid(source_id: str) -> UUID:raise ValueError(f"source_id must be a UUID, got: {source_id!r}") from err+def _synced_schemas(*, team: Team, source: ExternalDataSource) -> QuerySet[ExternalDataSchema]:+ return (+ ExternalDataSchema.objects.filter(team_id=team.pk, source_id=source.id, should_sync=True)+ .exclude(deleted=True)+ .select_related("table")+ )++def _synced_tables_by_repo(*, team: Team, source: ExternalDataSource) -> dict[str, dict[str, str]]:"""Map ``{repository: {endpoint: table name}}`` for a source's actively-synced curated schemas.@@ -364,13 +406,8 @@ def _synced_tables_by_repo(*, team: Team, source: ExternalDataSource) -> dict[stbare row with no legacy repo groups under ``''`` — the pre-multi-repo single-repo shape."""legacy_repo = _source_repository(source) or None- schemas = (- ExternalDataSchema.objects.filter(team_id=team.pk, source_id=source.id, should_sync=True)- .exclude(deleted=True)- .select_related("table")- )by_repo: dict[str, dict[str, str]] = {}- for schema in schemas:+ for schema in _synced_schemas(team=team, source=source):repository, endpoint = github_schema_repo_endpoint(schema.schema_metadata, schema.name, legacy_repo)if endpoint not in _CURATED_ENDPOINTS:continuediff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.pyindex 6d46d2f740c3..13be0d274a78 100644--- a/products/engineering_analytics/backend/logic/views/source_schema.py+++ b/products/engineering_analytics/backend/logic/views/source_schema.py@@ -109,3 +109,16 @@ TEAM_MEMBERS_COLUMNS: dict[str, dict[str, str]] = {"team_slug": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},"team_name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},}++# The Trunk merge-queue snapshot (TrunkIo source, opt-in MergeQueuePullRequests endpoint): one row+# per queue entry with the state it last reached. Trunk keeps no state history, so+# ``state_changed_at`` is the entry's last transition, not a timeline. Typed by the trunk_io+# pipeline (verified against a real connected source); Nullable like everything else it lands.+TRUNK_MERGE_QUEUE_COLUMNS: dict[str, dict[str, str]] = {+ "id": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "state": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "pr_number": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},+ "priority_name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "skip_the_line": {"clickhouse": "Nullable(Bool)", "hogql": "BooleanDatabaseField"},+ "state_changed_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+}diff --git a/products/engineering_analytics/backend/logic/views/trunk_merge_queue.py b/products/engineering_analytics/backend/logic/views/trunk_merge_queue.pynew file mode 100644index 000000000000..a5176deb481d--- /dev/null+++ b/products/engineering_analytics/backend/logic/views/trunk_merge_queue.py@@ -0,0 +1,16 @@+"""Curated view over the Trunk merge-queue snapshot (``TRUNK_MERGE_QUEUE_COLUMNS``)."""+++def build_query(table: str) -> str:+ """Curated SELECT over a synced Trunk merge-queue table: parsed last-transition time, the+ terminal-or-current state, and the skip-the-line flag. Rows without a state or transition+ time carry nothing any consumer can window on, so they drop here."""+ return f"""+ SELECT+ state,+ parseDateTimeBestEffort(state_changed_at) AS state_changed_at,+ ifNull(skip_the_line, false) AS skip_the_line,+ pr_number+ FROM {table}+ WHERE state IS NOT NULL AND state_changed_at IS NOT NULL+"""diff --git a/products/engineering_analytics/backend/presentation/serializers/workflows.py b/products/engineering_analytics/backend/presentation/serializers/workflows.pyindex 9792850e0d61..1cd734db671a 100644--- a/products/engineering_analytics/backend/presentation/serializers/workflows.py+++ b/products/engineering_analytics/backend/presentation/serializers/workflows.py@@ -504,6 +504,32 @@ class RepoOverviewSerializer(DataclassSerializer):"help_text": "The same fraction over the previous window. Null when no queue-landed merges.","allow_null": True,},+ "merge_queue_trunk_available": {+ "help_text": "Whether the team's TrunkIo warehouse source has the opt-in merge-queue endpoint "+ "synced and readable by the requesting user. When false, every "+ "merge_queue_failed_or_cancelled_* and merge_queue_skip_the_line_* field is null; "+ "fall back to merge_queue_failed_gate_merge_share."+ },+ "merge_queue_failed_or_cancelled_share": {+ "help_text": "Fraction (0-1) of concluded queue entries (merged, failed, or cancelled) that "+ "ended failed or cancelled, from the queue's own records. Windowed on each entry's last state "+ "change. Null when the Trunk source isn't synced or nothing concluded.",+ "allow_null": True,+ },+ "merge_queue_failed_or_cancelled_share_prev": {+ "help_text": "The same fraction over the previous window. Null when the Trunk source isn't "+ "synced or nothing concluded.",+ "allow_null": True,+ },+ "merge_queue_skip_the_line_count": {+ "help_text": "Queue entries flagged skip-the-line (prioritized past the queue order) in the "+ "window, whatever state they reached. Null when the Trunk source isn't synced.",+ "allow_null": True,+ },+ "merge_queue_skip_the_line_count_prev": {+ "help_text": "Skip-the-line entries over the previous window. Null when the Trunk source isn't synced.",+ "allow_null": True,+ },"median_time_to_green_seconds": {"help_text": "Median wall clock for a PR push round to settle fully green over the window — the ""window-level twin of time_to_green_series, same population and exclusions. Null when no fully "diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.pyindex d915190b465c..7ab6874ac317 100644--- a/products/engineering_analytics/backend/tests/_github_fixtures.py+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py@@ -1,4 +1,4 @@-"""GitHub source and warehouse-table fixtures shared across this product's test files."""+"""GitHub and Trunk source warehouse fixtures shared across this product's test files."""import osimport json@@ -59,6 +59,39 @@ def create_github_source()+def create_trunk_source(+ team: Team, *, prefix: str = "trunkprefix_", source_id: str = "trunk-source"+) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=team,+ source_id=source_id,+ connection_id=source_id,+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.TRUNKIO,+ prefix=prefix,+ job_inputs={},+ )+++def _trunk_queue_row(+ entry_id: str,+ state: str,+ pr_number: int,+ state_changed_at: str,+ *,+ skip_the_line: bool = False,+ priority_name: str = "medium",+) -> dict[str, Any]:+ return {+ "id": entry_id,+ "state": state,+ "pr_number": pr_number,+ "priority_name": priority_name,+ "skip_the_line": skip_the_line,+ "state_changed_at": state_changed_at,+ }++def link_schema(team: Team,source: ExternalDataSource,diff --git a/products/engineering_analytics/backend/tests/_logic_helpers.py b/products/engineering_analytics/backend/tests/_logic_helpers.pyindex 4ad7e0cda3f3..49ade9805608 100644--- a/products/engineering_analytics/backend/tests/_logic_helpers.py+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py@@ -172,6 +172,7 @@ class _WarehouseMixin(ClickhouseTestMixin, BaseTest):*,source: ExternalDataSource | None = None,prefix: str = GITHUB_SOURCE_PREFIX,+ schema_name: str | None = None,) -> None:# Defaults to the mixin's single shared source; pass source + prefix to seed a second# source (e.g. one GitHub source per repository) under a distinct table prefix.@@ -195,8 +196,9 @@ class _WarehouseMixin(ClickhouseTestMixin, BaseTest):source_prefix=prefix,)self.addCleanup(cleanup)- # base_name is "github_<endpoint>"; the synced schema/endpoint is its suffix.- link_schema(self.team, source, name=base_name.removeprefix("github_"), table=table)+ # base_name is "github_<endpoint>"; the synced schema/endpoint is its suffix. Non-GitHub+ # sources (Trunk) pass their endpoint's schema name explicitly.+ link_schema(self.team, source, name=schema_name or base_name.removeprefix("github_"), table=table)class _EndpointsWarehouseMixin(_WarehouseMixin):diff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.pyindex 3c2bbb43087e..7e38dc98a7b5 100644--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py@@ -17,6 +17,7 @@ from products.engineering_analytics.backend.logic.sources import GitHubTablesfrom products.engineering_analytics.backend.logic.views.source_schema import (ISSUE_EVENTS_COLUMNS,PULL_REQUESTS_COLUMNS,+ TRUNK_MERGE_QUEUE_COLUMNS,WORKFLOW_JOBS_COLUMNS,WORKFLOW_RUNS_COLUMNS,)@@ -24,7 +25,9 @@ from products.engineering_analytics.backend.tests._github_fixtures import (_issue_event_row,_pr_row,_run_row,+ _trunk_queue_row,connect_github_source_without_data,+ create_trunk_source,)from products.engineering_analytics.backend.tests._logic_helpers import (_RUN_QUERY,@@ -454,6 +457,51 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):assert overview.merge_queue_p95_first_gate_to_merge_seconds == pytest.approx(1.95 * 86400)assert overview.merge_queue_p99_first_gate_to_merge_seconds == pytest.approx(1.99 * 86400)assert overview.merge_queue_median_first_gate_to_merge_seconds_prev is None+ # No TrunkIo source connected: the Trunk-recorded outcomes read unavailable, never zero.+ assert overview.merge_queue_trunk_available is False+ assert overview.merge_queue_failed_or_cancelled_share is None+ assert overview.merge_queue_skip_the_line_count is None++ def test_repo_overview_trunk_queue_outcomes(self) -> None:+ # Guards the Trunk-recorded outcomes: only concluded states enter the share's denominator,+ # and windowing keys on each entry's last state change.+ self._create_table(+ "github_pull_requests",+ PULL_REQUESTS_COLUMNS,+ [_pr_row(80, "alice", "closed", 0, _ago(10), merged_at=_ago(2), head_sha="sha80")],+ )+ self._create_table(+ "github_workflow_runs",+ WORKFLOW_RUNS_COLUMNS,+ [_run_row(9500, "CI", "sha80", "completed", "success", _ago(2), _ago(2), pr_number=80)],+ )+ trunk = create_trunk_source(self.team)+ self._create_table(+ "trunk_io_merge_queue_pull_requests",+ TRUNK_MERGE_QUEUE_COLUMNS,+ [+ _trunk_queue_row("q1", "merged", 80, _ago(2), skip_the_line=True),+ _trunk_queue_row("q2", "merged", 81, _ago(3)),+ _trunk_queue_row("q3", "merged", 82, _ago(4)),+ _trunk_queue_row("q4", "failed", 83, _ago(5)),+ _trunk_queue_row("q5", "cancelled", 84, _ago(6)),+ # Still testing: concluded nothing, so it enters no denominator.+ _trunk_queue_row("q6", "testing", 85, _ago(1)),+ # Previous window (a -30d window's prev twin covers [-60d, -30d)).+ _trunk_queue_row("q7", "failed", 60, _ago(45)),+ _trunk_queue_row("q8", "merged", 61, _ago(44), skip_the_line=True),+ ],+ source=trunk,+ prefix="trunkprefix_",+ schema_name="MergeQueuePullRequests",+ )++ overview = api.get_repo_overview(team=self.team, include_series=False)+ assert overview.merge_queue_trunk_available is True+ assert overview.merge_queue_failed_or_cancelled_share == pytest.approx(0.4) # failed + cancelled of 5 concluded+ assert overview.merge_queue_failed_or_cancelled_share_prev == pytest.approx(0.5) # 1 of 2 concluded+ assert overview.merge_queue_skip_the_line_count == 1+ assert overview.merge_queue_skip_the_line_count_prev == 1def test_repo_overview_ready_to_merge_median_and_series(self) -> None:# Guards the overview's ready_by_pr join: the headline must anchor on the last readydiff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex ed7fdb1b2d6c..4147aadef114 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -159,6 +159,11 @@ def _repo_overview() -> contracts.RepoOverview:merge_queue_multi_attempt_merge_share_prev=0.38,merge_queue_failed_gate_merge_share=0.34,merge_queue_failed_gate_merge_share_prev=0.28,+ merge_queue_trunk_available=True,+ merge_queue_failed_or_cancelled_share=0.044,+ merge_queue_failed_or_cancelled_share_prev=0.032,+ merge_queue_skip_the_line_count=8,+ merge_queue_skip_the_line_count_prev=5,median_time_to_green_seconds=780.0,median_time_to_green_seconds_prev=540.0,jobs_available=True,@@ -354,6 +359,7 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):assert data["merge_queue_billable_minutes"] == 30.0 # the digest's queue row reads this keyassert data["merge_queue_merged_pr_count"] == 38assert data["merge_queue_median_first_gate_to_merge_seconds"] == 1920.0+ assert data["merge_queue_failed_or_cancelled_share"] == 0.044assert data["median_time_to_green_seconds"] == 780.0assert data["cost_series"] == []diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.pyindex e753b01234af..918e5ee13ce9 100644--- a/products/engineering_analytics/backend/tests/test_views.py+++ b/products/engineering_analytics/backend/tests/test_views.py@@ -9,7 +9,11 @@ from posthog.constants import AvailableFeaturefrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.access_control.backend.models.access_control import AccessControl-from products.engineering_analytics.backend.logic.sources import list_github_sources+from products.engineering_analytics.backend.logic.sources import (+ TRUNK_MERGE_QUEUE_SCHEMA,+ list_github_sources,+ resolve_trunk_merge_queue_table,+)from products.engineering_analytics.backend.logic.views import pull_requests, workflow_runsfrom products.engineering_analytics.backend.logic.views.source_schema import (PULL_REQUESTS_COLUMNS,@@ -20,6 +24,9 @@ from products.engineering_analytics.backend.tests._github_fixtures import (_run_row,create_github_source,create_github_warehouse_table,+ create_trunk_source,+ create_warehouse_table_row,+ link_schema,pr_association,pr_association_entry,repo_id,@@ -61,6 +68,24 @@ class TestListGithubSourcesAccessControl(BaseTest):)assert {source.id for source in visible} == {str(mine.id), str(theirs.id)}+ def test_trunk_resolver_denied_user_resolves_none(self) -> None:+ # The trunk resolver feeds team-scoped HogQL that enforces no per-user ACL, so it must apply+ # the same source RBAC as the GitHub path: a user denied every TrunkIo source resolves None+ # (consumers degrade to the failed-gate proxy) instead of reading the queue table.+ source = create_trunk_source(self.team)+ table = create_warehouse_table_row(+ self.team, name="trunkprefix_trunk_io_merge_queue_pull_requests", source=source+ )+ link_schema(self.team, source, name=TRUNK_MERGE_QUEUE_SCHEMA, table=table)++ assert resolve_trunk_merge_queue_table(self.team) == table.name+ assert (+ resolve_trunk_merge_queue_table(self.team, UserAccessControl(user=self.user, team=self.team)) == table.name+ )++ AccessControl.objects.create(team=self.team, resource="external_data_source", access_level="none")+ assert resolve_trunk_merge_queue_table(self.team, UserAccessControl(user=self.user, team=self.team)) is None+class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):"""The curated query builders, exercised as inline subqueries over realdiff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex e3f91dae536d..d93060faaf7e 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -1041,6 +1041,28 @@ export interface RepoOverviewApi {* @nullable*/merge_queue_failed_gate_merge_share_prev: number | null+ /** Whether the team's TrunkIo warehouse source has the opt-in merge-queue endpoint synced and readable by the requesting user. When false, every merge_queue_failed_or_cancelled_* and merge_queue_skip_the_line_* field is null; fall back to merge_queue_failed_gate_merge_share. */+ merge_queue_trunk_available: boolean+ /**+ * Fraction (0-1) of concluded queue entries (merged, failed, or cancelled) that ended failed or cancelled, from the queue's own records. Windowed on each entry's last state change. Null when the Trunk source isn't synced or nothing concluded.+ * @nullable+ */+ merge_queue_failed_or_cancelled_share: number | null+ /**+ * The same fraction over the previous window. Null when the Trunk source isn't synced or nothing concluded.+ * @nullable+ */+ merge_queue_failed_or_cancelled_share_prev: number | null+ /**+ * Queue entries flagged skip-the-line (prioritized past the queue order) in the window, whatever state they reached. Null when the Trunk source isn't synced.+ * @nullable+ */+ merge_queue_skip_the_line_count: number | null+ /**+ * Skip-the-line entries over the previous window. Null when the Trunk source isn't synced.+ * @nullable+ */+ merge_queue_skip_the_line_count_prev: number | null/*** Median wall clock for a PR push round to settle fully green over the window — the window-level twin of time_to_green_series, same population and exclusions. Null when no fully green rounds.* @nullablediff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsxindex 935ceee28271..03e98d4d6d10 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx@@ -58,6 +58,11 @@ const OVERVIEW: RepoOverviewApi = {merge_queue_failed_gate_merge_share_prev: 0.28,median_time_to_green_seconds: 13 * 60,median_time_to_green_seconds_prev: 9 * 60,+ merge_queue_trunk_available: false,+ merge_queue_failed_or_cancelled_share: null,+ merge_queue_failed_or_cancelled_share_prev: null,+ merge_queue_skip_the_line_count: null,+ merge_queue_skip_the_line_count_prev: null,jobs_available: true,default_branch: 'master',cost_series: [],@@ -255,3 +260,26 @@ export const RepoOverview: Story = {render: () => <App />,parameters: { pageUrl: urls.engineeringAnalytics() },}++// The Trunk-source variant: the failed-queue-run proxy card is replaced by the queue's own+// eviction records.+const OVERVIEW_WITH_TRUNK: RepoOverviewApi = {+ ...OVERVIEW,+ merge_queue_trunk_available: true,+ merge_queue_failed_or_cancelled_share: 0.044,+ merge_queue_failed_or_cancelled_share_prev: 0.032,+ merge_queue_skip_the_line_count: 8,+ merge_queue_skip_the_line_count_prev: 5,+}++export const RepoOverviewWithTrunkQueueData: Story = {+ render: () => <App />,+ parameters: { pageUrl: urls.engineeringAnalytics() },+ decorators: [+ mswDecorator({+ get: {+ 'api/projects/:team_id/engineering_analytics/repo_overview/': OVERVIEW_WITH_TRUNK,+ },+ }),+ ],+}diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsxindex dc9c262b9279..593a680cae47 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx@@ -177,7 +177,9 @@ export function RepoOverviewScene(): JSX.Element {</Section><Section id="merge-queue" title="Merge queue" busy={overviewLoading}>- {overview && overview.merge_queue_merged_pr_count === 0 ? (+ {overview &&+ overview.merge_queue_merged_pr_count === 0 &&+ overview.merge_queue_failed_or_cancelled_share == null ? (<LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">No merge queue activity in the window.</LemonCard>@@ -207,17 +209,31 @@ export function RepoOverviewScene(): JSX.Element {loading={overviewPending}emptyText="No queue-landed merges in the window."/>- <WindowComparisonCard- title="Merges with a failed queue run"- tooltip="Share of queue-landed merges where at least one gate run failed before the merge. Derived from CI run conclusions, not the queue's own eviction records."- value={overview?.merge_queue_failed_gate_merge_share}- previousValue={overview?.merge_queue_failed_gate_merge_share_prev}- formatValue={percent}- deltaUnit="pt"- goodWhenDown- loading={overviewPending}- emptyText="No queue-landed merges in the window."- />+ {overview?.merge_queue_trunk_available ? (+ <WindowComparisonCard+ title="Left the queue unmerged"+ tooltip="Share of concluded merge queue entries that ended failed or cancelled, from the queue's own records."+ value={overview?.merge_queue_failed_or_cancelled_share}+ previousValue={overview?.merge_queue_failed_or_cancelled_share_prev}+ formatValue={(v) => percent(v, 1)}+ deltaUnit="pt"+ goodWhenDown+ loading={overviewPending}+ emptyText="No concluded queue entries in the window."+ />+ ) : (+ <WindowComparisonCard+ title="Merges with a failed queue run"+ tooltip="Share of queue-landed merges where at least one gate run failed before the merge. Derived from CI run conclusions, not the queue's own eviction records."+ value={overview?.merge_queue_failed_gate_merge_share}+ previousValue={overview?.merge_queue_failed_gate_merge_share_prev}+ formatValue={percent}+ deltaUnit="pt"+ goodWhenDown+ loading={overviewPending}+ emptyText="No queue-landed merges in the window."+ />+ )}</div>)}</Section>diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7879637ba3e2..b1685b54eeee 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -71573,6 +71573,28 @@ export namespace Schemas {* @nullable*/merge_queue_failed_gate_merge_share_prev: number | null;+ /** Whether the team's TrunkIo warehouse source has the opt-in merge-queue endpoint synced and readable by the requesting user. When false, every merge_queue_failed_or_cancelled_* and merge_queue_skip_the_line_* field is null; fall back to merge_queue_failed_gate_merge_share. */+ merge_queue_trunk_available: boolean;+ /**+ * Fraction (0-1) of concluded queue entries (merged, failed, or cancelled) that ended failed or cancelled, from the queue's own records. Windowed on each entry's last state change. Null when the Trunk source isn't synced or nothing concluded.+ * @nullable+ */+ merge_queue_failed_or_cancelled_share: number | null;+ /**+ * The same fraction over the previous window. Null when the Trunk source isn't synced or nothing concluded.+ * @nullable+ */+ merge_queue_failed_or_cancelled_share_prev: number | null;+ /**+ * Queue entries flagged skip-the-line (prioritized past the queue order) in the window, whatever state they reached. Null when the Trunk source isn't synced.+ * @nullable+ */+ merge_queue_skip_the_line_count: number | null;+ /**+ * Skip-the-line entries over the previous window. Null when the Trunk source isn't synced.+ * @nullable+ */+ merge_queue_skip_the_line_count_prev: number | null;/*** Median wall clock for a PR push round to settle fully green over the window — the window-level twin of time_to_green_series, same population and exclusions. Null when no fully green rounds.* @nullable