Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(eng-analytics): repair the repo overview trend panels (#79923)

Raúl Negrón-Otero901d46939785
diff --git a/.github/scripts/eng-analytics-weekly-digest.mjs b/.github/scripts/eng-analytics-weekly-digest.mjs
index f0fc7743e54a..7e6b1b0f87b4 100644
--- a/.github/scripts/eng-analytics-weekly-digest.mjs
+++ b/.github/scripts/eng-analytics-weekly-digest.mjs
@@ -18,14 +18,15 @@
// - 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.
-// - open→merge median: bots/drafts excluded upstream; coarse by design (draft +
-// ready-for-review fused).
+// - ready→merge median: time from ready-for-review to merge, bots/drafts excluded
+// upstream. Falls back to the coarse open→merge median (draft + ready fused, and
+// labelled as such) when the draft/ready transitions aren't synced.
// - re-run cycles: runs with run_attempt > 1 — the waste driver behind minutes.
//
// Data caveat: the runs/jobs warehouse tables are webhook-fed and do not backfill
// a missed window, so a webhook outage undercounts the count-based rows (minutes,
// $, re-runs) and the WoW delta absorbs the hole. The PR-snapshot rows (merge
-// count, open→merge median) are robust to gaps.
+// count, cycle-time median) are robust to gaps.
const HOST = (process.env.POSTHOG_HOST || 'https://us.posthog.com').replace(/\/$/, '')
const PROJECT_ID = process.env.POSTHOG_PROJECT_ID || ''
@@ -174,12 +175,18 @@ function tableRows(overview) {
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
- )
+ // Cycle time reads ready→merge, which excludes time spent as a draft. Both windows have to carry
+ // it to compare like with like, so a repo without the issue-events sync (or a week that straddles
+ // its first sync) falls back to the coarse open→merge median, labelled as what it is.
+ const [cycleMetric, cycleCur, cyclePrev] =
+ overview.median_ready_to_merge_seconds != null && overview.median_ready_to_merge_seconds_prev != null
+ ? [
+ 'ready→merge median',
+ overview.median_ready_to_merge_seconds,
+ overview.median_ready_to_merge_seconds_prev,
+ ]
+ : ['open→merge median', overview.median_open_to_merge_seconds, overview.median_open_to_merge_seconds_prev]
+ add(cycleMetric, cycleCur, cyclePrev, fmtLongDuration)
add('re-run cycles', overview.rerun_cycles, overview.rerun_cycles_prev, fmtInt)
return rows
}
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index db76a0478f59..e3dc59e75614 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5971,9 +5971,9 @@ snapshots:
scenes-app-discussions--threads--light:
hash: v1.k794b7964.28ac830bf83be5cbb6d7a397d67c9b9c61711904a822de38402b82220b0f7a49.7wENY7hvo1-qAJwq5fcsvKGJsfRAF_vDkpnM8iqFZcc
scenes-app-engineering-analytics-repo-overview--repo-overview--dark:
- hash: v1.k794b7964.e9d318d698bc28adcb595d2777160017c2d7b891c6fbecc16b2fec2c380f0534.4C0Kv7dgxXX6anYHBO-NKS2RvwhJt52I22zkzxM-MZ0
+ hash: v1.k794b7964.ea0cac6dc4e88af4e62d1bec32c9abfb613c44f74713205c1990fa44d467190a._Jn8n4C9-F5naZmW4FU1Utu9_wVDapw2ekc7qSlbgvc
scenes-app-engineering-analytics-repo-overview--repo-overview--light:
- hash: v1.k794b7964.71bf30defa9c6821564b7c1b2406818b8cd34ba465b29f5c9aa58932c34317a0.5l4d1N7wInmykrgxNe2hT--AlLXmygTtADyOBC9MMuE
+ hash: v1.k794b7964.646864073ca10e6cd01f9523215da333ea50b674caede591e12c8e241f4f1590.h76KD47dx5rmRHXFYEen7HjjKJDRtqHIn8vcJ2g1Azk
scenes-app-engineering-analytics-run-activity-chart--default--dark:
hash: v1.k794b7964.7f17c5ac7c6862493f7c4d59e6e3c3146c42e3d7b08908ee1716d387c129ba64.lPsE9KrOSZee9wJq8zjqYnvk09numvEFWOn4mdCOgJE
scenes-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.py
index b1114563810d..22a60186ef72 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -996,18 +996,18 @@ class CostPerMergeBucket:
@dataclass(frozen=True)
class TimeToGreenBucket:
- """One time bucket of the repo's median time-to-green: the p50 wall-clock duration of *successful*
- CI runs attributed to pull requests (default-branch runs excluded), started in this bucket. Cancelled
- and failed runs end early and would bias the percentile low, so they are excluded — the same
- success-only population the workflow-health percentiles use. ``p50_seconds`` is None for a bucket with
- no successful PR run (a gap, not instant CI); the UI carries the last known value forward rather than
- dipping the trend to zero.
+ """One time bucket of the repo's median time-to-green: p50 wall clock from a PR push round's
+ first run start until every workflow on that head SHA first completed benign (merge-queue gates
+ and partially-attributed fork rounds excluded). A flake re-run stretches the wall to its
+ recovery; a re-fire after green does not, though a workflow first firing late on the SHA (as
+ marking a draft ready does) stretches it by the wait that preceded it. ``p50_seconds`` is None
+ for a bucket with no fully green round (a gap, not instant CI); the UI carries the last known
+ value forward.
"""
- # Bucket start, aligned to the granularity (top of hour / midnight / Monday).
+ # Bucket start, aligned to the granularity (top of hour / midnight / Monday). Keyed on round start.
bucket_start: datetime
- # Median wall-clock seconds of successful PR-attributed CI runs started in this bucket. None when the
- # bucket had no successful PR run.
+ # Median seconds from round start to all-green. None when the bucket had no fully green round.
p50_seconds: float | None
@@ -1038,6 +1038,20 @@ class OpenToMergeBucket:
p50_seconds: float | None
+@dataclass(frozen=True)
+class ReadyToMergeBucket:
+ """One time bucket of the repo's median cycle time: p50 of per-PR ``ready_to_merge_seconds``
+ (SPEC §6) over PRs merged in this bucket, bots and drafts excluded. ``p50_seconds`` is None
+ for a bucket with no observed value (a gap, not instant merges); the UI carries the last known
+ value forward.
+ """
+
+ # Bucket start, aligned to the granularity (top of hour / midnight / Monday). Keyed on merge time.
+ bucket_start: datetime
+ # Median per-PR ready_to_merge_seconds over PRs merged in this bucket. None when no observed value.
+ p50_seconds: float | None
+
+
@dataclass(frozen=True)
class RepoOverview:
"""Repo-level headline aggregates for the landing page, each with its previous-window twin
@@ -1061,6 +1075,10 @@ class RepoOverview:
# Coarse by design: merged_at - created_at (draft + ready time fused), median over PRs merged in the window.
median_open_to_merge_seconds: float | None
median_open_to_merge_seconds_prev: float | None
+ # The precise companion (SPEC §6): median per-PR ready_to_merge_seconds over merged PRs with an
+ # observed value. None means "not observed" (issue events unsynced or out of window), never zero.
+ median_ready_to_merge_seconds: float | None
+ median_ready_to_merge_seconds_prev: float | None
billable_minutes: float | None
billable_minutes_prev: float | None
estimated_cost_usd: float | None
@@ -1077,8 +1095,8 @@ class RepoOverview:
cost_series: list[CostPerMergeBucket]
# Bucket width of `cost_series`, chosen to fit the window: 'hour', 'day', or 'week'.
cost_series_granularity: str
- # Time-to-green trend: median CI duration of successful PR-attributed runs per bucket, oldest first,
- # bucketed by `time_to_green_series_granularity`. Empty buckets carry None (no successful PR run).
+ # Time-to-green trend: median wall clock for a PR push round to settle fully green, per bucket,
+ # oldest first, bucketed by `time_to_green_series_granularity`. Empty buckets carry None.
time_to_green_series: list[TimeToGreenBucket]
# Bucket width of `time_to_green_series`, chosen to fit the window: 'hour', 'day', or 'week'.
time_to_green_series_granularity: str
@@ -1092,6 +1110,11 @@ class RepoOverview:
open_to_merge_series: list[OpenToMergeBucket]
# Bucket width of `open_to_merge_series`, chosen to fit the window: 'hour', 'day', or 'week'.
open_to_merge_series_granularity: str
+ # Cycle-time trend: median per-PR ready_to_merge_seconds per bucket (bots/drafts excluded),
+ # oldest first. Empty when the issue-events table isn't synced; fall back to open_to_merge_series.
+ ready_to_merge_series: list[ReadyToMergeBucket]
+ # Bucket width of `ready_to_merge_series`, chosen to fit the window: 'hour', 'day', or 'week'.
+ ready_to_merge_series_granularity: str
@dataclass(frozen=True)
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 5cb9ee05b23d..6b4d2401c5f9 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -42,13 +42,73 @@ if TYPE_CHECKING:
@dataclass(frozen=True, kw_only=True)
-class IssueEventsWindow:
+class _IssueEventsWindow:
"""The observed issue-event range's edges as scalar subquery strings."""
start: str
end: str
+_READY_BY_PR_JOIN = "LEFT JOIN ready_by_pr AS re ON re.pr_number = pr.number"
+
+
+@dataclass(frozen=True, kw_only=True)
+class ReadyToMergeSql:
+ """The SQL for reading per-PR ready-to-merge seconds (SPEC §6), in the three pieces a query
+ substitutes. They are only valid together: ``cte`` belongs in the query's ``WITH`` list, ``join``
+ in its ``FROM`` clause with the PR source aliased ``pr``, and ``expr`` reads the joined row.
+
+ When the optional issue-events table isn't synced ``expr`` degrades to a constant NULL and the
+ other two are empty, so a caller substitutes all three unconditionally rather than branching on
+ whether the measure is observable.
+ """
+
+ cte: str
+ join: str
+ expr: str
+
+ @property
+ def observable(self) -> bool:
+ """False when ``expr`` is the constant NULL, so a query whose only output is this measure
+ can skip a scan that could return nothing else."""
+ return bool(self.cte)
+
+ @property
+ def with_clause(self) -> str:
+ """``cte`` as a whole ``WITH`` clause, for a query that has no other CTE."""
+ return f"WITH {self.cte} " if self.cte else ""
+
+ def median(self, *, scope: str) -> str:
+ """The measure's p50 over the rows matching ``scope``. Unobservable degrades to the NULL
+ expression itself, not a percentile over it: an aggregate needs a column type to work on,
+ and a bare NULL literal has none."""
+ return f"quantileIf(0.5)({self.expr}, {scope})" if self.observable else self.expr
+
+
+_READY_TO_MERGE_UNOBSERVABLE = ReadyToMergeSql(cte="", join="", expr="NULL")
+
+
+def _ready_to_merge_expr(window: _IssueEventsWindow) -> str:
+ """Per-PR ready-to-merge seconds, read off the ``ready_by_pr`` join.
+
+ Last transition is a ready -> merged_at minus it; no transition rows and the PR's whole
+ open-to-merge life inside the observed window -> never left ready, so open-to-merge IS
+ ready-to-merge; otherwise NULL (re-drafted, or unobservable). Both window bounds are load-
+ bearing: created_at before the window means pre-window flips are possible, and merged_at past
+ the window means the transitions may simply not have synced yet (every merge lands a `merged`
+ issue event, so an in-range merge with no transition rows is proof of never drafting). The
+ coalesce guards normalize a missed join, which lands NULL or 0 depending on join_use_nulls.
+ """
+ return f"""multiIf(
+ pr.merged_at IS NULL, NULL,
+ coalesce(re.last_is_ready, 0) = 1, dateDiff('second', re.last_transition_at, pr.merged_at),
+ coalesce(re.pr_number, 0) = 0
+ AND pr.created_at >= {window.start}
+ AND pr.merged_at <= {window.end}, pr.open_to_merge_seconds,
+ NULL
+ )"""
+
+
class CuratedGitHubSource:
"""A team's curated GitHub read layer, bound to its resolved warehouse tables.
@@ -126,19 +186,29 @@ class CuratedGitHubSource:
return None
return f"({issue_events.build_query(self._tables.issue_events)})"
- def issue_events_window(self) -> "IssueEventsWindow | None":
+ def ready_to_merge_sql(self) -> ReadyToMergeSql:
+ """SQL for the per-PR ready-to-merge measure, off the PR source aliased ``pr``. Degrades to
+ a constant NULL when the optional issue-events table isn't synced, so every consumer reads
+ the measure the same way."""
+ window = self._issue_events_window()
+ cte = self._ready_by_pr_cte()
+ if window is None or cte is None:
+ return _READY_TO_MERGE_UNOBSERVABLE
+ return ReadyToMergeSql(cte=cte, join=_READY_BY_PR_JOIN, expr=_ready_to_merge_expr(window))
+
+ def _issue_events_window(self) -> "_IssueEventsWindow | None":
"""Scalar subqueries bounding the observed issue-event range, or None when the table
isn't synced. The desc walk lands a contiguous range, so the min and max landed
timestamps are its edges; both are NULL over an empty table, so comparisons against
them are never-true."""
if not self._tables.issue_events:
return None
- return IssueEventsWindow(
+ return _IssueEventsWindow(
start=f"({issue_events.build_window_start_query(self._tables.issue_events)})",
end=f"({issue_events.build_window_end_query(self._tables.issue_events)})",
)
- def ready_by_pr_cte(self) -> str | None:
+ def _ready_by_pr_cte(self) -> str | None:
"""CTE: each PR's last observed draft-state transition, or None when the table isn't synced.
Only the LAST switch counts: for a merged PR the newest transition is necessarily the ready
@@ -268,12 +338,11 @@ class CuratedGitHubSource:
"""
def pr_list_rollup_query(self, select: str) -> str:
- """``pr_rollup_query`` plus the per-PR runs rollup and, when the issue-events table is
- synced, the ``ready_by_pr`` rollup; reference it only when ``issue_events_source()``
- is non-None."""
+ """``pr_rollup_query`` plus the per-PR runs rollup and, when it is observable, the
+ ``ready_by_pr`` rollup ``ready_to_merge_sql`` reads."""
ctes = [self.runs_cte(), self.ci_rollup_cte(), self.runs_by_pr_cte()]
- ready_cte = self.ready_by_pr_cte()
- if ready_cte is not None:
+ ready_cte = self.ready_to_merge_sql().cte
+ if ready_cte:
ctes.append(ready_cte)
return self._compose_pr_query(ctes, select)
diff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
index 1025f6f91be9..b743675cced5 100644
--- a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
@@ -106,6 +106,14 @@ def date_to_filter_clause(
return f"AND {column} <= {{date_to}}"
+def non_default_branch_predicate(branch_column: str = "r.head_branch") -> str:
+ """True when the branch expression names a branch other than the repo's default. The source
+ doesn't record which branch that is, so this excludes the common default names — the same
+ approximation ``repo_overview.query_default_branch`` resolves per-repo, not reused here
+ because it costs an extra query."""
+ return f"{branch_column} NOT IN ('master', 'main')"
+
+
def run_scope_filter_clause(
run_scope: WorkflowHealthRunScope,
*,
@@ -113,16 +121,14 @@ def run_scope_filter_clause(
attributed_predicate: str = "r.pr_number > 0",
) -> str:
if run_scope == WorkflowHealthRunScope.PULL_REQUEST:
- # A default-branch run can still carry a PR association (its SHA matches an open PR),
- # so attribution alone (pr_number > 0 — see the workflow_runs builder docstring) doesn't
- # keep trunk runs out. The source doesn't record which branch is the repo's default, so
- # exclude the common default-branch names — the same approximation repo_overview's
- # query_default_branch resolves per-repo, not reused here because it costs an extra query.
+ # A default-branch run can still carry a PR association (its SHA matches an open PR), so
+ # attribution alone (pr_number > 0 — see the workflow_runs builder docstring) doesn't keep
+ # trunk runs out; the scope needs both predicates.
# The cost queries pass the cost source's columns; there pr_number is 0→NULL normalized, so
# "attributed" becomes ``c.pr_number IS NOT NULL`` rather than ``> 0``.
# Merge-queue gate runs stay in this scope on purpose: a gate run is CI the PR paid for on
# its way to landing, and the runs builder already credits it to that PR rather than to the
# throwaway PR the queue opened. ``is_merge_queue`` splits the two populations, on the cost
# view and the job-history view alike.
- return f"AND {branch_column} NOT IN ('master', 'main') AND {attributed_predicate}"
+ return f"AND {non_default_branch_predicate(branch_column)} AND {attributed_predicate}"
return ""
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
index 8097f82822c8..6e9720ed84a2 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_list.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
@@ -57,25 +57,6 @@ _SELECT = f"""
LIMIT {_LIMIT + 1}
"""
-# Per merged PR: last transition is a ready -> merged_at minus it; no transition rows and the
-# PR's whole open-to-merge life inside the observed window -> never left ready, so open-to-merge
-# IS ready-to-merge; otherwise NULL (re-drafted, or unobservable). Both window bounds are load-
-# bearing: created_at before the window means pre-window flips are possible, and merged_at past
-# the window means the transitions may simply not have synced yet (every merge lands a `merged`
-# issue event, so an in-range merge with no transition rows is proof of never drafting). The
-# coalesce guards normalize a missed join, which lands NULL or 0 depending on join_use_nulls.
-_READY_TO_MERGE = """
- multiIf(
- pr.merged_at IS NULL, NULL,
- coalesce(re.last_is_ready, 0) = 1, dateDiff('second', re.last_transition_at, pr.merged_at),
- coalesce(re.pr_number, 0) = 0
- AND pr.created_at >= __READY_WINDOW_START__
- AND pr.merged_at <= __READY_WINDOW_END__, pr.open_to_merge_seconds,
- NULL
- ) AS ready_to_merge_seconds
-"""
-_READY_JOIN = "LEFT JOIN ready_by_pr AS re ON re.pr_number = pr.number"
-
# Per-push CI rounds for the visible PRs, for the push-history sparkline. Verdicts collapse like
# ``ci_rollup``: latest run per (push, workflow) via argMax, then any decisive failure turns the
@@ -156,20 +137,10 @@ def query_pull_request_list(
if author:
author_clause = "AND pr.author_handle = {author}"
placeholders["author"] = ast.Constant(value=author)
- # Without the optional issue-events table the column degrades to NULL rather than
- # referencing the absent ready_by_pr CTE.
- window = curated.issue_events_window()
- if window is not None:
- ready_column = _READY_TO_MERGE.replace("__READY_WINDOW_START__", window.start).replace(
- "__READY_WINDOW_END__", window.end
- )
- ready_join = _READY_JOIN
- else:
- ready_column = "NULL AS ready_to_merge_seconds"
- ready_join = ""
+ ready = curated.ready_to_merge_sql()
select = (
- _SELECT.replace("__READY_TO_MERGE__", ready_column)
- .replace("__READY_JOIN__", ready_join)
+ _SELECT.replace("__READY_TO_MERGE__", f"{ready.expr} AS ready_to_merge_seconds")
+ .replace("__READY_JOIN__", ready.join)
.replace("__AUTHOR__", author_clause)
)
response = curated.run(
diff --git a/products/engineering_analytics/backend/logic/queries/repo_overview.py b/products/engineering_analytics/backend/logic/queries/repo_overview.py
index 5a3d0f19c083..fe7ec125850e 100644
--- a/products/engineering_analytics/backend/logic/queries/repo_overview.py
+++ b/products/engineering_analytics/backend/logic/queries/repo_overview.py
@@ -5,11 +5,12 @@ every headline number ships with its previous-window twin and the UI can render
honest delta instead of a server-baked percentage. The PR medians (bots and drafts
excluded, 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.
+The chart series are a separate concern with a separate producer
+(``query_repo_series``): every series query computes unconditionally (except the
+ready-to-merge series, which is empty when that measure isn't observable), 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 dataclass
@@ -21,6 +22,7 @@ from products.engineering_analytics.backend.facade.contracts import (
CostPerMergeBucket,
OpenToMergeBucket,
PassRateBucket,
+ ReadyToMergeBucket,
RepoOverview,
TimeToGreenBucket,
)
@@ -55,17 +57,23 @@ _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 = """
+# The locked cycle-time recipe: a median over merges is a median over human, never-drafted PRs.
+_HUMAN_MERGES = "NOT is_bot AND NOT is_draft"
+
+# Medians follow the locked recipe; 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 = f"""
SELECT
- quantileIf(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, __CUR_MERGED__ AND {_HUMAN_MERGES}) AS median_cur,
+ quantileIf(0.5)(open_to_merge_seconds, __PREV_MERGED__ AND {_HUMAN_MERGES}) AS median_prev,
+ __READY_MEDIAN_CUR__ AS ready_median_cur,
+ __READY_MEDIAN_PREV__ AS ready_median_prev,
countIf(__CUR_MERGED__) AS merged_cur,
countIf(__PREV_MERGED__) AS merged_prev
FROM __PR_SOURCE__ AS pr
- WHERE merged_at IS NOT NULL AND merged_at >= {prev_from}
+ __READY_JOIN__
+ WHERE merged_at IS NOT NULL AND merged_at >= {{prev_from}}
"""
_DEFAULT_BRANCH_SELECT = """
@@ -113,21 +121,59 @@ _PASS_RATE_SERIES_SELECT = """
LIMIT 40000
"""
-# Median open->merge per bucket over PRs merged in it, bots and drafts excluded (the locked recipe). ``n``
-# guards the false zero: quantileIf over no matching rows returns 0, so a bucket whose only merges were
-# bots/drafts would draw a false dip — treat it as a gap (None) instead.
-_OPEN_TO_MERGE_SERIES_SELECT = """
+# Median of a per-PR duration per bucket, over the PRs merged in it. The inner select applies the
+# locked recipe once and names the measure, so a measure built from an expression (ready-to-merge)
+# is written into the query exactly once. ``n`` guards the false zero: an aggregate over no sample
+# returns 0, so a bucket whose only merges were bots, drafts, or PRs with no observed value would
+# draw a false dip; report the gap (None) instead.
+_MERGE_MEDIAN_SERIES_SELECT = f"""
SELECT
__BUCKET_FN__ AS bucket_start,
- quantileIf(0.5)(open_to_merge_seconds, NOT is_bot AND NOT is_draft) AS p50,
- countIf(NOT is_bot AND NOT is_draft) AS n
- FROM __PR_SOURCE__ AS pr
- WHERE merged_at IS NOT NULL AND merged_at >= {date_from} __DATE_TO_MERGED__
+ quantile(0.5)(measure) AS p50,
+ countIf(measure IS NOT NULL) AS n
+ FROM (
+ SELECT merged_at, __MEASURE__ AS measure
+ FROM __PR_SOURCE__ AS pr
+ __READY_JOIN__
+ WHERE merged_at IS NOT NULL AND merged_at >= {{date_from}} __DATE_TO_MERGED__ AND {_HUMAN_MERGES}
+ )
GROUP BY bucket_start
LIMIT 40000
"""
+def _query_merge_median_series(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+ granularity: Granularity,
+ measure: str,
+ join: str,
+ with_clause: str,
+ query_type: str,
+) -> list[tuple[datetime, float | None]]:
+ """``measure``'s median per bucket over the window's merges, oldest first and zero-filled: one
+ ``(bucket_start, p50)`` pair per bucket, p50 None where the bucket had no sample."""
+ 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:
+ placeholders["date_to"] = ast.Constant(value=date_to)
+ sql = with_clause + (
+ _MERGE_MEDIAN_SERIES_SELECT.replace("__MEASURE__", measure)
+ .replace("__READY_JOIN__", join)
+ .replace("__PR_SOURCE__", curated.pr_source())
+ .replace("__DATE_TO_MERGED__", date_to_clause)
+ .replace("__BUCKET_FN__", bucket_expr(granularity, "merged_at"))
+ )
+ response = curated.run(sql, query_type=query_type, placeholders=placeholders)
+ p50_by_bucket = {
+ normalize_bucket(bucket_start, granularity): (opt_float(p50) if (n or 0) > 0 else None)
+ for bucket_start, p50, n in response.results or []
+ }
+ return [(bucket, p50_by_bucket.get(bucket)) for bucket in window_buckets(date_from, date_to, granularity)]
+
+
def query_success_rate_series(
*,
curated: CuratedGitHubSource,
@@ -160,6 +206,34 @@ def query_success_rate_series(
]
+def query_ready_to_merge_series(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+ granularity: Granularity,
+) -> list[ReadyToMergeBucket]:
+ """Median per-PR ready_to_merge_seconds (SPEC §6) per bucket, oldest first, bots and drafts
+ excluded. Empty when the measure isn't observable, so a consumer falls back to the open-to-merge
+ series rather than reading an all-gap line as "nothing merged"."""
+ ready = curated.ready_to_merge_sql()
+ if not ready.observable:
+ return []
+ return [
+ ReadyToMergeBucket(bucket_start=bucket, p50_seconds=p50)
+ for bucket, p50 in _query_merge_median_series(
+ curated=curated,
+ date_from=date_from,
+ date_to=date_to,
+ granularity=granularity,
+ measure=ready.expr,
+ join=ready.join,
+ with_clause=ready.with_clause,
+ query_type="engineering_analytics.ready_to_merge_series",
+ )
+ ]
+
+
def query_open_to_merge_series(
*,
curated: CuratedGitHubSource,
@@ -169,32 +243,27 @@ def query_open_to_merge_series(
) -> list[OpenToMergeBucket]:
"""Median time-to-merge per bucket across the window, oldest first: p50 merged_at - created_at over PRs
merged in the bucket, bots and drafts excluded. Empty buckets carry ``p50_seconds`` None (a gap)."""
- 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:
- placeholders["date_to"] = ast.Constant(value=date_to)
- sql = (
- _OPEN_TO_MERGE_SERIES_SELECT.replace("__PR_SOURCE__", curated.pr_source())
- .replace("__DATE_TO_MERGED__", date_to_clause)
- .replace("__BUCKET_FN__", bucket_expr(granularity, "merged_at"))
- )
- response = curated.run(sql, query_type="engineering_analytics.open_to_merge_series", placeholders=placeholders)
- p50_by_bucket = {
- normalize_bucket(bucket_start, granularity): (opt_float(p50) if (n or 0) > 0 else None)
- for bucket_start, p50, n in response.results or []
- }
return [
- OpenToMergeBucket(bucket_start=bucket, p50_seconds=p50_by_bucket.get(bucket))
- for bucket in window_buckets(date_from, date_to, granularity)
+ OpenToMergeBucket(bucket_start=bucket, p50_seconds=p50)
+ for bucket, p50 in _query_merge_median_series(
+ curated=curated,
+ date_from=date_from,
+ date_to=date_to,
+ granularity=granularity,
+ measure="open_to_merge_seconds",
+ join="",
+ with_clause="",
+ query_type="engineering_analytics.open_to_merge_series",
+ )
]
@dataclass(frozen=True)
class RepoSeries:
- """The repo hub's four chart series over one window, on one shared bucket granularity.
+ """The repo hub's 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``
+ fields. Produced by ``query_repo_series`` (one bucketed scan per series) 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.
"""
@@ -204,6 +273,7 @@ class RepoSeries:
time_to_green: list[TimeToGreenBucket]
success_rate: list[PassRateBucket]
open_to_merge: list[OpenToMergeBucket]
+ ready_to_merge: list[ReadyToMergeBucket]
def query_repo_series(
@@ -212,7 +282,7 @@ def query_repo_series(
date_from: datetime,
date_to: datetime | None,
) -> RepoSeries:
- """All four chart series across the window — the one place their shared granularity is decided."""
+ """All chart series across the window: the one place their shared granularity is decided."""
granularity = pick_granularity(date_from, date_to)
return RepoSeries(
granularity=granularity,
@@ -228,6 +298,9 @@ def query_repo_series(
open_to_merge=query_open_to_merge_series(
curated=curated, date_from=date_from, date_to=date_to, granularity=granularity
),
+ ready_to_merge=query_ready_to_merge_series(
+ curated=curated, date_from=date_from, date_to=date_to, granularity=granularity
+ ),
)
@@ -240,6 +313,7 @@ def empty_repo_series(*, date_from: datetime, date_to: datetime | None) -> RepoS
time_to_green=[],
success_rate=[],
open_to_merge=[],
+ ready_to_merge=[],
)
@@ -281,14 +355,18 @@ def query_repo_overview(
pr_cur = "(merged_at >= {date_from}" + (" AND merged_at <= {date_to})" if date_to is not None else ")")
pr_prev = "(merged_at >= {prev_from} AND merged_at < {date_from})"
- pr_sql = (
- _PR_SELECT.replace("__CUR_MERGED__", pr_cur)
+ ready = curated.ready_to_merge_sql()
+ pr_sql = ready.with_clause + (
+ _PR_SELECT.replace("__READY_MEDIAN_CUR__", ready.median(scope=f"{pr_cur} AND {_HUMAN_MERGES}"))
+ .replace("__READY_MEDIAN_PREV__", ready.median(scope=f"{pr_prev} AND {_HUMAN_MERGES}"))
+ .replace("__READY_JOIN__", ready.join)
+ .replace("__CUR_MERGED__", pr_cur)
.replace("__PREV_MERGED__", pr_prev)
.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, merged_cur, merged_prev = (
- pr_response.results[0] if pr_response.results else (None, None, 0, 0)
+ median_cur, median_prev, ready_median_cur, ready_median_prev, merged_cur, merged_prev = (
+ pr_response.results[0] if pr_response.results else (None, None, None, None, 0, 0)
)
jobs_available = curated.jobs_source() is not None
@@ -316,6 +394,8 @@ def query_repo_overview(
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),
+ median_ready_to_merge_seconds=opt_float(ready_median_cur),
+ median_ready_to_merge_seconds_prev=opt_float(ready_median_prev),
billable_minutes=billable_seconds / 60 if billable_seconds is not None else None,
billable_minutes_prev=billable_seconds_prev / 60 if billable_seconds_prev is not None else None,
estimated_cost_usd=opt_float(cost_usd),
@@ -332,4 +412,6 @@ def query_repo_overview(
success_rate_series_granularity=series.granularity,
open_to_merge_series=series.open_to_merge,
open_to_merge_series_granularity=series.granularity,
+ ready_to_merge_series=series.ready_to_merge,
+ ready_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.py
index ca7ee7064024..6f857f6809b3 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py
@@ -42,6 +42,7 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impo
RUN_DURATION_PERCENTILE_CONDITION,
branch_filter_clause,
date_to_filter_clause,
+ non_default_branch_predicate,
run_duration_percentile_expr,
run_scope_filter_clause,
run_started_floor_constant,
@@ -109,12 +110,59 @@ _BUCKET_SELECT = f"""
"""
+# A push round is one (repo, head_sha): every workflow GitHub fired for that push. The measure is the
+# wall from the round's first run start to the moment its last workflow first completed benign: the
+# question a PR author asks ("how long until this push is green"), which no single run answers.
+#
+# Each workflow anchors on its FIRST benign completion, never its latest run: a flake re-run stretches
+# the wall to its recovery, while a re-fire after the round already went green cannot stretch it
+# retroactively. Benign is wider than success (a path-filtered workflow reports 'skipped' and holds
+# nothing back) and narrower than "not a decisive failure": a cancelled run reached no verdict.
+#
+# A round that can't be measured honestly is a non-sample, never a shorter one:
+# - a workflow with no benign completion (still running, or it never passed)
+# - no workflow that actually succeeded, so the round only ever skipped
+# - partial attribution: fork-PR runs land unassociated, so a per-run ``pr_number`` filter would
+# read a fork push as green in seconds. A round with any unattributed sibling drops out whole.
+#
+# Known overstatement: a workflow whose first run on the SHA lands late (marking a draft ready fires
+# workflows a draft never ran) stretches the wall, because the round really wasn't green until it
+# passed, so the wall then also covers the hours the PR sat in draft. Distinguishing that from a
+# slow queue would need a re-fire gap threshold, which is a number nobody can defend.
_TIME_TO_GREEN_SELECT = f"""
+ WITH workflows_on_push AS (
+ SELECT
+ repo_owner,
+ repo_name,
+ head_sha,
+ workflow_name,
+ min(pr_number > 0) AS attributed,
+ min(run_started_at) AS first_start,
+ min(if(
+ status = 'completed' AND coalesce(conclusion, '') IN ('success', 'skipped', 'neutral'),
+ updated_at, NULL
+ )) AS first_green_end,
+ countIf(status = 'completed' AND conclusion = 'success') > 0 AS has_success
+ FROM __RUNS_SOURCE__ AS r
+ WHERE run_started_at >= {{date_from}} __DATE_TO__
+ AND NOT r.is_merge_queue
+ AND {non_default_branch_predicate()}
+ GROUP BY repo_owner, repo_name, head_sha, workflow_name
+ ),
+ green_rounds AS (
+ SELECT
+ min(first_start) AS round_start,
+ dateDiff('second', min(first_start), max(first_green_end)) AS wall_seconds
+ FROM workflows_on_push
+ GROUP BY repo_owner, repo_name, head_sha
+ HAVING min(attributed) = 1
+ AND countIf(first_green_end IS NULL) = 0
+ AND countIf(has_success) > 0
+ )
SELECT
__BUCKET_FN__ AS bucket_start,
- {run_duration_percentile_expr(0.5)} AS p50_seconds
- FROM __RUNS_SOURCE__ AS r
- WHERE run_started_at >= {{date_from}} __DATE_TO__ __RUN_SCOPE__
+ quantile(0.5)(wall_seconds) AS p50_seconds
+ FROM green_rounds
GROUP BY bucket_start
LIMIT {_BUCKET_LIMIT}
"""
@@ -127,21 +175,19 @@ def query_time_to_green_series(
date_to: datetime | None,
granularity: Granularity,
) -> list[TimeToGreenBucket]:
- """Median time-to-green per bucket across the window, oldest first: the p50 wall-clock duration of
- successful, PR-attributed CI runs (default-branch runs excluded). Success-only + PR-scoped — the same
- population workflow-health's percentiles use — so it answers "how long until CI passes on a PR", not
- master build time. Empty buckets carry ``p50_seconds`` None (a gap, not instant CI)."""
+ """Median wall clock from a push round's first run start to all its workflows first green, per
+ bucket, oldest first, keyed on the bucket the round started in. Only fully green, fully attributed
+ rounds are samples (``_TIME_TO_GREEN_SELECT`` has the exclusions and the one known overstatement);
+ an empty bucket carries ``p50_seconds`` None (a gap, not instant CI)."""
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(started_floor=True))
.replace("__DATE_TO__", date_to_clause)
- .replace("__RUN_SCOPE__", run_scope_clause)
- .replace("__BUCKET_FN__", bucket_expr(granularity))
+ .replace("__BUCKET_FN__", bucket_expr(granularity, "round_start"))
)
response = curated.run(sql, query_type="engineering_analytics.time_to_green_series", placeholders=placeholders)
p50_by_bucket = {
diff --git a/products/engineering_analytics/backend/presentation/serializers/workflows.py b/products/engineering_analytics/backend/presentation/serializers/workflows.py
index 22a258efbc5f..266dd8924da9 100644
--- a/products/engineering_analytics/backend/presentation/serializers/workflows.py
+++ b/products/engineering_analytics/backend/presentation/serializers/workflows.py
@@ -8,6 +8,7 @@ from products.engineering_analytics.backend.facade.contracts import (
MasterFailureGroup,
OpenToMergeBucket,
PassRateBucket,
+ ReadyToMergeBucket,
RepoOverview,
RunFailureLogs,
TimeToGreenBucket,
@@ -268,8 +269,10 @@ class TimeToGreenBucketSerializer(DataclassSerializer):
"help_text": "Bucket start, aligned to time_to_green_series_granularity (top of hour, midnight, or Monday)."
},
"p50_seconds": {
- "help_text": "Median wall-clock seconds of successful PR-attributed CI runs started in this bucket. "
- "Null when the bucket had no successful PR run (a gap, not instant CI).",
+ "help_text": "Median wall-clock seconds from a PR push round's first run start until every "
+ "workflow on that head SHA first completed benign, over rounds started in this bucket "
+ "(merge-queue gates and partially-attributed fork rounds excluded). Null when the bucket had "
+ "no fully green round (a gap, not instant CI).",
"allow_null": True,
},
}
@@ -305,6 +308,22 @@ class OpenToMergeBucketSerializer(DataclassSerializer):
}
+class ReadyToMergeBucketSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = ReadyToMergeBucket
+ extra_kwargs = {
+ "bucket_start": {
+ "help_text": "Bucket start, aligned to ready_to_merge_series_granularity (top of hour, midnight, or Monday)."
+ },
+ "p50_seconds": {
+ "help_text": "Median per-PR ready_to_merge_seconds (merged_at minus the last observed "
+ "ready-for-review transition) over PRs merged in this bucket, bots and drafts excluded. "
+ "Null when nothing merged with an observed value (a gap, never zero).",
+ "allow_null": True,
+ },
+ }
+
+
class RepoOverviewSerializer(DataclassSerializer):
cost_series = CostPerMergeBucketSerializer(
many=True,
@@ -313,9 +332,9 @@ class RepoOverviewSerializer(DataclassSerializer):
)
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; the "
- "whole series is empty when include_series=false.",
+ help_text="Median time-to-green (p50 wall clock for a PR push round to settle fully green) 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.",
)
success_rate_series = PassRateBucketSerializer(
many=True,
@@ -329,6 +348,13 @@ class RepoOverviewSerializer(DataclassSerializer):
"the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null; "
"the whole series is empty when include_series=false.",
)
+ ready_to_merge_series = ReadyToMergeBucketSerializer(
+ many=True,
+ help_text="Median cycle time (p50 per-PR ready_to_merge_seconds, bots/drafts excluded) per bucket "
+ "across the window, oldest first, bucketed by ready_to_merge_series_granularity. Empty buckets carry "
+ "null; the whole series is empty when the issue-events table isn't synced or include_series=false, "
+ "so fall back to open_to_merge_series.",
+ )
class Meta:
dataclass = RepoOverview
@@ -361,6 +387,17 @@ class RepoOverviewSerializer(DataclassSerializer):
"help_text": "The same median over the previous window. Null when nothing merged.",
"allow_null": True,
},
+ "median_ready_to_merge_seconds": {
+ "help_text": "Median per-PR ready_to_merge_seconds (the true cycle time: merged_at minus the "
+ "last observed ready-for-review transition) over PRs merged in the window, bots and drafts "
+ "excluded. Null when the issue-events table isn't synced or no merged PR has an observed "
+ "value; fall back to median_open_to_merge_seconds and label it open-to-merge.",
+ "allow_null": True,
+ },
+ "median_ready_to_merge_seconds_prev": {
+ "help_text": "The same median over the previous window. Null when not observed.",
+ "allow_null": True,
+ },
"billable_minutes": {
"help_text": "Billable (self-hosted) job minutes in the window; null when the job-level source "
"isn't synced.",
@@ -403,6 +440,9 @@ class RepoOverviewSerializer(DataclassSerializer):
"open_to_merge_series_granularity": {
"help_text": "Bucket width of the open_to_merge_series trend: 'hour', 'day', or 'week'."
},
+ "ready_to_merge_series_granularity": {
+ "help_text": "Bucket width of the ready_to_merge_series trend: 'hour', 'day', or 'week'."
+ },
}
diff --git a/products/engineering_analytics/backend/tests/_logic_helpers.py b/products/engineering_analytics/backend/tests/_logic_helpers.py
index c2b51d2fbaaa..2a1e1ec1cb03 100644
--- a/products/engineering_analytics/backend/tests/_logic_helpers.py
+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py
@@ -68,6 +68,14 @@ def _ago_with_duration(days: int, duration_seconds: int) -> tuple[str, str]:
return started_at.strftime(fmt), updated_at.strftime(fmt)
+def _ago_offset_with_duration(days: int, offset_seconds: int, duration_seconds: int) -> tuple[str, str]:
+ """Like ``_ago_with_duration`` but shifted forward, so several runs can share one round anchor."""
+ started_at = timezone.now() - timedelta(days=days) + timedelta(seconds=offset_seconds)
+ updated_at = started_at + timedelta(seconds=duration_seconds)
+ fmt = "%Y-%m-%d %H:%M:%S"
+ return started_at.strftime(fmt), updated_at.strftime(fmt)
+
+
def _job_row(
job_id: int,
run_id: int,
diff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.py
index b2c5af16318a..d28fea74f4fb 100644
--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py
+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py
@@ -1,5 +1,7 @@
from datetime import UTC, datetime, timedelta
+from itertools import count
from types import SimpleNamespace
+from typing import Any
import pytest
from posthog.test.base import BaseTest
@@ -13,11 +15,13 @@ from products.engineering_analytics.backend.logic.queries._curated import Curate
from products.engineering_analytics.backend.logic.queries.pr_cost import query_cost_per_merge_series
from products.engineering_analytics.backend.logic.sources import GitHubTables
from products.engineering_analytics.backend.logic.views.source_schema import (
+ ISSUE_EVENTS_COLUMNS,
PULL_REQUESTS_COLUMNS,
WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
from products.engineering_analytics.backend.tests._github_fixtures import (
+ _issue_event_row,
_pr_row,
_run_row,
connect_github_source_without_data,
@@ -25,6 +29,7 @@ from products.engineering_analytics.backend.tests._github_fixtures import (
from products.engineering_analytics.backend.tests._logic_helpers import (
_RUN_QUERY,
_ago,
+ _ago_offset_with_duration,
_ago_with_duration,
_dt,
_EndpointsWarehouseMixin,
@@ -214,9 +219,9 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
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
+ # 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
+ # locked bots/drafts-excluded recipe, plus job-backed billable minutes, with every
# chart series empty. The default call keeps the series for the UI.
self._create_table(
"github_pull_requests",
@@ -261,16 +266,133 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
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_prev
+ assert overview.median_ready_to_merge_seconds is None # issue events unsynced: not observed, never zero
assert overview.cost_series == []
assert overview.time_to_green_series == []
assert overview.success_rate_series == []
assert overview.open_to_merge_series == []
+ assert overview.ready_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_time_to_green_measures_push_rounds_not_runs(self) -> None:
+ # A per-run median would read this fixture as ~5 min. The round definition asks a different
+ # question, how long until a push is green, so every rule below has to hold for the
+ # per-bucket medians to land where the assertions say.
+ run_ids = count(9600)
+
+ def _round(
+ head_sha: str,
+ *runs: tuple[str, str, str | None, int, int],
+ days_ago: int = 1,
+ pr_number: int | None = 90,
+ branch: str | None = None,
+ ) -> list[dict[str, Any]]:
+ """One push round's runs, each ``(workflow, status, conclusion, start offset, duration)``
+ in seconds from the round's anchor."""
+ return [
+ _run_row(
+ next(run_ids),
+ workflow,
+ head_sha,
+ status,
+ conclusion,
+ *_ago_offset_with_duration(days_ago, offset, duration),
+ pr_number=pr_number,
+ head_branch=branch or f"feat/{head_sha}",
+ )
+ for workflow, status, conclusion, offset, duration in runs
+ ]
+
+ self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [_pr_row(90, "alice", "open", 0, _ago(5), head_sha="green1")],
+ )
+ self._create_table(
+ "github_workflow_runs",
+ WORKFLOW_RUNS_COLUMNS,
+ [
+ # Lint flaked and re-ran green half an hour later, so the wall reaches the recovery
+ # (2400s) rather than any one run's duration.
+ *_round(
+ "green1",
+ ("CI", "completed", "success", 0, 600),
+ ("Lint", "completed", "failure", 0, 300),
+ ("Lint", "completed", "success", 1800, 600),
+ ),
+ # A skipped workflow holds nothing back, so this round is green at 300s.
+ *_round("green2", ("CI", "completed", "success", 0, 300), ("Docs", "completed", "skipped", 0, 60)),
+ # Green at 900s, then a re-fire failed an hour later: a later failure can neither
+ # stretch nor void a round that already went green.
+ *_round("flip1", ("CI", "completed", "success", 0, 900), ("CI", "completed", "failure", 3600, 300)),
+ # Never green: Lint never passed.
+ *_round("red1", ("CI", "completed", "success", 0, 300), ("Lint", "completed", "failure", 0, 300)),
+ # Still running.
+ *_round("pend1", ("CI", "in_progress", None, 0, 0)),
+ # Cancelled reaches no verdict, so this round never went green.
+ *_round("canc1", ("CI", "completed", "success", 0, 300), ("Deploy", "completed", "cancelled", 0, 60)),
+ # A fork push: one sibling lands unassociated, so the whole round drops. Without that
+ # guard the attributed 60s run alone would read as a green round.
+ *_round("fork1", ("Housekeeping", "completed", "success", 0, 60)),
+ *_round("fork1", ("CI", "completed", "success", 0, 60), pr_number=None),
+ # A green merge-queue gate round is CI the PR paid for, but not a push round.
+ *_round("mq1", ("CI", "completed", "success", 0, 60), branch="trunk-merge/pr-96/abc", pr_number=None),
+ # The known overstatement, pinned: a workflow first firing two hours in (what marking
+ # a draft ready does) carries the wait into the wall, because the push really wasn't
+ # green until it passed. Its own bucket, so the day above stays readable.
+ *_round(
+ "late1",
+ ("CI", "completed", "success", 0, 300),
+ ("Ready only", "completed", "success", 7200, 300),
+ days_ago=2,
+ ),
+ ],
+ )
+
+ overview = api.get_repo_overview(team=self.team)
+ observed = [b.p50_seconds for b in overview.time_to_green_series if b.p50_seconds is not None]
+ # Oldest first: late1's own wall, then the median of the round walls {2400, 300, 900}.
+ assert observed == [pytest.approx(7500.0), pytest.approx(900.0)]
+
+ def 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 ready
+ # transition (3 days), not open->merge (9 days), and keep the bot exclusion. The bot's
+ # merge bucket has no observed human value, so its series bucket must be None, not 0.
+ self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [
+ _pr_row(90, "alice", "closed", 0, _ago(10), merged_at=_ago(1), head_sha="sha90"),
+ _pr_row(91, "dependabot[bot]", "closed", 0, _ago(6), merged_at=_ago(2), head_sha="sha91"),
+ ],
+ )
+ self._create_table(
+ "github_workflow_runs",
+ WORKFLOW_RUNS_COLUMNS,
+ [_run_row(9600, "CI", "sha90", "completed", "success", _ago(1), _ago(1), pr_number=90)],
+ )
+ self._create_table(
+ "github_issue_events",
+ ISSUE_EVENTS_COLUMNS,
+ [
+ _issue_event_row(6000, "ready_for_review", 90, _ago(4)),
+ _issue_event_row(6001, "ready_for_review", 91, _ago(3)),
+ ],
+ )
+
+ overview = api.get_repo_overview(team=self.team)
+ day = 86400
+ assert overview.median_open_to_merge_seconds == pytest.approx(9 * day)
+ assert overview.median_ready_to_merge_seconds == pytest.approx(3 * day)
+ assert overview.median_ready_to_merge_seconds_prev is None # nothing merged in the prev window
+ observed = [b.p50_seconds for b in overview.ready_to_merge_series if b.p50_seconds is not None]
+ assert observed == [pytest.approx(3 * day)]
+ assert overview.ready_to_merge_series_granularity == "day"
+
def test_workflow_health_aggregates(self) -> None:
self._seed()
items = api.list_workflow_health(team=self.team, date_from="-30d")
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index a7ad64a9426b..1c37d960fb03 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -133,6 +133,8 @@ def _repo_overview() -> contracts.RepoOverview:
merged_pr_count_prev=40,
median_open_to_merge_seconds=3600.0,
median_open_to_merge_seconds_prev=4000.0,
+ median_ready_to_merge_seconds=3000.0,
+ median_ready_to_merge_seconds_prev=3500.0,
billable_minutes=100.0,
billable_minutes_prev=90.0,
estimated_cost_usd=12.5,
@@ -149,6 +151,8 @@ def _repo_overview() -> contracts.RepoOverview:
success_rate_series_granularity="day",
open_to_merge_series=[],
open_to_merge_series_granularity="day",
+ ready_to_merge_series=[],
+ ready_to_merge_series_granularity="day",
)
diff --git a/products/engineering_analytics/frontend/components/TrendCard.tsx b/products/engineering_analytics/frontend/components/TrendCard.tsx
index cc34497f3445..f2a9c4f7ed0d 100644
--- a/products/engineering_analytics/frontend/components/TrendCard.tsx
+++ b/products/engineering_analytics/frontend/components/TrendCard.tsx
@@ -8,13 +8,9 @@ import { LemonCard, LemonSkeleton } from '@posthog/lemon-ui'
import { Sparkline } from 'lib/components/Sparkline'
+import type { TrendSeries } from '../lib/trends'
import { DeltaBadge, percentChange } from './MetricTile'
-export interface TrendSeries {
- values: number[]
- labels: string[]
-}
-
export function TrendCard({
title,
series,
@@ -37,10 +33,10 @@ export function TrendCard({
}): JSX.Element {
const values = series?.values ?? []
const latest = values.length ? values[values.length - 1] : null
- // Baseline is the first point — the series builders already trim leading empty buckets and carry the
- // last value forward, so values[0] is real data, not zero-fill. A genuine leading 0 (e.g. a 0% pass
- // rate at the window's start) is a valid baseline: percentChange returns null off a zero baseline, so
- // the card shows no delta rather than mis-baselining against a later bucket.
+ // Baseline is the first point — `trendSeries` guarantees values[0] is real data, not zero-fill. A
+ // genuine leading 0 (e.g. a 0% pass rate at the window's start) is a valid baseline: percentChange
+ // returns null off a zero baseline, so the card shows no delta rather than mis-baselining against
+ // a later bucket.
const first = values.length ? values[0] : null
const deltaPct = percentChange(latest, first)
// Line color follows the delta's sentiment so the card reads at a glance: green the good way, red the
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index ea07a9f9aae8..3eb6099a54cd 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -838,7 +838,7 @@ export interface TimeToGreenBucketApi {
/** Bucket start, aligned to time_to_green_series_granularity (top of hour, midnight, or Monday). */
bucket_start: string
/**
- * Median wall-clock seconds of successful PR-attributed CI runs started in this bucket. Null when the bucket had no successful PR run (a gap, not instant CI).
+ * Median wall-clock seconds from a PR push round's first run start until every workflow on that head SHA first completed benign, over rounds started in this bucket (merge-queue gates and partially-attributed fork rounds excluded). Null when the bucket had no fully green round (a gap, not instant CI).
* @nullable
*/
p50_seconds: number | null
@@ -864,15 +864,27 @@ export interface OpenToMergeBucketApi {
p50_seconds: number | null
}
+export interface ReadyToMergeBucketApi {
+ /** Bucket start, aligned to ready_to_merge_series_granularity (top of hour, midnight, or Monday). */
+ bucket_start: string
+ /**
+ * Median per-PR ready_to_merge_seconds (merged_at minus the last observed ready-for-review transition) over PRs merged in this bucket, bots and drafts excluded. Null when nothing merged with an observed value (a gap, never zero).
+ * @nullable
+ */
+ p50_seconds: number | null
+}
+
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 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; the whole series is empty when include_series=false. */
+ /** Median time-to-green (p50 wall clock for a PR push round to settle fully green) 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; 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; the whole series is empty when include_series=false. */
open_to_merge_series: OpenToMergeBucketApi[]
+ /** Median cycle time (p50 per-PR ready_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by ready_to_merge_series_granularity. Empty buckets carry null; the whole series is empty when the issue-events table isn't synced or include_series=false, so fall back to open_to_merge_series. */
+ ready_to_merge_series: ReadyToMergeBucketApi[]
/** Workflow runs started in the window, all branches and workflows. */
run_count: number
/** Same count over the equal-length window immediately before date_from — the delta baseline. */
@@ -905,6 +917,16 @@ export interface RepoOverviewApi {
* @nullable
*/
median_open_to_merge_seconds_prev: number | null
+ /**
+ * Median per-PR ready_to_merge_seconds (the true cycle time: merged_at minus the last observed ready-for-review transition) over PRs merged in the window, bots and drafts excluded. Null when the issue-events table isn't synced or no merged PR has an observed value; fall back to median_open_to_merge_seconds and label it open-to-merge.
+ * @nullable
+ */
+ median_ready_to_merge_seconds: number | null
+ /**
+ * The same median over the previous window. Null when not observed.
+ * @nullable
+ */
+ median_ready_to_merge_seconds_prev: number | null
/**
* Billable (self-hosted) job minutes in the window; null when the job-level source isn't synced.
* @nullable
@@ -947,6 +969,8 @@ export interface RepoOverviewApi {
success_rate_series_granularity: string
/** Bucket width of the open_to_merge_series trend: 'hour', 'day', or 'week'. */
open_to_merge_series_granularity: string
+ /** Bucket width of the ready_to_merge_series trend: 'hour', 'day', or 'week'. */
+ ready_to_merge_series_granularity: string
}
export interface WorkflowRunActivityPointApi {
diff --git a/products/engineering_analytics/frontend/lib/trends.test.ts b/products/engineering_analytics/frontend/lib/trends.test.ts
new file mode 100644
index 000000000000..93b444f86185
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/trends.test.ts
@@ -0,0 +1,33 @@
+import { trendSeries } from './trends'
+
+describe('trendSeries', () => {
+ const buckets = (values: (number | null)[]): { bucket_start: string; value: number | null }[] =>
+ values.map((value, index) => ({ bucket_start: `2026-06-0${index + 1}T00:00:00Z`, value }))
+
+ const read = (bucket: { value: number | null }): number | null => bucket.value
+
+ it('is null when nothing was measured, so the card can show its empty state', () => {
+ expect(trendSeries(buckets([null, null]), read, 'day')).toBeNull()
+ expect(trendSeries([], read, 'day')).toBeNull()
+ })
+
+ it('drops leading empty buckets so the delta baselines against a measured value', () => {
+ // Without the trim the card would baseline on a zero-filled bucket and report a false rise.
+ expect(trendSeries(buckets([null, null, 10, 12]), read, 'day')).toEqual({
+ values: [10, 12],
+ labels: ['Jun 3', 'Jun 4'],
+ })
+ })
+
+ it('carries the last value across a gap instead of dipping to zero', () => {
+ expect(trendSeries(buckets([10, null, 12]), read, 'day')?.values).toEqual([10, 10, 12])
+ })
+
+ it('keeps a measured zero, which is a value rather than a gap', () => {
+ expect(trendSeries(buckets([10, 0, 12]), read, 'day')?.values).toEqual([10, 0, 12])
+ })
+
+ it('labels hourly buckets with the time', () => {
+ expect(trendSeries(buckets([10]), read, 'hour')?.labels).toEqual(['Jun 1 00:00'])
+ })
+})
diff --git a/products/engineering_analytics/frontend/lib/trends.ts b/products/engineering_analytics/frontend/lib/trends.ts
new file mode 100644
index 000000000000..757053400769
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/trends.ts
@@ -0,0 +1,41 @@
+import { dayjs } from 'lib/dayjs'
+
+/** A sparkline's plot: one value per label, oldest first, with no gaps left in either. */
+export interface TrendSeries {
+ values: number[]
+ labels: string[]
+}
+
+/** The API's bucketed series shape: oldest first, one bucket per interval across the window. */
+interface Bucketed {
+ bucket_start: string
+}
+
+/**
+ * A bucketed API series as a `TrendCard` plot, or null when no bucket carries a value — the card
+ * then shows its own empty state instead of a flat line.
+ *
+ * Empty buckets are a gap in the measurement ("nothing merged", "no run to time"), never a zero, so
+ * the two ways a gap can appear are both handled here rather than per metric: leading empty buckets
+ * are dropped, so the line opens on real data and the card's delta baselines against a real value,
+ * and a later gap carries the last known value forward instead of dipping to zero.
+ */
+export function trendSeries<T extends Bucketed>(
+ buckets: T[],
+ value: (bucket: T) => number | null | undefined,
+ granularity: string | undefined
+): TrendSeries | null {
+ const firstMeasured = buckets.findIndex((bucket) => value(bucket) != null)
+ if (firstMeasured === -1) {
+ return null
+ }
+ const labelFormat = granularity === 'hour' ? 'MMM D HH:mm' : 'MMM D'
+ const series: TrendSeries = { values: [], labels: [] }
+ let carried = 0
+ for (const bucket of buckets.slice(firstMeasured)) {
+ carried = value(bucket) ?? carried
+ series.values.push(carried)
+ series.labels.push(dayjs(bucket.bucket_start).format(labelFormat))
+ }
+ return series
+}
diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx
index 9e6925704fde..67a7352df304 100644
--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx
+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx
@@ -30,6 +30,8 @@ const OVERVIEW: RepoOverviewApi = {
merged_pr_count_prev: 49,
median_open_to_merge_seconds: 14 * 3600,
median_open_to_merge_seconds_prev: 19 * 3600,
+ median_ready_to_merge_seconds: 9 * 3600,
+ median_ready_to_merge_seconds_prev: 12 * 3600,
billable_minutes: 5230,
billable_minutes_prev: 4890,
estimated_cost_usd: 412.5,
@@ -63,6 +65,13 @@ const OVERVIEW: RepoOverviewApi = {
})
),
open_to_merge_series_granularity: 'day',
+ ready_to_merge_series: [9 * 3600, 11 * 3600, null, 8 * 3600, 10 * 3600, 12 * 3600, 9 * 3600].map(
+ (p50_seconds, i) => ({
+ bucket_start: `2026-06-${25 + i}T00:00:00Z`,
+ p50_seconds,
+ })
+ ),
+ ready_to_merge_series_granularity: 'day',
}
const ACTIVITY: WorkflowRunActivityApi = {
diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
index a8d25add93d2..0bb11c8a3072 100644
--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
@@ -4,11 +4,9 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { LemonButton, LemonCard, LemonSkeleton, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
-import { TimeSeriesLineChart, useChartTheme } from '@posthog/quill-charts'
+import { LemonButton, LemonCard, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
import { humanFriendlyNumber } from 'lib/utils/numbers'
-import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
@@ -40,6 +38,7 @@ export function RepoOverviewScene(): JSX.Element {
timeToGreenSeries,
passRateSeries,
openToMergeSeries,
+ readyToMergeSeries,
jobsAvailable,
overviewDefaultBranch,
notConnected,
@@ -52,8 +51,6 @@ export function RepoOverviewScene(): JSX.Element {
useValues(engineeringAnalyticsLogic)
const { loadOverview, loadRepoActivity, showMorePrs, showMoreWorkflows } = useActions(repoOverviewLogic)
const { searchParams } = useValues(router)
- const { timezone } = useValues(teamLogic)
- const chartTheme = useChartTheme()
// Window/source changes reload the overview, activity, and workflow health (the date-scoped
// surfaces); the PR backlog is current-state, not windowed, so it stays put. Surface the reload
@@ -76,6 +73,23 @@ export function RepoOverviewScene(): JSX.Element {
// during the initial fetch would misread as a broken setup — hold it back while loading.
const overviewPending = overviewLoading && !overview
+ // Cycle time is ready→merge wherever the backend can observe the draft/ready transitions. Without
+ // them it falls back to the coarse created→merged span and says so, rather than labelling one
+ // measure with the other's name.
+ const cycleTime = readyToMergeSeries
+ ? {
+ title: 'Median PR ready→merge',
+ series: readyToMergeSeries,
+ caption:
+ 'Median ready-for-review to merged time, bots and drafts excluded. Time as a draft is not counted.',
+ }
+ : {
+ title: 'Median PR open→merge',
+ series: openToMergeSeries,
+ caption:
+ 'Median created-to-merged time, bots and drafts excluded. Coarse: draft and ready time are fused.',
+ }
+
if (notConnected) {
return <ConnectGitHubSource />
}
@@ -147,7 +161,6 @@ export function RepoOverviewScene(): JSX.Element {
caption="Share of completed CI runs that passed, all branches."
/>
- {/* Median time-to-green on PR runs (success-only, PR-scoped; see #67398). */}
<TrendCard
title="PR time to green"
series={timeToGreenSeries}
@@ -155,61 +168,35 @@ export function RepoOverviewScene(): JSX.Element {
renderTooltipValue={formatAxisMinutes}
goodWhenDown
loading={overviewPending}
- emptyText="Not enough successful PR CI runs in the window yet."
- caption="Median time-to-green on pull requests: successful runs only, default branch excluded."
+ emptyText="No fully green PR pushes in the window yet."
+ caption="Median time from a push until every workflow on it is green. Only fully green pushes count."
/>
- {/* PR throughput: coarse created→merged time, bots and drafts excluded. */}
<TrendCard
- title="Median PR open→merge"
- series={openToMergeSeries}
+ title={cycleTime.title}
+ series={cycleTime.series}
formatValue={compactHoursLabel}
renderTooltipValue={compactHoursLabel}
goodWhenDown
loading={overviewPending}
emptyText="No PRs merged in the window yet."
- caption="Median created-to-merged time, bots and drafts excluded. Coarse: draft and ready time are fused."
+ caption={cycleTime.caption}
/>
- {/* CI cost per merged PR — the headline economic trend, so it earns a full quill line
- chart (axes + tooltip) rather than a sparkline. costPerMergeSeries carries ISO labels
- plus its interval; the chart owns tick/tooltip date formatting. Card chrome mirrors
- TrendCard so it sits flush in the grid. */}
- <LemonCard hoverEffect={false} className="flex flex-col p-4">
- <h3 className="mb-1 text-xs font-semibold text-secondary">Cost per merged PR</h3>
- {overviewPending ? (
- <LemonSkeleton className="h-20 w-full" />
- ) : jobsAvailable && costPerMergeSeries ? (
- <div className="h-20 w-full">
- <TimeSeriesLineChart
- series={[
- {
- key: 'cost_per_merge',
- label: 'Cost per merged PR',
- data: costPerMergeSeries.values,
- },
- ]}
- labels={costPerMergeSeries.labels}
- theme={chartTheme}
- config={{
- xAxis: { timezone, interval: costPerMergeSeries.interval },
- yAxis: { format: 'currency', currency: 'USD' },
- tooltip: { valueFormatter: (value) => compactUsd(value) },
- }}
- />
- </div>
- ) : (
- <div className="flex h-20 items-center text-xs text-secondary">
- {jobsAvailable
- ? 'No costable jobs in the window.'
- : 'Cost appears once the job-level source is synced.'}
- </div>
- )}
- <div className="mt-2 border-t border-primary pt-2 text-[11px] text-tertiary">
- Estimated Depot CI cost per merged PR, trailing-window ratio. Per-workflow spend is in
- Workflows below.
- </div>
- </LemonCard>
+ <TrendCard
+ title="Cost per merged PR"
+ series={jobsAvailable ? costPerMergeSeries : null}
+ formatValue={compactUsd}
+ renderTooltipValue={compactUsd}
+ goodWhenDown
+ loading={overviewPending}
+ emptyText={
+ jobsAvailable
+ ? 'No costable jobs in the window.'
+ : 'Cost appears once the job-level source is synced.'
+ }
+ caption="Estimated Depot CI cost per merged PR, trailing-window ratio. Per-workflow spend is in Workflows below."
+ />
</div>
</Section>
diff --git a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
index 627074a4b1fe..882789c4d083 100644
--- a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
@@ -9,6 +9,7 @@ import { engineeringAnalyticsRepoOverview, engineeringAnalyticsRepoRunActivity }
import type { RepoOverviewApi, WorkflowRunActivityApi } from '../generated/api.schemas'
import { ciStatusOf } from '../lib/ci'
import { HUB_PREVIEW_MAX, HUB_PREVIEW_ROWS, HUB_PREVIEW_STEP } from '../lib/preview'
+import { type TrendSeries, trendSeries } from '../lib/trends'
import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import { PullRequestRow, STUCK_AFTER_DAYS, engineeringAnalyticsLogic, isStuck } from './engineeringAnalyticsLogic'
import type { WorkflowHealthRow } from './engineeringAnalyticsLogic'
@@ -38,34 +39,22 @@ export interface repoOverviewLogicValues {
activityTruncated: boolean
attentionPrs: PullRequestRow[]
costByWorkflow: CostShareRow[]
- costPerMergeSeries: {
- interval: 'day' | 'hour' | 'week'
- labels: string[]
- values: number[]
- } | null
+ costPerMergeSeries: TrendSeries | null
draftCount: number
jobsAvailable: boolean
- openToMergeSeries: {
- labels: string[]
- values: number[]
- } | null
+ openToMergeSeries: TrendSeries | null
otherCostWorkflowCount: number
overview: RepoOverviewApi | null
overviewDefaultBranch: string
overviewFailed: boolean
overviewLoading: boolean
- passRateSeries: {
- labels: string[]
- values: number[]
- } | null
+ passRateSeries: TrendSeries | null
prPreviewCount: number
+ readyToMergeSeries: TrendSeries | null
repoActivity: WorkflowRunActivityApi
repoActivityFailed: boolean
repoActivityLoading: boolean
- timeToGreenSeries: {
- labels: string[]
- values: number[]
- } | null
+ timeToGreenSeries: TrendSeries | null
workflowPreviewCount: number
}
@@ -120,23 +109,11 @@ export interface repoOverviewLogicMeta {
draftCount: (pullRequests: PullRequestRow[]) => number
costByWorkflow: (workflowHealth: WorkflowHealthRow[]) => CostShareRow[]
otherCostWorkflowCount: (workflowHealth: WorkflowHealthRow[]) => number
- costPerMergeSeries: (overview: RepoOverviewApi | null) => {
- interval: 'day' | 'hour' | 'week'
- labels: string[]
- values: number[]
- } | null
- timeToGreenSeries: (overview: RepoOverviewApi | null) => {
- labels: string[]
- values: number[]
- } | null
- passRateSeries: (overview: RepoOverviewApi | null) => {
- labels: string[]
- values: number[]
- } | null
- openToMergeSeries: (overview: RepoOverviewApi | null) => {
- labels: string[]
- values: number[]
- } | null
+ costPerMergeSeries: (overview: RepoOverviewApi | null) => TrendSeries | null
+ timeToGreenSeries: (overview: RepoOverviewApi | null) => TrendSeries | null
+ passRateSeries: (overview: RepoOverviewApi | null) => TrendSeries | null
+ openToMergeSeries: (overview: RepoOverviewApi | null) => TrendSeries | null
+ readyToMergeSeries: (overview: RepoOverviewApi | null) => TrendSeries | null
}
}
@@ -311,98 +288,57 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
workflowHealth.filter((row) => (row.estimatedCostUsd ?? 0) > 0).length - TOP_COST_WORKFLOWS
),
],
- // Cost-per-merged-PR trend for the Cost section — the "is CI spend per shipped change creeping
- // up" chart. The backend delivers a trailing rolling ratio, so a null only means the whole
- // trailing window shipped nothing; plotted as 0 to keep the axis anchored. Null when the series
- // is empty (job source unsynced), so the section falls back to its existing empty state.
- // Labels stay ISO — the quill time-series chart owns tick/tooltip date formatting.
+ // The Trends strip, one selector per card. Each hands `trendSeries` the bucket list and the
+ // measure to read off a bucket; gap and baseline handling is the same for all of them and
+ // lives there.
+ // Cost per merged PR is a trailing rolling ratio, so a gap means the whole trailing window
+ // shipped nothing; carried forward like the rest, never drawn as $0 of CI.
costPerMergeSeries: [
(s) => [s.overview],
- (
- overview: RepoOverviewApi | null
- ): { values: number[]; labels: string[]; interval: 'hour' | 'day' | 'week' } | null => {
- const series = overview?.cost_series ?? []
- const firstData = series.findIndex((bucket) => bucket.cost_per_merge_usd != null)
- if (firstData === -1) {
- return null
- }
- const granularity = overview?.cost_series_granularity
- return {
- values: series.map((bucket) => bucket.cost_per_merge_usd ?? 0),
- labels: series.map((bucket) => bucket.bucket_start),
- interval: granularity === 'hour' ? 'hour' : granularity === 'week' ? 'week' : 'day',
- }
- },
+ (overview: RepoOverviewApi | null): TrendSeries | null =>
+ trendSeries(
+ overview?.cost_series ?? [],
+ (bucket) => bucket.cost_per_merge_usd,
+ overview?.cost_series_granularity
+ ),
],
- // Time-to-green trend (median success-only PR CI duration) in minutes. Empty buckets carry the last
- // known value forward — a gap means "no new PR run to time", not 0 min, so zero-filling would draw a
- // false dip. Trimmed to start at the first bucket with data so the line doesn't open on flat zeros.
- // Null when no bucket has a successful PR run, so the card shows its own empty state.
+ // In minutes, the unit the card's formatter labels.
timeToGreenSeries: [
(s) => [s.overview],
- (overview: RepoOverviewApi | null): { values: number[]; labels: string[] } | null => {
- const series = overview?.time_to_green_series ?? []
- const firstData = series.findIndex((bucket) => bucket.p50_seconds != null)
- if (firstData === -1) {
- return null
- }
- const fmt = overview?.time_to_green_series_granularity === 'hour' ? 'MMM D HH:mm' : 'MMM D'
- const trimmed = series.slice(firstData)
- let last = 0
- const values = trimmed.map((bucket) => {
- if (bucket.p50_seconds != null) {
- last = Math.round((bucket.p50_seconds / 60) * 10) / 10
- }
- return last
- })
- return { values, labels: trimmed.map((bucket) => dayjs(bucket.bucket_start).format(fmt)) }
- },
+ (overview: RepoOverviewApi | null): TrendSeries | null =>
+ trendSeries(
+ overview?.time_to_green_series ?? [],
+ (bucket) => (bucket.p50_seconds == null ? null : bucket.p50_seconds / 60),
+ overview?.time_to_green_series_granularity
+ ),
],
- // Pass-rate trend (0-1). Empty buckets carry the last known value forward so a gap (no completed
- // run) draws no false dip to zero; trimmed to start at the first bucket with data. Null when no
- // bucket has a completed run, so the card shows its own empty state.
passRateSeries: [
(s) => [s.overview],
- (overview: RepoOverviewApi | null): { values: number[]; labels: string[] } | null => {
- const series = overview?.success_rate_series ?? []
- const firstData = series.findIndex((bucket) => bucket.success_rate != null)
- if (firstData === -1) {
- return null
- }
- const fmt = overview?.success_rate_series_granularity === 'hour' ? 'MMM D HH:mm' : 'MMM D'
- const trimmed = series.slice(firstData)
- let last = 0
- const values = trimmed.map((bucket) => {
- if (bucket.success_rate != null) {
- last = bucket.success_rate
- }
- return last
- })
- return { values, labels: trimmed.map((bucket) => dayjs(bucket.bucket_start).format(fmt)) }
- },
+ (overview: RepoOverviewApi | null): TrendSeries | null =>
+ trendSeries(
+ overview?.success_rate_series ?? [],
+ (bucket) => bucket.success_rate,
+ overview?.success_rate_series_granularity
+ ),
],
- // Time-to-merge trend in seconds (median open→merge, bots/drafts excluded). Same carry-forward +
- // trim as time-to-green: a gap means "nothing merged", not instant merges, so zero-filling would
- // draw a false dip. Null when no bucket had a qualifying merge.
openToMergeSeries: [
(s) => [s.overview],
- (overview: RepoOverviewApi | null): { values: number[]; labels: string[] } | null => {
- const series = overview?.open_to_merge_series ?? []
- const firstData = series.findIndex((bucket) => bucket.p50_seconds != null)
- if (firstData === -1) {
- return null
- }
- const fmt = overview?.open_to_merge_series_granularity === 'hour' ? 'MMM D HH:mm' : 'MMM D'
- const trimmed = series.slice(firstData)
- let last = 0
- const values = trimmed.map((bucket) => {
- if (bucket.p50_seconds != null) {
- last = bucket.p50_seconds
- }
- return last
- })
- return { values, labels: trimmed.map((bucket) => dayjs(bucket.bucket_start).format(fmt)) }
- },
+ (overview: RepoOverviewApi | null): TrendSeries | null =>
+ trendSeries(
+ overview?.open_to_merge_series ?? [],
+ (bucket) => bucket.p50_seconds,
+ overview?.open_to_merge_series_granularity
+ ),
+ ],
+ // Null when the backend can't observe ready→merge, and the scene falls back to openToMergeSeries.
+ readyToMergeSeries: [
+ (s) => [s.overview],
+ (overview: RepoOverviewApi | null): TrendSeries | null =>
+ trendSeries(
+ overview?.ready_to_merge_series ?? [],
+ (bucket) => bucket.p50_seconds,
+ overview?.ready_to_merge_series_granularity
+ ),
],
}),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0117787ea7de..813feab73c27 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -66586,6 +66586,16 @@ export namespace Schemas {
createdAt: string | null;
}
+ export interface ReadyToMergeBucket {
+ /** Bucket start, aligned to ready_to_merge_series_granularity (top of hour, midnight, or Monday). */
+ bucket_start: string;
+ /**
+ * Median per-PR ready_to_merge_seconds (merged_at minus the last observed ready-for-review transition) over PRs merged in this bucket, bots and drafts excluded. Null when nothing merged with an observed value (a gap, never zero).
+ * @nullable
+ */
+ p50_seconds: number | null;
+ }
+
/**
* Request body for triggering a metrics recalculation.
*/
@@ -66779,7 +66789,7 @@ export namespace Schemas {
/** Bucket start, aligned to time_to_green_series_granularity (top of hour, midnight, or Monday). */
bucket_start: string;
/**
- * Median wall-clock seconds of successful PR-attributed CI runs started in this bucket. Null when the bucket had no successful PR run (a gap, not instant CI).
+ * Median wall-clock seconds from a PR push round's first run start until every workflow on that head SHA first completed benign, over rounds started in this bucket (merge-queue gates and partially-attributed fork rounds excluded). Null when the bucket had no fully green round (a gap, not instant CI).
* @nullable
*/
p50_seconds: number | null;
@@ -66788,12 +66798,14 @@ 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 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; the whole series is empty when include_series=false. */
+ /** Median time-to-green (p50 wall clock for a PR push round to settle fully green) 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; 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; the whole series is empty when include_series=false. */
open_to_merge_series: OpenToMergeBucket[];
+ /** Median cycle time (p50 per-PR ready_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by ready_to_merge_series_granularity. Empty buckets carry null; the whole series is empty when the issue-events table isn't synced or include_series=false, so fall back to open_to_merge_series. */
+ ready_to_merge_series: ReadyToMergeBucket[];
/** Workflow runs started in the window, all branches and workflows. */
run_count: number;
/** Same count over the equal-length window immediately before date_from — the delta baseline. */
@@ -66826,6 +66838,16 @@ export namespace Schemas {
* @nullable
*/
median_open_to_merge_seconds_prev: number | null;
+ /**
+ * Median per-PR ready_to_merge_seconds (the true cycle time: merged_at minus the last observed ready-for-review transition) over PRs merged in the window, bots and drafts excluded. Null when the issue-events table isn't synced or no merged PR has an observed value; fall back to median_open_to_merge_seconds and label it open-to-merge.
+ * @nullable
+ */
+ median_ready_to_merge_seconds: number | null;
+ /**
+ * The same median over the previous window. Null when not observed.
+ * @nullable
+ */
+ median_ready_to_merge_seconds_prev: number | null;
/**
* Billable (self-hosted) job minutes in the window; null when the job-level source isn't synced.
* @nullable
@@ -66868,6 +66890,8 @@ export namespace Schemas {
success_rate_series_granularity: string;
/** Bucket width of the open_to_merge_series trend: 'hour', 'day', or 'week'. */
open_to_merge_series_granularity: string;
+ /** Bucket width of the ready_to_merge_series trend: 'hour', 'day', or 'week'. */
+ ready_to_merge_series_granularity: string;
}
export type ReportPriority = typeof ReportPriority[keyof typeof ReportPriority];