: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(devex): scope workflow pages by run group instead of branch (#95398)
Julian Bez9d7b0de76ed1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 446e05288f2c..d04aec1f4e1f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6788,6 +6788,22 @@ snapshots:hash: v1.k794b7964.322bfce5ccced64987eb75406fa77e8a2ad80575597378810b984986f9fede0f.EwXIJ9x_Rc-dgkCVJJZBQM1W3voRSFtgHX95x8GbYIEscenes-app-engineering-analytics-test-health--trunk-quarantine-debt-owners-unavailable--light:hash: v1.k794b7964.8916de545edf558f799cc98ee4a901c19ba00fe7d0bb4f5312266705755e3e70.EO6V5mC_JCbSh5ZRrmyU09RT-hFV9f4Mtu_JkZ9m5Ng+ scenes-app-engineering-analytics-workflow--workflow-detail--dark:+ hash: v1.k794b7964.34f27a97a182defe9103de7bb4904e0511f539cbd69154cacf9407ea0e6ae5b6.fx9x83QbIPLTC1foUBSS6_dTDsJwN0pvV_LFjpFADL0+ scenes-app-engineering-analytics-workflow--workflow-detail--light:+ hash: v1.k794b7964.864df1dc201eed86c63c5c8665b410e3cee027ae31ea34a927c54339accf163e.QaubMm0ri-3h0lcu1XErjxehlk-ShT-TQFhXMSA89lo+ scenes-app-engineering-analytics-workflow--workflow-detail-scoped-to-pull-requests--dark:+ hash: v1.k794b7964.0c0f1d46522800e5607f6da430c28c78f944a36b2f8eb0299619d8823d29b260.bxyaidP2mR5LSlQuspIbfz_cnCiylWsjdwYT75rxrsM+ scenes-app-engineering-analytics-workflow--workflow-detail-scoped-to-pull-requests--light:+ hash: v1.k794b7964.6e8be9c87cb9906e6ae6633b9f011a1204266d33e81f5ea55ed34b0164d105ac.LVonrjG3XuvWRwgHUPA__XIPv4IxrK2v6UfyOMXfa4s+ scenes-app-engineering-analytics-workflows--workflow-list--dark:+ hash: v1.k794b7964.a6574f63289438debc52ecec13b02dbe441bc929a8d6f710da3186331cd8d1eb.KpORwpMNnIj4CILhscu52yveUkN_65SPEzYkBUAaumU+ scenes-app-engineering-analytics-workflows--workflow-list--light:+ hash: v1.k794b7964.5f05abb04f8ecaedb71a23c181ece577502973cffc121b6efa62a625b387b849.kvJE0j7aXn3msG_CABO1vJ0JnwNSl7xR6WvTI-96Uf4+ scenes-app-engineering-analytics-workflows--workflow-list-scoped-to-merge-queue--dark:+ hash: v1.k794b7964.c5861b175d342db52fea2665ce0e7fb957ccc6b3b26f57f75a3ef402d021d293.hVYlxFiBOoeoyiY3YjznW61SDRRFFdtyI2GKBFAPKB8+ scenes-app-engineering-analytics-workflows--workflow-list-scoped-to-merge-queue--light:+ hash: v1.k794b7964.81034f96a01d79a233f8293715962f309d39be65d6a41683a1c18ddfd1c100f6.Wv2sRm7umnWkCm2J-G71MT5c_2yKa4sRdlzIgOqOc6Mscenes-app-error-project-unavailable--access-revoked--dark:hash: v1.k794b7964.30ace8f015100159e1dedbed07ff9f0b0b770535870d5c98ea764b10ff1f7621.dTVw9qLa7D_e7ZNme4tVuPZov-0Gg1o84aiDl5zihF0scenes-app-error-project-unavailable--access-revoked--light:diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 73319508f325..7780392799e8 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -7,8 +7,8 @@ parameters and return canonical contract types.``repo`` is an optional ``owner/name`` filter, applied against the curated repoidentity (mapped from ``base.repo.full_name``). ``branch`` is an optional exact``head_branch`` filter for workflow health, a workflow's runs list, and its runner-costs; workflow health additionally takes a broader ``run_scope`` filter-(``pull_request`` scopes to PR-attributed runs). ``date_from`` / ``date_to`` accept+costs; the same surfaces also take a broader ``run_scope`` filter that selects one of+four run groups (``all``, ``default_branch``, ``pull_request``, ``merge_queue``). ``date_from`` / ``date_to`` acceptrelative strings (``-30d``) or ISO8601 and are resolved against the team timezone.``source_id`` selects a specific connected GitHub source when the team has more thanone; it defaults to the oldest connected source. ``user_access_control`` enforces the@@ -194,6 +194,7 @@ def list_workflow_runs(date_from: str | None = None,date_to: str | None = None,branch: str | None = None,+ run_scope: str | None = None,source_id: str | None = None,user_access_control: "UserAccessControl | None" = None,) -> list[WorkflowRunDetail]:@@ -204,6 +205,7 @@ def list_workflow_runs(date_from=date_from,date_to=date_to,branch=branch,+ run_scope=run_scope,)@@ -215,6 +217,7 @@ def get_workflow_run_activity(date_from: str | None = None,date_to: str | None = None,branch: str | None = None,+ run_scope: str | None = None,source_id: str | None = None,user_access_control: "UserAccessControl | None" = None,) -> WorkflowRunActivity:@@ -225,6 +228,7 @@ def get_workflow_run_activity(date_from=date_from,date_to=date_to,branch=branch,+ run_scope=run_scope,)@@ -236,6 +240,7 @@ def get_workflow_runner_costs(date_from: str | None = None,date_to: str | None = None,branch: str | None = None,+ run_scope: str | None = None,source_id: str | None = None,user_access_control: "UserAccessControl | None" = None,) -> list[WorkflowRunnerCost]:@@ -246,6 +251,7 @@ def get_workflow_runner_costs(date_from=date_from,date_to=date_to,branch=branch,+ run_scope=run_scope,)@@ -605,6 +611,7 @@ def list_job_aggregates(date_from: str | None = None,date_to: str | None = None,branch: str | None = None,+ run_scope: str | None = None,source_id: str | None = None,repo: str | None = None,user_access_control: "UserAccessControl | None" = None,@@ -615,4 +622,5 @@ def list_job_aggregates(date_from=date_from,date_to=date_to,branch=branch,+ run_scope=run_scope,)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 7b6efbde913f..ef7b37d1795e 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -105,8 +105,24 @@ class MetricQuality(StrEnum):class WorkflowHealthRunScope(StrEnum):+ """Which population of runs a workflow surface reports on.++ - ``all``: every run in the window.+ - ``default_branch``: runs whose head branch is master or main.+ - ``pull_request``: runs on a non-default branch that carry PR attribution and are not+ merge-queue gate runs.+ - ``merge_queue``: gate runs the merge queue fired before a merge landed.++ The three narrow values never overlap, so a caller can compare them without double-counting.+ They do not cover ``all``: a run on a non-default branch with no PR attribution (a fork PR,+ a release branch) appears only under ``all``, because GitHub does not associate a fork PR+ with its runs.+ """+ALL = "all"+ DEFAULT_BRANCH = "default_branch"PULL_REQUEST = "pull_request"+ MERGE_QUEUE = "merge_queue"class BrokenTestState(StrEnum):@@ -1042,6 +1058,10 @@ class WorkflowHealthItem:# runs excluded). Distinct from `successful_run_count`, which counts those no-op successes too, so# a duration comparison should size its min-sample gate on this, not on `successful_run_count`.percentile_run_count: int = 0+ # Runs on merge-queue gate branches in the window, counted regardless of the branch/run_scope+ # filter, so the list can rank queue-gating workflows (the closest proxy for a required check)+ # even when a scope is active.+ merge_queue_run_count: int = 0@dataclass(frozen=True)diff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.pyindex 376bb8a3b79f..5f90699c57c1 100644--- a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py@@ -184,12 +184,11 @@ def window_pair_predicates(column: str, *, date_to: datetime | None) -> WindowPr)-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 default_branch_predicate(branch_column: str = "r.head_branch") -> str:+ """True when the branch expression names the repo's default branch. The source does not record+ which branch that is, so the common default names stand in. ``repo_overview.query_default_branch``+ resolves it per repo, but that costs an extra query."""+ return f"{branch_column} IN ('master', 'main')"def run_scope_filter_clause(@@ -197,16 +196,35 @@ def run_scope_filter_clause(*,branch_column: str = "r.head_branch",attributed_predicate: str = "r.pr_number > 0",+ merge_queue_predicate: str = "r.is_merge_queue",) -> str:+ """The WHERE fragment that narrows a run population to one ``WorkflowHealthRunScope`` (see that+ enum for what each group covers), or '' for ``all``.++ ``pull_request`` needs all three predicates. 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) does not keep trunk runs out, and gate runs belong to+ ``merge_queue`` instead.+ """+ if run_scope == WorkflowHealthRunScope.DEFAULT_BRANCH:+ return f"AND {default_branch_predicate(branch_column)}"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 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 {non_default_branch_predicate(branch_column)} AND {attributed_predicate}"+ return (+ f"AND NOT {default_branch_predicate(branch_column)} AND {attributed_predicate} "+ f"AND NOT {merge_queue_predicate}"+ )+ if run_scope == WorkflowHealthRunScope.MERGE_QUEUE:+ return f"AND {merge_queue_predicate}"return ""+++def cost_run_scope_filter_clause(run_scope: WorkflowHealthRunScope, *, alias: str = "c") -> str:+ """``run_scope_filter_clause`` against the job cost source. That source keeps the run's branch as+ ``run_head_branch`` (distinct from the per-job ``head_branch``) and NULL-normalizes ``pr_number``,+ so the run predicates need these column names."""+ return run_scope_filter_clause(+ run_scope,+ branch_column=f"{alias}.run_head_branch",+ attributed_predicate=f"{alias}.pr_number IS NOT NULL",+ merge_queue_predicate=f"{alias}.is_merge_queue",+ )diff --git a/products/engineering_analytics/backend/logic/queries/job_aggregates.py b/products/engineering_analytics/backend/logic/queries/job_aggregates.pyindex 32a195aa2259..5211fc02cbcc 100644--- a/products/engineering_analytics/backend/logic/queries/job_aggregates.py+++ b/products/engineering_analytics/backend/logic/queries/job_aggregates.py@@ -17,12 +17,14 @@ from datetime import datetimefrom posthog.hogql import ast-from products.engineering_analytics.backend.facade.contracts import WorkflowJobAggregate+from products.engineering_analytics.backend.facade.contracts import WorkflowHealthRunScope, WorkflowJobAggregatefrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_floatfrom products.engineering_analytics.backend.logic.queries._workflow_filters import (DURATION_PERCENTILE_CONDITION,branch_filter_clause,+ cost_run_scope_filter_clause,date_to_filter_clause,+ run_scope_filter_clause,run_windowed_job_created_floor_constant,)@@ -60,6 +62,7 @@ _AGGREGATE_SELECT = f"""-- report retry pressure for jobs nobody retried.WHERE NOT is_rerun_copyAND workflow_name = {{workflow_name}} AND created_at >= {{date_from}} __DATE_TO__ __BRANCH__+ __JOBS_RUN_SCOPE__GROUP BY job_nameORDER BY job_count DESCLIMIT {_LIMIT}@@ -76,15 +79,26 @@ _COST_SELECT = f"""countIf(estimated_cost_usd IS NOT NULL) AS costed_jobsFROM __COST_SOURCE__ AS cWHERE workflow_name = {{workflow_name}} AND created_at >= {{date_from}} __DATE_TO__ __BRANCH__+ __COST_RUN_SCOPE__GROUP BY job_name"""-_RUN_COUNT_SELECT = """+_RUNS_WINDOW = (+ "workflow_name = {workflow_name} AND run_started_at >= {date_from}"+ " __RUNS_DATE_TO__ __RUNS_BRANCH__ __RUNS_RUN_SCOPE__"+)++_RUN_COUNT_SELECT = f"""SELECT count() AS total_runsFROM __RUNS_SOURCE__ AS r- WHERE workflow_name = {workflow_name} AND run_started_at >= {date_from} __RUNS_DATE_TO__ __RUNS_BRANCH__+ WHERE {_RUNS_WINDOW}"""+# The jobs source carries no attribution or merge-queue column, so a job can only be scoped through+# the run it belongs to. The subquery reuses the run-count window so both sides of the jobs table read+# the same population.+_RUNS_SCOPE_SUBQUERY = f"AND run_id IN (SELECT id FROM __RUNS_SOURCE__ AS r WHERE {_RUNS_WINDOW})"+def query_job_aggregates(*,@@ -93,6 +107,7 @@ def query_job_aggregates(date_from: datetime,date_to: datetime | None,branch: str | None,+ run_scope: WorkflowHealthRunScope = WorkflowHealthRunScope.ALL,) -> list[WorkflowJobAggregate]:# Both templates window the job's OWN created_at, but this query EXCLUDES re-run copies, and a copy# is only recognisable while its original attempt is still in the scan: a re-run a day or more after@@ -116,11 +131,17 @@ def query_job_aggregates(runs_date_to_clause = date_to_filter_clause(date_to, placeholders, column="run_started_at")branch_clause = branch_filter_clause(branch, placeholders, column="head_branch")runs_branch_clause = branch_filter_clause(branch, placeholders, column="head_branch")+ runs_run_scope_clause = run_scope_filter_clause(run_scope)+ cost_run_scope_clause = cost_run_scope_filter_clause(run_scope)+ jobs_run_scope_clause = _RUNS_SCOPE_SUBQUERY if runs_run_scope_clause else ""def fill(template: str) -> str:return (template.replace("__JOBS_SOURCE__", jobs_source).replace("__COST_SOURCE__", cost_source)+ .replace("__JOBS_RUN_SCOPE__", jobs_run_scope_clause)+ .replace("__COST_RUN_SCOPE__", cost_run_scope_clause)+ .replace("__RUNS_RUN_SCOPE__", runs_run_scope_clause).replace("__RUNS_SOURCE__", curated.run_source()).replace("__DATE_TO__", date_to_clause).replace("__RUNS_DATE_TO__", runs_date_to_clause)diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.pyindex e4b6c9dd9154..dc1ae3d3ecd9 100644--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py@@ -48,9 +48,9 @@ from products.engineering_analytics.backend.logic.queries._buckets import (from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries._workflow_filters import (branch_filter_clause,+ cost_run_scope_filter_clause,date_to_filter_clause,merge_queue_branch_predicate,- run_scope_filter_clause,run_windowed_job_created_floor_constant,window_pair_predicates,)@@ -275,9 +275,7 @@ def query_workflow_window_costs(}date_to_clause = date_to_filter_clause(date_to, placeholders, column="c.run_started_at")branch_clause = branch_filter_clause(branch, placeholders, column="c.run_head_branch")- run_scope_clause = run_scope_filter_clause(- run_scope, branch_column="c.run_head_branch", attributed_predicate="c.pr_number IS NOT NULL"- )+ run_scope_clause = cost_run_scope_filter_clause(run_scope)sql = (_WINDOW_COST_SELECT.replace("__COST_SOURCE__", cost_source).replace("__COST_AGGREGATES__", _cost_aggregates())@@ -550,8 +548,8 @@ def query_cost_per_merge_series(# 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. Grouped by the rendered (provider, os, vcpu) tier in SQL — the cost+# to the page's run window (and optional branch or run scope) so the figure always answers "spend over+# [window]", never an unbounded all-time. Grouped by the rendered (provider, os, vcpu) tier in SQL — the cost# source already classifies each job — and mapped to a display badge/label in Python._RUNNER_COST_SELECT = """SELECT@@ -562,7 +560,7 @@ _RUNNER_COST_SELECT = """__COST_AGGREGATES__FROM __COST_SOURCE__ AS cWHERE c.repo_owner = {repo_owner} AND c.repo_name = {repo_name} AND c.workflow_name = {workflow_name}- AND c.run_started_at >= {date_from} __DATE_TO__ __BRANCH__+ AND c.run_started_at >= {date_from} __DATE_TO__ __BRANCH__ __RUN_SCOPE__GROUP BY c.provider, c.os, c.vcpuLIMIT 1000000"""@@ -577,9 +575,10 @@ def query_workflow_runner_costs(date_from: datetime,date_to: datetime | None,branch: str | None = None,+ run_scope: WorkflowHealthRunScope = WorkflowHealthRunScope.ALL,) -> list[WorkflowRunnerCost]:- """A workflow's CI cost broken down by runner tier over [date_from, date_to] (optional branch),- highest spend first. Empty when the jobs source isn't synced. Grouped by the rendered+ """A workflow's CI cost broken down by runner tier over [date_from, date_to] (optional branch and+ run scope), highest spend first. Empty when the jobs source isn't synced. Grouped by the rendered(provider, os, vcpu) tier and mapped to its display badge/label via ``runner_tier_descriptor``."""cost_source = curated.job_cost_source(created_floor=True)if cost_source is None:@@ -593,11 +592,13 @@ def query_workflow_runner_costs(}date_to_clause = date_to_filter_clause(date_to, placeholders, column="c.run_started_at")branch_clause = branch_filter_clause(branch, placeholders, column="c.run_head_branch")+ run_scope_clause = cost_run_scope_filter_clause(run_scope)sql = (_RUNNER_COST_SELECT.replace("__COST_SOURCE__", cost_source).replace("__COST_AGGREGATES__", _cost_aggregates()).replace("__DATE_TO__", date_to_clause).replace("__BRANCH__", branch_clause)+ .replace("__RUN_SCOPE__", run_scope_clause))response = curated.run(sql,diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.pyindex 45ebba0c3f20..30ce3da39e7c 100644--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py@@ -2,7 +2,7 @@Run counts, success rate, and duration percentiles per ``workflow_name`` for runsstarted within ``[date_from, date_to]`` (``date_to`` optional), optionally scoped to-a single ``head_branch`` and/or attributed pull-request runs. Rates are over conclusive+a single ``head_branch`` and/or one ``run_scope`` group. Rates are over conclusiveruns (success or a decisive failure), so skipped, cancelled, neutral, and action-requiredruns never read as failures. Duration percentiles are over successful runs only becausecancelled, skipped, and failed runs end early and would bias a "how long does CI take"@@ -46,7 +46,7 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impoSUCCESSFUL_RUN_CONDITION,branch_filter_clause,date_to_filter_clause,- non_default_branch_predicate,+ default_branch_predicate,run_duration_percentile_expr,run_scope_filter_clause,run_started_floor_constant,@@ -77,7 +77,8 @@ _SELECT = f"""argMaxIf(conclusion, (run_started_at, id), status = 'completed') AS latest_conclusion,argMaxIf(id, (run_started_at, id), status = 'completed') AS latest_run_id,argMaxIf(run_attempt, (run_started_at, id), status = 'completed') AS latest_run_attempt,- countIf(run_attempt > 1) AS rerun_cycles+ countIf(run_attempt > 1) AS rerun_cycles,+ countIf(is_merge_queue) AS merge_queue_run_countFROM __RUNS_SOURCE__ AS rWHERE run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__ __RUN_SCOPE__GROUP BY repo_owner, repo_name, workflow_name@@ -99,6 +100,24 @@ _PREV_SELECT = f"""GROUP BY repo_owner, repo_name, workflow_name"""+# Merge-queue run counts over the same window with no branch/run_scope filter, so the list can rank+# queue-gating workflows whatever scope is active. Only needed when a filter is on: without one, the+# main query's own countIf already answers this. The scan covers only the workflows the main query+# returned, HAVING keeps the gating ones, and the explicit bound keeps HogQL's default 100-row cap+# from silently dropping some of them.+_GATING_SELECT = f"""+ SELECT+ repo_owner,+ repo_name,+ workflow_name,+ countIf(is_merge_queue) AS merge_queue_run_count+ FROM __RUNS_SOURCE__ AS r+ WHERE run_started_at >= {{date_from}} __DATE_TO__ AND workflow_name IN {{gating_workflow_names}}+ GROUP BY repo_owner, repo_name, workflow_name+ HAVING merge_queue_run_count > 0+ LIMIT {_LIMIT}+"""+_BUCKET_SELECT = f"""SELECTrepo_owner,@@ -152,7 +171,7 @@ _TIME_TO_GREEN_CTES = f"""FROM __RUNS_SOURCE__ AS rWHERE run_started_at >= {{scan_from}} __DATE_TO__AND NOT r.is_merge_queue- AND {non_default_branch_predicate()}+ AND NOT {default_branch_predicate()}GROUP BY repo_owner, repo_name, head_sha, workflow_name),green_rounds AS (@@ -334,6 +353,25 @@ def query_workflow_health(cost_by_workflow = query_workflow_window_costs(curated=curated, date_from=date_from, date_to=date_to, branch=branch, run_scope=run_scope, workload=workload)+ # Under an active branch or scope filter the main query's merge-queue count answers the filtered+ # population, which cannot rank workflows: under merge_queue every row would look gating, under+ # pull_request none would. So read the count from an unfiltered scan of the same window instead.+ scoped = bool(branch_clause or run_scope_clause)+ gating_by_workflow: dict[tuple[str, str, str], int] = {}+ if scoped:+ gating_response = curated.run(+ fill(_GATING_SELECT),+ query_type="engineering_analytics.workflow_health_gating",+ placeholders={+ **placeholders,+ "gating_workflow_names": ast.Constant(value=sorted({row[2] for row in response.results})),+ },+ workload=workload,+ )+ gating_by_workflow = {+ (repo_owner, repo_name, workflow_name): int(count or 0)+ for repo_owner, repo_name, workflow_name, count in gating_response.results or []+ }window = window_buckets(date_from, date_to, granularity)return [WorkflowHealthItem(@@ -370,6 +408,11 @@ def query_workflow_health(),rerun_cycles=rerun_cycles,success_rate_prev=prev_rate_by_workflow.get((repo_owner, repo_name, workflow_name)),+ merge_queue_run_count=(+ gating_by_workflow.get((repo_owner, repo_name, workflow_name), 0)+ if scoped+ else int(merge_queue_run_count or 0)+ ),)- for repo_owner, repo_name, workflow_name, run_count, successful_run_count, conclusive_run_count, percentile_run_count, success_rate, p50_seconds, p95_seconds, last_failure_at, completed_count, latest_failed, latest_conclusion, latest_run_id, latest_run_attempt, rerun_cycles in response.results+ for repo_owner, repo_name, workflow_name, run_count, successful_run_count, conclusive_run_count, percentile_run_count, success_rate, p50_seconds, p95_seconds, last_failure_at, completed_count, latest_failed, latest_conclusion, latest_run_id, latest_run_attempt, rerun_cycles, merge_queue_run_count in response.results]diff --git a/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py b/products/engineering_analytics/backend/logic/queries/workflow_run_activity.pyindex e51c4e729b28..a149b402df60 100644--- a/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py+++ b/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py@@ -25,12 +25,17 @@ from datetime import datetimefrom posthog.hogql import ast-from products.engineering_analytics.backend.facade.contracts import WorkflowRunActivity, WorkflowRunActivityPoint+from products.engineering_analytics.backend.facade.contracts import (+ WorkflowHealthRunScope,+ WorkflowRunActivity,+ WorkflowRunActivityPoint,+)from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries._workflow_filters import (NO_OP_RUN_FLAG,branch_filter_clause,date_to_filter_clause,+ run_scope_filter_clause,)# The chart plots a point per run and needs enough span to cover the window: an order of magnitude@@ -49,7 +54,7 @@ _SELECT = f"""{NO_OP_RUN_FLAG} AS is_noopFROM __RUNS_SOURCE__ AS rWHERE repo_owner = {{repo_owner}} AND repo_name = {{repo_name}} AND workflow_name = {{workflow_name}}- AND run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__+ AND run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__ __RUN_SCOPE__ORDER BY is_noop ASC, run_started_at DESC, run_attempt DESCLIMIT {_LIMIT + 1}"""@@ -64,6 +69,7 @@ def query_workflow_run_activity(date_from: datetime,date_to: datetime | None,branch: str | None = None,+ run_scope: WorkflowHealthRunScope = WorkflowHealthRunScope.ALL,) -> WorkflowRunActivity:placeholders: dict[str, ast.Expr] = {"repo_owner": ast.Constant(value=repo_owner),@@ -76,7 +82,8 @@ def query_workflow_run_activity(response = curated.run(_SELECT.replace("__RUNS_SOURCE__", curated.run_source()).replace("__DATE_TO__", date_to_clause)- .replace("__BRANCH__", branch_clause),+ .replace("__BRANCH__", branch_clause)+ .replace("__RUN_SCOPE__", run_scope_filter_clause(run_scope)),query_type="engineering_analytics.workflow_run_activity",placeholders=placeholders,)diff --git a/products/engineering_analytics/backend/logic/queries/workflow_run_list.py b/products/engineering_analytics/backend/logic/queries/workflow_run_list.pyindex 7b6a7c8dccb4..3ca225f8c458 100644--- a/products/engineering_analytics/backend/logic/queries/workflow_run_list.py+++ b/products/engineering_analytics/backend/logic/queries/workflow_run_list.py@@ -10,12 +10,13 @@ from datetime import datetimefrom posthog.hogql import ast-from products.engineering_analytics.backend.facade.contracts import WorkflowRunDetail+from products.engineering_analytics.backend.facade.contracts import WorkflowHealthRunScope, WorkflowRunDetailfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries._run_detail import RUN_DETAIL_COLUMNS, to_run_detailfrom products.engineering_analytics.backend.logic.queries._workflow_filters import (branch_filter_clause,date_to_filter_clause,+ run_scope_filter_clause,)# Safety bound on the runs list (mirrors the PR table's cap philosophy).@@ -26,7 +27,7 @@ _SELECT = f"""{RUN_DETAIL_COLUMNS}FROM __RUNS_SOURCE__ AS rWHERE repo_owner = {{repo_owner}} AND repo_name = {{repo_name}} AND workflow_name = {{workflow_name}}- AND run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__+ AND run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__ __RUN_SCOPE__ORDER BY run_started_at DESC, run_attempt DESCLIMIT {_LIMIT}"""@@ -41,6 +42,7 @@ def query_workflow_run_list(date_from: datetime,date_to: datetime | None,branch: str | None = None,+ run_scope: WorkflowHealthRunScope = WorkflowHealthRunScope.ALL,) -> list[WorkflowRunDetail]:placeholders: dict[str, ast.Expr] = {"repo_owner": ast.Constant(value=repo_owner),@@ -53,7 +55,8 @@ def query_workflow_run_list(response = curated.run(_SELECT.replace("__RUNS_SOURCE__", curated.run_source()).replace("__DATE_TO__", date_to_clause)- .replace("__BRANCH__", branch_clause),+ .replace("__BRANCH__", branch_clause)+ .replace("__RUN_SCOPE__", run_scope_filter_clause(run_scope)),query_type="engineering_analytics.workflow_run_list",placeholders=placeholders,)diff --git a/products/engineering_analytics/backend/logic/workflows.py b/products/engineering_analytics/backend/logic/workflows.pyindex fbdf2926d498..46a1cc14f271 100644--- a/products/engineering_analytics/backend/logic/workflows.py+++ b/products/engineering_analytics/backend/logic/workflows.py@@ -48,6 +48,19 @@ def build_workflow_jobs(return query_workflow_jobs(curated=curated, run_id=run_id, run_attempt=run_attempt)+def _parse_run_scope(value: str | None) -> WorkflowHealthRunScope:+ """Absent/blank selects 'all'; anything else must be an exact enum value (ValueError → 400)."""+ normalized = value.strip() if value else ""+ if not normalized:+ return WorkflowHealthRunScope.ALL+ try:+ return WorkflowHealthRunScope(normalized)+ except ValueError:+ raise ValueError(+ f"run_scope must be one of: {', '.join(scope.value for scope in WorkflowHealthRunScope)}"+ ) from None++def build_workflow_run_list(*,curated: CuratedGitHubSource,@@ -56,6 +69,7 @@ def build_workflow_run_list(date_from: str | None = None,date_to: str | None = None,branch: str | None = None,+ run_scope: str | None = None,) -> list[WorkflowRunDetail]:owner, name = _require_repo(repo)parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)@@ -67,6 +81,7 @@ def build_workflow_run_list(date_from=parsed_from,date_to=parsed_to,branch=branch,+ run_scope=_parse_run_scope(run_scope),)@@ -78,6 +93,7 @@ def build_workflow_run_activity(date_from: str | None = None,date_to: str | None = None,branch: str | None = None,+ run_scope: str | None = None,) -> WorkflowRunActivity:owner, name = _require_repo(repo)parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)@@ -89,6 +105,7 @@ def build_workflow_run_activity(date_from=parsed_from,date_to=parsed_to,branch=branch,+ run_scope=_parse_run_scope(run_scope),)@@ -100,6 +117,7 @@ def build_workflow_runner_costs(date_from: str | None = None,date_to: str | None = None,branch: str | None = None,+ run_scope: str | None = None,) -> list[WorkflowRunnerCost]:owner, name = _require_repo(repo)parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)@@ -111,6 +129,7 @@ def build_workflow_runner_costs(date_from=parsed_from,date_to=parsed_to,branch=branch,+ run_scope=_parse_run_scope(run_scope),)@@ -132,19 +151,6 @@ def build_workflow_health()-def _parse_run_scope(value: str | None) -> WorkflowHealthRunScope:- """Absent/blank selects 'all'; anything else must be an exact enum value (ValueError → 400)."""- normalized = value.strip() if value else ""- if not normalized:- return WorkflowHealthRunScope.ALL- try:- return WorkflowHealthRunScope(normalized)- except ValueError:- raise ValueError(- f"run_scope must be one of: {', '.join(scope.value for scope in WorkflowHealthRunScope)}"- ) from None--def build_repo_overview(*,curated: CuratedGitHubSource,@@ -210,8 +216,14 @@ def build_job_aggregates(date_from: str | None = None,date_to: str | None = None,branch: str | None = None,+ run_scope: str | None = None,) -> list[WorkflowJobAggregate]:parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)return query_job_aggregates(- curated=curated, workflow_name=workflow_name, date_from=parsed_from, date_to=parsed_to, branch=branch+ curated=curated,+ workflow_name=workflow_name,+ date_from=parsed_from,+ date_to=parsed_to,+ branch=branch,+ run_scope=_parse_run_scope(run_scope),)diff --git a/products/engineering_analytics/backend/presentation/serializers/workflows.py b/products/engineering_analytics/backend/presentation/serializers/workflows.pyindex 5ed7a958eb8a..68bb5aa15439 100644--- a/products/engineering_analytics/backend/presentation/serializers/workflows.py+++ b/products/engineering_analytics/backend/presentation/serializers/workflows.py@@ -248,6 +248,11 @@ class WorkflowHealthItemSerializer(DataclassSerializer):"percentile_run_count": {"help_text": "Successful runs that did real CI work. This is the p50/p95 sample count."},+ "merge_queue_run_count": {+ "help_text": "Runs on merge-queue gate branches (trunk-merge/**) in the window, counted regardless "+ "of branch or run_scope. Non-zero marks a workflow the queue runs before a merge lands, the closest "+ "available proxy for a required check."+ },}diff --git a/products/engineering_analytics/backend/presentation/views/_base.py b/products/engineering_analytics/backend/presentation/views/_base.pyindex 7a1d1e497661..30106bee9eb6 100644--- a/products/engineering_analytics/backend/presentation/views/_base.py+++ b/products/engineering_analytics/backend/presentation/views/_base.py@@ -65,9 +65,10 @@ _RUN_SCOPE = OpenApiParameter(location=OpenApiParameter.QUERY,required=False,enum=[scope.value for scope in WorkflowHealthRunScope],- description="Run scope for workflow health: 'all' (default) includes every run; 'pull_request' includes runs "- "attributed to pull requests, excluding default-branch (master/main) runs. Fork PRs carry no PR attribution "- "(a GitHub limitation), so 'pull_request' covers same-repo PRs only. Any other value is a 400.",+ description="Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on "+ "master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; "+ "'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR "+ "attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.",)_SOURCE_ID = OpenApiParameter(diff --git a/products/engineering_analytics/backend/presentation/views/workflows.py b/products/engineering_analytics/backend/presentation/views/workflows.pyindex fdfb2b8dc1a5..69095f79a9df 100644--- a/products/engineering_analytics/backend/presentation/views/workflows.py+++ b/products/engineering_analytics/backend/presentation/views/workflows.py@@ -67,8 +67,8 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):"by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive ""failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over ""successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. "- "Optionally scope to a single git branch via `branch`, "- "or to attributed pull-request runs via `run_scope=pull_request`. Use this for 'is CI getting slower' "+ "Optionally scope to a single git branch via `branch`, or to one run group via `run_scope` "+ "(default_branch, pull_request, merge_queue). Use this for 'is CI getting slower' ""and 'which workflow is the long pole'; compare two windows to get a trend."),)@@ -148,17 +148,18 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):_DATE_FROM,_DATE_TO,_BRANCH,+ _RUN_SCOPE,_SOURCE_ID,],responses={200: WorkflowRunDetailSerializer(many=True),- 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date or source_id."),+ 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date, run_scope, or source_id."),},description=("Runs of a single workflow within a repo over a window (date_from default -30d), newest first. "- "Optionally scope to a single git branch via `branch`. Each row is run-level — per-job and "- "per-step detail are not tracked yet. Use this as the GitHub 'workflow' page between the "- "workflow list and a single run."+ "Optionally scope to a single git branch via `branch` or to one run group via `run_scope`. "+ "Each row is run-level — per-job and per-step detail are not tracked yet. Use this as the "+ "GitHub 'workflow' page between the workflow list and a single run."),)@action(detail=False, methods=["get"], pagination_class=None)@@ -176,6 +177,7 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):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,+ run_scope=request.query_params.get("run_scope") or None,source_id=request.query_params.get("source_id") or None,user_access_control=self.user_access_control,)@@ -203,18 +205,20 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):_DATE_FROM,_DATE_TO,_BRANCH,+ _RUN_SCOPE,_SOURCE_ID,],responses={200: WorkflowRunActivitySerializer,- 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date or source_id."),+ 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date, run_scope, or source_id."),},description=("Compact per-run points for a single workflow over a window (date_from default -30d), newest first, for ""the run-activity chart: each run's start time, duration, conclusion, branch, and attributed PR. "- "Optionally scope to a single git branch via `branch`, matching workflow_runs. Leaner and higher-capped "- "than workflow_runs so the chart spans the full window even on busy workflows; `truncated` is true when "- "the cap is hit, so the chart covers only the most recent runs."+ "Optionally scope to a single git branch via `branch` or one run group via `run_scope`, matching "+ "workflow_runs. Leaner and higher-capped than workflow_runs so the chart spans the full window even "+ "on busy workflows; `truncated` is true when the cap is hit, so the chart covers only the most "+ "recent runs."),)@action(detail=False, methods=["get"], pagination_class=None)@@ -231,6 +235,7 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):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,+ run_scope=request.query_params.get("run_scope") or None,source_id=request.query_params.get("source_id") or None,user_access_control=self.user_access_control,)@@ -258,16 +263,17 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):_DATE_FROM,_DATE_TO,_BRANCH,+ _RUN_SCOPE,_SOURCE_ID,],responses={200: WorkflowRunnerCostSerializer(many=True),- 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date or source_id."),+ 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date, run_scope, or source_id."),},description=("A workflow's estimated CI cost broken down by runner tier over a window (date_from default "- "-30d), highest spend first. Optionally scope to a single git branch via `branch`. Returns an "- "empty list when the job-level source isn't synced."+ "-30d), highest spend first. Optionally scope to a single git branch via `branch` or one run "+ "group via `run_scope`. Returns an empty list when the job-level source isn't synced."),)@action(detail=False, methods=["get"], pagination_class=None)@@ -284,6 +290,7 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):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,+ run_scope=request.query_params.get("run_scope") or None,source_id=request.query_params.get("source_id") or None,user_access_control=self.user_access_control,)@@ -541,17 +548,19 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):_DATE_FROM,_DATE_TO,_BRANCH,+ _RUN_SCOPE,_SOURCE_ID,_REPO,],responses={200: WorkflowJobAggregateSerializer(many=True),- 400: OpenApiResponse(description="Missing workflow_name, or invalid date or source_id."),+ 400: OpenApiResponse(description="Missing workflow_name, or invalid date, run_scope, or source_id."),},description=("Per-job aggregates for one workflow over a window (default -30d), one row per de-sharded job ""name (matrix shards aggregate together), busiest first: queue p50, duration p50/p95, failure "- "rate, retry pressure, run share (below 1.0 = conditional job), and billable cost. Jobs always "+ "rate, retry pressure, run share (below 1.0 = conditional job), and billable cost. Optionally "+ "scope to a single git branch via `branch` or one run group via `run_scope`. Jobs always ""need their run as context — this is the aggregate view; use workflow_jobs for one run's jobs. ""Empty when the job-level source isn't synced."),@@ -568,6 +577,7 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):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,+ run_scope=request.query_params.get("run_scope") or None,source_id=request.query_params.get("source_id") or None,repo=request.query_params.get("repo") or None,user_access_control=self.user_access_control,diff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.pyindex ed9701265d2a..315ab920d877 100644--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py@@ -75,7 +75,7 @@ class TestWorkflowEndpointMapping(BaseTest):def test_workflow_health_maps_and_nulls_empty_window(self) -> None:# Columns: owner, name, workflow, run_count, successful_run_count, conclusive_run_count,# percentile_run_count, success_rate, p50, p95, last_failure_at, completed_count, latest_failed,- # latest_conclusion, latest_run_id, latest_run_attempt, rerun_cycles.+ # latest_conclusion, latest_run_id, latest_run_attempt, rerun_cycles, merge_queue_run_count.rows = [("PostHog",@@ -95,11 +95,12 @@ class TestWorkflowEndpointMapping(BaseTest):4321,1,3,+ 2,),# No completed runs: success_rate is NULL and quantileIf returns NaN — both map to None,# latest_run_failed is None (the completed_count guard), and latest_run_conclusion is None too# despite argMaxIf's '' default.- ("PostHog", "posthog", "Deploy", 2, 0, 0, 0, None, float("nan"), float("nan"), None, 0, 0, "", 0, 0, 0),+ ("PostHog", "posthog", "Deploy", 2, 0, 0, 0, None, float("nan"), float("nan"), None, 0, 0, "", 0, 0, 0, 0),]# A -30d window buckets by day. Must land inside the window (relative to now). Columns:# owner, name, workflow, bucket_start, run_count, completed, successes, failures.@@ -117,6 +118,7 @@ class TestWorkflowEndpointMapping(BaseTest):assert items[0].latest_run_id == 4321 and items[0].latest_run_attempt == 1assert items[1].latest_run_id is None and items[1].latest_run_attempt is Noneassert items[0].rerun_cycles == 3+ assert items[0].merge_queue_run_count == 2assert items[0].success_rate_prev == 0.95assert items[1].success_rate_prev is None# The series spans the whole window, zero-filled except the bucket with runs.@@ -690,37 +692,86 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):guard = next(item for item in health if item.workflow_name == "Guard")assert guard.p50_seconds == pytest.approx(4)- def test_workflow_health_pull_request_scope_excludes_default_branch_and_unattributed_runs(self) -> None:+ # The scenario matrix: PR attribution × head branch, plus one corroborated merge-queue gate run.+ # No run lands in two narrow scopes, and 9104 (off-default, unattributed) lands in none of them,+ # so the three narrow counts sum to one below the `all` count.+ _RUN_SCOPE_MATRIX = [+ (9101, "sha-pr", 91, "feature/pr", "alice"),+ (9102, "sha-master", None, "master", "alice"),+ (9103, "sha-master-pr", 91, "master", "alice"),+ (9104, "sha-branch", None, "feature/no-pr", "alice"),+ (9105, "sha-main-pr", 91, "main", "alice"),+ (9106, "sha-gate", None, "trunk-merge/pr-91/aaaa", "trunk-io[bot]"),+ ]++ def _seed_run_scope_matrix(self) -> None:self._create_table("github_pull_requests",PULL_REQUESTS_COLUMNS,[_pr_row(91, "alice", "open", 0, _ago(1), head_sha="sha91")],)- # The scenario matrix: PR-attributed × head branch. Only the attributed feature-branch- # run belongs in the pull_request scope.self._create_table("github_workflow_runs",WORKFLOW_RUNS_COLUMNS,[- _run_row(run_id, "CI", sha, "completed", "success", _ago(1), _ago(1), pr_number=pr, head_branch=head)- for run_id, sha, pr, head in [- (9101, "sha-pr", 91, "feature/pr"),- (9102, "sha-master", None, "master"),- (9103, "sha-master-pr", 91, "master"),- (9104, "sha-branch", None, "feature/no-pr"),- (9105, "sha-main-pr", 91, "main"),- ]+ _run_row(+ run_id,+ "CI",+ sha,+ "completed",+ "success",+ _ago(1),+ _ago(1),+ pr_number=pr,+ head_branch=head,+ actor=actor,+ )+ for run_id, sha, pr, head, actor in self._RUN_SCOPE_MATRIX],)- pull_request = next(+ @parameterized.expand(+ [+ ("pull_request", 1),+ ("default_branch", 3),+ ("merge_queue", 1),+ ("all", 6),+ ]+ )+ def test_workflow_health_run_scopes_partition_the_run_population(self, scope: str, expected: int) -> None:+ self._seed_run_scope_matrix()++ ci = next(item- for item in api.list_workflow_health(team=self.team, date_from="-30d", run_scope="pull_request")+ for item in api.list_workflow_health(team=self.team, date_from="-30d", run_scope=scope)if item.workflow_name == "CI")- # 1 exactly: over-exclusion drops to 0, a leaked master/main/unattributed row raises it above 1.- assert pull_request.run_count == 1+ assert ci.run_count == expected+ # The gating count ignores the active scope, so the list can rank queue-gating workflows+ # under every scope. A scope-filtered count would read 0 here under pull_request.+ assert ci.merge_queue_run_count == 1++ @parameterized.expand(+ [+ ("pull_request", [9101]),+ ("default_branch", [9102, 9103, 9105]),+ ("merge_queue", [9106]),+ ("all", [9101, 9102, 9103, 9104, 9105, 9106]),+ ]+ )+ def test_workflow_runs_honor_run_scope(self, scope: str, expected_ids: list[int]) -> None:+ self._seed_run_scope_matrix()++ runs = api.list_workflow_runs(+ team=self.team,+ repo="PostHog/posthog",+ workflow_name="CI",+ date_from="-30d",+ run_scope=scope,+ )++ assert sorted(run.id for run in runs) == expected_idsdef test_workflow_health_includes_cost_when_jobs_synced(self) -> None:# With the jobs source synced, each workflow carries its windowed billable cost + minutes.@@ -1067,6 +1118,19 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):)assert (all_jobs, main_jobs) == (3, 2)+ # A run scope narrows the same two job-level surfaces. The jobs source carries no branch+ # attribution of its own, so job_aggregates scopes through a run-id subquery; this is the one+ # place that subquery and the runner-cost scope clause run against a warehouse.+ default_branch_jobs = sum(+ c.job_count+ for c in api.get_workflow_runner_costs(+ team=self.team, repo=repo, workflow_name=workflow, run_scope="default_branch"+ )+ )+ assert default_branch_jobs == 2+ aggregates = api.list_job_aggregates(team=self.team, workflow_name=workflow, run_scope="default_branch")+ assert [(a.job_name, a.job_count) for a in aggregates] == [("build", 2)]+# The activity chart honors the same branch scope as the runs list, so it can't plot other# branches' runs under an applied branch filter.all_activity = api.get_workflow_run_activity(team=self.team, repo=repo, workflow_name=workflow)diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex 7e207d762e84..59eafa54f22e 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -588,13 +588,52 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "the maximum is 366" in response.json()["detail"]- def test_workflow_health_400_on_invalid_run_scope(self) -> None:- # A typo'd scope must 400, not silently return the all-runs population as a 200.- response = self.client.get(self._url("workflow_health"), {"run_scope": "bogus"})+ @parameterized.expand(+ [+ ("workflow_health", {}),+ ("workflow_runs", {"workflow_name": "CI", "repo": "PostHog/posthog"}),+ ("workflow_run_activity", {"workflow_name": "CI", "repo": "PostHog/posthog"}),+ ("workflow_runner_costs", {"workflow_name": "CI", "repo": "PostHog/posthog"}),+ ("job_aggregates", {"workflow_name": "CI"}),+ ]+ )+ def test_400_on_invalid_run_scope(self, action: str, params: dict[str, str]) -> None:+ # A typo'd scope must 400 on every endpoint that accepts it, not silently return the+ # all-runs population as a 200.+ response = self.client.get(self._url(action), {**params, "run_scope": "bogus"})assert response.status_code == status.HTTP_400_BAD_REQUESTassert "run_scope must be one of" in response.json()["detail"]+ @parameterized.expand(+ [+ ("workflow_runs", "list_workflow_runs", {"workflow_name": "CI", "repo": "PostHog/posthog"}, []),+ (+ "workflow_run_activity",+ "get_workflow_run_activity",+ {"workflow_name": "CI", "repo": "PostHog/posthog"},+ contracts.WorkflowRunActivity(points=[], truncated=False, limit=2000),+ ),+ (+ "workflow_runner_costs",+ "get_workflow_runner_costs",+ {"workflow_name": "CI", "repo": "PostHog/posthog"},+ [],+ ),+ ("job_aggregates", "list_job_aggregates", {"workflow_name": "CI"}, []),+ ]+ )+ def test_forwards_run_scope(+ self, action: str, facade_function: str, params: dict[str, str], result: object+ ) -> None:+ # The detail page scopes on the same group as the workflow list, so each of its endpoints+ # has to reach its facade function with the scope still attached.+ with mock.patch(f"{_VIEWS}.{facade_function}", return_value=result) as call:+ response = self.client.get(self._url(action), {**params, "run_scope": "merge_queue"})++ assert response.status_code == status.HTTP_200_OK+ assert call.call_args.kwargs["run_scope"] == "merge_queue"+@parameterized.expand(["sources", "quarantine"])def test_requires_authentication(self, action: str) -> None:# permission_classes live once on the shared viewset base and per-action scope drift isdiff --git a/products/engineering_analytics/frontend/components/ScopeBar.tsx b/products/engineering_analytics/frontend/components/ScopeBar.tsxindex 7fa3ac57b3f1..6788e76bbffd 100644--- a/products/engineering_analytics/frontend/components/ScopeBar.tsx+++ b/products/engineering_analytics/frontend/components/ScopeBar.tsx@@ -1,13 +1,21 @@// Shared scope bar: hierarchy chips (repo › workflow › run) on the left, dismissible filter chips on-// the right, and the shared branch/date scope (engineeringAnalyticsFiltersLogic) so a window picked on-// one page carries to the next.+// the right, and the shared date scope (engineeringAnalyticsFiltersLogic) so a window picked on one page+// carries to the next. The run-scope control lives here too, but pages dock it on their scope panel.import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { Fragment, ReactNode, useState } from 'react'import { IconX } from '@posthog/icons'-import { LemonButton, LemonDropdown, LemonInput, LemonSelect, Link, Spinner } from '@posthog/lemon-ui'+import {+ LemonButton,+ LemonDropdown,+ LemonInput,+ LemonSegmentedButton,+ LemonSelect,+ Link,+ Spinner,+} from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { cn } from 'lib/utils/css-classes'@@ -15,7 +23,11 @@ import { dateMapping } from 'lib/utils/dateFilters'import { urls } from 'scenes/urls'import { scopeFromValue, withScope } from '../lib/scope'-import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from '../scenes/engineeringAnalyticsFiltersLogic'+import {+ RUN_SCOPE_OPTIONS,+ SHARED_DEFAULT_DATE_FROM,+ engineeringAnalyticsFiltersLogic,+} from '../scenes/engineeringAnalyticsFiltersLogic'import { engineeringAnalyticsLogic } from '../scenes/engineeringAnalyticsLogic'import { workflowSwitcherLogic } from '../scenes/workflowSwitcherLogic'@@ -192,77 +204,28 @@ export function WorkflowScopeChip({)}-/** Branch chip opening a small picker — a shared CI scope: an exact head_branch, all branches, or the- * pull-request lens (non-default-branch runs). Only workflow health honors the PR lens; exact-branch- * surfaces fall back to all branches for it. No default-branch preset — the repo's default (master vs- * main) isn't known here, so type it exactly instead of guessing. */-export function BranchScopeChip(): JSX.Element {- const { branchInput, appliedBranch, pullRequestScope } = useValues(engineeringAnalyticsFiltersLogic)- const { setBranchFilter, applyBranchFilter, setAppliedBranch, scopeToPullRequests } = useActions(- engineeringAnalyticsFiltersLogic- )- const [visible, setVisible] = useState(false)+const RUN_SCOPE_SEGMENTS = RUN_SCOPE_OPTIONS.map((option) => ({+ ...option,+ 'data-attr': `engineering-analytics-run-scope-${option.value}`,+}))+/** The shared run-scope control: four fixed groups that partition the repo's runs. Every workflow+ * surface sends the picked group, so a drill-down reports the same population as the list it came from. */+export function RunScopeControl(): JSX.Element {+ const { runScope } = useValues(engineeringAnalyticsFiltersLogic)+ const { setRunScope } = useActions(engineeringAnalyticsFiltersLogic)return (- <LemonDropdown- visible={visible}- onVisibilityChange={setVisible}- closeOnClickInside={false}- overlay={- <div className="flex w-72 flex-col gap-2 p-1">- <LemonInput- type="search"- size="small"- placeholder="Branch name (exact)"- value={branchInput}- onChange={setBranchFilter}- onPressEnter={() => {- applyBranchFilter()- setVisible(false)- }}- autoFocus- data-attr="engineering-analytics-branch-filter"- />- <div className="flex flex-wrap gap-1">- <LemonButton- size="xsmall"- type={pullRequestScope ? 'primary' : 'secondary'}- onClick={() => {- scopeToPullRequests()- setVisible(false)- }}- tooltip="CI on pull-request branches, excluding master/main. Same-repo PRs only — fork PRs carry no attribution. Applies to workflow health."- >- Pull requests- </LemonButton>- <LemonButton- size="xsmall"- type={!pullRequestScope && !appliedBranch ? 'primary' : 'secondary'}- onClick={() => {- setAppliedBranch('')- setVisible(false)- }}- >- all branches- </LemonButton>- </div>- </div>- }- >- <span className={cn(CHIP_CLASS, 'cursor-pointer')} title="One CI scope for every section below">- {pullRequestScope ? (- <strong className="font-semibold text-primary">pull requests</strong>- ) : appliedBranch ? (- <>- {'branch: '}- <strong className="font-semibold text-primary">{appliedBranch}</strong>- </>- ) : (- <strong className="font-semibold text-tertiary">all branches</strong>- )}- <span className="text-[8px] text-tertiary">▼</span>- </span>- </LemonDropdown>+ <LemonSegmentedButton+ size="small"+ value={runScope}+ onChange={(value) => {+ // Re-picking the active group would reload every surface for no change.+ if (value !== runScope) {+ setRunScope(value)+ }+ }}+ options={RUN_SCOPE_SEGMENTS}+ />)}@@ -282,11 +245,20 @@ export function ScopeDateFilter(): JSX.Element {)}+/** The scope-panel rim both workflow pages share: run group on the left, window on the right. */+export function WorkflowScopeControls(): JSX.Element {+ return (+ <>+ <RunScopeControl />+ <ScopeDateFilter />+ </>+ )+}+export function ScopeBar({repoSlot,crumbs = [],lensFilter,- showBranch = false,showDate = true,extra,}: {@@ -296,7 +268,6 @@ export function ScopeBar({crumbs?: ScopeCrumb[]/** The active cross-cutting lens (pr: #N) — dismissible, zooms out to `to`. */lensFilter?: LensChip- showBranch?: booleanshowDate?: booleanextra?: ReactNode}): JSX.Element {@@ -329,7 +300,6 @@ export function ScopeBar({</Link></span>)}- {showBranch && <BranchScopeChip />}{showDate && <ScopeDateFilter />}{extra}</span>diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsxindex 8029f61ec089..ff8c319f7844 100644--- a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx+++ b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx@@ -14,6 +14,7 @@ import { capitalizeFirstLetter } from 'lib/utils/strings'import { urls } from 'scenes/urls'import { rowNavigationProps } from '../lib/rowNavigation'+import { isGatingWorkflow, orderWorkflowHealthRows } from '../lib/runHealth'import { withScope } from '../lib/scope'import { WorkflowHealthRow, workflowFailureSeries } from '../scenes/engineeringAnalyticsLogic'import { BillableBadge } from './BillableBadge'@@ -75,8 +76,8 @@ export interface WorkflowHealthTableProps {loading?: boolean/** Threaded into the Workflow-name link so it preserves the active source. */sourceId?: string | null- /** Column sort override. Default (null) keeps the rows' failing-first-then-name order — the one- * convention shared with the PR page; pass a column to sort by it instead. */+ /** Column sort override. Default (null) keeps the rows' merge-queue-first, then busiest, then+ * by-name order; pass a column to sort by it instead. */defaultSorting?: { columnKey: string; order: 1 | -1 } | null/** Show the billable cost column (needs per-workflow cost on the rows). */showCost?: boolean@@ -108,24 +109,24 @@ export function WorkflowHealthTable({compact = false,}: WorkflowHealthTableProps): JSX.Element {const { searchParams } = useValues(router)- // Each row opens the workflow's runs page, carrying the active window/branch scope + source so the- // drill-down doesn't silently widen to all branches.+ // Each row opens the workflow's runs page, carrying the active window, run scope, and source so the+ // drill-down reports the same group of runs.const rowUrl = (row: WorkflowHealthRow): string =>withScope(urls.engineeringAnalyticsWorkflowRuns(row.repoOwner, row.repoName, row.workflowName),searchParams,sourceId)- // Failing workflows first — the order a reviewer triages in — then everything else alphabetically by- // name. The one convention shared with the PR page; a passed defaultSorting still overrides on click.- const orderedRows = [...rows].sort(- (a, b) =>- Number(b.latestRunFailed === true) - Number(a.latestRunFailed === true) ||- a.workflowName.localeCompare(b.workflowName)- )+ // Workflows the merge queue runs come first, because they gate every merge. Failing workflows stay+ // findable through the Status tag and its sorter, so they need no pass of their own.+ const orderedRows = orderWorkflowHealthRows(rows)+ // Computed once for the whole table: without a gating row there is nothing to rank against, so a repo+ // with no merge queue mutes nothing.+ const hasGatingRow = orderedRows.some(isGatingWorkflow)const columns: LemonTableColumns<WorkflowHealthRow> = [{title: 'Workflow',+ tooltip: 'Workflows that run in the merge queue come first. Other workflows are muted.',key: 'workflowName',sorter: (a, b) => a.workflowName.localeCompare(b.workflowName),render: (_, row) => (@@ -299,8 +300,14 @@ export function WorkflowHealthTable({columns={displayColumns}dataSource={orderedRows}rowKey={(row) => `${row.repoOwner}/${row.repoName}:${row.workflowName}`}- // De-emphasize workflows with nothing settled — no pass/fail signal to read.- rowClassName={(row) => cn('cursor-pointer', row.successRate === null && 'opacity-60')}+ // De-emphasize a workflow with nothing settled (no pass/fail signal to read) and, once the repo+ // has gating workflows, every workflow that does not gate a merge.+ rowClassName={(row) =>+ cn(+ 'cursor-pointer',+ (row.successRate === null || (hasGatingRow && !isGatingWorkflow(row))) && 'opacity-60'+ )+ }onRow={(row) => rowNavigationProps(rowUrl(row))}loading={loading}useURLForSorting={false}diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 6868b75afe83..221a89d3412a 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -1604,6 +1604,8 @@ export interface WorkflowHealthItemApi {success_rate_prev?: number | null/** Successful runs that did real CI work. This is the p50/p95 sample count. */percentile_run_count?: number+ /** Runs on merge-queue gate branches (trunk-merge/**) in the window, counted regardless of branch or run_scope. Non-zero marks a workflow the queue runs before a merge lands, the closest available proxy for a required check. */+ merge_queue_run_count?: number}export interface WorkflowJobApi {@@ -1829,6 +1831,10 @@ export type EngineeringAnalyticsJobAggregatesParams = {* 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.*/repo?: string+ /**+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.+ */+ run_scope?: EngineeringAnalyticsJobAggregatesRunScope/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/@@ -1839,6 +1845,16 @@ export type EngineeringAnalyticsJobAggregatesParams = {workflow_name: string}+export type EngineeringAnalyticsJobAggregatesRunScope =+ (typeof EngineeringAnalyticsJobAggregatesRunScope)[keyof typeof EngineeringAnalyticsJobAggregatesRunScope]++export const EngineeringAnalyticsJobAggregatesRunScope = {+ All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',+ PullRequest: 'pull_request',+} as const+export type EngineeringAnalyticsMasterFailuresParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.@@ -2115,7 +2131,7 @@ export type EngineeringAnalyticsWorkflowHealthParams = {*/repo?: string/**- * Run scope for workflow health: 'all' (default) includes every run; 'pull_request' includes runs attributed to pull requests, excluding default-branch (master/main) runs. Fork PRs carry no PR attribution (a GitHub limitation), so 'pull_request' covers same-repo PRs only. Any other value is a 400.+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.*/run_scope?: EngineeringAnalyticsWorkflowHealthRunScope/**@@ -2129,6 +2145,8 @@ export type EngineeringAnalyticsWorkflowHealthRunScope =export const EngineeringAnalyticsWorkflowHealthRunScope = {All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',PullRequest: 'pull_request',} as const@@ -2183,6 +2201,10 @@ export type EngineeringAnalyticsWorkflowRunActivityParams = {* 'owner/name' repository the workflow belongs to.*/repo: string+ /**+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.+ */+ run_scope?: EngineeringAnalyticsWorkflowRunActivityRunScope/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/@@ -2193,6 +2215,16 @@ export type EngineeringAnalyticsWorkflowRunActivityParams = {workflow_name: string}+export type EngineeringAnalyticsWorkflowRunActivityRunScope =+ (typeof EngineeringAnalyticsWorkflowRunActivityRunScope)[keyof typeof EngineeringAnalyticsWorkflowRunActivityRunScope]++export const EngineeringAnalyticsWorkflowRunActivityRunScope = {+ All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',+ PullRequest: 'pull_request',+} as const+export type EngineeringAnalyticsWorkflowRunnerCostsParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.@@ -2210,6 +2242,10 @@ export type EngineeringAnalyticsWorkflowRunnerCostsParams = {* 'owner/name' repository the workflow belongs to.*/repo: string+ /**+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.+ */+ run_scope?: EngineeringAnalyticsWorkflowRunnerCostsRunScope/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/@@ -2220,6 +2256,16 @@ export type EngineeringAnalyticsWorkflowRunnerCostsParams = {workflow_name: string}+export type EngineeringAnalyticsWorkflowRunnerCostsRunScope =+ (typeof EngineeringAnalyticsWorkflowRunnerCostsRunScope)[keyof typeof EngineeringAnalyticsWorkflowRunnerCostsRunScope]++export const EngineeringAnalyticsWorkflowRunnerCostsRunScope = {+ All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',+ PullRequest: 'pull_request',+} as const+export type EngineeringAnalyticsWorkflowRunsParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.@@ -2237,6 +2283,10 @@ export type EngineeringAnalyticsWorkflowRunsParams = {* 'owner/name' repository the workflow belongs to.*/repo: string+ /**+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.+ */+ run_scope?: EngineeringAnalyticsWorkflowRunsRunScope/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/@@ -2246,3 +2296,13 @@ export type EngineeringAnalyticsWorkflowRunsParams = {*/workflow_name: string}++export type EngineeringAnalyticsWorkflowRunsRunScope =+ (typeof EngineeringAnalyticsWorkflowRunsRunScope)[keyof typeof EngineeringAnalyticsWorkflowRunsRunScope]++export const EngineeringAnalyticsWorkflowRunsRunScope = {+ All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',+ PullRequest: 'pull_request',+} as constdiff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex 2d3a7579ba25..2115b6f9b9ed 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -360,7 +360,7 @@ export const getEngineeringAnalyticsJobAggregatesUrl = (}/**- * Per-job aggregates for one workflow over a window (default -30d), one row per de-sharded job name (matrix shards aggregate together), busiest first: queue p50, duration p50/p95, failure rate, retry pressure, run share (below 1.0 = conditional job), and billable cost. Jobs always need their run as context — this is the aggregate view; use workflow_jobs for one run's jobs. Empty when the job-level source isn't synced.+ * Per-job aggregates for one workflow over a window (default -30d), one row per de-sharded job name (matrix shards aggregate together), busiest first: queue p50, duration p50/p95, failure rate, retry pressure, run share (below 1.0 = conditional job), and billable cost. Optionally scope to a single git branch via `branch` or one run group via `run_scope`. Jobs always need their run as context — this is the aggregate view; use workflow_jobs for one run's jobs. Empty when the job-level source isn't synced.*/export const engineeringAnalyticsJobAggregates = async (projectId: string,@@ -889,7 +889,7 @@ export const getEngineeringAnalyticsWorkflowHealthUrl = (}/**- * Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, or to attributed pull-request runs via `run_scope=pull_request`. Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.+ * Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, or to one run group via `run_scope` (default_branch, pull_request, merge_queue). Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.*/export const engineeringAnalyticsWorkflowHealth = async (projectId: string,@@ -988,7 +988,7 @@ export const getEngineeringAnalyticsWorkflowRunActivityUrl = (}/**- * Compact per-run points for a single workflow over a window (date_from default -30d), newest first, for the run-activity chart: each run's start time, duration, conclusion, branch, and attributed PR. Optionally scope to a single git branch via `branch`, matching workflow_runs. Leaner and higher-capped than workflow_runs so the chart spans the full window even on busy workflows; `truncated` is true when the cap is hit, so the chart covers only the most recent runs.+ * Compact per-run points for a single workflow over a window (date_from default -30d), newest first, for the run-activity chart: each run's start time, duration, conclusion, branch, and attributed PR. Optionally scope to a single git branch via `branch` or one run group via `run_scope`, matching workflow_runs. Leaner and higher-capped than workflow_runs so the chart spans the full window even on busy workflows; `truncated` is true when the cap is hit, so the chart covers only the most recent runs.*/export const engineeringAnalyticsWorkflowRunActivity = async (projectId: string,@@ -1021,7 +1021,7 @@ export const getEngineeringAnalyticsWorkflowRunnerCostsUrl = (}/**- * A workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Optionally scope to a single git branch via `branch`. Returns an empty list when the job-level source isn't synced.+ * A workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Optionally scope to a single git branch via `branch` or one run group via `run_scope`. Returns an empty list when the job-level source isn't synced.*/export const engineeringAnalyticsWorkflowRunnerCosts = async (projectId: string,@@ -1054,7 +1054,7 @@ export const getEngineeringAnalyticsWorkflowRunsUrl = (}/**- * Runs of a single workflow within a repo over a window (date_from default -30d), newest first. Optionally scope to a single git branch via `branch`. Each row is run-level — per-job and per-step detail are not tracked yet. Use this as the GitHub 'workflow' page between the workflow list and a single run.+ * Runs of a single workflow within a repo over a window (date_from default -30d), newest first. Optionally scope to a single git branch via `branch` or to one run group via `run_scope`. Each row is run-level — per-job and per-step detail are not tracked yet. Use this as the GitHub 'workflow' page between the workflow list and a single run.*/export const engineeringAnalyticsWorkflowRuns = async (projectId: string,diff --git a/products/engineering_analytics/frontend/lib/runHealth.test.ts b/products/engineering_analytics/frontend/lib/runHealth.test.tsindex cd8a464bd9c0..913396610d7c 100644--- a/products/engineering_analytics/frontend/lib/runHealth.test.ts+++ b/products/engineering_analytics/frontend/lib/runHealth.test.ts@@ -1,9 +1,11 @@import {CostableJob,+ OrderableWorkflowRow,RunCostSummary,computeFleetSummary,computeHealthSummary,isNoOpRun,+ orderWorkflowHealthRows,summarizeRunCost,} from './runHealth'@@ -215,6 +217,39 @@ describe('runHealth', () => {expect(computeFleetSummary(rows).passRate).toBe(expected)})+ it.each<[string, OrderableWorkflowRow[], string[]]>([+ // A gating workflow outranks a busier non-gating one: the queue runs it before every merge.+ [+ 'merge-queue workflows first, then run count',+ [+ { workflowName: 'Docs', runCount: 900, mergeQueueRunCount: 0 },+ { workflowName: 'Backend CI', runCount: 40, mergeQueueRunCount: 12 },+ { workflowName: 'Frontend CI', runCount: 300, mergeQueueRunCount: 5 },+ ],+ ['Frontend CI', 'Backend CI', 'Docs'],+ ],+ // A repo with no merge queue falls straight through to run count.+ [+ 'no gating rows leaves pure run-count order',+ [+ { workflowName: 'Docs', runCount: 90, mergeQueueRunCount: 0 },+ { workflowName: 'Backend CI', runCount: 400, mergeQueueRunCount: 0 },+ ],+ ['Backend CI', 'Docs'],+ ],+ // Equal run counts settle by name, so the table keeps a fixed order between renders.+ [+ 'equal run counts settle by name',+ [+ { workflowName: 'Zeta', runCount: 10, mergeQueueRunCount: 0 },+ { workflowName: 'Alpha', runCount: 10, mergeQueueRunCount: 0 },+ ],+ ['Alpha', 'Zeta'],+ ],+ ])('orderWorkflowHealthRows: %s', (_name, rows, expected) => {+ expect(orderWorkflowHealthRows(rows).map((row) => row.workflowName)).toEqual(expected)+ })+const job = (runner_provider: string,duration_seconds: number | null,diff --git a/products/engineering_analytics/frontend/lib/runHealth.ts b/products/engineering_analytics/frontend/lib/runHealth.tsindex 04421d05a716..6e37ec7cf05e 100644--- a/products/engineering_analytics/frontend/lib/runHealth.ts+++ b/products/engineering_analytics/frontend/lib/runHealth.ts@@ -241,6 +241,31 @@ export function computeFleetSummary(rows: FleetRow[]): FleetSummary {}}+/** The fields the workflow-list order reads. Structural, so a table row and a test fixture both satisfy+ * it without importing the full health row. */+export interface OrderableWorkflowRow {+ workflowName: string+ runCount: number+ mergeQueueRunCount: number+}++/** A workflow the merge queue runs on its gate branches, so it blocks a merge from landing. It is the+ * closest proxy for a required check that the run data carries. */+export function isGatingWorkflow(row: OrderableWorkflowRow): boolean {+ return row.mergeQueueRunCount > 0+}++/** The workflow list's default order: gating workflows first, then the busiest, then by name. The name+ * tiebreak keeps equal run counts in a fixed order, so the table does not reshuffle between renders. */+export function orderWorkflowHealthRows<T extends OrderableWorkflowRow>(rows: T[]): T[] {+ return [...rows].sort(+ (a, b) =>+ Number(isGatingWorkflow(b)) - Number(isGatingWorkflow(a)) ||+ b.runCount - a.runCount ||+ a.workflowName.localeCompare(b.workflowName)+ )+}+/*** Roll a run's jobs up to one cost figure, mirroring the backend cost model (logic/cost.py): only* self-hosted runners are billable, and a job contributes once settled. Returns null when there'sdiff --git a/products/engineering_analytics/frontend/lib/scope.ts b/products/engineering_analytics/frontend/lib/scope.tsindex 74dfb14d1aff..5a6db7c33ceb 100644--- a/products/engineering_analytics/frontend/lib/scope.ts+++ b/products/engineering_analytics/frontend/lib/scope.ts@@ -1,10 +1,10 @@import { combineUrl, router } from 'kea-router'-/** Carry the shared window + branch scope (and active source/repo) onto an internal nav URL, so drilling- * in, switching workflows, or stepping back never silently resets it. The scope lives in the URL — every- * cross-page link threads it the same way the tab links do (`?date_from` / `?date_to` / `?q` / `?source`- * / `?repo`). The pull-request lens (`?run_scope`) is intentionally not carried: only workflow health- * honors it, so it stays on the Workflows tab rather than following a drill-down that can't apply it. */+/** Carry the shared window + run scope (and active source/repo) onto an internal nav URL, so drilling in,+ * switching workflows, or stepping back never silently resets it. The scope lives in the URL, and every+ * cross-page link threads it the same way the tab links do (`?date_from` / `?date_to` / `?run_scope` /+ * `?source` / `?repo`). Every workflow surface reads `run_scope`, so a drill-down keeps the same group+ * of runs instead of widening back to all of them. */export function withScope(url: string,searchParams: Record<string, string | undefined>,@@ -13,16 +13,16 @@ export function withScope(return combineUrl(url, {...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),- ...(searchParams.q ? { q: searchParams.q } : {}),+ ...(searchParams.run_scope ? { run_scope: searchParams.run_scope } : {}),...(sourceId ? { source: sourceId } : {}),- // Carry the repo scope of a multi-repo source (set by the picker) the same way as `?q` — from- // the current URL — so every withScope-based link preserves it with no caller change.+ // Carry the repo scope of a multi-repo source (set by the picker) from the current URL the same+ // way as `?run_scope`, so every withScope-based link preserves it with no caller change....(searchParams.repo ? { repo: searchParams.repo } : {}),}).url}-/** Like withScope, but reads the live URL for module-level link builders that don't have- * searchParams in scope — so a source-only link still carries the current window / branch / repo. */+/** Like withScope, but reads the live URL for module-level link builders that don't have searchParams in+ * scope, so a source-only link still carries the current window / run scope / repo. */export function withCurrentScope(url: string, sourceId: string | null | undefined): string {return withScope(url, router.values.searchParams, sourceId)}diff --git a/products/engineering_analytics/frontend/lib/storyFixtures.ts b/products/engineering_analytics/frontend/lib/storyFixtures.tsnew file mode 100644index 000000000000..404b4b858298--- /dev/null+++ b/products/engineering_analytics/frontend/lib/storyFixtures.ts@@ -0,0 +1,41 @@+// Story-only fixture builders. App code never imports this file.++import type { WorkflowHealthBucketApi, WorkflowHealthItemApi } from '../generated/api.schemas'++function sevenDayBuckets(): WorkflowHealthBucketApi[] {+ return [0, 1, 2, 3, 4, 5, 6].map((day) => ({+ bucket_start: `2026-06-${25 + day}T00:00:00Z`,+ run_count: 44 + day,+ completed: 40 + day,+ successes: 40 + day,+ failures: 0,+ }))+}++/** A healthy workflow row. Pass the fields a story needs to differ; the rest stay plausible. */+export function workflowHealthItem(+ overrides: Partial<WorkflowHealthItemApi> & { workflow_name: string }+): WorkflowHealthItemApi {+ return {+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },+ run_count: 320,+ successful_run_count: 304,+ conclusive_run_count: 320,+ success_rate: 0.95,+ success_rate_prev: 0.92,+ p50_seconds: 540,+ p95_seconds: 1680,+ last_failure_at: null,+ latest_run_failed: false,+ latest_run_conclusion: 'success',+ latest_run_id: 123456,+ latest_run_attempt: 1,+ granularity: 'day',+ billable_minutes: 2880,+ estimated_cost_usd: 96,+ rerun_cycles: 6,+ merge_queue_run_count: 0,+ buckets: sevenDayBuckets(),+ ...overrides,+ }+}diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.stories.tsxnew file mode 100644index 000000000000..f2fde4f80d4b--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.stories.tsx@@ -0,0 +1,125 @@+import { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++import type { GitHubSourceApi, WorkflowHealthItemApi } from '../generated/api.schemas'+import { workflowHealthItem } from '../lib/storyFixtures'++const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', prefix: '' }]++function healthItem(+ workflowName: string,+ runCount: number,+ mergeQueueRunCount: number,+ successRate: number | null,+ failing: boolean = false+): WorkflowHealthItemApi {+ const settled = successRate !== null+ return workflowHealthItem({+ workflow_name: workflowName,+ run_count: runCount,+ successful_run_count: settled ? Math.round(runCount * successRate) : 0,+ conclusive_run_count: settled ? runCount : 0,+ success_rate: successRate,+ success_rate_prev: settled ? successRate - 0.02 : null,+ p50_seconds: settled ? 480 : null,+ p95_seconds: settled ? 1520 : null,+ last_failure_at: failing ? '2026-07-01T15:20:00Z' : null,+ latest_run_failed: settled ? failing : null,+ latest_run_conclusion: settled ? (failing ? 'failure' : 'success') : null,+ latest_run_id: settled ? 900000 + runCount : null,+ billable_minutes: runCount * 9,+ estimated_cost_usd: runCount * 0.6,+ rerun_cycles: failing ? 14 : 2,+ merge_queue_run_count: mergeQueueRunCount,+ buckets: [0, 1, 2, 3, 4, 5, 6].map((day) => ({+ bucket_start: `2026-06-${25 + day}T00:00:00Z`,+ run_count: Math.round(runCount / 7),+ completed: settled ? Math.round(runCount / 7) : 0,+ successes: settled ? Math.round((runCount / 7) * successRate) : 0,+ failures: failing && day % 2 === 0 ? 3 : 0,+ })),+ })+}++// The list's whole ordering space: gating workflows the merge queue runs (one of them failing), busier+// workflows it does not gate, and one with nothing settled in the window.+const WORKFLOW_HEALTH: WorkflowHealthItemApi[] = [+ healthItem('Backend CI', 412, 186, 0.93),+ healthItem('Frontend CI', 388, 174, 0.96),+ healthItem('E2E - Playwright', 210, 96, 0.74, true),+ healthItem('Docs preview', 940, 0, 0.99),+ healthItem('Container images', 132, 0, 0.88),+ healthItem('Storybook', 96, 0, 0.91),+ healthItem('Nightly benchmarks', 21, 0, 0.62, true),+ healthItem('Release', 4, 0, null),+]++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Engineering Analytics/Workflows',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-07-02',+ featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],+ testOptions: {+ waitForSelector: '[data-attr="engineering-analytics-workflow-table"]',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ 'api/projects/:team_id/engineering_analytics/sources/': SOURCES,+ 'api/projects/:team_id/engineering_analytics/workflow_health/': WORKFLOW_HEALTH,+ // Sibling-tab loaders mount with the scene; stub them so the story renders without error toasts.+ 'api/projects/:team_id/engineering_analytics/ci_cards/': {+ open_prs: 18,+ repos: 1,+ stuck: 3,+ failing_ci: 4,+ },+ 'api/projects/:team_id/engineering_analytics/pull_requests/': {+ items: [],+ truncated: false,+ limit: 1000,+ },+ 'api/projects/:team_id/engineering_analytics/quarantine/': {+ available: false,+ entries: [],+ parse_errors: [],+ parse_warnings: [],+ repo: null,+ source_url: null,+ generated_at: null,+ },+ 'api/projects/:team_id/engineering_analytics/trunk_quarantine/': {+ available: false,+ ttl_days: 15,+ repository: null,+ trunk_url: null,+ teams: [],+ tests: [],+ },+ },+ }),+ ],+}+export default meta++type Story = StoryObj<typeof meta>++export const WorkflowList: Story = {+ render: () => <App />,+ parameters: { pageUrl: urls.engineeringAnalyticsWorkflows() },+}++// The scope hydrates from the URL, so this opens on the merge-queue group.+export const WorkflowListScopedToMergeQueue: Story = {+ render: () => <App />,+ parameters: { pageUrl: `${urls.engineeringAnalyticsWorkflows()}?run_scope=merge_queue` },+}diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsxindex 748beea53c32..d9971ab3bb90 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx@@ -7,7 +7,8 @@ import { LemonButton, LemonInput, LemonSegmentedButton } from '@posthog/lemon-uiimport { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'import { ConnectGitHubSource } from '../components/ConnectGitHubSource'import { RepoEntityHeader } from '../components/EntityHeader'-import { BranchScopeChip, ScopeDateFilter, SourceScopeChip } from '../components/ScopeBar'+import { SourceScopeChip, WorkflowScopeControls } from '../components/ScopeBar'+import { ScopePanel } from '../components/ScopePanel'import { WorkflowHealthTable } from '../components/WorkflowHealthTable'import { WorkflowsHealthHeader } from '../components/WorkflowsHealthHeader'import { WORKFLOW_HEALTH_LIMIT, WorkflowStatusFilter, engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'@@ -17,6 +18,7 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {fleetSummary,fleetTruncated,filteredWorkflowHealth,+ workflowHealth,workflowHealthLoading,workflowSearch,workflowStatusFilter,@@ -41,64 +43,66 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {<div className="flex flex-col gap-4"><RepoEntityHeader repoFullName={activeSource?.repo || ''} right={<SourceScopeChip pickerOnly />} />- {/* Branch + window govern every surface below — the same scope the overview's date filter carries. */}- <div className="flex flex-wrap items-center justify-end gap-2">- <BranchScopeChip />- <ScopeDateFilter />- </div>+ {/* Scope + window govern every surface inside the panel, the same scope the overview carries. */}+ <ScopePanel busy={workflowHealthLoading && workflowHealth.length > 0} controls={<WorkflowScopeControls />}>+ <WorkflowsHealthHeader+ summary={fleetSummary}+ truncated={fleetTruncated}+ loading={workflowHealthLoading}+ />- <WorkflowsHealthHeader summary={fleetSummary} truncated={fleetTruncated} loading={workflowHealthLoading} />+ <div className="flex flex-wrap items-center gap-2">+ <LemonInput+ type="search"+ placeholder="Search workflows…"+ value={workflowSearch}+ onChange={setWorkflowSearch}+ className="w-64"+ data-attr="engineering-analytics-workflow-search"+ />+ <LemonSegmentedButton+ size="small"+ value={workflowStatusFilter}+ onChange={(value) => setWorkflowStatusFilter(value as WorkflowStatusFilter)}+ options={[+ { value: 'all', label: 'All' },+ {+ value: 'failing',+ label: fleetSummary.failingNow > 0 ? `Failing (${fleetSummary.failingNow})` : 'Failing',+ },+ { value: 'passing', label: 'Passing' },+ ]}+ />+ </div>- <div className="flex flex-wrap items-center gap-2">- <LemonInput- type="search"- placeholder="Search workflows…"- value={workflowSearch}- onChange={setWorkflowSearch}- className="w-64"- data-attr="engineering-analytics-workflow-search"- />- <LemonSegmentedButton- size="small"- value={workflowStatusFilter}- onChange={(value) => setWorkflowStatusFilter(value as WorkflowStatusFilter)}- options={[- { value: 'all', label: 'All' },- {- value: 'failing',- label: fleetSummary.failingNow > 0 ? `Failing (${fleetSummary.failingNow})` : 'Failing',- },- { value: 'passing', label: 'Passing' },- ]}+ <WorkflowHealthTable+ rows={filteredWorkflowHealth}+ loading={workflowHealthLoading}+ sourceId={sourceId}+ showCost={workflowCostAvailable}+ pageSize={25}+ emptyState={+ hasActiveWorkflowFilters ? (+ <div className="flex flex-col items-center gap-2">+ <span>No workflows match these filters.</span>+ <LemonButton type="secondary" size="small" onClick={resetWorkflowFilters}>+ Clear filters+ </LemonButton>+ </div>+ ) : (+ 'No workflow runs in this window. Try widening the date range or run scope.'+ )+ }/>- </div>-- <WorkflowHealthTable- rows={filteredWorkflowHealth}- loading={workflowHealthLoading}- sourceId={sourceId}- showCost={workflowCostAvailable}- pageSize={25}- emptyState={- hasActiveWorkflowFilters ? (- <div className="flex flex-col items-center gap-2">- <span>No workflows match these filters.</span>- <LemonButton type="secondary" size="small" onClick={resetWorkflowFilters}>- Clear filters- </LemonButton>- </div>- ) : (- 'No workflow runs in this window. Try widening the date range or branch scope.'- )- }- />- <div className="text-xs text-tertiary">- Pass rate compares successful runs with runs that failed, timed out, failed to start, or became stale.- Skipped, canceled, neutral, and action-required runs are excluded. Durations cover successful runs only.- Health is workflow-level, not per-job.- {fleetTruncated && ` Showing the top ${WORKFLOW_HEALTH_LIMIT} workflows by run count.`}- </div>+ <div className="text-xs text-tertiary">+ Pass rate compares successful runs with runs that failed, timed out, failed to start, or became+ stale. Skipped, canceled, neutral, and action-required runs are excluded. Durations cover successful+ runs only. Health is workflow-level, not per-job. Workflows that run in the merge queue sort first;+ the rest are muted.+ {fleetTruncated && ` Showing the top ${WORKFLOW_HEALTH_LIMIT} workflows by run count.`}+ </div>+ </ScopePanel></div>)}diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsxindex 31a4119a2d6d..a333fe334f56 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx@@ -13,6 +13,7 @@ import type {WorkflowHealthItemApi,WorkflowRunActivityApi,} from '../generated/api.schemas'+import { workflowHealthItem } from '../lib/storyFixtures'const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', prefix: '' }]@@ -98,31 +99,26 @@ const ACTIVITY: WorkflowRunActivityApi = {limit: 500,}+const RUN_COUNT = 320+function healthItem(workflowName: string,costUsd: number,failures: number[],- successRate: number+ successRate: number,+ mergeQueueRunCount: number = 0): WorkflowHealthItemApi {- return {- repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },+ return workflowHealthItem({workflow_name: workflowName,- run_count: 320,- successful_run_count: Math.round(320 * successRate),- conclusive_run_count: 320,+ run_count: RUN_COUNT,+ successful_run_count: Math.round(RUN_COUNT * successRate),+ conclusive_run_count: RUN_COUNT,success_rate: successRate,success_rate_prev: successRate - 0.03,- p50_seconds: 540,- p95_seconds: 1680,last_failure_at: failures.some((f) => f > 0) ? '2026-07-01T16:00:00Z' : null,- latest_run_failed: false,- latest_run_conclusion: 'success',- latest_run_id: 123456,- latest_run_attempt: 1,- granularity: 'day',billable_minutes: costUsd * 12,estimated_cost_usd: costUsd,- rerun_cycles: 6,+ merge_queue_run_count: mergeQueueRunCount,buckets: failures.map((failed, i) => ({bucket_start: `2026-06-${25 + i}T00:00:00Z`,run_count: 44 + i,@@ -130,13 +126,14 @@ function healthItem(successes: 40 + i - failed,failures: failed,})),- }+ })}+// Two workflows the merge queue runs, so the table shows both the gating order and the muted rest.const WORKFLOW_HEALTH: WorkflowHealthItemApi[] = [- healthItem('Backend CI', 210.4, [2, 0, 4, 1, 0, 3, 1], 0.91),+ healthItem('Backend CI', 210.4, [2, 0, 4, 1, 0, 3, 1], 0.91, 186),healthItem('E2E - Playwright', 130.2, [5, 3, 6, 2, 4, 5, 3], 0.78),- healthItem('Frontend CI', 71.9, [0, 1, 0, 0, 2, 0, 1], 0.95),+ healthItem('Frontend CI', 71.9, [0, 1, 0, 0, 2, 0, 1], 0.95, 174),]const PULL_REQUESTS: PullRequestListApi = {diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsxindex 676a10a55415..ef72059c3821 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx@@ -55,7 +55,7 @@ export function RepoOverviewScene(): JSX.Element {// The hub previews each table: a short, sorted slice with "Show more" to grow in place, and "View all"// to the dedicated full table. Workflows are ranked by cost (or run count) to pick the top few; the- // table then displays them failing-first-then-name. attentionPrs is already ordered failing-first.+ // table then displays them merge-queue-first. attentionPrs is already ordered failing-first.const shownPrs = attentionPrs.slice(0, prPreviewCount)const canShowMorePrs = shownPrs.length < attentionPrs.length && prPreviewCount < HUB_PREVIEW_MAX// Rank the leaderboard by spend when cost is known (where the money goes), else by run volume.@@ -216,7 +216,7 @@ export function RepoOverviewScene(): JSX.Element {)}<Linkto={- // A bare link would reset the shared window / branch / repo scope (the filters+ // A bare link would reset the shared window / run scope / repo (the filters// logic re-hydrates from the URL on every route), so carry it, plus the source.withScope(urls.engineeringAnalyticsWorkflows(), searchParams, sourceId)}diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.stories.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.stories.tsxnew file mode 100644index 000000000000..1c2ea113ba0f--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.stories.tsx@@ -0,0 +1,199 @@+import { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++import type {+ GitHubSourceApi,+ WorkflowHealthItemApi,+ WorkflowJobAggregateApi,+ WorkflowRunActivityApi,+ WorkflowRunDetailApi,+ WorkflowRunnerCostApi,+} from '../generated/api.schemas'+import { workflowHealthItem } from '../lib/storyFixtures'++const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', prefix: '' }]++const REPO = { provider: 'github', owner: 'PostHog', name: 'posthog' }+const GATE_BRANCH = 'trunk-merge/pr-4821/8f21c0de-5b44-4a19-9c07-2d6e11ab7f30'++function run(+ id: number,+ headBranch: string,+ conclusion: string | null,+ durationSeconds: number | null,+ startedAt: string,+ prNumber: number,+ runAttempt: number = 1+): WorkflowRunDetailApi {+ return {+ repo: REPO,+ id,+ workflow_name: 'Backend CI',+ head_sha: `c0ffee${id}`,+ head_branch: headBranch,+ status: conclusion === null ? 'in_progress' : 'completed',+ conclusion,+ run_started_at: startedAt,+ updated_at: startedAt,+ duration_seconds: durationSeconds,+ run_attempt: runAttempt,+ pr_number: prNumber,+ commit_pr_number: prNumber === 0 ? 4788 : null,+ }+}++// The lead column's whole state space: default-branch pushes, a PR branch, a merge-queue gate branch,+// a decisive failure, and a re-run attempt.+const RUNS: WorkflowRunDetailApi[] = [+ run(880141, 'master', 'success', 1420, '2026-07-01T08:05:00Z', 0),+ run(880152, 'feat/run-scope-groups', 'success', 1510, '2026-07-01T09:40:00Z', 4820),+ run(880163, 'feat/run-scope-groups', 'failure', 980, '2026-07-01T11:12:00Z', 4820),+ run(880163, 'feat/run-scope-groups', 'success', 1580, '2026-07-01T11:44:00Z', 4820, 2),+ run(880178, GATE_BRANCH, 'success', 1690, '2026-07-01T13:20:00Z', 4821),+ run(880190, 'master', 'success', 1380, '2026-07-01T15:02:00Z', 0),+]++const ACTIVITY: WorkflowRunActivityApi = {+ points: [1420, 1510, 980, 1580, 1690, 1380, 1455, 2210, 1340, 1520, 1610, 1290].map((duration, i) => ({+ run_id: 880100 + i,+ conclusion: i === 2 ? 'failure' : 'success',+ run_started_at: `2026-06-${26 + Math.floor(i / 2)}T${String(8 + (i % 2) * 6).padStart(2, '0')}:00:00Z`,+ duration_seconds: duration,+ head_branch: i % 3 === 0 ? 'master' : 'feat/run-scope-groups',+ pr_number: i % 3 === 0 ? 0 : 4820,+ head_sha: `c0ffee${String(i).padStart(2, '0')}`,+ })),+ truncated: false,+ limit: 500,+}++// One billable tier and one free tier, so the share bar and the "free" label both render.+const RUNNER_COSTS: WorkflowRunnerCostApi[] = [+ {+ provider: 'self_hosted',+ runner_label: 'depot-ubuntu-16',+ job_count: 184,+ billable_minutes: 2140,+ estimated_cost_usd: 61.4,+ },+ {+ provider: 'github_hosted',+ runner_label: 'ubuntu-latest',+ job_count: 42,+ billable_minutes: 310,+ estimated_cost_usd: null,+ },+]++const JOB_AGGREGATES: WorkflowJobAggregateApi[] = [+ {+ job_name: 'Python tests',+ job_count: 96,+ shard_count: 8,+ runs_in: 12,+ run_share: 1,+ queue_p50_seconds: 34,+ p50_seconds: 720,+ p95_seconds: 1180,+ failure_rate: 0.08,+ retry_job_count: 6,+ billable_minutes: 1420,+ estimated_cost_usd: 40.7,+ },+ {+ job_name: 'Migrations',+ job_count: 12,+ shard_count: 1,+ runs_in: 12,+ run_share: 1,+ queue_p50_seconds: 21,+ p50_seconds: 240,+ p95_seconds: 410,+ failure_rate: 0,+ retry_job_count: 0,+ billable_minutes: 320,+ estimated_cost_usd: 9.2,+ },+ {+ job_name: 'Async migrations check',+ job_count: 5,+ shard_count: 1,+ runs_in: 5,+ run_share: 0.42,+ queue_p50_seconds: 18,+ p50_seconds: 110,+ p95_seconds: 190,+ failure_rate: null,+ retry_job_count: 0,+ billable_minutes: null,+ estimated_cost_usd: null,+ },+]++// Only the workflow-switcher dropdown reads this, and it loads on first open.+const WORKFLOW_HEALTH: WorkflowHealthItemApi[] = ['Backend CI', 'Frontend CI', 'E2E - Playwright'].map(+ (workflowName): WorkflowHealthItemApi =>+ workflowHealthItem({+ workflow_name: workflowName,+ run_count: 312,+ successful_run_count: 292,+ conclusive_run_count: 306,+ success_rate_prev: 0.93,+ p50_seconds: 1440,+ p95_seconds: 2180,+ last_failure_at: '2026-07-01T11:12:00Z',+ latest_run_id: 880190,+ billable_minutes: 2140,+ estimated_cost_usd: 61.4,+ rerun_cycles: 4,+ merge_queue_run_count: 148,+ buckets: [],+ })+)++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Engineering Analytics/Workflow',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-07-02',+ featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],+ testOptions: {+ waitForSelector: '[data-attr="engineering-analytics-workflow-runs-table"]',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ 'api/projects/:team_id/engineering_analytics/sources/': SOURCES,+ 'api/projects/:team_id/engineering_analytics/workflow_runs/': RUNS,+ 'api/projects/:team_id/engineering_analytics/workflow_run_activity/': ACTIVITY,+ 'api/projects/:team_id/engineering_analytics/workflow_runner_costs/': RUNNER_COSTS,+ 'api/projects/:team_id/engineering_analytics/job_aggregates/': JOB_AGGREGATES,+ 'api/projects/:team_id/engineering_analytics/workflow_health/': WORKFLOW_HEALTH,+ },+ }),+ ],+}+export default meta++type Story = StoryObj<typeof meta>++const WORKFLOW_URL = urls.engineeringAnalyticsWorkflowRuns('PostHog', 'posthog', 'Backend CI')++export const WorkflowDetail: Story = {+ render: () => <App />,+ parameters: { pageUrl: WORKFLOW_URL },+}++// The scope hydrates from the URL, so this opens on the pull-request group.+export const WorkflowDetailScopedToPullRequests: Story = {+ render: () => <App />,+ parameters: { pageUrl: `${WORKFLOW_URL}?run_scope=pull_request` },+}diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsxindex 8311d2479deb..f6f083136feb 100644--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx@@ -22,7 +22,8 @@ import { JobAggregatesTable } from '../components/JobAggregatesTable'import { MetricTile } from '../components/MetricTile'import { RunActivityChart } from '../components/RunActivityChart'import { RunConclusionTag } from '../components/runTables'-import { RepoScopeChip, ScopeBar, WorkflowScopeChip } from '../components/ScopeBar'+import { RepoScopeChip, ScopeBar, WorkflowScopeChip, WorkflowScopeControls } from '../components/ScopeBar'+import { ScopePanel } from '../components/ScopePanel'import { Section } from '../components/Section'import { ShareRow } from '../components/ShareRow'import type { WorkflowRunnerCostApi } from '../generated/api.schemas'@@ -81,6 +82,8 @@ export const scene: SceneExport<WorkflowRunsLogicProps> = {}),}+const refreshing = (loading: boolean, rows: unknown[]): boolean => loading && rows.length > 0+export function WorkflowRunsScene(): JSX.Element {const {runRows,@@ -110,6 +113,12 @@ export function WorkflowRunsScene(): JSX.Element {const { searchParams } = useValues(router)const githubUrl = githubWorkflowUrl(repoOwner, repoName, workflowName)+ // The rim spinner means "these numbers are updating", so each read only counts once it has data on+ // screen to update. A first load shows the sections' own skeletons instead.+ const healthBusy = refreshing(runActivityLoading, activityRuns)+ const costBusy = refreshing(runnerCostsLoading, runnerCosts)+ const panelBusy =+ refreshing(runsLoading, runRows) || healthBusy || costBusy || refreshing(jobAggregatesLoading, jobAggregates)// Master's own verdict when the window has master runs; the overall fleet state otherwise.const verdictPill =masterConclusion != null ? (@@ -282,7 +291,7 @@ export function WorkflowRunsScene(): JSX.Element {</LemonButton>}/>- {/* Same window + branch scope as the repo hub, so numbers match after drilling in. */}+ {/* Navigation only: the window and run scope dock on the panel below. */}<ScopeBarrepoSlot={<RepoScopeChip@@ -303,7 +312,7 @@ export function WorkflowRunsScene(): JSX.Element {),},]}- showBranch+ showDate={false}/><EntityHeadericon={<IconGear />}@@ -311,124 +320,129 @@ export function WorkflowRunsScene(): JSX.Element {slug={`${repoOwner}/${repoName}`}right={verdictPill}/>- <div className="flex flex-wrap gap-2.5">- <MetricTile- label="Pass rate"- tooltip={`${humanFriendlyNumber(healthSummary.passedRuns)} of ${humanFriendlyNumber(- healthSummary.conclusiveRuns- )} runs with a pass-or-fail result passed.`}- value={percent(healthSummary.passRate)}- loading={runsLoading}- />- <MetricTile- label="Runs"- tooltip={- healthSummary.reruns > 0- ? `Includes ${humanFriendlyNumber(healthSummary.reruns)} re-run cycles.`- : undefined- }- value={compactCount(healthSummary.totalRuns)}- sub={runsTruncated ? `stats cover the most recent ${runRows.length}` : undefined}- loading={runsLoading}- />- <MetricTile- label="Duration p50"- tooltip="Wall-clock, over successful runs."- value={- healthSummary.medianSeconds != null ? humanFriendlyDuration(healthSummary.medianSeconds) : '—'- }- sub={- healthSummary.p95Seconds != null- ? `→ ${humanFriendlyDuration(healthSummary.p95Seconds)} p95`- : undefined- }- loading={runsLoading}- />- <MetricTile- label="Queue time p50"- tooltip="From job created to started, weighted across the workflow's jobs."- value={queueP50Seconds != null ? humanFriendlyDuration(queueP50Seconds) : '—'}- loading={jobAggregatesLoading}- />- <MetricTile- label="Cost"- tooltip={- costSummary?.estimatedCostUsd != null- ? `${compactMinutes(costSummary.billableMinutes)} billable · ${compactUsd(- healthSummary.totalRuns > 0- ? costSummary.estimatedCostUsd / healthSummary.totalRuns- : null- )} per run.`- : 'Available once the job-level source is synced.'- }- value={costSummary?.estimatedCostUsd != null ? compactUsd(costSummary.estimatedCostUsd) : '—'}- sub={costSummary?.estimatedCostUsd != null ? undefined : 'Job-level source not synced'}- loading={runnerCostsLoading}- />- </div>- <Section id="health" title="Health" busy={runActivityLoading && activityRuns.length > 0}>- <RunActivityChart runs={activityRuns} truncated={activityTruncated} />- </Section>- <Section id="jobs" title="Jobs">- <JobAggregatesTable- aggregates={jobAggregates}- loading={jobAggregatesLoading}- totalCostUsd={costSummary?.estimatedCostUsd ?? null}- />- </Section>- <Section id="cost" title="Cost" busy={runnerCostsLoading && runnerCosts.length > 0}>- {runnerCosts.length > 0 ? (- <RunnerTierCard costs={runnerCosts} />- ) : (- <span className="text-xs text-secondary">- No cost data. The job-level source isn't synced, or nothing ran in the window.- </span>- )}- </Section>- <Section id="runs" title="Runs">- <LemonCard hoverEffect={false} className="overflow-hidden p-0">- <LemonTable<WorkflowRunRow>- dataSource={runRows}- columns={runColumns}- size="small"- embedded+ {/* Same window + run scope as the repo hub, so numbers match after drilling in. */}+ <ScopePanel busy={panelBusy} controls={<WorkflowScopeControls />}>+ <div className="flex flex-wrap gap-2.5">+ <MetricTile+ label="Pass rate"+ tooltip={`${humanFriendlyNumber(healthSummary.passedRuns)} of ${humanFriendlyNumber(+ healthSummary.conclusiveRuns+ )} runs with a pass-or-fail result passed.`}+ value={percent(healthSummary.passRate)}+ loading={runsLoading}+ />+ <MetricTile+ label="Runs"+ tooltip={+ healthSummary.reruns > 0+ ? `Includes ${humanFriendlyNumber(healthSummary.reruns)} re-run cycles.`+ : undefined+ }+ value={compactCount(healthSummary.totalRuns)}+ sub={runsTruncated ? `stats cover the most recent ${runRows.length}` : undefined}+ loading={runsLoading}+ />+ <MetricTile+ label="Duration p50"+ tooltip="Wall-clock, over successful runs."+ value={+ healthSummary.medianSeconds != null+ ? humanFriendlyDuration(healthSummary.medianSeconds)+ : '—'+ }+ sub={+ healthSummary.p95Seconds != null+ ? `→ ${humanFriendlyDuration(healthSummary.p95Seconds)} p95`+ : undefined+ }loading={runsLoading}- rowKey={(run) => `${run.id}-${run.runAttempt}`}- useURLForSorting={false}- defaultSorting={{ columnKey: 'started', order: -1 }}- pagination={{ pageSize: 25 }}- onRow={(run) => ({- className: 'cursor-pointer',- onClick: () =>- setRunExpanded(- `${run.id}-${run.runAttempt}`,- !expandedRunKeys.includes(`${run.id}-${run.runAttempt}`),- run.runId,- run.runAttempt- ),- })}- expandable={{- noIndent: true,- isRowExpanded: (run) => expandedRunKeys.includes(`${run.id}-${run.runAttempt}`),- expandedRowRender: (run) => (- <GroupedJobsTable- jobs={runJobs[jobCacheKey(run.id, run.runAttempt)]}- loading={runJobsLoading}- embedded- />- ),- }}- emptyState="No runs for this workflow in the connected source."- nouns={['run', 'runs']}- data-attr="engineering-analytics-workflow-runs-table"/>- <div className="border-t border-primary px-4 py-2 text-[11px] text-tertiary">- {runsTruncated- ? `Showing the most recent ${runRows.length} runs in the window.`- : `${runRows.length} runs in the window.`}- </div>- </LemonCard>- </Section>+ <MetricTile+ label="Queue time p50"+ tooltip="From job created to started, weighted across the workflow's jobs."+ value={queueP50Seconds != null ? humanFriendlyDuration(queueP50Seconds) : '—'}+ loading={jobAggregatesLoading}+ />+ <MetricTile+ label="Cost"+ tooltip={+ costSummary?.estimatedCostUsd != null+ ? `${compactMinutes(costSummary.billableMinutes)} billable · ${compactUsd(+ healthSummary.totalRuns > 0+ ? costSummary.estimatedCostUsd / healthSummary.totalRuns+ : null+ )} per run.`+ : 'Available once the job-level source is synced.'+ }+ value={costSummary?.estimatedCostUsd != null ? compactUsd(costSummary.estimatedCostUsd) : '—'}+ sub={costSummary?.estimatedCostUsd != null ? undefined : 'Job-level source not synced'}+ loading={runnerCostsLoading}+ />+ </div>+ <Section id="health" title="Health" busy={healthBusy}>+ <RunActivityChart runs={activityRuns} truncated={activityTruncated} />+ </Section>+ <Section id="jobs" title="Jobs">+ <JobAggregatesTable+ aggregates={jobAggregates}+ loading={jobAggregatesLoading}+ totalCostUsd={costSummary?.estimatedCostUsd ?? null}+ />+ </Section>+ <Section id="cost" title="Cost" busy={costBusy}>+ {runnerCosts.length > 0 ? (+ <RunnerTierCard costs={runnerCosts} />+ ) : (+ <span className="text-xs text-secondary">+ No cost data. The job-level source isn't synced, or nothing ran in the window.+ </span>+ )}+ </Section>+ <Section id="runs" title="Runs">+ <LemonCard hoverEffect={false} className="overflow-hidden p-0">+ <LemonTable<WorkflowRunRow>+ dataSource={runRows}+ columns={runColumns}+ size="small"+ embedded+ loading={runsLoading}+ rowKey={(run) => `${run.id}-${run.runAttempt}`}+ useURLForSorting={false}+ defaultSorting={{ columnKey: 'started', order: -1 }}+ pagination={{ pageSize: 25 }}+ onRow={(run) => ({+ className: 'cursor-pointer',+ onClick: () =>+ setRunExpanded(+ `${run.id}-${run.runAttempt}`,+ !expandedRunKeys.includes(`${run.id}-${run.runAttempt}`),+ run.runId,+ run.runAttempt+ ),+ })}+ expandable={{+ noIndent: true,+ isRowExpanded: (run) => expandedRunKeys.includes(`${run.id}-${run.runAttempt}`),+ expandedRowRender: (run) => (+ <GroupedJobsTable+ jobs={runJobs[jobCacheKey(run.id, run.runAttempt)]}+ loading={runJobsLoading}+ embedded+ />+ ),+ }}+ emptyState="No runs for this workflow in the connected source."+ nouns={['run', 'runs']}+ data-attr="engineering-analytics-workflow-runs-table"+ />+ <div className="border-t border-primary px-4 py-2 text-[11px] text-tertiary">+ {runsTruncated+ ? `Showing the most recent ${runRows.length} runs in the window.`+ : `${runRows.length} runs in the window.`}+ </div>+ </LemonCard>+ </Section>+ </ScopePanel></SceneContent>)}diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.tsindex 144216b94eb4..5f787459bd74 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'import { actionToUrl, router, urlToAction } from 'kea-router'import { EngineeringAnalyticsWorkflowHealthRunScope } from '../generated/api.schemas'@@ -7,41 +7,69 @@ import { EngineeringAnalyticsWorkflowHealthRunScope } from '../generated/api.sch// to the others. 7 days: long enough to read a week of spend, short enough that health reads as recent.export const SHARED_DEFAULT_DATE_FROM = '-7d'-// The "non-default branch" lens: PR-attributed runs with the default branch (master/main) excluded.-const PR_SCOPE = EngineeringAnalyticsWorkflowHealthRunScope.PullRequest+/** The four groups the backend partitions a repo's runs into. Derived from the generated enum, so a+ * backend rename breaks the typecheck here instead of silently sending a value the API rejects. */+export type RunScope = EngineeringAnalyticsWorkflowHealthRunScope-// The workflow-health request params the active branch scope resolves to. `run_scope` is workflow_health's-// alone; every other surface reads `appliedBranch` (which the PR lens leaves empty, so they fall back to-// all branches). Owning the scope→params mapping here means no consumer re-derives which param to send.-export interface BranchHealthParams {- branch?: string- run_scope?: typeof PR_SCOPE+/** The request params the active scope resolves to. `all` sends nothing, because the backend already+ * reports every run when the param is absent. */+export interface RunScopeParams {+ run_scope?: RunScope+}++/** The scope picker's options, in display order. */+export const RUN_SCOPE_OPTIONS: { value: RunScope; label: string; tooltip: string }[] = [+ {+ value: EngineeringAnalyticsWorkflowHealthRunScope.All,+ label: 'All runs',+ tooltip:+ 'Every run in the window, including branches with no pull request attribution such as fork pull requests.',+ },+ {+ value: EngineeringAnalyticsWorkflowHealthRunScope.DefaultBranch,+ label: 'Default branch',+ tooltip: 'Runs on master or main.',+ },+ {+ value: EngineeringAnalyticsWorkflowHealthRunScope.PullRequest,+ label: 'Pull requests',+ tooltip: 'Runs on pull request branches of this repository. Merge queue runs have their own scope.',+ },+ {+ value: EngineeringAnalyticsWorkflowHealthRunScope.MergeQueue,+ label: 'Merge queue',+ tooltip: 'Runs on merge queue gate branches, the checks that run right before a pull request lands.',+ },+]++const RUN_SCOPE_VALUES: RunScope[] = RUN_SCOPE_OPTIONS.map((option) => option.value)++/** Resolve the scope a URL asks for. An unknown `run_scope` falls back to all runs rather than failing+ * the request. `?q=` was the exact-branch param this scope replaced: master and main are the only two+ * values a fixed group can still honor, so they map to the default branch and every other branch is+ * dropped. */+function runScopeFromUrl(runScope: string | undefined, legacyBranch: string | undefined): RunScope {+ if (runScope) {+ return RUN_SCOPE_VALUES.includes(runScope as RunScope)+ ? (runScope as RunScope)+ : EngineeringAnalyticsWorkflowHealthRunScope.All+ }+ if (legacyBranch === 'master' || legacyBranch === 'main') {+ return EngineeringAnalyticsWorkflowHealthRunScope.DefaultBranch+ }+ return EngineeringAnalyticsWorkflowHealthRunScope.All}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface engineeringAnalyticsFiltersLogicValues {- appliedBranch: string- branchHealthParams: BranchHealthParams- branchInput: stringdateFrom: string | nulldateTo: string | null- pullRequestScope: boolean+ runScope: RunScope+ runScopeParams: RunScopeParams}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface engineeringAnalyticsFiltersLogicActions {- applyBranchFilter: () => {- value: true- }- scopeToPullRequests: () => {- value: true- }- setAppliedBranch: (branch: string) => {- branch: string- }- setBranchFilter: (branch: string) => {- branch: string- }setDateRange: (dateFrom: string | null,dateTo: string | null@@ -49,12 +77,15 @@ export interface engineeringAnalyticsFiltersLogicActions {dateFrom: string | nulldateTo: string | null}+ setRunScope: (scope: RunScope) => {+ scope: EngineeringAnalyticsWorkflowHealthRunScope+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface engineeringAnalyticsFiltersLogicMeta {__keaTypeGenInternalSelectorTypes: {- branchHealthParams: (appliedBranch: string, pullRequestScope: boolean) => BranchHealthParams+ runScopeParams: (runScope: EngineeringAnalyticsWorkflowHealthRunScope) => RunScopeParams}}@@ -65,76 +96,34 @@ export type engineeringAnalyticsFiltersLogicType = MakeLogicType<engineeringAnalyticsFiltersLogicMeta>-// The branch scope is shared like the window. An exact branch is a server-side head_branch filter; the PR-// lens is a run_scope. The two are mutually exclusive — the reducers keep an invalid "branch + lens" state-// from ever existing — so a page only ever sees one of them.+// The run scope is shared like the window: one of four fixed groups that partition a repo's runs, not a+// branch a user types. Every workflow surface sends the same group, so the list and the detail page+// report the same population.export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersLogicType>([path(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsFiltersLogic']),actions({setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),- setBranchFilter: (branch: string) => ({ branch }),- applyBranchFilter: true,- setAppliedBranch: (branch: string) => ({ branch }),- // The "non-default branch" lens: PR-attributed runs, default branch (master/main) excluded.- scopeToPullRequests: true,+ setRunScope: (scope: RunScope) => ({ scope }),}),reducers({dateFrom: [SHARED_DEFAULT_DATE_FROM as string | null, { setDateRange: (_, { dateFrom }) => dateFrom }],dateTo: [null as string | null, { setDateRange: (_, { dateTo }) => dateTo }],- // branchInput is the staged text in the box; appliedBranch is what exact-branch consumers send. ''- // means all branches; the PR lens clears both, since it's mutually exclusive with an exact branch.- branchInput: [- '',- {- setBranchFilter: (_, { branch }) => branch,- scopeToPullRequests: () => '',- },- ],- appliedBranch: [- '',- {- setAppliedBranch: (_, { branch }) => branch,- scopeToPullRequests: () => '',- },- ],- // Applying any exact branch — including clearing to all — turns the PR lens off.- pullRequestScope: [- false,- {- scopeToPullRequests: () => true,- setAppliedBranch: () => false,- },+ runScope: [+ EngineeringAnalyticsWorkflowHealthRunScope.All as RunScope,+ { setRunScope: (_, { scope }) => scope },],}),selectors({- branchHealthParams: [- (s) => [s.appliedBranch, s.pullRequestScope],- (appliedBranch: string, pullRequestScope: boolean): BranchHealthParams =>- pullRequestScope ? { run_scope: PR_SCOPE } : appliedBranch ? { branch: appliedBranch } : {},+ runScopeParams: [+ (s) => [s.runScope],+ (runScope: RunScope): RunScopeParams =>+ runScope === EngineeringAnalyticsWorkflowHealthRunScope.All ? {} : { run_scope: runScope },],}),- listeners(({ actions, values }) => ({- setBranchFilter: ({ branch }) => {- // The input's clear (×) only fires onChange('') — apply on empty so it resets to all branches.- if (branch.trim() === '') {- actions.applyBranchFilter()- }- },- applyBranchFilter: () => {- const next = values.branchInput.trim()- // Skip promoting (and the reload it triggers) when nothing changes — unless the PR lens is on,- // which an exact branch must clear.- if (next === values.appliedBranch && !values.pullRequestScope) {- return- }- actions.setAppliedBranch(next)- },- })),-actionToUrl(({ values }) => ({// Replace, not push — nudging a scope shouldn't stack back-history. Defaults are omitted.setDateRange: () => {@@ -152,23 +141,16 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL}return [pathname, next, hashParams, { replace: true }]},- // Mirror the exact branch into `?q=` so a branch-scoped view is shareable; drop the mutually- // exclusive PR lens.- setAppliedBranch: () => {+ // Mirror the scope into `?run_scope=` so a scoped view is shareable, and drop the `?q=` branch+ // param it replaced so an old link stops re-hydrating a branch nothing reads any more.+ setRunScope: () => {const { pathname, searchParams, hashParams } = router.values.currentLocationconst next = { ...searchParams }- if (values.appliedBranch) {- next.q = values.appliedBranch+ if (values.runScope === EngineeringAnalyticsWorkflowHealthRunScope.All) {+ delete next.run_scope} else {- delete next.q+ next.run_scope = values.runScope}- delete next.run_scope- return [pathname, next, hashParams, { replace: true }]- },- scopeToPullRequests: () => {- const { pathname, searchParams, hashParams } = router.values.currentLocation- const next = { ...searchParams }- next.run_scope = PR_SCOPEdelete next.qreturn [pathname, next, hashParams, { replace: true }]},@@ -183,19 +165,10 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersLif (dateFrom !== values.dateFrom || dateTo !== values.dateTo) {actions.setDateRange(dateFrom, dateTo)}- if (searchParams.run_scope === PR_SCOPE) {- if (!values.pullRequestScope) {- actions.scopeToPullRequests()- }- return- }- const branch = (searchParams.q ?? '').trim()- if (branch !== values.appliedBranch || values.pullRequestScope) {- actions.setBranchFilter(branch)- // An empty value already applies via setBranchFilter's listener; a real branch needs the apply.- if (branch !== '') {- actions.setAppliedBranch(branch)- }+ const runScope = runScopeFromUrl(searchParams.run_scope, searchParams.q)+ // A leftover `?q=` dispatches even when the scope is unchanged, so actionToUrl strips it.+ if (runScope !== values.runScope || searchParams.q !== undefined) {+ actions.setRunScope(runScope)}},})),diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.tsindex c563633e32b4..e8eb5239efed 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts@@ -172,6 +172,7 @@ function makeWorkflow(overrides: Partial<WorkflowHealthRow> = {}): WorkflowHealtlatestRunConclusion: 'success',granularity: 'day',buckets: [],+ mergeQueueRunCount: 0,...overrides,}}@@ -345,44 +346,28 @@ describe('engineeringAnalyticsLogic', () => {expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '2026-01-01', date_to: '2026-03-01' })})- it('filters workflow health by the shared branch scope, only reloading on a real change', async () => {- // Branch lives in the shared filters logic (so it carries into the workflow detail page); the- // Workflows tab reads it and reloads workflow health when it's applied.+ it('scopes workflow health to the shared run group', async () => {+ // The scope lives in the shared filters logic so it carries into the workflow detail page; the+ // Workflows tab reads it and reloads workflow health whenever the group changes.logic = engineeringAnalyticsLogic()logic.mount()const filters = engineeringAnalyticsFiltersLogic()extraUnmounts.push(filters.mount())await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])+ // All runs is the default, and the backend already reports every run when the param is absent.expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d' })- // Typing only stages the value — no reload until applied.- filters.actions.setBranchFilter('main')- expect(filters.values.branchInput).toBe('main')- expect(filters.values.appliedBranch).toBe('')-- // Applying promotes it and reloads with the branch param (trimmed).- filters.actions.setBranchFilter(' main ')- filters.actions.applyBranchFilter()+ filters.actions.setRunScope('pull_request')await expectLogic(logic).toDispatchActions(['loadWorkflowHealth', 'loadWorkflowHealthSuccess'])- expect(filters.values.appliedBranch).toBe('main')- expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d', branch: 'main' })-- // Re-applying an unchanged value (e.g. a blur with no edit) does not reload.- mockWorkflowHealth.mockClear()- filters.actions.applyBranchFilter()- await expectLogic(logic).toNotHaveDispatchedActions(['loadWorkflowHealth'])- expect(mockWorkflowHealth).not.toHaveBeenCalled()+ expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d', run_scope: 'pull_request' })- // The applied branch persists across a date-range reload.+ // The group persists across a window change.filters.actions.setDateRange('-90d', null)await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])- expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d', branch: 'main' })+ expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d', run_scope: 'pull_request' })- // Clearing the box (e.g. the search × button, which only fires onChange('')) applies- // immediately — no Enter/blur needed — and drops the filter.- filters.actions.setBranchFilter('')- await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])- expect(filters.values.appliedBranch).toBe('')+ filters.actions.setRunScope('all')+ await expectLogic(logic).toDispatchActions(['loadWorkflowHealth', 'loadWorkflowHealthSuccess'])expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d' })})diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.tsindex eb98381b91f7..da023890ac6b 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts@@ -32,7 +32,7 @@ import { CIStatus, ciStatusOf } from '../lib/ci'import { type FleetSummary, computeFleetSummary } from '../lib/runHealth'import { scopeToValue } from '../lib/scope'import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'-import type { BranchHealthParams } from './engineeringAnalyticsFiltersLogic'+import type { RunScopeParams } from './engineeringAnalyticsFiltersLogic'// Mirrors the endpoint's server-side limit.export const PR_TABLE_LIMIT = 1000@@ -130,6 +130,9 @@ export interface WorkflowHealthRow {rerunCycles?: number/** Success rate over the previous equal-length window. */successRatePrev?: number | null+ /** Runs on merge-queue gate branches, counted regardless of the active scope. Above zero marks a+ * workflow the queue runs before a merge lands, so the list can rank it first. */+ mergeQueueRunCount: number}export interface WorkflowFailureSeries {@@ -388,9 +391,9 @@ export function loaderStatusFromError(errorObject: unknown): LoaderStatus {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface engineeringAnalyticsLogicValues {- branchHealthParams: BranchHealthParams // engineeringAnalyticsFiltersLogicdateFrom: string | null // engineeringAnalyticsFiltersLogicdateTo: string | null // engineeringAnalyticsFiltersLogic+ runScopeParams: RunScopeParams // engineeringAnalyticsFiltersLogicactiveCard: CardFilter | nullactiveSource: GitHubSourceApi | nullanyLoading: boolean@@ -677,7 +680,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTypath(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsLogic']),connect(() => ({- values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'branchHealthParams']],+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'runScopeParams']],})),actions({@@ -738,7 +741,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyconst items = await engineeringAnalyticsWorkflowHealth(projectId(), {date_from: values.dateFrom ?? undefined,date_to: values.dateTo ?? undefined,- ...values.branchHealthParams,+ ...values.runScopeParams,source_id: values.sourceId ?? undefined,repo: values.scopeRepo ?? undefined,})@@ -767,6 +770,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyestimatedCostUsd: it.estimated_cost_usd ?? null,rerunCycles: it.rerun_cycles ?? 0,successRatePrev: it.success_rate_prev ?? null,+ mergeQueueRunCount: it.merge_queue_run_count ?? 0,}))},@@ -1210,10 +1214,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {actions.loadWorkflowHealth()},- [engineeringAnalyticsFiltersLogic.actionTypes.setAppliedBranch]: () => {- actions.loadWorkflowHealth()- },- [engineeringAnalyticsFiltersLogic.actionTypes.scopeToPullRequests]: () => {+ [engineeringAnalyticsFiltersLogic.actionTypes.setRunScope]: () => {actions.loadWorkflowHealth()},applyCardFilter: ({ card }) => {@@ -1255,7 +1256,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy}),urlToAction(({ actions, values }) => {- // `?q=` (branch scope) is hydrated by engineeringAnalyticsFiltersLogic, not here.+ // `?run_scope=` is hydrated by engineeringAnalyticsFiltersLogic, not here.const applyScope = (source: string | undefined, repo: string | undefined): void => {const nextSource = source ?? nullconst nextRepo = repo ?? nulldiff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.tsindex b32d6157239e..2939ed8881c7 100644--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts@@ -56,7 +56,7 @@ describe('workflowRunsLogic', () => {logic?.unmount()})- it('scopes the runs list, activity chart, and cost breakdown to the shared branch, reloading all on a change', async () => {+ it('sends the shared run scope to every windowed read on the page, reloading all of them on a change', async () => {logic = workflowRunsLogic({ repoOwner: 'PostHog', repoName: 'posthog', workflowName: 'CI', sourceId: null })logic.mount()const filters = engineeringAnalyticsFiltersLogic()@@ -65,29 +65,34 @@ describe('workflowRunsLogic', () => {'loadRunsSuccess','loadRunActivitySuccess','loadRunnerCostsSuccess',+ 'loadJobAggregatesSuccess',])- // No branch applied → the endpoints see every branch (the pre-fix behavior for the whole page).- const runsArgs = { workflow_name: 'CI', repo: 'PostHog/posthog', date_from: '-7d', branch: undefined }- expect(mockRuns).toHaveBeenLastCalledWith('1', expect.objectContaining(runsArgs))- expect(mockRunActivity).toHaveBeenLastCalledWith('1', expect.objectContaining(runsArgs))- expect(mockRunnerCosts).toHaveBeenLastCalledWith('1', expect.objectContaining(runsArgs))+ const windowedReads = [mockRuns, mockRunActivity, mockRunnerCosts, mockJobAggregates]+ for (const read of windowedReads) {+ expect(read).toHaveBeenLastCalledWith(+ '1',+ expect.objectContaining({ workflow_name: 'CI', repo: 'PostHog/posthog', date_from: '-7d' })+ )+ // All runs is the default, and the backend already reports every run when the param is absent.+ expect(read.mock.lastCall?.[1]).not.toHaveProperty('run_scope')+ }- // Applying a branch on the shared filters logic reloads all three reads scoped to it — so the detail- // page's numbers (and the chart's runs) match the branch-scoped Workflows tab instead of widening- // back to all branches.- filters.actions.setBranchFilter('master')- filters.actions.applyBranchFilter()+ // Picking a group on the shared filters logic reloads all four reads scoped to it, so the detail+ // page's numbers and its chart match the list it was opened from.+ filters.actions.setRunScope('merge_queue')await expectLogic(logic).toDispatchActions(['loadRuns','loadRunActivity','loadRunnerCosts',+ 'loadJobAggregates','loadRunsSuccess','loadRunActivitySuccess','loadRunnerCostsSuccess',+ 'loadJobAggregatesSuccess',])- expect(mockRuns).toHaveBeenLastCalledWith('1', expect.objectContaining({ branch: 'master' }))- expect(mockRunActivity).toHaveBeenLastCalledWith('1', expect.objectContaining({ branch: 'master' }))- expect(mockRunnerCosts).toHaveBeenLastCalledWith('1', expect.objectContaining({ branch: 'master' }))+ for (const read of windowedReads) {+ expect(read).toHaveBeenLastCalledWith('1', expect.objectContaining({ run_scope: 'merge_queue' }))+ }})})diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.tsindex ade5c95a7a16..0bbf6f225fc6 100644--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts@@ -25,6 +25,7 @@ import type {import { jobCacheKey } from '../lib/jobs'import { type CostSummary, type HealthSummary, computeHealthSummary } from '../lib/runHealth'import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'+import type { RunScopeParams } from './engineeringAnalyticsFiltersLogic'const projectId = (): string => String(ApiConfig.getCurrentProjectId())@@ -57,9 +58,9 @@ export interface WorkflowRunsLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowRunsLogicValues {- appliedBranch: string // engineeringAnalyticsFiltersLogicdateFrom: string | null // engineeringAnalyticsFiltersLogicdateTo: string | null // engineeringAnalyticsFiltersLogic+ runScopeParams: RunScopeParams // engineeringAnalyticsFiltersLogicactivityRuns: ActivityRun[]activityTruncated: booleanbreadcrumbs: Breadcrumb[]@@ -218,10 +219,10 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([props({} as WorkflowRunsLogicProps),key((props) => `${props.repoOwner}/${props.repoName}/${props.workflowName}@${props.sourceId ?? ''}`),- // Same window and branch scope as the Workflows tab, so drilling in keeps the scope instead of- // silently widening back to all branches.+ // Same window and run scope as the Workflows tab, so drilling in keeps the group of runs instead of+ // silently widening back to every branch.connect(() => ({- values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'appliedBranch']],+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'runScopeParams']],})),actions({@@ -244,7 +245,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([repo: `${props.repoOwner}/${props.repoName}`,date_from: values.dateFrom ?? undefined,date_to: values.dateTo ?? undefined,- branch: values.appliedBranch || undefined,+ ...values.runScopeParams,source_id: props.sourceId ?? undefined,}),},@@ -260,7 +261,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([repo: `${props.repoOwner}/${props.repoName}`,date_from: values.dateFrom ?? undefined,date_to: values.dateTo ?? undefined,- branch: values.appliedBranch || undefined,+ ...values.runScopeParams,source_id: props.sourceId ?? undefined,}),},@@ -275,7 +276,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([repo: `${props.repoOwner}/${props.repoName}`,date_from: values.dateFrom ?? undefined,date_to: values.dateTo ?? undefined,- branch: values.appliedBranch || undefined,+ ...values.runScopeParams,source_id: props.sourceId ?? undefined,}),},@@ -290,7 +291,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([repo: `${props.repoOwner}/${props.repoName}`,date_from: values.dateFrom ?? undefined,date_to: values.dateTo ?? undefined,- branch: values.appliedBranch || undefined,+ ...values.runScopeParams,source_id: props.sourceId ?? undefined,}),},@@ -479,7 +480,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([actions.loadRunnerCosts()actions.loadJobAggregates()},- [engineeringAnalyticsFiltersLogic.actionTypes.setAppliedBranch]: () => {+ [engineeringAnalyticsFiltersLogic.actionTypes.setRunScope]: () => {actions.loadRuns()actions.loadRunActivity()actions.loadRunnerCosts()diff --git a/products/engineering_analytics/frontend/scenes/workflowSwitcherLogic.ts b/products/engineering_analytics/frontend/scenes/workflowSwitcherLogic.tsindex 4e5938fb43ed..0e7bcd1bb1cf 100644--- a/products/engineering_analytics/frontend/scenes/workflowSwitcherLogic.ts+++ b/products/engineering_analytics/frontend/scenes/workflowSwitcherLogic.ts@@ -8,6 +8,7 @@ import { ApiConfig } from 'lib/api'import { engineeringAnalyticsWorkflowHealth } from '../generated/api'import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'+import type { RunScopeParams } from './engineeringAnalyticsFiltersLogic'export interface WorkflowSwitcherLogicProps {repoOwner: string@@ -17,9 +18,9 @@ export interface WorkflowSwitcherLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowSwitcherLogicValues {- appliedBranch: string // engineeringAnalyticsFiltersLogicdateFrom: string | null // engineeringAnalyticsFiltersLogicdateTo: string | null // engineeringAnalyticsFiltersLogic+ runScopeParams: RunScopeParams // engineeringAnalyticsFiltersLogicworkflowNames: string[] | nullworkflowNamesLoading: boolean}@@ -64,7 +65,7 @@ export const workflowSwitcherLogic = kea<workflowSwitcherLogicType>([key(({ repoOwner, repoName, sourceId }) => `${repoOwner}/${repoName}:${sourceId ?? ''}`),connect(() => ({- values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'appliedBranch']],+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'runScopeParams']],})),actions({@@ -81,7 +82,7 @@ export const workflowSwitcherLogic = kea<workflowSwitcherLogicType>([const items = await engineeringAnalyticsWorkflowHealth(String(ApiConfig.getCurrentProjectId()), {date_from: values.dateFrom ?? undefined,date_to: values.dateTo ?? undefined,- branch: values.appliedBranch || undefined,+ ...values.runScopeParams,source_id: props.sourceId ?? undefined,repo: `${props.repoOwner}/${props.repoName}`,})diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex 5a53b4643000..af4342dafef3 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -362,17 +362,14 @@ tools:this for "is CI getting faster or slower", "which GitHub Actions workflow is the slow or flaky long pole",and CI duration trends. Success rate covers runs that succeeded or ended in failure, timeout, startupfailure, or staleness. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over- successful runs only, so superseded cancels and failed runs never bias the duration percentile. For- PR-branch CI health, pass run_scope=pull_request (same-repo PRs only — fork PRs carry no PR attribution). To- get a trend, call this over two adjacent windows and compare.+ successful runs only, so superseded cancels and failed runs never bias the duration percentile. Pass+ run_scope to report on one group of runs: default_branch, pull_request (PR branches only, same-repo PRs —+ fork PRs carry no PR attribution), merge_queue, or all. To get a trend, call this over two adjacent windows+ and compare.param_overrides:date_from:description: Window start — relative ('-24h', '-7d') or ISO8601. Defaults to -24h.date_to:description: Window end — relative or ISO8601. Defaults to now.- run_scope:- description: >- Run scope. Use "pull_request" for PR CI runs (excludes default-branch master/main runs; same-repo- PRs only, since fork PRs carry no PR attribution); omit or pass "all" for every run.feature_flag: engineering-analyticsurl_prefix: /engineering-analytics/workflowsdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 05d3dbfca5b7..5a24511dcdc7 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -12128,7 +12128,7 @@}},"workflow-health": {- "description": "Per-workflow CI health over a window: run count, success rate, p50/p95 duration, and last failure time. Use this for \"is CI getting faster or slower\", \"which GitHub Actions workflow is the slow or flaky long pole\", and CI duration trends. Success rate covers runs that succeeded or ended in failure, timeout, startup failure, or staleness. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so superseded cancels and failed runs never bias the duration percentile. For PR-branch CI health, pass run_scope=pull_request (same-repo PRs only — fork PRs carry no PR attribution). To get a trend, call this over two adjacent windows and compare.",+ "description": "Per-workflow CI health over a window: run count, success rate, p50/p95 duration, and last failure time. Use this for \"is CI getting faster or slower\", \"which GitHub Actions workflow is the slow or flaky long pole\", and CI duration trends. Success rate covers runs that succeeded or ended in failure, timeout, startup failure, or staleness. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so superseded cancels and failed runs never bias the duration percentile. Pass run_scope to report on one group of runs: default_branch, pull_request (PR branches only, same-repo PRs — fork PRs carry no PR attribution), merge_queue, or all. To get a trend, call this over two adjacent windows and compare.","category": "Engineering analytics","feature": "engineering_analytics","summary": "Per-workflow CI health",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 112be5747f6f..95dbf2bdc9fe 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -12756,7 +12756,7 @@}},"workflow-health": {- "description": "Per-workflow CI health over a window: run count, success rate, p50/p95 duration, and last failure time. Use this for \"is CI getting faster or slower\", \"which GitHub Actions workflow is the slow or flaky long pole\", and CI duration trends. Success rate covers runs that succeeded or ended in failure, timeout, startup failure, or staleness. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so superseded cancels and failed runs never bias the duration percentile. For PR-branch CI health, pass run_scope=pull_request (same-repo PRs only — fork PRs carry no PR attribution). To get a trend, call this over two adjacent windows and compare.",+ "description": "Per-workflow CI health over a window: run count, success rate, p50/p95 duration, and last failure time. Use this for \"is CI getting faster or slower\", \"which GitHub Actions workflow is the slow or flaky long pole\", and CI duration trends. Success rate covers runs that succeeded or ended in failure, timeout, startup failure, or staleness. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so superseded cancels and failed runs never bias the duration percentile. Pass run_scope to report on one group of runs: default_branch, pull_request (PR branches only, same-repo PRs — fork PRs carry no PR attribution), merge_queue, or all. To get a trend, call this over two adjacent windows and compare.","category": "Engineering analytics","feature": "engineering_analytics","summary": "Per-workflow CI health",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0b619bc86d8a..5eff19e3ecd7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -89167,6 +89167,8 @@ export namespace Schemas {success_rate_prev?: number | null;/** Successful runs that did real CI work. This is the p50/p95 sample count. */percentile_run_count?: number;+ /** Runs on merge-queue gate branches (trunk-merge/**) in the window, counted regardless of branch or run_scope. Non-zero marks a workflow the queue runs before a merge lands, the closest available proxy for a required check. */+ merge_queue_run_count?: number;}export interface WorkflowJob {@@ -94878,6 +94880,10 @@ export namespace Schemas {* 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.*/repo?: string;+ /**+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.+ */+ run_scope?: EngineeringAnalyticsJobAggregatesRunScope;/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/@@ -94888,6 +94894,16 @@ export namespace Schemas {workflow_name: string;};+ export type EngineeringAnalyticsJobAggregatesRunScope = typeof EngineeringAnalyticsJobAggregatesRunScope[keyof typeof EngineeringAnalyticsJobAggregatesRunScope];+++ export const EngineeringAnalyticsJobAggregatesRunScope = {+ All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',+ PullRequest: 'pull_request',+ } as const;+export type EngineeringAnalyticsMasterFailuresParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.@@ -95164,7 +95180,7 @@ export namespace Schemas {*/repo?: string;/**- * Run scope for workflow health: 'all' (default) includes every run; 'pull_request' includes runs attributed to pull requests, excluding default-branch (master/main) runs. Fork PRs carry no PR attribution (a GitHub limitation), so 'pull_request' covers same-repo PRs only. Any other value is a 400.+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.*/run_scope?: EngineeringAnalyticsWorkflowHealthRunScope;/**@@ -95178,6 +95194,8 @@ export namespace Schemas {export const EngineeringAnalyticsWorkflowHealthRunScope = {All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',PullRequest: 'pull_request',} as const;@@ -95232,6 +95250,10 @@ export namespace Schemas {* 'owner/name' repository the workflow belongs to.*/repo: string;+ /**+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.+ */+ run_scope?: EngineeringAnalyticsWorkflowRunActivityRunScope;/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/@@ -95242,6 +95264,16 @@ export namespace Schemas {workflow_name: string;};+ export type EngineeringAnalyticsWorkflowRunActivityRunScope = typeof EngineeringAnalyticsWorkflowRunActivityRunScope[keyof typeof EngineeringAnalyticsWorkflowRunActivityRunScope];+++ export const EngineeringAnalyticsWorkflowRunActivityRunScope = {+ All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',+ PullRequest: 'pull_request',+ } as const;+export type EngineeringAnalyticsWorkflowRunnerCostsParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.@@ -95259,6 +95291,10 @@ export namespace Schemas {* 'owner/name' repository the workflow belongs to.*/repo: string;+ /**+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.+ */+ run_scope?: EngineeringAnalyticsWorkflowRunnerCostsRunScope;/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/@@ -95269,6 +95305,16 @@ export namespace Schemas {workflow_name: string;};+ export type EngineeringAnalyticsWorkflowRunnerCostsRunScope = typeof EngineeringAnalyticsWorkflowRunnerCostsRunScope[keyof typeof EngineeringAnalyticsWorkflowRunnerCostsRunScope];+++ export const EngineeringAnalyticsWorkflowRunnerCostsRunScope = {+ All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',+ PullRequest: 'pull_request',+ } as const;+export type EngineeringAnalyticsWorkflowRunsParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.@@ -95286,6 +95332,10 @@ export namespace Schemas {* 'owner/name' repository the workflow belongs to.*/repo: string;+ /**+ * Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.+ */+ run_scope?: EngineeringAnalyticsWorkflowRunsRunScope;/*** Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/@@ -95296,6 +95346,16 @@ export namespace Schemas {workflow_name: string;};+ export type EngineeringAnalyticsWorkflowRunsRunScope = typeof EngineeringAnalyticsWorkflowRunsRunScope[keyof typeof EngineeringAnalyticsWorkflowRunsRunScope];+++ export const EngineeringAnalyticsWorkflowRunsRunScope = {+ All: 'all',+ DefaultBranch: 'default_branch',+ MergeQueue: 'merge_queue',+ PullRequest: 'pull_request',+ } as const;+export type EnvironmentsListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.tsindex 15cb5dad977a..d709fb0597f1 100644--- a/services/mcp/src/generated/engineering_analytics/api.ts+++ b/services/mcp/src/generated/engineering_analytics/api.ts@@ -248,7 +248,7 @@ export const EngineeringAnalyticsTeamCiHealthQueryParams = () => zod.object({})/**- * Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, or to attributed pull-request runs via `run_scope=pull_request`. Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.+ * Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, or to one run group via `run_scope` (default_branch, pull_request, merge_queue). Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.*/export const EngineeringAnalyticsWorkflowHealthParams = () => zod.object({project_id: zod@@ -274,10 +274,10 @@ export const EngineeringAnalyticsWorkflowHealthQueryParams = () => zod.object({"'owner\/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository."),run_scope: zod- .enum(['all', 'pull_request'])+ .enum(['all', 'default_branch', 'merge_queue', 'pull_request']).optional().describe(- "Run scope for workflow health: 'all' (default) includes every run; 'pull_request' includes runs attributed to pull requests, excluding default-branch (master\/main) runs. Fork PRs carry no PR attribution (a GitHub limitation), so 'pull_request' covers same-repo PRs only. Any other value is a 400."+ "Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400."),source_id: zod.string()@@ -321,7 +321,7 @@ export const EngineeringAnalyticsWorkflowJobsQueryParams = () => zod.object({})/**- * A workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Optionally scope to a single git branch via `branch`. Returns an empty list when the job-level source isn't synced.+ * A workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Optionally scope to a single git branch via `branch` or one run group via `run_scope`. Returns an empty list when the job-level source isn't synced.*/export const EngineeringAnalyticsWorkflowRunnerCostsParams = () => zod.object({project_id: zod@@ -341,6 +341,12 @@ export const EngineeringAnalyticsWorkflowRunnerCostsQueryParams = () => zod.objedate_from: zod.string().optional().describe("Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d."),date_to: zod.string().optional().describe('Window end: relative or ISO8601. Defaults to now.'),repo: zod.string().describe("'owner\/name' repository the workflow belongs to."),+ run_scope: zod+ .enum(['all', 'default_branch', 'merge_queue', 'pull_request'])+ .optional()+ .describe(+ "Which group of runs to report on: 'all' (default) is every run; 'default_branch' is runs on master or main; 'pull_request' is runs on PR branches, excluding default-branch and merge-queue runs; 'merge_queue' is the gate runs the merge queue fired before a merge landed. Fork PRs carry no PR attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400."+ ),source_id: zod.string().optional()diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.tsindex 65c21da61c08..6701d8e4ebd7 100644--- a/services/mcp/src/tools/generated/engineering_analytics.ts+++ b/services/mcp/src/tools/generated/engineering_analytics.ts@@ -238,6 +238,7 @@ const engineeringAnalyticsWorkflowRunnerCosts = (): ToolBase<date_from: params.date_from,date_to: params.date_to,repo: params.repo,+ run_scope: params.run_scope,source_id: params.source_id,workflow_name: params.workflow_name,},@@ -306,9 +307,6 @@ const WorkflowHealthSchema = () => {date_to: EngineeringAnalyticsWorkflowHealthQueryParams.shape['date_to'].describe('Window end — relative or ISO8601. Defaults to now.'),- run_scope: EngineeringAnalyticsWorkflowHealthQueryParams.shape['run_scope'].describe(- 'Run scope. Use "pull_request" for PR CI runs (excludes default-branch master/main runs; same-repo PRs only, since fork PRs carry no PR attribution); omit or pass "all" for every run.'- ),})}