: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): add merge queue row to the weekly CI digest (#76820)
Raúl Negrón-Oterocab75a3b5a66
diff --git a/.github/scripts/eng-analytics-weekly-digest.mjs b/.github/scripts/eng-analytics-weekly-digest.mjsindex f2a745c3199d..f0fc7743e54a 100644--- a/.github/scripts/eng-analytics-weekly-digest.mjs+++ b/.github/scripts/eng-analytics-weekly-digest.mjs@@ -10,9 +10,11 @@//// GHA cron ──> GET /api/projects/:id/engineering_analytics/repo_overview/ ──> Slack//-// One native-table message (Block Kit `table`), five rows, each with its WoW delta:+// One native-table message (Block Kit `table`), six rows, each with its WoW delta:// - CI minutes: billable (self-hosted) compute minutes across the whole bill,// master and scheduled runs included.+// - └ merge queue: the slice of CI minutes spent on merge-queue batch branches+// (trunk-merge/**) — broken out so queue-settings changes get their own delta.// - min / merged PR: the same bill divided by the week's merged-PR count (bots// included — the merge population that triggered the spend).// - est. Depot $: the product's tier-laddered estimate of that spend.@@ -104,9 +106,11 @@ function fmtInt(n) {return Math.round(n).toLocaleString('en-US')}-// Minutes at CI-bill scale: '3.04M' past a million, thousands-separated below.+// Minutes at CI-bill scale: M-notation from 100k up ('3.04M', '0.38M'), thousands-separated+// below. The low threshold keeps same-unit rows — CI minutes and its merge-queue slice — in one+// notation, while a near-zero slice still reads as a plain count instead of '0.00M'.function fmtMinutes(minutes) {- return minutes >= 1_000_000 ? `${(minutes / 1_000_000).toFixed(2)}M` : fmtInt(minutes)+ return minutes >= 100_000 ? `${(minutes / 1_000_000).toFixed(2)}M` : fmtInt(minutes)}// Estimated dollars, no cents ('$13,160').@@ -162,6 +166,7 @@ function tableRows(overview) {// Null-propagating so `add`'s missing-value guard stays the only degradation path.const perPr = (minutes, merges) => (minutes != null && merges ? minutes / merges : null)add('CI minutes', overview.billable_minutes, overview.billable_minutes_prev, fmtMinutes)+ add('└ merge queue', overview.merge_queue_billable_minutes, overview.merge_queue_billable_minutes_prev, fmtMinutes)add('min / merged PR',perPr(overview.billable_minutes, overview.merged_pr_count),diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 88a58d01ce08..3b41dba21c43 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -1054,6 +1054,10 @@ class RepoOverview:billable_minutes_prev: float | Noneestimated_cost_usd: float | Noneestimated_cost_usd_prev: float | None+ # The slice of billable_minutes spent on merge-queue batch branches, broken out so queue-settings+ # changes show up as their own delta instead of hiding inside the total.+ merge_queue_billable_minutes: float | None+ merge_queue_billable_minutes_prev: float | Nonejobs_available: bool# 'master' or 'main', picked by observed run volume in the current window.default_branch: strdiff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.pyindex 9cec6d08001b..84e4209f9a56 100644--- a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py@@ -10,6 +10,16 @@ from posthog.hogql import astfrom products.engineering_analytics.backend.facade.contracts import WorkflowHealthRunScope+# Trunk's merge-queue batch branches. Trunk-specific and hardcoded like KNOWN_BOT_HANDLES;+# defined once here so every surface breaks queue spend out with the same key.+MERGE_QUEUE_BRANCH_PREFIX = "trunk-merge/"+++def merge_queue_branch_predicate(branch_sql: str) -> str:+ """True when the branch expression names a merge-queue batch branch."""+ return f"startsWith({branch_sql}, '{MERGE_QUEUE_BRANCH_PREFIX}')"++# The base duration-percentile population, for runs and jobs alike: successful instances# only. Cancelled/skipped (superseded) and failed instances end early, so including them# answers "how long until CI stopped", not "how long does CI take to pass". Jobs use thisdiff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.pyindex 2be44d527f4f..55c93aa0b611 100644--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py@@ -19,6 +19,7 @@ real $0.00). Grouped results are small, but each query keeps an explicit ``LIMITfrom collections import defaultdictfrom collections.abc import Iterable+from dataclasses import dataclassfrom datetime import datetimefrom posthog.hogql import ast@@ -48,6 +49,7 @@ from products.engineering_analytics.backend.logic.queries._curated import Curatefrom products.engineering_analytics.backend.logic.queries._workflow_filters import (branch_filter_clause,date_to_filter_clause,+ merge_queue_branch_predicate,run_scope_filter_clause,)@@ -330,8 +332,9 @@ def query_author_workflow_costs(# The window-cost shape twice over — the current window and the equal-length one before it — as# per-window conditional aggregates on one cost-source scan, so the repo hub's delta doesn't pay the# scan twice. The previous window is half-open ([prev_from, date_from)) so no run lands in both.+# __QUEUE_AGG__ rides the same scan: the merge-queue slice of each window's billable seconds._WINDOW_COST_WITH_PREV_SELECT = """- SELECT c.workflow_name AS workflow_name, __CUR_AGG__, __PREV_AGG__+ SELECT c.workflow_name AS workflow_name, __CUR_AGG__, __PREV_AGG__, __QUEUE_AGG__FROM __COST_SOURCE__ AS cWHERE c.run_started_at >= {prev_from} __DATE_TO__GROUP BY c.workflow_name@@ -339,23 +342,40 @@ _WINDOW_COST_WITH_PREV_SELECT = """"""+@dataclass(frozen=True, kw_only=True)+class WindowCostsWithPrev:+ """Per-workflow cost aggregates for a window and its previous twin, plus the merge-queue slice+ of each window's billable seconds — carried on the same scan so queue spend never needs a+ second pass over the cost source."""++ by_workflow: dict[str, PRCostAggregate]+ by_workflow_prev: dict[str, PRCostAggregate]+ merge_queue_billable_seconds: float+ merge_queue_billable_seconds_prev: float+++_EMPTY_WINDOW_COSTS = WindowCostsWithPrev(+ by_workflow={}, by_workflow_prev={}, merge_queue_billable_seconds=0.0, merge_queue_billable_seconds_prev=0.0+)++def query_workflow_window_costs_with_prev(*,curated: CuratedGitHubSource,date_from: datetime,date_to: datetime | None,prev_from: datetime,-) -> tuple[dict[str, PRCostAggregate], dict[str, PRCostAggregate]]:+) -> WindowCostsWithPrev:"""``query_workflow_window_costs`` for [date_from, date_to] and [prev_from, date_from] in one scan.- Returns ``(current, previous)``, both keyed by workflow_name; empty when the jobs source isn't synced.+ Both dicts are keyed by workflow_name; everything is empty when the jobs source isn't synced.A workflow lands in a window's dict only when it had at least one job in that window (same as theprior implementation), so a workflow present only in the other window doesn't create a phantomzero-cost entry."""cost_source = curated.job_cost_source()if cost_source is None:- return {}, {}+ return _EMPTY_WINDOW_COSTSplaceholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from),"prev_from": ast.Constant(value=prev_from),@@ -367,10 +387,16 @@ def query_workflow_window_costs_with_prev(if date_to is not None:date_to_clause = "AND c.run_started_at <= {date_to}"placeholders["date_to"] = ast.Constant(value=date_to)+ queue = merge_queue_branch_predicate("c.head_branch")+ queue_agg = (+ f"sumIf(ifNull(c.billable_seconds, 0), {queue} AND {cur}) AS queue_billable_seconds, "+ f"sumIf(ifNull(c.billable_seconds, 0), {queue} AND {prev}) AS queue_billable_seconds_prev"+ )sql = (_WINDOW_COST_WITH_PREV_SELECT.replace("__COST_SOURCE__", cost_source).replace("__CUR_AGG__", _cost_aggregates(when=cur)).replace("__PREV_AGG__", _cost_aggregates(when=prev, suffix="_prev"))+ .replace("__QUEUE_AGG__", queue_agg).replace("__DATE_TO__", date_to_clause))response = curated.run(@@ -378,6 +404,7 @@ def query_workflow_window_costs_with_prev()by_workflow_cur: dict[str, PRCostAggregate] = {}by_workflow_prev: dict[str, PRCostAggregate] = {}+ queue_billable = queue_billable_prev = 0.0for workflow_name, *columns in response.results or []:workflow = workflow_name or ""cur_agg = _aggregate(*columns[0:5])@@ -386,7 +413,14 @@ def query_workflow_window_costs_with_prev(by_workflow_cur[workflow] = cur_aggif _has_jobs(prev_agg):by_workflow_prev[workflow] = prev_agg- return by_workflow_cur, by_workflow_prev+ queue_billable += float(columns[10] or 0.0)+ queue_billable_prev += float(columns[11] or 0.0)+ return WindowCostsWithPrev(+ by_workflow=by_workflow_cur,+ by_workflow_prev=by_workflow_prev,+ merge_queue_billable_seconds=queue_billable,+ merge_queue_billable_seconds_prev=queue_billable_prev,+ )# CI cost per merged PR over time (repo hub's Cost section trend). Two bucketed scans — cost by rundiff --git a/products/engineering_analytics/backend/logic/queries/repo_overview.py b/products/engineering_analytics/backend/logic/queries/repo_overview.pyindex efe90a66f786..5a3d0f19c083 100644--- a/products/engineering_analytics/backend/logic/queries/repo_overview.py+++ b/products/engineering_analytics/backend/logic/queries/repo_overview.py@@ -292,14 +292,18 @@ def query_repo_overview()jobs_available = curated.jobs_source() is not None- cost_cur, cost_prev = query_workflow_window_costs_with_prev(+ costs = query_workflow_window_costs_with_prev(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)+ cost_cur, cost_prev = costs.by_workflow, costs.by_workflow_prev# Per-workflow figures can be None (billable time on an unknown tier) — sum what's known.billable_seconds = sum(c.billable_seconds or 0.0 for c in cost_cur.values()) if cost_cur else Nonebillable_seconds_prev = sum(c.billable_seconds or 0.0 for c in cost_prev.values()) if cost_prev else Nonecost_usd = sum(c.estimated_cost_usd or 0.0 for c in cost_cur.values()) if cost_cur else Nonecost_usd_prev = sum(c.estimated_cost_usd or 0.0 for c in cost_prev.values()) if cost_prev else None+ # The queue slice mirrors billable_minutes' null gating so both go null together.+ queue_minutes = costs.merge_queue_billable_seconds / 60 if cost_cur else None+ queue_minutes_prev = costs.merge_queue_billable_seconds_prev / 60 if cost_prev else Nonereturn RepoOverview(run_count=run_count,@@ -316,6 +320,8 @@ def query_repo_overview(billable_minutes_prev=billable_seconds_prev / 60 if billable_seconds_prev is not None else None,estimated_cost_usd=opt_float(cost_usd),estimated_cost_usd_prev=opt_float(cost_usd_prev),+ merge_queue_billable_minutes=queue_minutes,+ merge_queue_billable_minutes_prev=queue_minutes_prev,jobs_available=jobs_available,default_branch=default_branch,cost_series=series.cost,diff --git a/products/engineering_analytics/backend/presentation/serializers/workflows.py b/products/engineering_analytics/backend/presentation/serializers/workflows.pyindex c081e11c7e02..22a258efbc5f 100644--- a/products/engineering_analytics/backend/presentation/serializers/workflows.py+++ b/products/engineering_analytics/backend/presentation/serializers/workflows.py@@ -379,6 +379,16 @@ class RepoOverviewSerializer(DataclassSerializer):"help_text": "Estimated cost over the previous window; null when the job-level source isn't synced.","allow_null": True,},+ "merge_queue_billable_minutes": {+ "help_text": "Slice of billable_minutes spent on merge-queue batch branches (trunk-merge/**); "+ "null when the job-level source isn't synced.",+ "allow_null": True,+ },+ "merge_queue_billable_minutes_prev": {+ "help_text": "Merge-queue billable minutes over the previous window; null when the job-level "+ "source isn't synced.",+ "allow_null": True,+ },"jobs_available": {"help_text": "Whether the job-level source is synced (cost and queue figures exist)."},"default_branch": {"help_text": "'master' or 'main', picked by observed run volume in the window."},"cost_series_granularity": {diff --git a/products/engineering_analytics/backend/presentation/views/workflows.py b/products/engineering_analytics/backend/presentation/views/workflows.pyindex baef8834a9bb..064c5a25d98b 100644--- a/products/engineering_analytics/backend/presentation/views/workflows.py+++ b/products/engineering_analytics/backend/presentation/views/workflows.py@@ -359,8 +359,9 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):description=("Repo-level headline aggregates over a window (default -30d): run count, success rate, re-run ""cycles, merged-PR count (bots included), median PR open-to-merge (bots and drafts excluded; "- "coarse — draft and ready time fused), and billable minutes + estimated cost — each with its "- "equal-length previous-window twin so a caller can render honest deltas. Also carries the "+ "coarse — draft and ready time fused), and billable minutes + estimated cost (with the merge-queue "+ "slice of billable minutes broken out) — each with its equal-length previous-window twin so a "+ "caller can render honest deltas. Also carries the ""detected default branch and its completed-run history series (skippable via include_series=false). ""Cost figures are null until the job-level source is synced."),diff --git a/products/engineering_analytics/backend/tests/_logic_helpers.py b/products/engineering_analytics/backend/tests/_logic_helpers.pyindex 33f42bc0d48a..63acf3708def 100644--- a/products/engineering_analytics/backend/tests/_logic_helpers.py+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py@@ -78,6 +78,7 @@ def _job_row(labels: str = '["depot-ubuntu-22.04-4"]',started: str = "2026-01-01 00:00:00",completed: str = "2026-01-01 00:02:00",+ head_branch: str = "main",) -> dict[str, Any]:return {"id": job_id,@@ -88,7 +89,7 @@ def _job_row("status": "completed","conclusion": conclusion,"head_sha": "sha60",- "head_branch": "main",+ "head_branch": head_branch,"labels": labels,"runner_name": "runner-1","runner_group_name": "depot",diff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.pyindex 1629ca9cf756..b2c5af16318a 100644--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py@@ -236,22 +236,31 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):[_run_row(9500, "CI", "sha80", "completed", "success", _ago(2), _ago(2), pr_number=80),_run_row(9501, "CI", "sha81", "completed", "success", _ago(3), _ago(3), pr_number=81, run_attempt=2),+ # A merge-queue batch run: its job funds the queue slice, and only it.+ _run_row(+ 9502, "CI", "sha82q", "completed", "success", _ago(2), _ago(2), head_branch="trunk-merge/gr-1"+ ),],)self._create_table("github_workflow_jobs",WORKFLOW_JOBS_COLUMNS,- [_job_row(95000, 9500, "build", "success", labels='["depot-ubuntu-22.04-4"]')],+ [+ _job_row(95000, 9500, "build", "success", labels='["depot-ubuntu-22.04-4"]'),+ _job_row(95020, 9502, "build", "success", head_branch="trunk-merge/gr-1"),+ ],)overview = api.get_repo_overview(team=self.team, include_series=False)assert overview.merged_pr_count == 2 # 80 and 81; 82 merged long before the windowassert overview.merged_pr_count_prev == 0assert overview.median_open_to_merge_seconds == pytest.approx(8 * 86400) # bot PR 81 excluded- assert overview.run_count == 2+ assert overview.run_count == 3assert overview.rerun_cycles == 1- assert overview.billable_minutes == pytest.approx(2.0) # one 120s job on a billable tier- assert overview.estimated_cost_usd == pytest.approx(0.016) # 2 min x $0.004 x 2 (4-core)+ assert overview.billable_minutes == pytest.approx(4.0) # two 120s jobs on a billable tier+ assert overview.estimated_cost_usd == pytest.approx(0.032) # 4 min x $0.004 x 2 (4-core)+ assert overview.merge_queue_billable_minutes == pytest.approx(2.0) # only the trunk-merge/** job+ assert overview.merge_queue_billable_minutes_prev is None # no prev-window jobs, like billable_minutes_prevassert overview.cost_series == []assert overview.time_to_green_series == []assert overview.success_rate_series == []diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex 7e58b73289c3..94bb0f08bd43 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -136,6 +136,8 @@ def _repo_overview() -> contracts.RepoOverview:billable_minutes_prev=90.0,estimated_cost_usd=12.5,estimated_cost_usd_prev=11.0,+ merge_queue_billable_minutes=30.0,+ merge_queue_billable_minutes_prev=0.0,jobs_available=True,default_branch="master",cost_series=[],@@ -322,6 +324,7 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):data = response.json()assert data["merged_pr_count"] == 42assert data["merged_pr_count_prev"] == 40+ assert data["merge_queue_billable_minutes"] == 30.0 # the digest's queue row reads this keyassert data["cost_series"] == []def test_repo_overview_400_on_bad_include_series(self) -> None:diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex e188b24f2c1f..c2c6709740e2 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -911,6 +911,16 @@ export interface RepoOverviewApi {* @nullable*/estimated_cost_usd_prev: number | null+ /**+ * Slice of billable_minutes spent on merge-queue batch branches (trunk-merge/**); null when the job-level source isn't synced.+ * @nullable+ */+ merge_queue_billable_minutes: number | null+ /**+ * Merge-queue billable minutes over the previous window; null when the job-level source isn't synced.+ * @nullable+ */+ merge_queue_billable_minutes_prev: number | null/** Whether the job-level source is synced (cost and queue figures exist). */jobs_available: boolean/** 'master' or 'main', picked by observed run volume in the window. */diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex 26c12c4b6e01..3b47ecef2f4c 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -564,7 +564,7 @@ export const getEngineeringAnalyticsRepoOverviewUrl = (}/**- * Repo-level headline aggregates over a window (default -30d): run count, success rate, re-run cycles, merged-PR count (bots included), median PR open-to-merge (bots and drafts excluded; coarse — draft and ready time fused), and billable minutes + estimated cost — each with its equal-length previous-window twin so a caller can render honest deltas. Also carries the detected default branch and its completed-run history series (skippable via include_series=false). Cost figures are null until the job-level source is synced.+ * Repo-level headline aggregates over a window (default -30d): run count, success rate, re-run cycles, merged-PR count (bots included), median PR open-to-merge (bots and drafts excluded; coarse — draft and ready time fused), and billable minutes + estimated cost (with the merge-queue slice of billable minutes broken out) — each with its equal-length previous-window twin so a caller can render honest deltas. Also carries the detected default branch and its completed-run history series (skippable via include_series=false). Cost figures are null until the job-level source is synced.*/export const engineeringAnalyticsRepoOverview = async (projectId: string,diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsxindex 8fc1393a4689..055c6c5d089e 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx@@ -34,6 +34,9 @@ const OVERVIEW: RepoOverviewApi = {billable_minutes_prev: 4890,estimated_cost_usd: 412.5,estimated_cost_usd_prev: 361.0,+ // A slice of billable_minutes above, not an addition to it.+ merge_queue_billable_minutes: 1180,+ merge_queue_billable_minutes_prev: 940,jobs_available: true,default_branch: 'master',cost_series_granularity: 'day',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fee352afa8e4..d7bd39995e37 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -63309,6 +63309,16 @@ export namespace Schemas {* @nullable*/estimated_cost_usd_prev: number | null;+ /**+ * Slice of billable_minutes spent on merge-queue batch branches (trunk-merge/**); null when the job-level source isn't synced.+ * @nullable+ */+ merge_queue_billable_minutes: number | null;+ /**+ * Merge-queue billable minutes over the previous window; null when the job-level source isn't synced.+ * @nullable+ */+ merge_queue_billable_minutes_prev: number | null;/** Whether the job-level source is synced (cost and queue figures exist). */jobs_available: boolean;/** 'master' or 'main', picked by observed run volume in the window. */