:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(engineering-analytics): repo hub cost trend and commit scatter (#68556)
Julian Bezadcbb03c57b5
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex ea025773beb1..17d9054968ba 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -293,6 +293,23 @@ def get_repo_overview()+def get_repo_run_activity(+ *,+ team: Team,+ date_from: str | None = None,+ date_to: str | None = None,+ branch: str | None = None,+ source_id: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> WorkflowRunActivity:+ return logic.build_repo_run_activity(+ curated=_authorized_source(team, source_id, user_access_control),+ date_from=date_from,+ date_to=date_to,+ branch=branch,+ )++def list_master_failures(*,team: Team,diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex e7578ac209a5..9ebfb9ddab08 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -620,6 +620,31 @@ class WorkflowHealthItem:success_rate_prev: float | None = None+@dataclass(frozen=True)+class CostPerMergeBucket:+ """One time bucket of the repo's CI cost normalized by merged PRs — the "is CI spend per shipped+ change trending up" series. ``cost_per_merge_usd`` is the headline: estimated Depot cost over a+ trailing window ending at this bucket (24 h / 7 d / 4 w to match the grain) divided by PRs merged+ in the same trailing window. The rolling ratio exists because a strict per-bucket division has a+ hole in every bucket that shipped nothing and pairs spend with merges that usually happened a+ bucket later. Cost counts by run start and merges by merge time — the same coarse alignment the+ daily depot tooling uses. ``estimated_cost_usd`` and ``merges`` stay bucket-local (the raw inputs);+ empty buckets are zero-filled: ``merges`` 0, cost None.+ """++ # Bucket start, aligned to the granularity (top of hour / midnight / Monday).+ bucket_start: datetime+ # Estimated Depot CI cost (USD) of all runs started in this bucket. None when nothing was costable+ # (no billable self-hosted Linux jobs, or the job source isn't synced).+ estimated_cost_usd: float | None+ # PRs merged in this bucket (all authors, bots included — matches the cost numerator's population).+ merges: int+ # Trailing-window cost / trailing-window merges (window sized to the grain). None when the trailing+ # window had no merges or no costable cost, so a dead stretch is never shown as an infinite or zero+ # cost-per-merge.+ cost_per_merge_usd: float | None++@dataclass(frozen=True)class RepoOverview:"""Repo-level headline aggregates for the landing page, each with its previous-window twin@@ -644,6 +669,11 @@ class RepoOverview:jobs_available: bool# 'master' or 'main', picked by observed run volume in the current window.default_branch: str+ # Cost-per-merged-PR trend across the window, oldest first, zero-filled, bucketed by+ # `cost_series_granularity`. Empty when the job-level source isn't synced.+ cost_series: list[CostPerMergeBucket]+ # Bucket width of `cost_series`, chosen to fit the window: 'hour', 'day', or 'week'.+ cost_series_granularity: str@dataclass(frozen=True)diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 8c416dee327c..6df101e82a36 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -52,6 +52,7 @@ from products.engineering_analytics.backend.logic.queries.pr_lifecycle import qufrom 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_listfrom products.engineering_analytics.backend.logic.queries.repo_overview import query_default_branch, query_repo_overview+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_jobsfrom products.engineering_analytics.backend.logic.queries.workflow_run import query_workflow_run@@ -266,6 +267,21 @@ def build_repo_overview(return query_repo_overview(curated=curated, date_from=parsed_from, date_to=parsed_to)+def build_repo_run_activity(+ *,+ curated: CuratedGitHubSource,+ date_from: str | None = None,+ date_to: str | None = None,+ branch: str | None = None,+) -> WorkflowRunActivity:+ parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)+ resolved_branch = (branch or "").strip()+ if not resolved_branch:+ # No branch given: collapse the repo's default branch, as observed in the window.+ resolved_branch = query_default_branch(curated=curated, date_from=parsed_from, date_to=parsed_to)+ return query_repo_run_activity(curated=curated, date_from=parsed_from, date_to=parsed_to, branch=resolved_branch)++def build_master_failures(*,curated: CuratedGitHubSource,diff --git a/products/engineering_analytics/backend/logic/queries/_buckets.py b/products/engineering_analytics/backend/logic/queries/_buckets.pynew file mode 100644index 000000000000..cfa6d86ee32d--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/_buckets.py@@ -0,0 +1,69 @@+"""Shared time-bucketing helpers for the windowed trend series.++The per-bucket history adapts its granularity to the window length (hour / day / week)+so a trend keeps a readable number of points — per-day buckets are useless for a 24h+window and far too many for a year. Used by the workflow-health sparkline and the repo+hub's cost-per-merge series, so the two agree on grain and bucket alignment.+"""++from datetime import date, datetime, timedelta+from typing import Literal++Granularity = Literal["hour", "day", "week"]++_BUCKET_STEP: dict[Granularity, timedelta] = {+ "hour": timedelta(hours=1),+ "day": timedelta(days=1),+ "week": timedelta(weeks=1),+}+++def bucket_expr(granularity: Granularity, column: str = "run_started_at") -> str:+ """ClickHouse truncation expression for ``column`` at ``granularity``. Week starts Monday (mode 1)."""+ if granularity == "hour":+ return f"toStartOfHour({column})"+ if granularity == "day":+ return f"toStartOfDay({column})"+ return f"toStartOfWeek({column}, 1)"+++def pick_granularity(date_from: datetime, date_to: datetime | None) -> Granularity:+ """Hour for short windows, week for long ones — keeps the series at a readable point count."""+ end = date_to or datetime.now(tz=date_from.tzinfo)+ span = end - date_from+ if span <= timedelta(hours=48):+ return "hour"+ if span <= timedelta(days=90):+ return "day"+ return "week"+++def window_buckets(date_from: datetime, date_to: datetime | None, granularity: Granularity) -> list[datetime]:+ """Every bucket start across the window, oldest first — the zero-fill spine a sparse series maps onto."""+ end = date_to or datetime.now(tz=date_from.tzinfo)+ start = normalize_bucket(date_from, granularity)+ end_aligned = normalize_bucket(end, granularity)+ if end_aligned < start:+ return []+ step = _BUCKET_STEP[granularity]+ buckets: list[datetime] = []+ current = start+ while current <= end_aligned:+ buckets.append(current)+ current += step+ return buckets+++def normalize_bucket(value: datetime | date, granularity: Granularity) -> datetime:+ """Align a timestamp to its bucket start, tz-naive, so query rows and the zero-fill spine key alike.++ ClickHouse can hand the bucket back as a ``date`` (date/week truncation) or a ``datetime``+ (hour truncation); widen the former so both sides key on the same type.+ """+ naive = value.replace(tzinfo=None) if isinstance(value, datetime) else datetime(value.year, value.month, value.day)+ if granularity == "hour":+ return naive.replace(minute=0, second=0, microsecond=0)+ midnight = naive.replace(hour=0, minute=0, second=0, microsecond=0)+ if granularity == "week":+ return midnight - timedelta(days=midnight.weekday())+ return midnightdiff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.pyindex 71e3b0053265..3e487f9c1899 100644--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py@@ -16,12 +16,20 @@ from typing import Anyfrom posthog.hogql import astfrom products.engineering_analytics.backend.facade.contracts import (+ CostPerMergeBucket,PRCostSummary,RunCost,WorkflowCost,WorkflowRunnerCost,)from products.engineering_analytics.backend.logic.cost import PRCostAggregate, aggregate_pr_cost, runner_descriptor+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# Pre-aggregated per (workflow, run, attempt, runner-label) — a raw per-job SELECT has no LIMIT, so HogQL@@ -337,6 +345,121 @@ def query_workflow_window_costs_with_prev()+# CI cost per merged PR over time (repo hub's Cost section trend). Two bucketed scans — cost by run+# start, merges by merge time — folded together per bucket. Cost stays a Python rollup (aggregate_pr_cost)+# so the runner-tier multiplier never leaves the backend; only the finished/elapsed/unfinished group+# columns cross from HogQL, same as every other cost query here.+_COST_SERIES_SELECT = """+ SELECT+ __BUCKET_FN__ AS bucket_start,+ j.labels,+ countIf(j.duration_seconds IS NOT NULL) AS finished,+ sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,+ countIf(j.duration_seconds IS NULL) AS unfinished+ FROM __JOBS_SOURCE__ AS j+ INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt+ WHERE r.run_started_at >= {date_from} __DATE_TO__+ GROUP BY bucket_start, j.labels+ LIMIT 1000000+"""++# The headline ratio is a trailing rolling window, not a per-bucket division: a strict per-bucket+# cost/merges has a hole in every bucket that shipped nothing (most hours, quiet weekends), and it+# pairs a bucket's spend with that same bucket's merges even though a PR's CI usually ran before its+# merge bucket. Summing cost and merges over a trailing window sized to the grain smooths both out+# while keeping the whole-bill economics (master/scheduled spend included). Buckets near date_from+# see a partial window — the scans are window-bounded, so there's no pre-window data to reach back to.+_ROLLING_BUCKETS: dict[Granularity, int] = {"hour": 24, "day": 7, "week": 4}++# Merged PRs per bucket — the divisor. All authors and bots, no draft/bot filter, so the population+# matches the cost numerator (every run counted, whoever triggered it); a merged PR is never a draft.+_MERGES_SERIES_SELECT = """+ SELECT __BUCKET_FN__ AS bucket_start, count() AS merges+ FROM __PR_SOURCE__ AS pr+ WHERE merged_at IS NOT NULL AND merged_at >= {date_from} __DATE_TO_MERGED__+ GROUP BY bucket_start+ LIMIT 40000+"""+++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 = pick_granularity(date_from, date_to)+ jobs_source = curated.jobs_source()+ if jobs_source is None:+ return granularity, []++ placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}+ date_to_runs = ""+ date_to_merged = ""+ if date_to is not None:+ date_to_runs = "AND r.run_started_at <= {date_to}"+ date_to_merged = "AND merged_at <= {date_to}"+ placeholders["date_to"] = ast.Constant(value=date_to)++ cost_sql = (+ _COST_SERIES_SELECT.replace("__JOBS_SOURCE__", jobs_source)+ .replace("__RUNS_SOURCE__", curated.run_source())+ .replace("__BUCKET_FN__", bucket_expr(granularity, "r.run_started_at"))+ .replace("__DATE_TO__", date_to_runs)+ )+ cost_response = curated.run(+ cost_sql, query_type="engineering_analytics.cost_per_merge_cost", placeholders=placeholders+ )+ jobs_by_bucket: dict[datetime, list[tuple[list[str], float | None]]] = defaultdict(list)+ for bucket_start, labels, finished, elapsed, unfinished in cost_response.results or []:+ key = normalize_bucket(bucket_start, granularity)+ jobs_by_bucket[key].extend(+ _expand_jobs(_parse_labels(labels), int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))+ )+ cost_by_bucket = {bucket: aggregate_pr_cost(jobs).estimated_cost_usd for bucket, jobs in jobs_by_bucket.items()}++ merges_sql = (+ _MERGES_SERIES_SELECT.replace("__PR_SOURCE__", curated.pr_source())+ .replace("__BUCKET_FN__", bucket_expr(granularity, "merged_at"))+ .replace("__DATE_TO_MERGED__", date_to_merged)+ )+ merges_response = curated.run(+ merges_sql, query_type="engineering_analytics.cost_per_merge_merges", placeholders=placeholders+ )+ merges_by_bucket = {+ normalize_bucket(bucket_start, granularity): int(merges or 0)+ for bucket_start, merges in merges_response.results or []+ }++ spine = window_buckets(date_from, date_to, granularity)+ window = _ROLLING_BUCKETS[granularity]+ buckets: list[CostPerMergeBucket] = []+ for index, bucket in enumerate(spine):+ trailing = spine[max(0, index - window + 1) : index + 1]+ trailing_costs = [cost for b in trailing if (cost := cost_by_bucket.get(b)) is not None]+ trailing_cost = sum(trailing_costs) if trailing_costs else None+ trailing_merges = sum(merges_by_bucket.get(b, 0) for b in trailing)+ buckets.append(+ CostPerMergeBucket(+ bucket_start=bucket,+ estimated_cost_usd=cost_by_bucket.get(bucket),+ merges=merges_by_bucket.get(bucket, 0),+ cost_per_merge_usd=(trailing_cost / trailing_merges)+ if (trailing_cost is not None and trailing_merges)+ else None,+ )+ )+ return granularity, buckets++# Per-runner-tier cost for one workflow (single-workflow page "where the spend goes" breakdown), scoped# to the page's run window (and optional branch) so the figure always answers "spend over [window]",# never an unbounded all-time.diff --git a/products/engineering_analytics/backend/logic/queries/repo_overview.py b/products/engineering_analytics/backend/logic/queries/repo_overview.pyindex 01992878be33..90536f8573e8 100644--- a/products/engineering_analytics/backend/logic/queries/repo_overview.py+++ b/products/engineering_analytics/backend/logic/queries/repo_overview.py@@ -12,7 +12,10 @@ from posthog.hogql import astfrom products.engineering_analytics.backend.facade.contracts import RepoOverviewfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float-from products.engineering_analytics.backend.logic.queries.pr_cost import query_workflow_window_costs_with_prev+from products.engineering_analytics.backend.logic.queries.pr_cost import (+ query_cost_per_merge_series,+ query_workflow_window_costs_with_prev,+)_RUNS_SELECT = """SELECT@@ -118,6 +121,10 @@ 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+ )+return RepoOverview(run_count=run_count,run_count_prev=run_count_prev,@@ -133,4 +140,6 @@ 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,)diff --git a/products/engineering_analytics/backend/logic/queries/repo_run_activity.py b/products/engineering_analytics/backend/logic/queries/repo_run_activity.pynew file mode 100644index 000000000000..b046c915688d--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/repo_run_activity.py@@ -0,0 +1,108 @@+"""Curated query: one collapsed point per default-branch commit for the repo-health chart.++The repo hub's master-health chart plots the health of the default branch over the window. A single+push to the default branch fans out into many workflow runs (one row per workflow file), so plotting+every ``github_workflow_runs`` row would show a cloud of dots per commit. Instead this collapses all of+a commit's workflow runs into **one point per ``head_sha``** — the unit an engineer reads as "did master+go green for this commit, and how long did its CI take":++- ``run_started_at`` = the earliest workflow start for the commit (when the commit's CI kicked off).+- ``duration_seconds`` = wall-clock from the first workflow start to the last workflow finish, and only+ once **every** workflow settled — while any is still running the commit's CI isn't done, so duration is+ null (the point drops off the scatter and feeds the in-flight band instead), mirroring the per-run chart.+- ``conclusion`` = the commit's overall verdict: red if **any** workflow decisively failed+ (``failure`` / ``timed_out``), else '' (still in flight) if any hasn't settled, else ``success`` when at+ least one passed, else ``neutral`` (only cancelled/skipped). One decisive failure turns the commit red,+ matching how a human reads a broken default branch.++Rows are first collapsed to the **latest run per ``(head_sha, workflow_name)``** (the same ``argMax``+rule as ``ci_rollup``), so a workflow that failed and was re-run to green reads green, and superseded+attempts don't stretch the commit's wall clock or flip its verdict.++Reuses the ``WorkflowRunActivity`` contract so the same ``RunActivityChart`` renders it. Same+``run_started_at >= date_from`` filter as ``workflow_run_activity`` (a commit whose earliest run has no+parseable start can't be placed on the time axis). Fetches ``_LIMIT + 1`` rows so an overflow reports as+``truncated`` rather than silently dropping the oldest commits.+"""++from datetime import datetime++from posthog.hogql import ast++from products.engineering_analytics.backend.facade.contracts import WorkflowRunActivity, WorkflowRunActivityPoint+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource++# One point per commit, so the cap is in commits (not runs) — comfortably above the busiest window's+# default-branch commit count while bounding the wire size. Newest commits win when the cap is hit.+_LIMIT = 2000++_SELECT = f"""+ SELECT+ max(w.id) AS run_id,+ multiIf(+ countIf(w.status = 'completed' AND w.conclusion IN ('failure', 'timed_out')) > 0, 'failure',+ countIf(w.status != 'completed') > 0, '',+ countIf(w.conclusion = 'success') > 0, 'success',+ 'neutral'+ ) AS conclusion,+ min(w.run_started_at) AS run_started_at,+ if(countIf(w.status != 'completed') = 0, dateDiff('second', min(w.run_started_at), max(w.updated_at)), NULL)+ AS duration_seconds,+ any(w.head_branch) AS head_branch+ FROM (+ SELECT+ argMax(r.id, r.run_started_at) AS id,+ argMax(r.status, r.run_started_at) AS status,+ argMax(r.conclusion, r.run_started_at) AS conclusion,+ max(r.run_started_at) AS run_started_at,+ argMax(r.updated_at, r.run_started_at) AS updated_at,+ any(r.head_branch) AS head_branch,+ r.head_sha AS head_sha+ FROM __RUNS_SOURCE__ AS r+ WHERE r.run_started_at >= {{date_from}} AND r.head_branch = {{branch}} __DATE_TO__+ GROUP BY r.head_sha, r.workflow_name+ ) AS w+ GROUP BY w.head_sha+ ORDER BY min(w.run_started_at) DESC+ LIMIT {_LIMIT + 1}+"""+++def query_repo_run_activity(+ *,+ curated: CuratedGitHubSource,+ date_from: datetime,+ date_to: datetime | None,+ branch: str,+) -> WorkflowRunActivity:+ date_to_clause = ""+ placeholders: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=date_from),+ "branch": ast.Constant(value=branch),+ }+ if date_to is not None:+ date_to_clause = "AND r.run_started_at <= {date_to}"+ placeholders["date_to"] = ast.Constant(value=date_to)+ response = curated.run(+ _SELECT.replace("__RUNS_SOURCE__", curated.run_source()).replace("__DATE_TO__", date_to_clause),+ query_type="engineering_analytics.repo_run_activity",+ placeholders=placeholders,+ )+ rows = response.results or []+ truncated = len(rows) > _LIMIT+ points = [_to_point(row) for row in rows[:_LIMIT]]+ return WorkflowRunActivity(points=points, truncated=truncated, limit=_LIMIT)+++def _to_point(row: tuple) -> WorkflowRunActivityPoint:+ run_id, conclusion, run_started_at, duration_seconds, head_branch = row+ return WorkflowRunActivityPoint(+ run_id=int(run_id),+ # '' is the in-flight sentinel from the multiIf (not every workflow settled) — normalize to None.+ conclusion=conclusion or None,+ run_started_at=run_started_at,+ duration_seconds=int(duration_seconds) if duration_seconds is not None else None,+ head_branch=head_branch or "",+ # Default-branch commits aren't attributed to a single PR — the chart hides the PR line at 0.+ pr_number=0,+ )diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.pyindex c1fc1b56befc..c805ebd92a2e 100644--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py@@ -10,33 +10,24 @@ so the trend sparkline keeps a readable number of points — per-day buckets arefor a 24h window and far too many for a year."""-from datetime import date, datetime, timedelta-from typing import Literal+from datetime import datetimefrom posthog.hogql import astfrom products.engineering_analytics.backend.facade.contracts import RepoRef, WorkflowHealthBucket, WorkflowHealthItem+from products.engineering_analytics.backend.logic.queries._buckets import (+ bucket_expr,+ normalize_bucket,+ pick_granularity,+ window_buckets,+)from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_floatfrom products.engineering_analytics.backend.logic.queries.pr_cost import query_workflow_window_costs-Granularity = Literal["hour", "day", "week"]-_LIMIT = 100# Generous bound: _LIMIT workflows x at most ~366 daily buckets._BUCKET_LIMIT = 40000-# ClickHouse bucket function per granularity. Week starts Monday (mode 1).-_BUCKET_FN: dict[Granularity, str] = {- "hour": "toStartOfHour(run_started_at)",- "day": "toStartOfDay(run_started_at)",- "week": "toStartOfWeek(run_started_at, 1)",-}-_BUCKET_STEP: dict[Granularity, timedelta] = {- "hour": timedelta(hours=1),- "day": timedelta(days=1),- "week": timedelta(weeks=1),-}-_SELECT = f"""SELECTrepo_owner,@@ -96,7 +87,7 @@ def query_workflow_health(date_to: datetime | None,branch: str | None = None,) -> list[WorkflowHealthItem]:- granularity = _pick_granularity(date_from, date_to)+ granularity = pick_granularity(date_from, date_to)date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""# An empty/whitespace branch is "no filter", not a literal match on ''.branch = branch.strip() if branch else None@@ -114,7 +105,7 @@ def query_workflow_health(template.replace("__RUNS_SOURCE__", runs_source).replace("__DATE_TO__", date_to_clause).replace("__BRANCH__", branch_clause)- .replace("__BUCKET_FN__", _BUCKET_FN[granularity])+ .replace("__BUCKET_FN__", bucket_expr(granularity)))response = curated.run(@@ -146,13 +137,13 @@ def query_workflow_health(for repo_owner, repo_name, workflow_name, bucket_start, run_count, completed, successes, failures in (bucket_response.results or []):- key = _normalize(bucket_start, granularity)+ key = normalize_bucket(bucket_start, granularity)buckets_by_workflow.setdefault((repo_owner, repo_name, workflow_name), {})[key] = WorkflowHealthBucket(bucket_start=key, run_count=run_count, completed=completed, successes=successes, failures=failures)cost_by_workflow = query_workflow_window_costs(curated=curated, date_from=date_from, date_to=date_to, branch=branch)- window = _window_buckets(date_from, date_to, granularity)+ window = window_buckets(date_from, date_to, granularity)return [WorkflowHealthItem(repo=RepoRef(provider="github", owner=repo_owner, name=repo_name),@@ -186,44 +177,3 @@ def query_workflow_health()for repo_owner, repo_name, workflow_name, run_count, success_rate, p50_seconds, p95_seconds, last_failure_at, completed_count, latest_failed, latest_conclusion, rerun_cycles in response.results]---def _pick_granularity(date_from: datetime, date_to: datetime | None) -> Granularity:- """Hour for short windows, week for long ones — keeps the sparkline at a readable point count."""- end = date_to or datetime.now(tz=date_from.tzinfo)- span = end - date_from- if span <= timedelta(hours=48):- return "hour"- if span <= timedelta(days=90):- return "day"- return "week"---def _window_buckets(date_from: datetime, date_to: datetime | None, granularity: Granularity) -> list[datetime]:- end = date_to or datetime.now(tz=date_from.tzinfo)- start = _normalize(date_from, granularity)- end_aligned = _normalize(end, granularity)- if end_aligned < start:- return []- step = _BUCKET_STEP[granularity]- buckets: list[datetime] = []- current = start- while current <= end_aligned:- buckets.append(current)- current += step- return buckets---def _normalize(value: datetime | date, granularity: Granularity) -> datetime:- """Align a timestamp to its bucket start, tz-naive, so query rows and the zero-fill series key alike.-- ClickHouse can hand the bucket back as a ``date`` (date/week truncation) or a ``datetime``- (hour truncation); widen the former so both sides key on the same type.- """- naive = value.replace(tzinfo=None) if isinstance(value, datetime) else datetime(value.year, value.month, value.day)- if granularity == "hour":- return naive.replace(minute=0, second=0, microsecond=0)- midnight = naive.replace(hour=0, minute=0, second=0, microsecond=0)- if granularity == "week":- return midnight - timedelta(days=midnight.weekday())- return midnightdiff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.pyindex 6992b8432d95..fdd0845e9c56 100644--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py@@ -183,17 +183,92 @@ _DEMO_MATRIX: dict[str, list[str | None]] = {}-def _demo_multi_push(- prs: list[dict[str, Any]], runs: list[dict[str, Any]]-) -> tuple[dict[str, Any], list[dict[str, Any]]]:- # Anchor the demo just after the fixture's newest row so the rebase lands its last push at "now".+def _fixture_anchor(prs: list[dict[str, Any]], runs: list[dict[str, Any]]) -> datetime:+ # Just after the fixture's newest row, so the rebase lands synthesized data at "now".newest = max(datetime.fromisoformat(row[field])for row, fields in [*((pr, PR_DATE_FIELDS) for pr in prs), *((run, RUN_DATE_FIELDS) for run in runs)]for field in fieldsif row[field] is not None)- anchor = newest + timedelta(hours=1)+ return newest + timedelta(hours=1)+++# Synthetic default-branch commit stream: the captured snapshot holds only ~a dozen master SHAs, which+# draws the master-health scatter as a near-empty chart. Deterministic (index arithmetic, no random),+# local-seed only; SHAs are prefixed "aa57e2" so they read as seeded in the UI.+_MASTER_WORKFLOWS = ("Backend CI", "Frontend CI", "Rust CI", "E2E Tests", "Lint", "Storybook")+_MASTER_DAYS = 7+_MASTER_COMMITS_PER_DAY = 18+++def _demo_master_commits(anchor: datetime) -> list[dict[str, Any]]:+ def iso(dt: datetime) -> str:+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")++ total = _MASTER_DAYS * _MASTER_COMMITS_PER_DAY+ spacing_minutes = _MASTER_DAYS * 24 * 60 // total+ demo_runs: list[dict[str, Any]] = []+ for commit_index in range(total):+ # Even spacing with a per-commit wobble so the X axis doesn't read as a metronome.+ age_minutes = (total - 1 - commit_index) * spacing_minutes + (commit_index * 37) % 90+ commit_time = anchor - timedelta(minutes=age_minutes)+ sha = f"aa57e2{commit_index:04d}" + "e" * 30+ red_commit = commit_index % 9 == 4 # an occasional broken master push+ cancelled_commit = commit_index % 17 == 9 # a rare all-cancelled push (neutral dot)+ for wf_index, workflow in enumerate(_MASTER_WORKFLOWS):+ # Newest two commits keep one workflow running so the in-flight band has live data.+ running = commit_index >= total - 2 and wf_index == len(_MASTER_WORKFLOWS) - 1+ if running:+ conclusion = None+ elif cancelled_commit:+ conclusion = "cancelled"+ elif red_commit and wf_index == 2:+ conclusion = "failure"+ else:+ conclusion = "success"+ start = commit_time + timedelta(minutes=wf_index)+ duration = timedelta(minutes=4 + (commit_index * 7 + wf_index * 11) % 48)+ demo_runs.append(+ {+ "id": 9_800_000_000 + commit_index * 10 + wf_index,+ "name": workflow,+ "head_sha": sha,+ "head_branch": "master",+ "status": "in_progress" if running else "completed",+ "conclusion": conclusion,+ "created_at": iso(start),+ "run_started_at": iso(start),+ "updated_at": iso(start) if running else iso(start + duration),+ "run_attempt": 1,+ "repository": {"full_name": "PostHog/posthog"},+ "pull_requests": [],+ }+ )+ return demo_runs+++def _spread_merges(prs: list[dict[str, Any]], anchor: datetime) -> None:+ # The snapshot captured recently-updated PRs, so their merge times all cluster on the capture day —+ # the cost-per-merge trend then collapses into a single bucket. Re-spread merged PRs evenly across+ # the seeded window (deterministic, index arithmetic) so the trend has a divisor in every bucket.+ span_hours = _MASTER_DAYS * 24+ merged = [pr for pr in prs if pr.get("merged_at")]+ for index, pr in enumerate(merged):+ merged_at = anchor - timedelta(hours=(index * 11) % span_hours, minutes=(index * 13) % 60)+ created_raw = pr.get("created_at")+ if created_raw:+ created = datetime.fromisoformat(created_raw)+ if merged_at < created:+ merged_at = created + timedelta(hours=1)+ pr["merged_at"] = merged_at.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _demo_multi_push(+ prs: list[dict[str, Any]], runs: list[dict[str, Any]]+) -> tuple[dict[str, Any], list[dict[str, Any]]]:+ # Anchor the demo just after the fixture's newest row so the rebase lands its last push at "now".+ anchor = _fixture_anchor(prs, runs)push_shas = [f"demo00{k + 1}" + "f" * 33 for k in range(4)] # 40 chars, distinct first 7 (demo001…demo004)workflows = list(_DEMO_MATRIX.keys())@@ -295,6 +370,13 @@ class Command(BaseCommand):demo_pr, demo_runs = _demo_multi_push(prs, runs)prs.append(demo_pr)runs.extend(demo_runs)+ # Spread merge times across the window so the cost-per-merge trend has a divisor per bucket.+ _spread_merges(prs, _fixture_anchor(prs, runs))+ # The synthetic stream owns master: the snapshot's own master rows are a dozen SHAs whose+ # scheduled/re-triggered runs span days, which pins the scatter's Y axis at 100h+ and crushes+ # every real duration to the baseline. PR-branch rows stay untouched.+ runs = [run for run in runs if run.get("head_branch") != "master"]+ runs.extend(_demo_master_commits(_fixture_anchor(prs, runs)))# Always normalize timestamps to a ClickHouse-friendly format; rebasing is optional.shift = timedelta(0) if options["keep_dates"] else self._rebase_delta(prs, runs)diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.pyindex b072a033b90a..cc358f1be1ea 100644--- a/products/engineering_analytics/backend/presentation/serializers.py+++ b/products/engineering_analytics/backend/presentation/serializers.py@@ -16,6 +16,7 @@ from products.engineering_analytics.backend.facade.contracts import (CIFailureLogs,CIJobFailureLog,CIStatusRollup,+ CostPerMergeBucket,GitHubSource,MasterFailureGroup,PRCostSummary,@@ -644,7 +645,35 @@ class WorkflowHealthItemSerializer(DataclassSerializer):}+class CostPerMergeBucketSerializer(DataclassSerializer):+ class Meta:+ dataclass = CostPerMergeBucket+ extra_kwargs = {+ "bucket_start": {+ "help_text": "Bucket start, aligned to cost_series_granularity (top of hour, midnight, or Monday)."+ },+ "estimated_cost_usd": {+ "help_text": "Estimated Depot CI cost (USD) of all runs started in this bucket. Null when nothing "+ "was costable (no billable self-hosted Linux jobs) or the job source isn't synced.",+ "allow_null": True,+ },+ "merges": {"help_text": "PRs merged in this bucket (all authors, bots included)."},+ "cost_per_merge_usd": {+ "help_text": "Rolling ratio: trailing-window CI cost divided by trailing-window merges "+ "(24 h / 7 d / 4 w to match the granularity). Null when the trailing window had no merges "+ "or no costable cost.",+ "allow_null": True,+ },+ }++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.",+ )+class Meta:dataclass = RepoOverviewextra_kwargs = {@@ -691,6 +720,9 @@ class RepoOverviewSerializer(DataclassSerializer):},"jobs_available": {"help_text": "Whether the job-level source is synced (cost and queue figures exist)."},"default_branch": {"help_text": "'master' or 'main', picked by observed run volume in the window."},+ "cost_series_granularity": {+ "help_text": "Bucket width of the cost_series trend, chosen to fit the window: 'hour', 'day', or 'week'."+ },}diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.pyindex 2a736e10cfdb..0796cb33e161 100644--- a/products/engineering_analytics/backend/presentation/views.py+++ b/products/engineering_analytics/backend/presentation/views.py@@ -144,6 +144,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe"author_workflow_costs","workflow_jobs","repo_overview",+ "repo_run_activity","master_failures","run_failure_logs","job_aggregates",@@ -780,6 +781,52 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSereturn _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")return Response(RepoOverviewSerializer(instance=result).data)+ @extend_schema(+ operation_id="engineering_analytics_repo_run_activity",+ parameters=[+ _DATE_FROM,+ _DATE_TO,+ # This endpoint never aggregates across branches, so the shared _BRANCH "omit to aggregate"+ # wording would misdescribe the omit behavior in every generated client.+ OpenApiParameter(+ name="branch",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Optional exact git branch (head_branch) to chart, e.g. 'main'. "+ "Omit or leave blank to use the repo's detected default branch.",+ ),+ _SOURCE_ID,+ ],+ responses={+ 200: WorkflowRunActivitySerializer,+ 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),+ },+ description=(+ "Default-branch health as compact chart points over a window (default -30d), newest first, for the "+ "repo-hub run-activity chart. All of a commit's workflow runs are collapsed into ONE point per commit "+ "(head SHA): its earliest workflow start, wall-clock duration until the last workflow settled (null "+ "while any is still running), and an overall conclusion that is 'failure' if any workflow decisively "+ "failed, else 'success' when at least one passed, else 'neutral'. `branch` overrides the detected "+ "default branch. `truncated` is true when more commits matched than the cap, so the chart covers only "+ "the most recent commits."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def repo_run_activity(self, request: Request, **kwargs) -> Response:+ try:+ result = api.get_repo_run_activity(+ team=self.team,+ date_from=request.query_params.get("date_from") or None,+ date_to=request.query_params.get("date_to") or None,+ branch=request.query_params.get("branch") or None,+ 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 Response(WorkflowRunActivitySerializer(instance=result).data)+@extend_schema(operation_id="engineering_analytics_master_failures",parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _SOURCE_ID],diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.pyindex 1f2158a306f9..aee919b0cfda 100644--- a/products/engineering_analytics/backend/tests/test_logic.py+++ b/products/engineering_analytics/backend/tests/test_logic.py@@ -25,6 +25,7 @@ from products.engineering_analytics.backend.facade.contracts import ()from products.engineering_analytics.backend.logic import build_workflow_healthfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries.pr_cost import query_cost_per_merge_seriesfrom products.engineering_analytics.backend.logic.sources import (PULL_REQUESTS_SCHEMA,WORKFLOW_RUNS_SCHEMA,@@ -364,6 +365,85 @@ class TestEndpointMapping(BaseTest):assert items[1].last_failure_at is None+class TestCostPerMergeSeries(BaseTest):+ """The cost-per-merged-PR trend on the repo hub: bucketing, zero-fill, and the cost/merge+ division guard. The two warehouse scans are mocked (curated fully faked), so this tests the+ Python fold — the runner-tier cost model, the bucket join, the empty-bucket handling — without+ a warehouse. The tier multiplier stays server-side; only group columns cross the mock boundary."""++ @staticmethod+ def _curated(cost_rows: list[tuple], merges_rows: list[tuple], *, jobs_synced: bool = True) -> mock.Mock:+ curated = mock.Mock()+ curated.jobs_source.return_value = "px_github_workflow_jobs" if jobs_synced else None+ curated.run_source.return_value = "px_github_workflow_runs"+ curated.pr_source.return_value = "px_github_pull_requests"+ # Cost scan first, then the merges scan — the call order in query_cost_per_merge_series.+ curated.run.side_effect = [_resp(cost_rows), _resp(merges_rows)]+ return curated++ def test_buckets_cost_per_merge_and_zero_fills(self) -> None:+ date_from = _dt("2026-06-01T00:00:00")+ date_to = _dt("2026-06-30T00:00:00") # 29-day window -> day granularity, deterministic buckets.+ # Columns: bucket_start, labels, finished, elapsed, unfinished. depot-4 (4-core) bills at 2x, so+ # 2 min -> 2 * 0.004 * 2 = 0.016; 1 min -> 0.008.+ cost_rows = [+ (datetime(2026, 6, 2), '["depot-ubuntu-22.04-4"]', 1, 120.0, 0),+ (datetime(2026, 6, 3), '["depot-ubuntu-22.04-4"]', 1, 60.0, 0),+ (datetime(2026, 6, 6), '["depot-ubuntu-22.04-4"]', 1, 120.0, 0), # cost but no merges below+ ]+ # Columns: bucket_start, merges.+ merges_rows = [+ (datetime(2026, 6, 2), 4),+ (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+ )++ assert granularity == "day"+ assert len(buckets) == 30 # June 1..30 inclusive, zero-filled.+ by_day = {bucket.bucket_start: bucket for bucket in buckets}++ # estimated_cost_usd / merges stay bucket-local; the ratio is the trailing 7-day rolling window.+ assert by_day[datetime(2026, 6, 2)].estimated_cost_usd == pytest.approx(0.016)+ assert by_day[datetime(2026, 6, 2)].merges == 4+ assert by_day[datetime(2026, 6, 2)].cost_per_merge_usd == pytest.approx(0.016 / 4)+ assert by_day[datetime(2026, 6, 3)].cost_per_merge_usd == pytest.approx((0.016 + 0.008) / 6)++ # A merge-only day still gets a ratio from the trailing window's cost.+ assert by_day[datetime(2026, 6, 5)].estimated_cost_usd is None+ assert by_day[datetime(2026, 6, 5)].merges == 3+ assert by_day[datetime(2026, 6, 5)].cost_per_merge_usd == pytest.approx((0.016 + 0.008) / 9)++ # A cost-only day likewise divides by the trailing window's merges (no divide-by-zero hole).+ assert by_day[datetime(2026, 6, 6)].estimated_cost_usd == pytest.approx(0.016)+ assert by_day[datetime(2026, 6, 6)].merges == 0+ assert by_day[datetime(2026, 6, 6)].cost_per_merge_usd == pytest.approx((0.016 + 0.008 + 0.016) / 9)++ # Once the trailing window slides past the merges (Jun 5 + 7d), cost alone yields no ratio.+ assert by_day[datetime(2026, 6, 12)].cost_per_merge_usd is None++ # An untouched bucket keeps its raw fields zero-filled but inherits the trailing ratio while+ # the window still covers data (Jun 10 window = Jun 4..10: Jun 6 cost / Jun 5 merges).+ empty = by_day[datetime(2026, 6, 10)]+ assert (empty.estimated_cost_usd, empty.merges) == (None, 0)+ assert empty.cost_per_merge_usd == pytest.approx(0.016 / 3)++ # A bucket whose whole trailing window is empty is fully null.+ dead = by_day[datetime(2026, 6, 20)]+ assert (dead.estimated_cost_usd, dead.merges, dead.cost_per_merge_usd) == (None, 0, None)++ 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")+ )+ assert granularity == "day"+ assert buckets == []+ curated.run.assert_not_called() # no jobs source -> no scan is issued++class TestResolveGitHubTables(BaseTest):"""The per-team table resolver over the warehouse models (ORM only, no object storage).No source is connected in setUp so the missing-source path can be exercised."""@@ -920,6 +1000,49 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):)assert [p.run_id for p in wide.points] == [8102, 8101, 8104]+ def test_repo_run_activity_collapses_workflows_per_commit(self) -> None:+ # The repo-health chart folds every workflow run of a default-branch commit into ONE point: the+ # verdict is failure if any workflow failed, success if all settled and at least one passed, and+ # in-flight (null) while any is still running. Two workflows on the same head_sha must not yield+ # two dots. Runs off the default branch and outside the window are excluded.+ self._create_table(+ "github_pull_requests",+ _PULL_REQUESTS_COLUMNS,+ [_pr_row(95, "alice", "open", 0, _ago(1), head_sha="sha95")],+ )+ self._create_table(+ "github_workflow_runs",+ _WORKFLOW_RUNS_COLUMNS,+ [+ # Commit A: two workflows, both passed -> one green dot with a wall-clock duration spanning+ # the earliest start to the latest finish (not either workflow's own duration).+ _run_row(9601, "CI", "sha-a", "completed", "success", _ago(3), _ago(2), head_branch="main"),+ _run_row(9602, "Deploy", "sha-a", "completed", "success", _ago(3), _ago(1), head_branch="main"),+ # Commit B: one workflow failed -> the whole commit is red even though the other passed.+ _run_row(9603, "CI", "sha-b", "completed", "failure", _ago(2), _ago(2), head_branch="main"),+ _run_row(9604, "Deploy", "sha-b", "completed", "success", _ago(2), _ago(2), head_branch="main"),+ # Commit C: one workflow still running -> in-flight, so conclusion and duration are null.+ _run_row(9605, "CI", "sha-c", "completed", "success", _ago(1), _ago(1), head_branch="main"),+ _run_row(9606, "Deploy", "sha-c", "in_progress", None, _ago(1), _ago(1), head_branch="main"),+ # A PR-branch commit and an out-of-window commit: both excluded from default-branch health.+ _run_row(9607, "CI", "sha-d", "completed", "failure", _ago(1), _ago(1), head_branch="feat"),+ _run_row(9608, "CI", "sha-e", "completed", "success", _ago(60), _ago(60), head_branch="main"),+ ],+ )+ activity = api.get_repo_run_activity(team=self.team)+ by_started = sorted(activity.points, key=lambda p: p.run_started_at)+ # Three default-branch commits in the window -> three points (six runs collapsed), oldest first here.+ assert len(activity.points) == 3+ commit_a, commit_b, commit_c = by_started+ assert commit_a.conclusion == "success"+ assert commit_a.duration_seconds is not None and commit_a.duration_seconds > 0+ assert commit_b.conclusion == "failure"+ # In-flight commit: unsettled workflow leaves the verdict and duration null (drops off the scatter).+ assert commit_c.conclusion is None+ assert commit_c.duration_seconds is None+ # Default-branch commits carry no single attributed PR.+ assert all(p.pr_number == 0 for p in activity.points)+def test_workflow_detail_branch_filter(self) -> None:# The workflow detail page's runs list and runner-cost breakdown must honor the same branch scope# as the Workflows tab — without it, drilling in from a branch-scoped tab widened back to everydiff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex 51a53c0fc27f..9c70f90f8bcd 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -198,6 +198,30 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert list_health.call_args.kwargs["branch"] == "main"+ def test_repo_run_activity_serializes_and_forwards_branch(self) -> None:+ result = contracts.WorkflowRunActivity(+ points=[+ contracts.WorkflowRunActivityPoint(+ run_id=9601,+ conclusion="success",+ run_started_at=datetime(2026, 1, 20, tzinfo=UTC),+ duration_seconds=180,+ head_branch="main",+ pr_number=0,+ )+ ],+ truncated=False,+ limit=2000,+ )+ with mock.patch(f"{_VIEWS}.get_repo_run_activity", return_value=result) as get_activity:+ response = self.client.get(self._url("repo_run_activity"), {"branch": "main"})++ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["points"][0]["run_id"] == 9601+ assert body["points"][0]["conclusion"] == "success"+ assert get_activity.call_args.kwargs["branch"] == "main"+def test_pr_lifecycle_serializes(self) -> None:with mock.patch(f"{_VIEWS}.get_pr_lifecycle", return_value=_pr_lifecycle()) as get:response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "10", "repo": "PostHog/posthog"})diff --git a/products/engineering_analytics/frontend/components/PullRequestTable.tsx b/products/engineering_analytics/frontend/components/PullRequestTable.tsxindex 3318b634c93d..4bb7d15cf5d8 100644--- a/products/engineering_analytics/frontend/components/PullRequestTable.tsx+++ b/products/engineering_analytics/frontend/components/PullRequestTable.tsx@@ -51,6 +51,8 @@ export interface PullRequestTableProps {pageSize?: numberemptyState?: ReactNodedataAttr?: string+ /** Drop the table's own border when it sits inside a LemonCard (the hub) — avoids a double frame. */+ embedded?: boolean}export function PullRequestTable({@@ -62,6 +64,7 @@ export function PullRequestTable({pageSize = 50,emptyState,dataAttr = 'engineering-analytics-pr-table',+ embedded = false,}: PullRequestTableProps): JSX.Element {const columns: LemonTableColumns<PullRequestRow> = [{@@ -194,6 +197,7 @@ export function PullRequestTable({<LemonTabledata-attr={dataAttr}size="small"+ embedded={embedded}columns={columns}dataSource={rows}rowKey={prKeyOf}diff --git a/products/engineering_analytics/frontend/components/RunActivityChart.tsx b/products/engineering_analytics/frontend/components/RunActivityChart.tsxindex 5a28e5f80e54..08313cd21d9f 100644--- a/products/engineering_analytics/frontend/components/RunActivityChart.tsx+++ b/products/engineering_analytics/frontend/components/RunActivityChart.tsx@@ -28,6 +28,9 @@ interface RunActivityChartProps {title?: string/** The runs list was capped server-side, so the chart shows the most recent runs, not the full window. */truncated?: boolean+ /** Singular noun for each plotted point in the header count — 'run' by default, 'commit' on the repo-health+ * view where every dot is a whole commit's collapsed workflows. */+ noun?: stringclassName?: string}@@ -54,6 +57,14 @@ const Y_TICK_COUNT = 4const X_TICK_COUNT = 5// A scatter of one point says nothing; only draw once there's a spread to read.const MIN_POINTS = 2++const isPlottable = (run: ActivityRun): run is ActivityRun & { startedAt: string; durationSeconds: number } =>+ run.startedAt != null && run.durationSeconds != null && run.durationSeconds >= 0++/** False when RunActivityChart would render null, so callers can show their empty state instead. */+export function hasEnoughRunActivity(runs: ActivityRun[]): boolean {+ return runs.filter(isPlottable).length >= MIN_POINTS+}// The focus lens defaults to the most recent day — the "live" view — over a window that's wider than that.// Below this much total span there's nothing to pan over, so the brush is hidden and the chart shows it all.const LENS_MS = 24 * 60 * 60 * 1000@@ -227,6 +238,7 @@ export function RunActivityChart({runs,title = 'Run activity',truncated = false,+ noun = 'run',className,}: RunActivityChartProps): JSX.Element | null {// The lens sub-range the scatter/band zoom into; null = the default (most recent day). Declared before@@ -256,10 +268,7 @@ export function RunActivityChart({})// Only completed runs land on the scatter — a still-running run has no final duration to place on Y.- const plottable = runs.filter(- (run): run is ActivityRun & { startedAt: string; durationSeconds: number } =>- run.startedAt != null && run.durationSeconds != null && run.durationSeconds >= 0- )+ const plottable = runs.filter(isPlottable)if (plottable.length < MIN_POINTS) {return null}@@ -395,12 +404,14 @@ export function RunActivityChart({<h3 className="mb-0">{title}</h3><Tooltiptitle={- truncated ? `Covers the most recent ${plottable.length} runs, not the full window.` : undefined+ truncated+ ? `Covers the most recent ${plottable.length} ${noun}s, not the full window.`+ : undefined}><span className="text-xs whitespace-nowrap text-secondary tabular-nums">{truncated ? 'recent ' : ''}- {brushable ? `${visible.length} of ${plottable.length}` : plottable.length} runs · median{' '}+ {brushable ? `${visible.length} of ${plottable.length}` : plottable.length} {noun}s · median{' '}{formatAxisMinutes(medianMin)} · peak {peak} in flight</span></Tooltip>diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsxindex 3b30a8d5023e..0cd390286ab1 100644--- a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx+++ b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx@@ -81,6 +81,8 @@ export interface WorkflowHealthTableProps {pageSize?: numberemptyState?: ReactNodedataAttr?: string+ /** Drop the table's own border when it sits inside a LemonCard (the hub) — avoids a double frame. */+ embedded?: boolean}export function WorkflowHealthTable({@@ -92,6 +94,7 @@ export function WorkflowHealthTable({pageSize = 50,emptyState,dataAttr = 'engineering-analytics-workflow-table',+ embedded = false,}: WorkflowHealthTableProps): JSX.Element {const { searchParams } = useValues(router)// Carry the active window/branch scope into the drill-down; without `q` the detail page would@@ -275,6 +278,7 @@ export function WorkflowHealthTable({<LemonTabledata-attr={dataAttr}size="small"+ embedded={embedded}columns={columns}dataSource={rows}rowKey={(row) => `${row.repoOwner}/${row.repoName}:${row.workflowName}`}diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 14ce6845d650..f7b111733dc0 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -574,7 +574,26 @@ export interface QuarantineRequestResultApi {branch: string}+export interface CostPerMergeBucketApi {+ /** Bucket start, aligned to cost_series_granularity (top of hour, midnight, or Monday). */+ bucket_start: string+ /**+ * Estimated Depot CI cost (USD) of all runs started in this bucket. Null when nothing was costable (no billable self-hosted Linux jobs) or the job source isn't synced.+ * @nullable+ */+ estimated_cost_usd: number | null+ /** PRs merged in this bucket (all authors, bots included). */+ merges: number+ /**+ * Rolling ratio: trailing-window CI cost divided by trailing-window merges (24 h / 7 d / 4 w to match the granularity). Null when the trailing window had no merges or no costable cost.+ * @nullable+ */+ cost_per_merge_usd: 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. */+ cost_series: CostPerMergeBucketApi[]/** 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. */@@ -627,6 +646,38 @@ export interface RepoOverviewApi {jobs_available: boolean/** 'master' or 'main', picked by observed run volume in the window. */default_branch: string+ /** Bucket width of the cost_series trend, chosen to fit the window: 'hour', 'day', or 'week'. */+ cost_series_granularity: string+}++export interface WorkflowRunActivityPointApi {+ /** GitHub Actions run id. */+ run_id: number+ /**+ * Run conclusion ('success', 'failure', 'timed_out', 'cancelled', 'skipped', ...), or null while still in progress.+ * @nullable+ */+ conclusion: string | null+ /** When the run started. Never null on this endpoint: runs without a parseable start timestamp are excluded from the window (they can't be plotted on the chart's time axis). */+ run_started_at: string+ /**+ * Wall-clock duration in seconds; null until the run completes.+ * @nullable+ */+ duration_seconds: number | null+ /** Git branch the run was triggered on, or '' when unknown. */+ head_branch: string+ /** Attributed pull request number, or 0 when unattributed. */+ pr_number: number+}++export interface WorkflowRunActivityApi {+ /** Per-run chart points, newest first, capped at `limit`. */+ points: WorkflowRunActivityPointApi[]+ /** True when more runs matched than the cap; `points` is the newest `limit` runs, so the chart covers only the most recent activity, not the full window. */+ truncated: boolean+ /** Maximum number of run points returned in `points`. */+ limit: number}export interface RunFailureLogsApi {@@ -762,36 +813,6 @@ export interface WorkflowJobApi {estimated_cost_usd: number | null}-export interface WorkflowRunActivityPointApi {- /** GitHub Actions run id. */- run_id: number- /**- * Run conclusion ('success', 'failure', 'timed_out', 'cancelled', 'skipped', ...), or null while still in progress.- * @nullable- */- conclusion: string | null- /** When the run started. Never null on this endpoint: runs without a parseable start timestamp are excluded from the window (they can't be plotted on the chart's time axis). */- run_started_at: string- /**- * Wall-clock duration in seconds; null until the run completes.- * @nullable- */- duration_seconds: number | null- /** Git branch the run was triggered on, or '' when unknown. */- head_branch: string- /** Attributed pull request number, or 0 when unattributed. */- pr_number: number-}--export interface WorkflowRunActivityApi {- /** Per-run chart points, newest first, capped at `limit`. */- points: WorkflowRunActivityPointApi[]- /** True when more runs matched than the cap; `points` is the newest `limit` runs, so the chart covers only the most recent activity, not the full window. */- truncated: boolean- /** Maximum number of run points returned in `points`. */- limit: number-}-export interface WorkflowRunnerCostApi {/** 'self_hosted' (billable), 'github_hosted' (free), or 'unknown'. */provider: string@@ -977,6 +998,25 @@ export type EngineeringAnalyticsRepoOverviewParams = {source_id?: string}+export type EngineeringAnalyticsRepoRunActivityParams = {+ /**+ * Optional exact git branch (head_branch) to chart, e.g. 'main'. Omit or leave blank to use the repo's detected default branch.+ */+ branch?: string+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string+ /**+ * Window end: relative or ISO8601. Defaults to now.+ */+ date_to?: string+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.+ */+ source_id?: string+}+export type EngineeringAnalyticsRunFailureLogsParams = {/*** Workflow run id whose failure logs to fetch.diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex 2ba232fe6cc1..59219318b067 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -22,6 +22,7 @@ import type {EngineeringAnalyticsPullRequestsParams,EngineeringAnalyticsQuarantineParams,EngineeringAnalyticsRepoOverviewParams,+ EngineeringAnalyticsRepoRunActivityParams,EngineeringAnalyticsRunFailureLogsParams,EngineeringAnalyticsWorkflowHealthParams,EngineeringAnalyticsWorkflowJobsParams,@@ -424,6 +425,39 @@ export const engineeringAnalyticsRepoOverview = async (})}+export const getEngineeringAnalyticsRepoRunActivityUrl = (+ projectId: string,+ params?: EngineeringAnalyticsRepoRunActivityParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/engineering_analytics/repo_run_activity/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/repo_run_activity/`+}++/**+ * Default-branch health as compact chart points over a window (default -30d), newest first, for the repo-hub run-activity chart. All of a commit's workflow runs are collapsed into ONE point per commit (head SHA): its earliest workflow start, wall-clock duration until the last workflow settled (null while any is still running), and an overall conclusion that is 'failure' if any workflow decisively failed, else 'success' when at least one passed, else 'neutral'. `branch` overrides the detected default branch. `truncated` is true when more commits matched than the cap, so the chart covers only the most recent commits.+ */+export const engineeringAnalyticsRepoRunActivity = async (+ projectId: string,+ params?: EngineeringAnalyticsRepoRunActivityParams,+ options?: RequestInit+): Promise<WorkflowRunActivityApi> => {+ return apiMutator<WorkflowRunActivityApi>(getEngineeringAnalyticsRepoRunActivityUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsRunFailureLogsUrl = (projectId: string,params: EngineeringAnalyticsRunFailureLogsParamsdiff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsxindex 53bb2a650869..d11536771ca5 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx@@ -7,7 +7,7 @@ import { combineUrl, router } from 'kea-router'import { IconBox } from '@posthog/icons'import { LemonCard, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'-import { QueryCard } from 'lib/components/Cards/InsightCard/QueryCard'+import { Sparkline } from 'lib/components/Sparkline'import { TZLabel } from 'lib/components/TZLabel'import { cn } from 'lib/utils/css-classes'import { humanFriendlyNumber } from 'lib/utils/numbers'@@ -19,6 +19,7 @@ import { EntityHeader } from '../components/EntityHeader'import { FailureLogGroups } from '../components/FailureLogs'import { DeltaBadge, MetricTile, percentChange, pointChange } from '../components/MetricTile'import { PullRequestTable } from '../components/PullRequestTable'+import { RunActivityChart, hasEnoughRunActivity } from '../components/RunActivityChart'import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'import { Section, SectionNav, scrollToSection } from '../components/Section'import { ShareRow } from '../components/ShareRow'@@ -116,7 +117,7 @@ function MasterFailuresSection(): JSX.Element {return (<Section id="now" title={`Failing on ${defaultBranch}`} note="Last 24 hours">- <LemonCard hoverEffect={false} className="p-0">+ <LemonCard hoverEffect={false} className="overflow-hidden p-0"><LemonTable<MasterFailureGroupApi>dataSource={masterFailures}loading={masterFailuresLoading}@@ -232,12 +233,15 @@ function MasterFailuresSection(): JSX.Element {export function RepoOverviewScene(): JSX.Element {const {overview,- masterSuccessRateQuery,- masterFailedRunsQuery,+ activityRuns,+ activityTruncated,+ repoActivityLoading,+ repoActivityFailed,attentionPrs,draftCount,costByWorkflow,otherCostWorkflowCount,+ costPerMergeSeries,jobsAvailable,defaultBranch,notConnected,@@ -254,7 +258,7 @@ export function RepoOverviewScene(): JSX.Element {costLensEnabled,activeSource,} = useValues(engineeringAnalyticsLogic)- const { loadOverview, loadMasterFailures } = useActions(repoOverviewLogic)+ const { loadOverview, loadMasterFailures, loadRepoActivity } = useActions(repoOverviewLogic)const { searchParams } = useValues(router)if (notConnected) {@@ -266,6 +270,7 @@ export function RepoOverviewScene(): JSX.Element {onRetry={() => {loadOverview()loadMasterFailures()+ loadRepoActivity()}}/>)@@ -363,23 +368,23 @@ export function RepoOverviewScene(): JSX.Element {/><Section id="master" title={`${defaultBranch === 'main' ? 'Main' : 'Master'} health`}>- {masterSuccessRateQuery && masterFailedRunsQuery ? (- <div className="grid gap-2.5 lg:grid-cols-2">- <QueryCard- title={`Success rate on ${defaultBranch}`}- query={masterSuccessRateQuery}- uniqueKey="engineering-analytics-master-success-rate"- />- <QueryCard- title={`Failed runs on ${defaultBranch}`}- description={`Completed runs on ${defaultBranch} whose conclusion wasn't success.`}- query={masterFailedRunsQuery}- uniqueKey="engineering-analytics-master-failed-runs"- />- </div>+ {/* One dot per commit to the default branch: X = when its CI started, Y = wall-clock CI+ duration, color = the commit's overall verdict (red if any workflow failed). Replaces the+ old success-rate line + failed-runs bar — the scatter says time, outcome, and cost at once. */}+ {hasEnoughRunActivity(activityRuns) ? (+ <RunActivityChart+ runs={activityRuns}+ truncated={activityTruncated}+ title={`Every ${defaultBranch} commit`}+ noun="commit"+ />) : (<LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">- Loading…+ {repoActivityLoading+ ? 'Loading…'+ : repoActivityFailed+ ? `Couldn't load ${defaultBranch} activity. Refresh to retry.`+ : `Not enough completed runs on ${defaultBranch} in the window to chart yet.`}</LemonCard>)}</Section>@@ -407,12 +412,13 @@ export function RepoOverviewScene(): JSX.Element {stuck >7d</span></div>- <LemonCard hoverEffect={false} className="p-0">+ <LemonCard hoverEffect={false} className="overflow-hidden p-0"><PullRequestTablerows={attentionPrs}loading={pullRequestsLoading}sourceId={sourceId}costLensEnabled={costLensEnabled}+ embeddedpageSize={HUB_TABLE_PAGE_SIZE}emptyState="Nothing failing or stuck in the open backlog."dataAttr="engineering-analytics-attention-prs"@@ -426,12 +432,13 @@ export function RepoOverviewScene(): JSX.Element {</Section><Section id="workflows" title="Workflows">- <LemonCard hoverEffect={false} className="p-0">+ <LemonCard hoverEffect={false} className="overflow-hidden p-0"><WorkflowHealthTablerows={workflowHealth}loading={workflowHealthLoading}sourceId={sourceId}showCost={jobsAvailable}+ embeddeddefaultSorting={{ columnKey: 'runCount', order: -1 }}pageSize={HUB_TABLE_PAGE_SIZE}emptyState="No workflow runs in the window."@@ -458,6 +465,26 @@ export function RepoOverviewScene(): JSX.Element {</Section><Section id="cost" title="Cost">+ {jobsAvailable && costPerMergeSeries ? (+ <LemonCard hoverEffect={false} className="mb-2 p-4">+ <h3 className="mb-1 text-xs font-semibold text-secondary">Cost per merged PR</h3>+ <Sparkline+ data={costPerMergeSeries.values}+ labels={costPerMergeSeries.labels}+ name="Cost per merged PR"+ type="line"+ className="h-24 w-full"+ renderLabel={(label) => label}+ renderTooltipValue={(value) => compactUsd(value)}+ />+ <div className="mt-2 border-t border-primary pt-2 text-[11px] text-tertiary">+ Estimated Depot CI cost per PR merged. Each point divides a trailing window's CI cost by its+ merges (24 h, 7 d, or 4 w to match the grain), so quiet buckets don't punch holes in the+ trend. Cost counts by run start, merges by merge time — the same coarse split the daily+ depot tooling uses.+ </div>+ </LemonCard>+ ) : null}{jobsAvailable && costByWorkflow.length > 0 ? (<LemonCard hoverEffect={false} className="p-4"><h3 className="mb-1 text-xs font-semibold text-secondary">By workflow</h3>diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsxindex 6a29506cd155..c1f1708f27fe 100644--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx@@ -390,7 +390,7 @@ export function WorkflowRunsScene(): JSX.Element {)}</Section><Section id="runs" title="Runs">- <LemonCard hoverEffect={false} className="p-0">+ <LemonCard hoverEffect={false} className="overflow-hidden p-0"><LemonTable<WorkflowRunRow>dataSource={runRows}columns={runColumns}diff --git a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.tsindex 4923fe01b4ce..5f56dec13971 100644--- a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts+++ b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts@@ -2,20 +2,23 @@ import { actions, afterMount, connect, kea, listeners, path, reducers, selectorsimport { loaders } from 'kea-loaders'import { ApiConfig } from 'lib/api'-import { Dayjs, dayjs } from 'lib/dayjs'-import { dateStringToDayJs } from 'lib/utils/dateFilters'--import { DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'-import { ChartDisplayType } from '~/types'+import { dayjs } from 'lib/dayjs'+import type { ActivityRun } from '../components/RunActivityChart'import {engineeringAnalyticsMasterFailures,engineeringAnalyticsRepoOverview,+ engineeringAnalyticsRepoRunActivity,engineeringAnalyticsRunFailureLogs,} from '../generated/api'-import type { MasterFailureGroupApi, RepoOverviewApi, RunFailureLogsApi } from '../generated/api.schemas'+import type {+ MasterFailureGroupApi,+ RepoOverviewApi,+ RunFailureLogsApi,+ WorkflowRunActivityApi,+} from '../generated/api.schemas'import { ciStatusOf } from '../lib/ci'-import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'import { PullRequestRow, STUCK_AFTER_DAYS, engineeringAnalyticsLogic, isStuck } from './engineeringAnalyticsLogic'import type { repoOverviewLogicType } from './repoOverviewLogicType'@@ -32,65 +35,6 @@ export interface CostShareRow {share: number}-// Warehouse timestamps are strings — parse like the curated builders do (repo_overview._BUCKET_SELECT).-const RUN_STARTED_AT = 'parseDateTimeBestEffort(run_started_at)'--// Refuse to interpolate anything but a plain identifier into SQL.-const TABLE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/--// Backend granularity ladder (workflow_health._pick_granularity): hour ≤48h, day ≤90d, else week.-function bucketExpr(from: Dayjs, to: Dayjs): string {- const spanHours = to.diff(from, 'hour')- if (spanHours <= 48) {- return `toStartOfHour(${RUN_STARTED_AT})`- }- if (spanHours <= 90 * 24) {- return `toStartOfDay(${RUN_STARTED_AT})`- }- return `toStartOfWeek(${RUN_STARTED_AT}, 1)`-}--function masterHealthSql(- metricSelect: string,- table: string,- branch: string,- dateFrom: string | null,- dateTo: string | null-): string | null {- const from = dateStringToDayJs(dateFrom ?? SHARED_DEFAULT_DATE_FROM)- if (!from) {- return null- }- const to = dateTo ? dateStringToDayJs(dateTo) : null- const where = [- `status = 'completed'`,- `head_branch = '${branch}'`,- `${RUN_STARTED_AT} >= toDateTime('${from.format('YYYY-MM-DD HH:mm:ss')}')`,- ]- if (to) {- where.push(`${RUN_STARTED_AT} <= toDateTime('${to.format('YYYY-MM-DD HH:mm:ss')}')`)- }- return [- 'SELECT',- ` ${bucketExpr(from, to ?? dayjs())} AS bucket_start,`,- ` ${metricSelect}`,- `FROM ${table}`,- `WHERE ${where.join('\n AND ')}`,- 'GROUP BY bucket_start',- 'ORDER BY bucket_start',- 'LIMIT 400',- ].join('\n')-}--function masterHealthNode(sql: string, display: ChartDisplayType, yColumn: string): DataVisualizationNode {- return {- kind: NodeKind.DataVisualizationNode,- source: { kind: NodeKind.HogQLQuery, query: sql },- display,- chartSettings: { xAxis: { column: 'bucket_start' }, yAxis: [{ column: yColumn }] },- }-}-export const repoOverviewLogic = kea<repoOverviewLogicType>([path(['products', 'engineering_analytics', 'frontend', 'scenes', 'repoOverviewLogic']),@@ -101,7 +45,6 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([engineeringAnalyticsLogic,['sourceId',- 'activeSource','pullRequests','pullRequestsLoading','cards',@@ -138,6 +81,19 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([}),},],+ // One collapsed point per default-branch commit (all its workflows folded together) for the+ // master-health scatter — the backend owns the collapse, so the UI just plots the points.+ repoActivity: [+ { points: [], truncated: false, limit: 0 } as WorkflowRunActivityApi,+ {+ loadRepoActivity: async (): Promise<WorkflowRunActivityApi> =>+ await engineeringAnalyticsRepoRunActivity(projectId(), {+ date_from: values.dateFrom ?? undefined,+ date_to: values.dateTo ?? undefined,+ source_id: values.sourceId ?? undefined,+ }),+ },+ ],// 'unavailable' marks a failed fetch so we don't retry on every expand.failureLogs: [{} as Record<number, RunFailureLogsApi | 'unavailable'>,@@ -171,6 +127,16 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([loadOverviewFailure: () => true,},],+ // Without this, a failed activity fetch is indistinguishable from a quiet branch — the scene+ // would show the "no runs" empty state over a real error.+ repoActivityFailed: [+ false,+ {+ loadRepoActivity: () => false,+ loadRepoActivitySuccess: () => false,+ loadRepoActivityFailure: () => true,+ },+ ],}),selectors({@@ -180,50 +146,21 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([(s) => [s.masterFailures],(masterFailures): number => new Set(masterFailures.map((group) => group.workflow_name)).size,],- // The warehouse table behind the master-health embeds, mirroring the backend's per-team- // `prefix + github_workflow_runs` resolution (logic/sources.py).- runsTableName: [- (s) => [s.activeSource],- (activeSource): string | null => {- if (!activeSource) {- return null- }- const table = `${activeSource.prefix}github_workflow_runs`- return TABLE_IDENTIFIER.test(table) ? table : null- },- ],- masterSuccessRateQuery: [- (s) => [s.runsTableName, s.defaultBranch, s.dateFrom, s.dateTo],- (runsTableName, defaultBranch, dateFrom, dateTo): DataVisualizationNode | null => {- if (!runsTableName) {- return null- }- const sql = masterHealthSql(- `round(100 * countIf(conclusion = 'success') / count(), 1) AS success_rate`,- runsTableName,- defaultBranch,- dateFrom,- dateTo- )- return sql ? masterHealthNode(sql, ChartDisplayType.ActionsLineGraph, 'success_rate') : null- },- ],- masterFailedRunsQuery: [- (s) => [s.runsTableName, s.defaultBranch, s.dateFrom, s.dateTo],- (runsTableName, defaultBranch, dateFrom, dateTo): DataVisualizationNode | null => {- if (!runsTableName) {- return null- }- const sql = masterHealthSql(- `countIf(conclusion != 'success') AS failed_runs`,- runsTableName,- defaultBranch,- dateFrom,- dateTo- )- return sql ? masterHealthNode(sql, ChartDisplayType.ActionsBar, 'failed_runs') : null- },+ // Backend-collapsed commit points, mapped to the shared chart shape (one dot per default-branch+ // commit: start time, wall-clock CI duration, overall verdict).+ activityRuns: [+ (s) => [s.repoActivity],+ (repoActivity): ActivityRun[] =>+ repoActivity.points.map((point) => ({+ runId: point.run_id,+ conclusion: point.conclusion,+ startedAt: point.run_started_at,+ durationSeconds: point.duration_seconds,+ headBranch: point.head_branch,+ prNumber: point.pr_number,+ })),],+ activityTruncated: [(s) => [s.repoActivity], (repoActivity): boolean => repoActivity.truncated],// Open PRs with failing CI or stuck (open >7d, non-draft, non-bot) — not the full open list.attentionPrs: [(s) => [s.pullRequests],@@ -271,6 +208,24 @@ 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.+ costPerMergeSeries: [+ (s) => [s.overview],+ (overview): { values: number[]; labels: string[] } | null => {+ const series = overview?.cost_series ?? []+ if (!series.length) {+ return null+ }+ const fmt = overview?.cost_series_granularity === 'hour' ? 'MMM D HH:mm' : 'MMM D'+ return {+ values: series.map((bucket) => bucket.cost_per_merge_usd ?? 0),+ labels: series.map((bucket) => dayjs(bucket.bucket_start).format(fmt)),+ }+ },+ ],}),listeners(({ actions, values }) => ({@@ -279,22 +234,27 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([actions.loadFailureLogs({ runId })}},- // The failures feed is pinned to -24h, so it only re-reads on source change / refresh.+ // The failures feed is pinned to -24h, so it only re-reads on source change / refresh; the+ // activity scatter follows the shared window like the overview tiles.[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {actions.loadOverview()+ actions.loadRepoActivity()},[engineeringAnalyticsLogic.actionTypes.setSourceId]: () => {actions.loadOverview()actions.loadMasterFailures()+ actions.loadRepoActivity()},[engineeringAnalyticsLogic.actionTypes.refresh]: () => {actions.loadOverview()actions.loadMasterFailures()+ actions.loadRepoActivity()},})),afterMount(({ actions }) => {actions.loadOverview()actions.loadMasterFailures()+ actions.loadRepoActivity()}),])diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex 21c9d47d7106..8d7e6d83f7d7 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -70,6 +70,9 @@ tools:engineering-analytics-repo-overview:operation: engineering_analytics_repo_overviewenabled: false+ engineering-analytics-repo-run-activity:+ operation: engineering_analytics_repo_run_activity+ enabled: falseengineering-analytics-run-failure-logs:operation: engineering_analytics_run_failure_logsenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4a0db4356b28..02f89f808b7f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13853,6 +13853,23 @@ export namespace Schemas {readonly updated_at: string;}+ export interface CostPerMergeBucket {+ /** Bucket start, aligned to cost_series_granularity (top of hour, midnight, or Monday). */+ bucket_start: string;+ /**+ * Estimated Depot CI cost (USD) of all runs started in this bucket. Null when nothing was costable (no billable self-hosted Linux jobs) or the job source isn't synced.+ * @nullable+ */+ estimated_cost_usd: number | null;+ /** PRs merged in this bucket (all authors, bots included). */+ merges: number;+ /**+ * Rolling ratio: trailing-window CI cost divided by trailing-window merges (24 h / 7 d / 4 w to match the granularity). Null when the trailing window had no merges or no costable cost.+ * @nullable+ */+ cost_per_merge_usd: number | null;+ }+export interface CoverageStats {/** Distinct sessions observed within the last `recent_days` days. */recent_sessions: number;@@ -47608,6 +47625,8 @@ 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. */+ cost_series: CostPerMergeBucket[];/** 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. */@@ -47660,6 +47679,8 @@ export namespace Schemas {jobs_available: boolean;/** 'master' or 'main', picked by observed run volume in the window. */default_branch: string;+ /** Bucket width of the cost_series trend, chosen to fit the window: 'hour', 'day', or 'week'. */+ cost_series_granularity: string;}export interface ScanEvidence {@@ -62915,6 +62936,25 @@ export namespace Schemas {source_id?: string;};+ export type EngineeringAnalyticsRepoRunActivityParams = {+ /**+ * Optional exact git branch (head_branch) to chart, e.g. 'main'. Omit or leave blank to use the repo's detected default branch.+ */+ branch?: string;+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string;+ /**+ * Window end: relative or ISO8601. Defaults to now.+ */+ date_to?: string;+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.+ */+ source_id?: string;+ };+export type EngineeringAnalyticsRunFailureLogsParams = {/*** Workflow run id whose failure logs to fetch.