: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
perf(engineering-analytics): fix repo_overview digest timeout (#70494)
Raúl Negrón-Otero18ef45b95ec5
diff --git a/.github/scripts/eng-analytics-weekly-digest.mjs b/.github/scripts/eng-analytics-weekly-digest.mjsindex f1424b714024..f2a745c3199d 100644--- a/.github/scripts/eng-analytics-weekly-digest.mjs+++ b/.github/scripts/eng-analytics-weekly-digest.mjs@@ -1,10 +1,12 @@// Weekly engineering-analytics CI digest, posted to #alerts-devex on Monday.//// PULL model: this script reads the engineering_analytics product's repo_overview-// endpoint (the same curated layer that backs its MCP tools and UI) for the last-// 7 days and the 7 days before, and relays one week-over-week table to Slack. It-// does NOT re-derive any metric from the GitHub API — the product owns the-// numbers, this owns the cadence + the Slack relay.+// endpoint (the same curated layer that backs its MCP tools and UI) ONCE for the+// last 7 days — every headline ships with its equal-length previous-window twin,+// so one call carries the whole week-over-week table — and relays it to Slack. It+// asks for headlines only (include_series=false; the chart series exist for the+// UI) and does NOT re-derive any metric from the GitHub API — the product owns+// the numbers, this owns the cadence + the Slack relay.//// GHA cron ──> GET /api/projects/:id/engineering_analytics/repo_overview/ ──> Slack//@@ -52,22 +54,52 @@ async function api(action, params = {}) {if (SOURCE_ID) {url.searchParams.set('source_id', SOURCE_ID)}- const res = await fetch(url, { headers: { Authorization: `Bearer ${API_KEY}` } })+ // Bounds every attempt (the gateway answers within ~2min; this only catches a hung connection)+ // so worst-case retries stay well inside the workflow's timeout-minutes.+ const res = await fetch(url, {+ headers: { Authorization: `Bearer ${API_KEY}` },+ signal: AbortSignal.timeout(150_000),+ })const body = await res.text()+ const fail = (detail, retryable) => {+ throw Object.assign(new Error(`${action} -> ${res.status}: ${detail}`), { retryable })+ }let parsedtry {parsed = JSON.parse(body)} catch {- // A 200 with a non-JSON body (proxy interstitial, maintenance HTML) is still a failure.- throw new Error(`${action} -> ${res.status}: non-JSON response (${body.slice(0, 120)})`)+ // A non-JSON body (proxy interstitial, maintenance HTML) is still a failure whatever the+ // status — the endpoint only speaks JSON — but it's infra noise, so always worth retrying.+ fail(`non-JSON response (${body.slice(0, 120)})`, true)}if (!res.ok) {- // The endpoint 400s with a clear `detail` when no GitHub source is connected.- throw new Error(`${action} -> ${res.status}: ${parsed.detail || body}`)+ // The endpoint 400s with a clear `detail` when no GitHub source is connected — a+ // configuration error a retry can't fix; 5xx/429 are transients worth riding out.+ fail(parsed?.detail || body, res.status >= 500 || res.status === 429)}return parsed}+const RETRY_ATTEMPTS = 3+const RETRY_DELAY_MS = 30_000++// The warehouse queries share a ClickHouse cluster with everything else; a contended Monday+// morning can push one attempt past the API gateway's timeout. Ride transients out instead of+// failing the week's digest. Errors without a retryable flag (network failures, aborts) retry too.+async function apiWithRetry(action, params) {+ for (let attempt = 1; ; attempt++) {+ try {+ return await api(action, params)+ } catch (err) {+ if (err.retryable === false || attempt >= RETRY_ATTEMPTS) {+ throw err+ }+ console.warn(`${err.message} — attempt ${attempt}/${RETRY_ATTEMPTS}, retrying in ${RETRY_DELAY_MS / 1000}s`)+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))+ }+ }+}+function fmtInt(n) {return Math.round(n).toLocaleString('en-US')}@@ -112,23 +144,14 @@ function fmtDelta(current, previous) {return s.startsWith('-') ? `${s}%` : `+${s}%`}-// Merged-PR count for an overview window: the cost_series buckets are zero-filled and-// bucket-local (merges counted by merged_at), so their sum is the window's exact count.-// The series is empty until the github_workflow_jobs source syncs — null then.-function sumMerges(overview) {- if (!overview.cost_series || overview.cost_series.length === 0) {- return null- }- return overview.cost_series.reduce((total, bucket) => total + bucket.merges, 0)-}-function cell(text) {return { type: 'raw_text', text }}// One table row per metric, added only when both windows carry the value, so a-// not-yet-synced jobs source degrades to fewer rows instead of a broken message.-function tableRows(cur, prev) {+// not-yet-synced jobs source (null cost fields) or an old backend (no merged_pr_count)+// degrades to fewer rows instead of a broken message.+function tableRows(overview) {const rows = []const add = (metric, curValue, prevValue, format) => {if (curValue == null || prevValue == null) {@@ -138,11 +161,21 @@ function tableRows(cur, prev) {}// 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', cur.billable_minutes, prev.billable_minutes, fmtMinutes)- add('min / merged PR', perPr(cur.billable_minutes, sumMerges(cur)), perPr(prev.billable_minutes, sumMerges(prev)), fmtInt)- add('est. Depot $', cur.estimated_cost_usd, prev.estimated_cost_usd, fmtUsd)- add('open→merge median', cur.median_open_to_merge_seconds, prev.median_open_to_merge_seconds, fmtLongDuration)- add('re-run cycles', cur.rerun_cycles, prev.rerun_cycles, fmtInt)+ add('CI minutes', overview.billable_minutes, overview.billable_minutes_prev, fmtMinutes)+ add(+ 'min / merged PR',+ perPr(overview.billable_minutes, overview.merged_pr_count),+ perPr(overview.billable_minutes_prev, overview.merged_pr_count_prev),+ fmtInt+ )+ add('est. Depot $', overview.estimated_cost_usd, overview.estimated_cost_usd_prev, fmtUsd)+ add(+ 'open→merge median',+ overview.median_open_to_merge_seconds,+ overview.median_open_to_merge_seconds_prev,+ fmtLongDuration+ )+ add('re-run cycles', overview.rerun_cycles, overview.rerun_cycles_prev, fmtInt)return rows}@@ -189,14 +222,15 @@ async function main() {}const now = new Date()const thisFrom = new Date(now.getTime() - WEEK_MS).toISOString()- const priorFrom = new Date(now.getTime() - 2 * WEEK_MS).toISOString()- // Two window-scoped calls (not the endpoint's baked _prev twins) so the merged-count- // sum and the other rows share windows exactly.- const [cur, prev] = await Promise.all([- api('repo_overview', { date_from: thisFrom, date_to: now.toISOString() }),- api('repo_overview', { date_from: priorFrom, date_to: thisFrom }),- ])- const rows = tableRows(cur, prev)+ // One headline-only call: the endpoint bakes every metric's equal-length previous-window+ // twin (prev = [date_from - 7d, date_from)) and the merged-PR counts into the same scans,+ // so the rows share windows exactly without a second call.+ const overview = await apiWithRetry('repo_overview', {+ date_from: thisFrom,+ date_to: now.toISOString(),+ include_series: 'false',+ })+ const rows = tableRows(overview)if (rows.length === 0) {// Every metric was null (key valid but nothing synced). Fail the job so the// breakage is visible instead of posting an empty table.diff --git a/.github/workflows/eng-analytics-weekly-digest.yml b/.github/workflows/eng-analytics-weekly-digest.ymlindex 5de6fdc6aeb2..601cfcf0aa67 100644--- a/.github/workflows/eng-analytics-weekly-digest.yml+++ b/.github/workflows/eng-analytics-weekly-digest.yml@@ -30,7 +30,9 @@ permissions:jobs:digest:runs-on: ubuntu-latest- timeout-minutes: 5+ # Covers the script's worst case: 3 endpoint attempts x 150s abort plus 2 x 30s+ # backoffs (~8.5min; it retries transient 5xxs from a contended warehouse cluster), plus setup.+ timeout-minutes: 12# Never run from forks (no secret access anyway), only the canonical repo.# Manual dispatch is master-only so branch-controlled code can't run with the secrets.if: >-diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 292bd131de7d..e297cab8c4ca 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -309,6 +309,7 @@ def get_repo_overview(team: Team,date_from: str | None = None,date_to: str | None = None,+ include_series: bool = True,source_id: str | None = None,user_access_control: "UserAccessControl | None" = None,) -> RepoOverview:@@ -316,6 +317,7 @@ def get_repo_overview(curated=_authorized_source(team, source_id, user_access_control),date_from=date_from,date_to=date_to,+ include_series=include_series,)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex e9ed47d7b8e2..6c43552d0cdc 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -791,6 +791,8 @@ class RepoOverview:so the UI renders honest deltas. The previous window has the same length as the current oneand ends where it starts. Cost figures are None when the job-level source isn't synced(``jobs_available``); the PR merge median excludes bots and drafts per the locked recipe.+ The chart series are empty when the caller asked to skip them (``include_series=false``) —+ headline-only consumers like the weekly digest shouldn't pay for chart queries they never read."""run_count: int@@ -799,6 +801,10 @@ class RepoOverview:success_rate_prev: float | Nonererun_cycles: intrerun_cycles_prev: int+ # All merged PRs in the window, bots included — the merge population that triggered the CI spend,+ # so cost-per-merge ratios use the same denominator as the cost series' bucket-local merges.+ merged_pr_count: int+ merged_pr_count_prev: int# Coarse by design: merged_at - created_at (draft + ready time fused), median over PRs merged in the window.median_open_to_merge_seconds: float | Nonemedian_open_to_merge_seconds_prev: float | Nonediff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 41dca8074641..fc9103b9a5d5 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -56,7 +56,12 @@ from products.engineering_analytics.backend.logic.queries.pr_cost import (from products.engineering_analytics.backend.logic.queries.pr_lifecycle import query_pr_lifecyclefrom products.engineering_analytics.backend.logic.queries.pr_runs import query_pr_runsfrom products.engineering_analytics.backend.logic.queries.pull_request_list import query_pull_request_list-from products.engineering_analytics.backend.logic.queries.repo_overview import query_default_branch, query_repo_overview+from products.engineering_analytics.backend.logic.queries.repo_overview import (+ empty_repo_series,+ query_default_branch,+ query_repo_overview,+ query_repo_series,+)from products.engineering_analytics.backend.logic.queries.repo_run_activity import query_repo_run_activityfrom products.engineering_analytics.backend.logic.queries.workflow_health import query_workflow_healthfrom products.engineering_analytics.backend.logic.queries.workflow_jobs import query_workflow_jobs@@ -329,9 +334,17 @@ def build_repo_overview(curated: CuratedGitHubSource,date_from: str | None = None,date_to: str | None = None,+ include_series: bool = True,) -> RepoOverview:parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)- return query_repo_overview(curated=curated, date_from=parsed_from, date_to=parsed_to)+ # The one place the endpoint's include_series toggle decides anything: headline-only consumers+ # (the weekly digest) compose the empty series instead of paying the four chart scans.+ series = (+ query_repo_series(curated=curated, date_from=parsed_from, date_to=parsed_to)+ if include_series+ else empty_repo_series(date_from=parsed_from, date_to=parsed_to)+ )+ return query_repo_overview(curated=curated, date_from=parsed_from, date_to=parsed_to, series=series)def build_current_branch_health(*, curated: CuratedGitHubSource) -> CurrentBranchHealth:diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 94f4cc5da343..402b8dd52202 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -73,9 +73,11 @@ class CuratedGitHubSource:"""Curated pull-requests ``SELECT``, parenthesised for use as a subquery."""return f"({pull_requests.build_query(self._tables.pull_requests)})"- def run_source(self) -> str:- """Curated workflow-runs ``SELECT``, parenthesised for use as a subquery."""- return f"({workflow_runs.build_query(self._tables.workflow_runs)})"+ def run_source(self, *, started_floor: bool = False) -> str:+ """Curated workflow-runs ``SELECT``, parenthesised for use as a subquery. ``started_floor``+ adds the raw-string scan floor — callers must register {run_started_floor} (see+ run_started_floor_constant)."""+ return f"({workflow_runs.build_query(self._tables.workflow_runs, started_floor=started_floor)})"def jobs_source(self) -> str | None:"""Curated workflow-jobs ``SELECT`` subquery, or None when the optional jobs table isn't synced."""diff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.pyindex 33b2663916ae..d0f5b6dedc47 100644--- a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py@@ -4,7 +4,7 @@ Clauses qualify columns with ``r`` — every consuming template reads the runssource as ``FROM __RUNS_SOURCE__ AS r`` (or joins it as ``r``)."""-from datetime import datetime+from datetime import datetime, timedeltafrom posthog.hogql import ast@@ -24,6 +24,15 @@ LATEST_COMPLETED_RUN_FAILED = ()+def run_started_floor_constant(window_start: datetime) -> ast.Constant:+ """Raw-string scan floor for the runs builder's {run_started_floor} placeholder: a date-only+ string one day below the window start. Compares lexicographically below every in-window+ ISO timestamp ('2026-07-11' < '2026-07-11T...'), and the one-day slack absorbs any timezone+ offset between the window's zone and the UTC strings GitHub lands, so the coarse floor can+ never cut rows the precise parsed {date_from} filter would keep."""+ return ast.Constant(value=(window_start - timedelta(days=1)).strftime("%Y-%m-%d"))++def branch_filter_clause(branch: str | None, placeholders: dict[str, ast.Expr], *, column: str = "r.head_branch") -> str:diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.pyindex c1dffe70fbc1..ac8ccdd88934 100644--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py@@ -40,7 +40,6 @@ from products.engineering_analytics.backend.logic.queries._buckets import (Granularity,bucket_expr,normalize_bucket,- pick_granularity,window_buckets,)from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource@@ -325,7 +324,7 @@ 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. Window predicates mirror the two separate calls exactly.+# scan twice. The previous window is half-open ([prev_from, date_from)) so no run lands in both._WINDOW_COST_WITH_PREV_SELECT = """SELECT c.workflow_name AS workflow_name, __CUR_AGG__, __PREV_AGG__FROM __COST_SOURCE__ AS c@@ -357,7 +356,8 @@ def query_workflow_window_costs_with_prev("prev_from": ast.Constant(value=prev_from),}cur = "(c.run_started_at >= {date_from}" + (" AND c.run_started_at <= {date_to})" if date_to else ")")- prev = "(c.run_started_at >= {prev_from} AND c.run_started_at <= {date_from})"+ # Half-open: a run starting exactly at date_from is current, not both windows.+ prev = "(c.run_started_at >= {prev_from} AND c.run_started_at < {date_from})"date_to_clause = ""if date_to is not None:date_to_clause = "AND c.run_started_at <= {date_to}"@@ -420,19 +420,19 @@ def query_cost_per_merge_series(curated: CuratedGitHubSource,date_from: datetime,date_to: datetime | None,-) -> tuple[Granularity, list[CostPerMergeBucket]]:- """CI cost per merged PR across [date_from, date_to], bucketed to fit the window, oldest first.-- Returns ``(granularity, buckets)``. ``buckets`` is zero-filled across the whole window so the trend- has no gaps; each bucket's ``cost_per_merge_usd`` is the trailing-window ratio (see- ``_ROLLING_BUCKETS``) while ``estimated_cost_usd``/``merges`` stay bucket-local. When the job-level source isn't synced there's no cost to divide, so ``buckets`` is- empty (the UI shows the same "sync jobs" state as the other cost surfaces); the granularity is still- returned so the caller can label an empty chart consistently.+ granularity: Granularity,+) -> list[CostPerMergeBucket]:+ """CI cost per merged PR across [date_from, date_to] at ``granularity``, oldest first.++ Buckets are zero-filled across the whole window so the trend has no gaps; each bucket's+ ``cost_per_merge_usd`` is the trailing-window ratio (see ``_ROLLING_BUCKETS``) while+ ``estimated_cost_usd``/``merges`` stay bucket-local. When the job-level source isn't synced+ there's no cost to divide, so the series is empty (the UI shows the same "sync jobs" state as+ the other cost surfaces)."""- granularity = pick_granularity(date_from, date_to)cost_source = curated.job_cost_source()if cost_source is None:- return granularity, []+ return []placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}date_to_runs = ""@@ -486,7 +486,7 @@ def query_cost_per_merge_series(else None,))- return granularity, buckets+ return buckets# Per-runner-tier cost for one workflow (single-workflow page "where the spend goes" breakdown), scopeddiff --git a/products/engineering_analytics/backend/logic/queries/repo_overview.py b/products/engineering_analytics/backend/logic/queries/repo_overview.pyindex a729559d27c2..efe90a66f786 100644--- a/products/engineering_analytics/backend/logic/queries/repo_overview.py+++ b/products/engineering_analytics/backend/logic/queries/repo_overview.py@@ -4,13 +4,26 @@ One runs scan covers the current window and the equal-length window before it, severy headline number ships with its previous-window twin and the UI can render anhonest delta instead of a server-baked percentage. The PR medians (bots and draftsexcluded, per the locked cycle-time recipe) come from the PR snapshot the same way.++The four chart series are a separate concern with a separate producer+(``query_repo_series``): every series query computes unconditionally, the shared+bucket granularity is decided exactly once, and a headline-only consumer composes+``query_repo_overview`` with ``empty_repo_series`` instead of flag-switching what+the query layer computes."""+from dataclasses import dataclassfrom datetime import datetimefrom posthog.hogql import ast-from products.engineering_analytics.backend.facade.contracts import OpenToMergeBucket, PassRateBucket, RepoOverview+from products.engineering_analytics.backend.facade.contracts import (+ CostPerMergeBucket,+ OpenToMergeBucket,+ PassRateBucket,+ RepoOverview,+ TimeToGreenBucket,+)from products.engineering_analytics.backend.logic.queries._buckets import (Granularity,bucket_expr,@@ -19,6 +32,7 @@ from products.engineering_analytics.backend.logic.queries._buckets import (window_buckets,)from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float+from products.engineering_analytics.backend.logic.queries._workflow_filters import run_started_floor_constantfrom products.engineering_analytics.backend.logic.queries.pr_cost import (query_cost_per_merge_series,query_workflow_window_costs_with_prev,@@ -41,10 +55,15 @@ _RUNS_SELECT = """WHERE run_started_at >= {prev_from} __DATE_TO__"""+# Medians follow the locked cycle-time recipe (bots/drafts excluded); the merged counts deliberately+# don't — they are the merge population that triggered the CI spend, the same all-authors population+# the cost series' bucket-local merges count, so cost-per-merge ratios divide by a matching denominator._PR_SELECT = """SELECTquantileIf(0.5)(open_to_merge_seconds, __CUR_MERGED__ AND NOT is_bot AND NOT is_draft) AS median_cur,- quantileIf(0.5)(open_to_merge_seconds, __PREV_MERGED__ AND NOT is_bot AND NOT is_draft) AS median_prev+ quantileIf(0.5)(open_to_merge_seconds, __PREV_MERGED__ AND NOT is_bot AND NOT is_draft) AS median_prev,+ countIf(__CUR_MERGED__) AS merged_cur,+ countIf(__PREV_MERGED__) AS merged_prevFROM __PR_SOURCE__ AS prWHERE merged_at IS NOT NULL AND merged_at >= {prev_from}"""@@ -65,11 +84,16 @@ def query_default_branch("""'master' or 'main', by observed run volume in the window — the cheap standalone variant of thedetection the overview aggregate gets for free."""date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""- placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}+ placeholders: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=date_from),+ "run_started_floor": run_started_floor_constant(date_from),+ }if date_to is not None:placeholders["date_to"] = ast.Constant(value=date_to)response = curated.run(- _DEFAULT_BRANCH_SELECT.replace("__RUNS_SOURCE__", curated.run_source()).replace("__DATE_TO__", date_to_clause),+ _DEFAULT_BRANCH_SELECT.replace("__RUNS_SOURCE__", curated.run_source(started_floor=True)).replace(+ "__DATE_TO__", date_to_clause+ ),query_type="engineering_analytics.default_branch",placeholders=placeholders,)@@ -109,16 +133,19 @@ def query_success_rate_series(curated: CuratedGitHubSource,date_from: datetime,date_to: datetime | None,-) -> tuple[Granularity, list[PassRateBucket]]:+ granularity: Granularity,+) -> list[PassRateBucket]:"""Pass rate per bucket across the window, oldest first: completed runs that succeeded, all branches —the same population as the headline pass rate. Empty buckets carry ``success_rate`` None (a gap)."""- granularity = pick_granularity(date_from, date_to)- placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}+ placeholders: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=date_from),+ "run_started_floor": run_started_floor_constant(date_from),+ }date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""if date_to is not None:placeholders["date_to"] = ast.Constant(value=date_to)sql = (- _PASS_RATE_SERIES_SELECT.replace("__RUNS_SOURCE__", curated.run_source())+ _PASS_RATE_SERIES_SELECT.replace("__RUNS_SOURCE__", curated.run_source(started_floor=True)).replace("__DATE_TO__", date_to_clause).replace("__BUCKET_FN__", bucket_expr(granularity, "run_started_at")))@@ -127,11 +154,10 @@ def query_success_rate_series(normalize_bucket(bucket_start, granularity): opt_float(success_rate)for bucket_start, success_rate in response.results or []}- buckets = [+ return [PassRateBucket(bucket_start=bucket, success_rate=rate_by_bucket.get(bucket))for bucket in window_buckets(date_from, date_to, granularity)]- return granularity, bucketsdef query_open_to_merge_series(@@ -139,10 +165,10 @@ def query_open_to_merge_series(curated: CuratedGitHubSource,date_from: datetime,date_to: datetime | None,-) -> tuple[Granularity, list[OpenToMergeBucket]]:+ granularity: Granularity,+) -> list[OpenToMergeBucket]:"""Median time-to-merge per bucket across the window, oldest first: p50 merged_at - created_at over PRsmerged in the bucket, bots and drafts excluded. Empty buckets carry ``p50_seconds`` None (a gap)."""- granularity = pick_granularity(date_from, date_to)placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}date_to_clause = "AND merged_at <= {date_to}" if date_to is not None else ""if date_to is not None:@@ -157,11 +183,64 @@ def query_open_to_merge_series(normalize_bucket(bucket_start, granularity): (opt_float(p50) if (n or 0) > 0 else None)for bucket_start, p50, n in response.results or []}- buckets = [+ return [OpenToMergeBucket(bucket_start=bucket, p50_seconds=p50_by_bucket.get(bucket))for bucket in window_buckets(date_from, date_to, granularity)]- return granularity, buckets+++@dataclass(frozen=True)+class RepoSeries:+ """The repo hub's four chart series over one window, on one shared bucket granularity.++ Internal to the read layer: ``RepoOverview`` flattens it into the contract's per-series+ fields. Produced by ``query_repo_series`` (four bucketed scans) or ``empty_repo_series``+ (no scans — the headline-only shape), so callers compose which one they pay for instead+ of the query layer flag-switching what it computes.+ """++ granularity: Granularity+ cost: list[CostPerMergeBucket]+ time_to_green: list[TimeToGreenBucket]+ success_rate: list[PassRateBucket]+ open_to_merge: list[OpenToMergeBucket]+++def query_repo_series(+ *,+ curated: CuratedGitHubSource,+ date_from: datetime,+ date_to: datetime | None,+) -> RepoSeries:+ """All four chart series across the window — the one place their shared granularity is decided."""+ granularity = pick_granularity(date_from, date_to)+ return RepoSeries(+ granularity=granularity,+ cost=query_cost_per_merge_series(+ curated=curated, date_from=date_from, date_to=date_to, granularity=granularity+ ),+ time_to_green=query_time_to_green_series(+ curated=curated, date_from=date_from, date_to=date_to, granularity=granularity+ ),+ success_rate=query_success_rate_series(+ curated=curated, date_from=date_from, date_to=date_to, granularity=granularity+ ),+ open_to_merge=query_open_to_merge_series(+ curated=curated, date_from=date_from, date_to=date_to, granularity=granularity+ ),+ )+++def empty_repo_series(*, date_from: datetime, date_to: datetime | None) -> RepoSeries:+ """The series a headline-only read carries: no buckets, no scans, but the same granularity a+ full read would use, so the contract's non-null granularity fields stay meaningful."""+ return RepoSeries(+ granularity=pick_granularity(date_from, date_to),+ cost=[],+ time_to_green=[],+ success_rate=[],+ open_to_merge=[],+ )def query_repo_overview(@@ -169,6 +248,7 @@ def query_repo_overview(curated: CuratedGitHubSource,date_from: datetime,date_to: datetime | None,+ series: RepoSeries,) -> RepoOverview:end = date_to or datetime.now(tz=date_from.tzinfo)prev_from = date_from - (end - date_from)@@ -179,6 +259,9 @@ def query_repo_overview(placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from),"prev_from": ast.Constant(value=prev_from),+ # The scan reaches back to prev_from (the previous comparison window), so the raw floor+ # comes from prev_from, not date_from — a date_from floor would cut the prev-window rows.+ "run_started_floor": run_started_floor_constant(prev_from),}if date_to is not None:placeholders["date_to"] = ast.Constant(value=date_to)@@ -186,7 +269,7 @@ def query_repo_overview(runs_sql = (_RUNS_SELECT.replace("__CUR__", cur).replace("__PREV__", prev)- .replace("__RUNS_SOURCE__", curated.run_source())+ .replace("__RUNS_SOURCE__", curated.run_source(started_floor=True)).replace("__DATE_TO__", date_to_clause))runs_response = curated.run(@@ -204,7 +287,9 @@ def query_repo_overview(.replace("__PR_SOURCE__", curated.pr_source()))pr_response = curated.run(pr_sql, query_type="engineering_analytics.repo_overview_prs", placeholders=placeholders)- median_cur, median_prev = pr_response.results[0] if pr_response.results else (None, None)+ median_cur, median_prev, merged_cur, merged_prev = (+ pr_response.results[0] if pr_response.results else (None, None, 0, 0)+ )jobs_available = curated.jobs_source() is not Nonecost_cur, cost_prev = query_workflow_window_costs_with_prev(@@ -216,19 +301,6 @@ def query_repo_overview(cost_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- cost_series_granularity, cost_series = query_cost_per_merge_series(- curated=curated, date_from=date_from, date_to=date_to- )- ttg_series_granularity, ttg_series = query_time_to_green_series(- curated=curated, date_from=date_from, date_to=date_to- )- pass_rate_series_granularity, pass_rate_series = query_success_rate_series(- curated=curated, date_from=date_from, date_to=date_to- )- open_to_merge_series_granularity, open_to_merge_series = query_open_to_merge_series(- curated=curated, date_from=date_from, date_to=date_to- )-return RepoOverview(run_count=run_count,run_count_prev=run_count_prev,@@ -236,6 +308,8 @@ def query_repo_overview(success_rate_prev=opt_float(success_rate_prev),rerun_cycles=reruns,rerun_cycles_prev=reruns_prev,+ merged_pr_count=int(merged_cur or 0),+ merged_pr_count_prev=int(merged_prev or 0),median_open_to_merge_seconds=opt_float(median_cur),median_open_to_merge_seconds_prev=opt_float(median_prev),billable_minutes=billable_seconds / 60 if billable_seconds is not None else None,@@ -244,12 +318,12 @@ def query_repo_overview(estimated_cost_usd_prev=opt_float(cost_usd_prev),jobs_available=jobs_available,default_branch=default_branch,- cost_series=cost_series,- cost_series_granularity=cost_series_granularity,- time_to_green_series=ttg_series,- time_to_green_series_granularity=ttg_series_granularity,- success_rate_series=pass_rate_series,- success_rate_series_granularity=pass_rate_series_granularity,- open_to_merge_series=open_to_merge_series,- open_to_merge_series_granularity=open_to_merge_series_granularity,+ cost_series=series.cost,+ cost_series_granularity=series.granularity,+ time_to_green_series=series.time_to_green,+ time_to_green_series_granularity=series.granularity,+ success_rate_series=series.success_rate,+ success_rate_series_granularity=series.granularity,+ open_to_merge_series=series.open_to_merge,+ open_to_merge_series_granularity=series.granularity,)diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.pyindex 86b3bd79f6d4..40671f87057e 100644--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py@@ -25,6 +25,7 @@ from products.engineering_analytics.backend.facade.contracts import (WorkflowHealthRunScope,)from products.engineering_analytics.backend.logic.queries._buckets import (+ Granularity,bucket_expr,normalize_bucket,pick_granularity,@@ -37,6 +38,7 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impobranch_filter_clause,date_to_filter_clause,run_scope_filter_clause,+ run_started_floor_constant,)from products.engineering_analytics.backend.logic.queries.pr_cost import query_workflow_window_costs@@ -112,17 +114,20 @@ def query_time_to_green_series(curated: CuratedGitHubSource,date_from: datetime,date_to: datetime | None,-) -> tuple[str, list[TimeToGreenBucket]]:+ granularity: Granularity,+) -> list[TimeToGreenBucket]:"""Median time-to-green per bucket across the window, oldest first: the p50 wall-clock duration ofsuccessful, PR-attributed CI runs (default-branch runs excluded). Success-only + PR-scoped — the samepopulation workflow-health's percentiles use — so it answers "how long until CI passes on a PR", notmaster build time. Empty buckets carry ``p50_seconds`` None (a gap, not instant CI)."""- granularity = pick_granularity(date_from, date_to)- placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}+ placeholders: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=date_from),+ "run_started_floor": run_started_floor_constant(date_from),+ }date_to_clause = date_to_filter_clause(date_to, placeholders)run_scope_clause = run_scope_filter_clause(WorkflowHealthRunScope.PULL_REQUEST)sql = (- _TIME_TO_GREEN_SELECT.replace("__RUNS_SOURCE__", curated.run_source())+ _TIME_TO_GREEN_SELECT.replace("__RUNS_SOURCE__", curated.run_source(started_floor=True)).replace("__DATE_TO__", date_to_clause).replace("__RUN_SCOPE__", run_scope_clause).replace("__BUCKET_FN__", bucket_expr(granularity))@@ -132,11 +137,10 @@ def query_time_to_green_series(normalize_bucket(bucket_start, granularity): opt_float(p50_seconds)for bucket_start, p50_seconds in response.results or []}- buckets = [+ return [TimeToGreenBucket(bucket_start=bucket, p50_seconds=p50_by_bucket.get(bucket))for bucket in window_buckets(date_from, date_to, granularity)]- return granularity, bucketsdef query_workflow_health(@@ -148,12 +152,15 @@ def query_workflow_health(run_scope: WorkflowHealthRunScope,) -> list[WorkflowHealthItem]:granularity = pick_granularity(date_from, date_to)- placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}+ placeholders: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=date_from),+ "run_started_floor": run_started_floor_constant(date_from),+ }date_to_clause = date_to_filter_clause(date_to, placeholders)branch_clause = branch_filter_clause(branch, placeholders)run_scope_clause = run_scope_filter_clause(run_scope)- runs_source = curated.run_source()+ runs_source = curated.run_source(started_floor=True)def fill(template: str) -> str:return (@@ -183,7 +190,13 @@ def query_workflow_health(prev_response = curated.run(fill(_PREV_SELECT),query_type="engineering_analytics.workflow_health_prev",- placeholders={**placeholders, "prev_from": ast.Constant(value=prev_from)},+ # The prev window scans [prev_from, date_from); its scan floor must come from prev_from, not+ # date_from, or the raw prefilter would cut every previous-window row before the parsed filter.+ placeholders={+ **placeholders,+ "prev_from": ast.Constant(value=prev_from),+ "run_started_floor": run_started_floor_constant(prev_from),+ },)prev_rate_by_workflow: dict[tuple[str, str, str], float | None] = {(repo_owner, repo_name, workflow_name): opt_float(success_rate)diff --git a/products/engineering_analytics/backend/logic/views/workflow_runs.py b/products/engineering_analytics/backend/logic/views/workflow_runs.pyindex f4a34bfac571..38e4985a5ca0 100644--- a/products/engineering_analytics/backend/logic/views/workflow_runs.py+++ b/products/engineering_analytics/backend/logic/views/workflow_runs.py@@ -26,12 +26,28 @@ Nullable JSON with ``ifNull`` (a Nullable column cannot feed ``JSONExtractArrayRSELECT derives the duration and repo identity off those parsed columns, which alsoavoids referencing a same-SELECT alias as another expression's input.+Because those timestamps land as zero-padded ISO-8601 strings, they compare correctly+lexicographically ('2026-07-11' < '2026-07-11T09:00:00'). Every windowed consumer filters+on ``parseDateTimeBestEffort(run_started_at)``, and a predicate over a computed column cannot+be pushed down to the parquet/S3 scan — so each windowed query full-scans the runs table. With+``started_floor`` the builder wraps the source in an innermost prefilter on the RAW string column+(``run_started_at >= {run_started_floor}``), a coarse floor the scan CAN prune on. The precise+parsed ``{date_from}`` filter downstream stays the authoritative bound; the raw floor only trims+the scan. Callers register the ``{run_started_floor}`` placeholder via ``run_started_floor_constant``+(a date-only string one day below the window start, so it can never cut a row the parsed filter keeps).+Every query module embeds this ``SELECT`` as a subquery (see ``_curated``);nothing registers it as a global HogQL view."""-def build_query(table_name: str) -> str:+def build_query(table_name: str, *, started_floor: bool = False) -> str:+ # The raw floor must live in its OWN innermost SELECT, not the parsing SELECT below: that SELECT+ # aliases parseDateTimeBestEffort(run_started_at) AS run_started_at, and ClickHouse alias resolution+ # would make a WHERE there compare the parsed DateTime against the string. Keep it on the raw column.+ table_source = (+ f"(SELECT * FROM {table_name} WHERE run_started_at >= {{run_started_floor}})" if started_floor else table_name+ )return f"""SELECTid,@@ -62,6 +78,6 @@ def build_query(table_name: str) -> str:parseDateTimeBestEffort(run_started_at) AS run_started_at,parseDateTimeBestEffort(updated_at) AS updated_at,parseDateTimeBestEffort(created_at) AS created_at- FROM {table_name}+ FROM {table_source})"""diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.pyindex 3dce2e3bf547..c46b561d464d 100644--- a/products/engineering_analytics/backend/presentation/serializers.py+++ b/products/engineering_analytics/backend/presentation/serializers.py@@ -803,22 +803,25 @@ class RepoOverviewSerializer(DataclassSerializer):cost_series = CostPerMergeBucketSerializer(many=True,help_text="CI cost per merged PR across the window, oldest first, zero-filled, bucketed by "- "cost_series_granularity. Empty when the job-level source isn't synced.",+ "cost_series_granularity. Empty when the job-level source isn't synced or include_series=false.",)time_to_green_series = TimeToGreenBucketSerializer(many=True,help_text="Median time-to-green (p50 successful PR-attributed CI run duration) per bucket across the "- "window, oldest first, bucketed by time_to_green_series_granularity. Empty buckets carry null.",+ "window, oldest first, bucketed by time_to_green_series_granularity. Empty buckets carry null; the "+ "whole series is empty when include_series=false.",)success_rate_series = PassRateBucketSerializer(many=True,help_text="CI pass rate (completed runs that succeeded, all branches) per bucket across the window, "- "oldest first, bucketed by success_rate_series_granularity. Empty buckets carry null.",+ "oldest first, bucketed by success_rate_series_granularity. Empty buckets carry null; the whole "+ "series is empty when include_series=false.",)open_to_merge_series = OpenToMergeBucketSerializer(many=True,help_text="Median time-to-merge (p50 open_to_merge_seconds, bots/drafts excluded) per bucket across "- "the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null.",+ "the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null; "+ "the whole series is empty when include_series=false.",)class Meta:@@ -838,6 +841,11 @@ class RepoOverviewSerializer(DataclassSerializer):},"rerun_cycles": {"help_text": "Runs in the window that were a 2nd+ attempt (attempt > 1)."},"rerun_cycles_prev": {"help_text": "Re-run cycles over the previous window."},+ "merged_pr_count": {+ "help_text": "PRs merged in the window, all authors and bots included — the merge population "+ "that triggered the CI spend, so it divides cleanly into billable_minutes and estimated_cost_usd."+ },+ "merged_pr_count_prev": {"help_text": "Merged-PR count over the previous window."},"median_open_to_merge_seconds": {"help_text": "Median merged_at - created_at over PRs merged in the window, bots and drafts excluded. ""Coarse by design: draft and ready-for-review time are fused. Null when nothing merged.",diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.pyindex e36cd496c1df..85959ec36301 100644--- a/products/engineering_analytics/backend/presentation/views.py+++ b/products/engineering_analytics/backend/presentation/views.py@@ -139,6 +139,19 @@ def _optional_int_param(request: Request, name: str) -> int | None:raise ValueError(f"{name} must be an integer") from None+def _bool_param(request: Request, name: str, *, default: bool) -> bool:+ """Optional boolean query param; the default when absent/blank, ValueError when present but not true/false."""+ raw = request.query_params.get(name)+ if not raw:+ return default+ lowered = raw.lower()+ if lowered in ("true", "1"):+ return True+ if lowered in ("false", "0"):+ return False+ raise ValueError(f"{name} must be true or false")++@extend_schema(tags=[ENGINEERING_ANALYTICS_TAG])class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""PR and CI lifecycle analytics over the GitHub warehouse data."""@@ -844,17 +857,31 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe@extend_schema(operation_id="engineering_analytics_repo_overview",- parameters=[_DATE_FROM, _DATE_TO, _SOURCE_ID],+ parameters=[+ _DATE_FROM,+ _DATE_TO,+ OpenApiParameter(+ name="include_series",+ type=OpenApiTypes.BOOL,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Set false to skip the chart series (cost_series, time_to_green_series, "+ "success_rate_series, open_to_merge_series return empty) and their query cost — for "+ "headline-only consumers like the weekly digest. Defaults to true.",+ ),+ _SOURCE_ID,+ ],responses={200: RepoOverviewSerializer,400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),},description=("Repo-level headline aggregates over a window (default -30d): run count, success rate, re-run "- "cycles, 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. Cost figures are null until the job-level source is synced."+ "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."),)@action(detail=False, methods=["get"], pagination_class=None)@@ -864,11 +891,12 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSeteam=self.team,date_from=request.query_params.get("date_from") or None,date_to=request.query_params.get("date_to") or None,+ include_series=_bool_param(request, "include_series", default=True),source_id=request.query_params.get("source_id") or None,user_access_control=self.user_access_control,)except ValueError as exc:- return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")+ return _bad_request(exc, fallback="Invalid date_from, date_to, include_series, or source_id")return Response(RepoOverviewSerializer(instance=result).data)@extend_schema(diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.pyindex 2695c35ad303..48523a7204cb 100644--- a/products/engineering_analytics/backend/tests/test_logic.py+++ b/products/engineering_analytics/backend/tests/test_logic.py@@ -449,11 +449,10 @@ class TestCostPerMergeSeries(BaseTest):(datetime(2026, 6, 3), 2),(datetime(2026, 6, 5), 3), # merges but no cost above]- granularity, buckets = query_cost_per_merge_series(- curated=self._curated(cost_rows, merges_rows), date_from=date_from, date_to=date_to+ buckets = query_cost_per_merge_series(+ curated=self._curated(cost_rows, merges_rows), date_from=date_from, date_to=date_to, granularity="day")- assert granularity == "day"assert len(buckets) == 30 # June 1..30 inclusive, zero-filled.by_day = {bucket.bucket_start: bucket for bucket in buckets}@@ -488,10 +487,9 @@ class TestCostPerMergeSeries(BaseTest):def test_empty_when_jobs_source_unsynced(self) -> None:curated = self._curated([], [], jobs_synced=False)- granularity, buckets = query_cost_per_merge_series(- curated=curated, date_from=_dt("2026-06-01T00:00:00"), date_to=_dt("2026-06-30T00:00:00")+ buckets = query_cost_per_merge_series(+ curated=curated, date_from=_dt("2026-06-01T00:00:00"), date_to=_dt("2026-06-30T00:00:00"), granularity="day")- assert granularity == "day"assert buckets == []curated.run.assert_not_called() # no jobs source -> no scan is issued@@ -729,6 +727,56 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):assert cards.stuck == 1 # only 11 (10 recent, 12 draft, 13 and 16 bots)assert cards.failing_ci == 1 # only 10 has a failing latest run+ def test_repo_overview_headlines_and_series_toggle(self) -> None:+ # The weekly digest's whole read path: headline aggregates with include_series=False must+ # still carry every number the digest renders — merged counts over ALL merged PRs (bots+ # included: the merge population that triggered the spend) while the median keeps the+ # locked bots/drafts-excluded recipe, plus job-backed billable minutes — with all four+ # chart series empty. The default call keeps the series for the UI.+ self._create_table(+ "github_pull_requests",+ _PULL_REQUESTS_COLUMNS,+ [+ # human, merged in window: open->merge = 8 days; the median's only sample+ _pr_row(80, "alice", "closed", 0, _ago(10), merged_at=_ago(2), head_sha="sha80"),+ # bot, merged in window: counted in merged_pr_count, excluded from the median+ _pr_row(81, "dependabot[bot]", "closed", 0, _ago(4), merged_at=_ago(3), head_sha="sha81"),+ # merged before the window (and before its prev twin): in neither count+ _pr_row(82, "alice", "closed", 0, _ago(120), merged_at=_ago(90), head_sha="sha82"),+ ],+ )+ self._create_table(+ "github_workflow_runs",+ _WORKFLOW_RUNS_COLUMNS,+ [+ _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),+ ],+ )+ self._create_table(+ "github_workflow_jobs",+ WORKFLOW_JOBS_COLUMNS,+ [_job_row(95000, 9500, "build", "success", labels='["depot-ubuntu-22.04-4"]')],+ )++ 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 window+ assert overview.merged_pr_count_prev == 0+ assert overview.median_open_to_merge_seconds == pytest.approx(8 * 86400) # bot PR 81 excluded+ assert overview.run_count == 2+ assert 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.cost_series == []+ assert overview.time_to_green_series == []+ assert overview.success_rate_series == []+ assert overview.open_to_merge_series == []+ assert overview.cost_series_granularity == "day" # the grain the series would have used++ with_series = api.get_repo_overview(team=self.team)+ assert len(with_series.cost_series) > 0 # zero-filled spine across the default -30d window+ assert len(with_series.success_rate_series) > 0+def test_pull_request_list_window_and_rollup(self) -> None:self._seed()result = api.list_pull_requests(team=self.team)@@ -797,9 +845,9 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):def test_pr_cost_clamps_clock_skewed_negative_durations(self) -> None:# Two jobs share one run/label group: a normal +120s job and a clock-skewed -120s one# (completed_at < started_at). The grouped sum must clamp the negative per-job (greatest(.,0))- # so it doesn't cancel its group-mate's elapsed before the even-split expansion. Without the- # clamp the group sums to 0s and the PR reads $0.00; with it, the skewed job contributes 0 and- # the normal job's 120s survives = 2 billable min, depot 4-core (2x) at $0.004/min = $0.016.+ # so it doesn't cancel its group-mate's elapsed inside the group total. Without the clamp the+ # group sums to 0s and the PR reads $0.00; with it, the skewed job contributes 0 and the+ # normal job's 120s survives = 2 billable min, depot 4-core (2x) at $0.004/min = $0.016.self._create_table("github_pull_requests",_PULL_REQUESTS_COLUMNS,@@ -852,6 +900,28 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):assert ci.last_failure_at is not Noneassert ci.billable_minutes is None # no jobs source seeded → no cost figure+ def test_workflow_health_prev_window_survives_raw_scan_floor(self) -> None:+ # The prev-window query's raw-string scan floor must come from prev_from, not date_from.+ # A run in [prev_from, date_from) sits below the date_from floor; if that floor leaked into+ # the prev scan the innermost raw prefilter would drop it and success_rate_prev would go None.+ # A -30d window puts its prev twin at [-60d, -30d), so _ago(45) lands squarely in it.+ self._create_table(+ "github_pull_requests",+ _PULL_REQUESTS_COLUMNS,+ [_pr_row(60, "alice", "open", 0, _ago(2), head_sha="sha60")],+ )+ self._create_table(+ "github_workflow_runs",+ _WORKFLOW_RUNS_COLUMNS,+ [+ _run_row(6001, "CI", "sha60", "completed", "success", _ago(2), _ago(2), pr_number=60),+ _run_row(6002, "CI", "sha60p", "completed", "success", _ago(45), _ago(45), pr_number=60),+ ],+ )+ ci = next(i for i in api.list_workflow_health(team=self.team, date_from="-30d") if i.workflow_name == "CI")+ assert ci.success_rate == 1.0+ assert ci.success_rate_prev == 1.0+def test_workflow_health_duration_percentiles_exclude_cancelled_and_failed_runs(self) -> None:self._create_table("github_pull_requests",diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex ea9565ddd13f..55c5dce0d795 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -84,6 +84,35 @@ def _workflow_health() -> contracts.WorkflowHealthItem:)+def _repo_overview() -> contracts.RepoOverview:+ return contracts.RepoOverview(+ run_count=10,+ run_count_prev=8,+ success_rate=0.9,+ success_rate_prev=0.85,+ rerun_cycles=2,+ rerun_cycles_prev=1,+ merged_pr_count=42,+ merged_pr_count_prev=40,+ median_open_to_merge_seconds=3600.0,+ median_open_to_merge_seconds_prev=4000.0,+ billable_minutes=100.0,+ billable_minutes_prev=90.0,+ estimated_cost_usd=12.5,+ estimated_cost_usd_prev=11.0,+ jobs_available=True,+ default_branch="master",+ cost_series=[],+ cost_series_granularity="day",+ time_to_green_series=[],+ time_to_green_series_granularity="day",+ success_rate_series=[],+ success_rate_series_granularity="day",+ open_to_merge_series=[],+ open_to_merge_series_granularity="day",+ )++def _workflow_run() -> contracts.WorkflowRunDetail:return contracts.WorkflowRunDetail(repo=contracts.RepoRef(provider="github", owner="PostHog", name="posthog"),@@ -211,6 +240,33 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):assert list_health.call_args.kwargs["branch"] == "main"assert list_health.call_args.kwargs["run_scope"] == "pull_request"+ @parameterized.expand(+ [+ ("default_true", {}, True),+ ("explicit_false", {"include_series": "false"}, False),+ ("explicit_true", {"include_series": "true"}, True),+ ]+ )+ def test_repo_overview_serializes_and_forwards_include_series(self, _name, params, expected) -> None:+ # The weekly digest depends on this param actually reaching the facade — a rename or+ # parse regression silently restores the full chart-query cost it exists to skip.+ with mock.patch(f"{_VIEWS}.get_repo_overview", return_value=_repo_overview()) as get:+ response = self.client.get(self._url("repo_overview"), params)++ assert response.status_code == status.HTTP_200_OK+ assert get.call_args.kwargs["include_series"] is expected+ data = response.json()+ assert data["merged_pr_count"] == 42+ assert data["merged_pr_count_prev"] == 40+ assert data["cost_series"] == []++ def test_repo_overview_400_on_bad_include_series(self) -> None:+ with mock.patch(f"{_VIEWS}.get_repo_overview", return_value=_repo_overview()):+ response = self.client.get(self._url("repo_overview"), {"include_series": "maybe"})++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "include_series" in response.json()["detail"]+def test_current_branch_health_serializes(self) -> None:with mock.patch(f"{_VIEWS}.get_current_branch_health", return_value=_current_branch_health()):response = self.client.get(self._url("current_branch_health"))diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex d9177f2bb45a..8cd72c99fb53 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -679,13 +679,13 @@ export interface OpenToMergeBucketApi {}export interface RepoOverviewApi {- /** CI cost per merged PR across the window, oldest first, zero-filled, bucketed by cost_series_granularity. Empty when the job-level source isn't synced. */+ /** CI cost per merged PR across the window, oldest first, zero-filled, bucketed by cost_series_granularity. Empty when the job-level source isn't synced or include_series=false. */cost_series: CostPerMergeBucketApi[]- /** Median time-to-green (p50 successful PR-attributed CI run duration) per bucket across the window, oldest first, bucketed by time_to_green_series_granularity. Empty buckets carry null. */+ /** Median time-to-green (p50 successful PR-attributed CI run duration) per bucket across the window, oldest first, bucketed by time_to_green_series_granularity. Empty buckets carry null; the whole series is empty when include_series=false. */time_to_green_series: TimeToGreenBucketApi[]- /** CI pass rate (completed runs that succeeded, all branches) per bucket across the window, oldest first, bucketed by success_rate_series_granularity. Empty buckets carry null. */+ /** CI pass rate (completed runs that succeeded, all branches) per bucket across the window, oldest first, bucketed by success_rate_series_granularity. Empty buckets carry null; the whole series is empty when include_series=false. */success_rate_series: PassRateBucketApi[]- /** Median time-to-merge (p50 open_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null. */+ /** Median time-to-merge (p50 open_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null; the whole series is empty when include_series=false. */open_to_merge_series: OpenToMergeBucketApi[]/** Workflow runs started in the window, all branches and workflows. */run_count: number@@ -705,6 +705,10 @@ export interface RepoOverviewApi {rerun_cycles: number/** Re-run cycles over the previous window. */rerun_cycles_prev: number+ /** PRs merged in the window, all authors and bots included — the merge population that triggered the CI spend, so it divides cleanly into billable_minutes and estimated_cost_usd. */+ merged_pr_count: number+ /** Merged-PR count over the previous window. */+ merged_pr_count_prev: number/*** Median merged_at - created_at over PRs merged in the window, bots and drafts excluded. Coarse by design: draft and ready-for-review time are fused. Null when nothing merged.* @nullable@@ -1127,6 +1131,10 @@ export type EngineeringAnalyticsRepoOverviewParams = {* Window end: relative or ISO8601. Defaults to now.*/date_to?: string+ /**+ * Set false to skip the chart series (cost_series, time_to_green_series, success_rate_series, open_to_merge_series return empty) and their query cost — for headline-only consumers like the weekly digest. Defaults to true.+ */+ include_series?: boolean/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex fbc0bde03133..12b7b84147ab 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -482,7 +482,7 @@ export const getEngineeringAnalyticsRepoOverviewUrl = (}/**- * Repo-level headline aggregates over a window (default -30d): run count, success rate, re-run cycles, 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. 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 — 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 8fdc7f74a5e2..f8ef1bfa40b3 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx@@ -26,6 +26,9 @@ const OVERVIEW: RepoOverviewApi = {success_rate_prev: 0.82,rerun_cycles: 41,rerun_cycles_prev: 30,+ // Matches the cost_series merges below: 8 merges x 7 daily buckets.+ merged_pr_count: 56,+ merged_pr_count_prev: 49,median_open_to_merge_seconds: 14 * 3600,median_open_to_merge_seconds_prev: 19 * 3600,billable_minutes: 5230,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a2c0a45ac0f2..3d458cb9bc8b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -51646,13 +51646,13 @@ export namespace Schemas {}export interface RepoOverview {- /** CI cost per merged PR across the window, oldest first, zero-filled, bucketed by cost_series_granularity. Empty when the job-level source isn't synced. */+ /** CI cost per merged PR across the window, oldest first, zero-filled, bucketed by cost_series_granularity. Empty when the job-level source isn't synced or include_series=false. */cost_series: CostPerMergeBucket[];- /** Median time-to-green (p50 successful PR-attributed CI run duration) per bucket across the window, oldest first, bucketed by time_to_green_series_granularity. Empty buckets carry null. */+ /** Median time-to-green (p50 successful PR-attributed CI run duration) per bucket across the window, oldest first, bucketed by time_to_green_series_granularity. Empty buckets carry null; the whole series is empty when include_series=false. */time_to_green_series: TimeToGreenBucket[];- /** CI pass rate (completed runs that succeeded, all branches) per bucket across the window, oldest first, bucketed by success_rate_series_granularity. Empty buckets carry null. */+ /** CI pass rate (completed runs that succeeded, all branches) per bucket across the window, oldest first, bucketed by success_rate_series_granularity. Empty buckets carry null; the whole series is empty when include_series=false. */success_rate_series: PassRateBucket[];- /** Median time-to-merge (p50 open_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null. */+ /** Median time-to-merge (p50 open_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null; the whole series is empty when include_series=false. */open_to_merge_series: OpenToMergeBucket[];/** Workflow runs started in the window, all branches and workflows. */run_count: number;@@ -51672,6 +51672,10 @@ export namespace Schemas {rerun_cycles: number;/** Re-run cycles over the previous window. */rerun_cycles_prev: number;+ /** PRs merged in the window, all authors and bots included — the merge population that triggered the CI spend, so it divides cleanly into billable_minutes and estimated_cost_usd. */+ merged_pr_count: number;+ /** Merged-PR count over the previous window. */+ merged_pr_count_prev: number;/*** Median merged_at - created_at over PRs merged in the window, bots and drafts excluded. Coarse by design: draft and ready-for-review time are fused. Null when nothing merged.* @nullable@@ -69269,6 +69273,10 @@ export namespace Schemas {* Window end: relative or ISO8601. Defaults to now.*/date_to?: string;+ /**+ * Set false to skip the chart series (cost_series, time_to_green_series, success_rate_series, open_to_merge_series return empty) and their query cost — for headline-only consumers like the weekly digest. Defaults to true.+ */+ include_series?: boolean;/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/