Skip to content

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

feat(eng-analytics): pr run scope + success-only ci percentiles (#67398)

Raúl Negrón-Oteroaa582e0200e1
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 8b36cc69963d..c0effacbfc9c 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -141,7 +141,7 @@ A PR's current CI status is the head-SHA join between the two (the `ci_rollup` C
- `ci_cards` — open-PR backlog counts (open / repos / stuck >7d / failing CI).
- `pull_requests` — PR list with head-SHA CI rollup; `date_from` recency window. Capped (newest first) and returned as `{items, truncated, limit}` so the page never silently under-counts against `ci_cards`.
-- `workflow_health` — per-workflow run count, success rate, p50/p95 duration, last failure over a `date_from`/`date_to` window, optionally scoped to a single git `branch` (`head_branch`).
+- `workflow_health` — per-workflow run count, success rate, p50/p95 duration, last failure over a `date_from`/`date_to` window, optionally scoped to a single git `branch` (`head_branch`) or PR-attributed runs excluding the default branch (`run_scope=pull_request`; master/main, same-repo PRs only). p50/p95 are over successful runs only — there is no knob, because cancelled (superseded) and failed runs end early and would bias any duration percentile low.
- `pr_lifecycle` — PR header + ordered CI-run timeline (a genuine assembly; `metric_quality = "partial"` until reviews/deploys land).
- `ci_failure_logs` — the thinned failure log lines for a PR's CI, grouped by job. Resolves the PR to its run_ids via the same `pull_requests` attribution as `pr_runs`, then reads the Logs product (`service.name = github-ci-logs`) joined on `run_id`. Reads from Logs, not the warehouse.
- `flaky_tests` — the flaky-test leaderboard: per-test CI spans from the Traces product (`trace_spans`, emitted by Backend CI's report-test-timings job) grouped by pytest nodeid over a window (default `-7d`, max 30 days), ranked by flakiness signal. A test qualifies by passing on retry (`rerun_passed`) at least `min_rerun_passes` times (default 1) OR failing on at least `min_failed_prs` distinct PRs (default 3). Absolute counts only, never rates — sub-threshold passing runs aren't emitted, so denominators are biased. Reads from Traces, not the warehouse.
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index d2406263f9c9..b110fd0b9a8a 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -7,7 +7,8 @@ parameters and return canonical contract types.
``repo`` is an optional ``owner/name`` filter, applied against the curated repo
identity (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. ``date_from`` / ``date_to`` accept
+costs; workflow health additionally takes a broader ``run_scope`` filter
+(``pull_request`` scopes to PR-attributed runs). ``date_from`` / ``date_to`` accept
relative strings (``-30d``) or ISO8601 and are resolved against the team timezone.
``source_id`` selects a specific connected GitHub source when the team has more than
one; it defaults to the oldest connected source. ``user_access_control`` enforces the
@@ -242,6 +243,7 @@ def list_workflow_health(
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[WorkflowHealthItem]:
@@ -250,6 +252,7 @@ def list_workflow_health(
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.py
index 113adf1c589b..d82400fa7e27 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -85,6 +85,11 @@ class MetricQuality(StrEnum):
PARTIAL = "partial"
+class WorkflowHealthRunScope(StrEnum):
+ ALL = "all"
+ PULL_REQUEST = "pull_request"
+
+
class PRLifecycleEventKind(StrEnum):
OPENED = "opened"
CI_STARTED = "ci_started"
@@ -635,8 +640,10 @@ class QuarantineRequestResult:
@dataclass(frozen=True)
class WorkflowHealthItem:
- """Per-workflow CI health over a window. Rates and percentiles are over
- completed runs only, so they are ``None`` when the window has none.
+ """Per-workflow CI health over a window. ``success_rate`` is over completed runs;
+ ``p50_seconds``/``p95_seconds`` are over successful runs only (cancelled, skipped,
+ and failed runs end early and would bias a duration percentile low). Each is
+ ``None`` when the window has no qualifying runs.
"""
repo: RepoRef
@@ -760,8 +767,9 @@ class RunFailureLogs:
class WorkflowJobAggregate:
"""Per-job aggregates for one workflow over a window, one row per de-sharded job name
(matrix ``(G/N)`` suffix stripped; unexpanded ``${{ matrix.* }}`` templates collapsed).
- Rates and percentiles are over completed jobs; cost is None when every instance ran on
- an unknown tier."""
+ ``failure_rate`` is over completed jobs; ``p50_seconds``/``p95_seconds`` are over
+ successful jobs only (cancelled and failed instances end early and would bias a
+ duration percentile low); cost is None when every instance ran on an unknown tier."""
job_name: str
# Job instances observed in the window (all shards, all attempts).
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index fadb88aaece6..9cda2a3b1144 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -26,6 +26,7 @@ from products.engineering_analytics.backend.facade.contracts import (
RunFailureLogs,
WorkflowCost,
WorkflowHealthItem,
+ WorkflowHealthRunScope,
WorkflowJob,
WorkflowJobAggregate,
WorkflowRunActivity,
@@ -236,9 +237,16 @@ def build_workflow_health(
date_from: str | None = None,
date_to: str | None = None,
branch: str | None = None,
+ run_scope: str | None = None,
) -> list[WorkflowHealthItem]:
parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WORKFLOW_WINDOW)
- return query_workflow_health(curated=curated, date_from=parsed_from, date_to=parsed_to, branch=branch)
+ return query_workflow_health(
+ curated=curated,
+ date_from=parsed_from,
+ date_to=parsed_to,
+ branch=branch,
+ run_scope=_parse_run_scope(run_scope),
+ )
def build_flaky_tests(
@@ -276,6 +284,19 @@ def _parse_date(team: Team, value: str) -> datetime:
return relative_date_parse(value, team.timezone_info)
+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 _parse_window(
team: Team, date_from: str | None, date_to: str | None, *, default: str, max_days: int = _MAX_WINDOW_DAYS
) -> tuple[datetime, datetime | None]:
diff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
new file mode 100644
index 000000000000..6db01fa878d0
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
@@ -0,0 +1,47 @@
+"""Shared predicates for curated workflow-run window queries.
+
+Clauses qualify columns with ``r`` — every consuming template reads the runs
+source as ``FROM __RUNS_SOURCE__ AS r`` (or joins it as ``r``).
+"""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.facade.contracts import WorkflowHealthRunScope
+
+# The one duration-percentile population, for runs and jobs alike: successful instances
+# only. Cancelled/skipped (superseded) and failed instances end early, so including them
+# answers "how long until CI stopped", not "how long does CI take to pass".
+DURATION_PERCENTILE_CONDITION = "status = 'completed' AND conclusion = 'success'"
+
+
+def branch_filter_clause(branch: str | None, placeholders: dict[str, ast.Expr]) -> str:
+ """Exact ``head_branch`` filter; registers its ``{branch}`` placeholder.
+
+ An empty/whitespace branch is "no filter", not a literal match on ''.
+ """
+ value = branch.strip() if branch else ""
+ if not value:
+ return ""
+ placeholders["branch"] = ast.Constant(value=value)
+ return "AND r.head_branch = {branch}"
+
+
+def date_to_filter_clause(date_to: datetime | None, placeholders: dict[str, ast.Expr]) -> str:
+ """Optional window end; registers its ``{date_to}`` placeholder."""
+ if date_to is None:
+ return ""
+ placeholders["date_to"] = ast.Constant(value=date_to)
+ return "AND r.run_started_at <= {date_to}"
+
+
+def run_scope_filter_clause(run_scope: WorkflowHealthRunScope) -> str:
+ if run_scope == WorkflowHealthRunScope.PULL_REQUEST:
+ # A default-branch run can still carry a PR association (its SHA matches an open PR),
+ # so attribution (pr_number > 0 — see the workflow_runs builder docstring) alone doesn't
+ # keep trunk runs out. The source doesn't record which branch is the repo's default, so
+ # exclude the common default-branch names — the same approximation repo_overview's
+ # query_default_branch resolves per-repo, not reused here because it costs an extra query.
+ return "AND r.head_branch NOT IN ('master', 'main') AND r.pr_number > 0"
+ return ""
diff --git a/products/engineering_analytics/backend/logic/queries/job_aggregates.py b/products/engineering_analytics/backend/logic/queries/job_aggregates.py
index c03711603350..f03e02aea903 100644
--- a/products/engineering_analytics/backend/logic/queries/job_aggregates.py
+++ b/products/engineering_analytics/backend/logic/queries/job_aggregates.py
@@ -2,7 +2,8 @@
The workflow page's jobs table: one row per de-sharded job name (the matrix "(G/N)"
suffix stripped in SQL with the same rule the frontend's jobGroups uses), with queue
-p50 (created -> started, where runner-capacity problems hide), duration percentiles,
+p50 (created -> started, where runner-capacity problems hide), duration percentiles
+(successful jobs only — the shared DURATION_PERCENTILE_CONDITION population),
failure rate, retry pressure, run share (conditional jobs skip — "runs in 31% of
runs"), and billable cost. Jobs carry ``workflow_name`` / ``head_branch`` /
``created_at`` directly, so no join to the runs table is needed; the run-share
@@ -19,6 +20,7 @@ from posthog.hogql import ast
from products.engineering_analytics.backend.facade.contracts import WorkflowJobAggregate
from products.engineering_analytics.backend.logic.cost import estimate_job_cost_usd
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float
+from products.engineering_analytics.backend.logic.queries._workflow_filters import DURATION_PERCENTILE_CONDITION
from products.engineering_analytics.backend.logic.queries.pr_cost import _parse_labels
_LIMIT = 200
@@ -38,8 +40,8 @@ _AGGREGATE_SELECT = f"""
uniq(name) AS shard_count,
uniq(run_id) AS runs_in,
quantile(0.5)(queue_seconds) AS queue_p50_seconds,
- quantileIf(0.5)(duration_seconds, status = 'completed') AS p50_seconds,
- quantileIf(0.95)(duration_seconds, status = 'completed') AS p95_seconds,
+ quantileIf(0.5)(duration_seconds, {DURATION_PERCENTILE_CONDITION}) AS p50_seconds,
+ quantileIf(0.95)(duration_seconds, {DURATION_PERCENTILE_CONDITION}) AS p95_seconds,
countIf(conclusion IN ('failure', 'timed_out')) / nullIf(countIf(status = 'completed'), 0) AS failure_rate,
countIf(run_attempt > 1) AS retry_job_count
FROM __JOBS_SOURCE__ AS j
diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.py
index 3e487f9c1899..b3747a02a9a6 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py
@@ -20,6 +20,7 @@ from products.engineering_analytics.backend.facade.contracts import (
PRCostSummary,
RunCost,
WorkflowCost,
+ WorkflowHealthRunScope,
WorkflowRunnerCost,
)
from products.engineering_analytics.backend.logic.cost import PRCostAggregate, aggregate_pr_cost, runner_descriptor
@@ -31,6 +32,11 @@ from products.engineering_analytics.backend.logic.queries._buckets import (
window_buckets,
)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ branch_filter_clause,
+ date_to_filter_clause,
+ run_scope_filter_clause,
+)
# Pre-aggregated per (workflow, run, attempt, runner-label) — a raw per-job SELECT has no LIMIT, so HogQL
# caps it at DEFAULT_RETURNED_ROWS (100) and silently drops the rest, undercounting any PR with >100 jobs.
@@ -167,7 +173,7 @@ _WINDOW_COST_SELECT = """
countIf(j.duration_seconds IS NULL) AS unfinished
FROM __JOBS_SOURCE__ AS j
INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt
- WHERE r.run_started_at >= {date_from} __DATE_TO__ __BRANCH__
+ WHERE r.run_started_at >= {date_from} __DATE_TO__ __BRANCH__ __RUN_SCOPE__
GROUP BY r.workflow_name, j.labels
LIMIT 1000000
"""
@@ -179,8 +185,9 @@ def query_workflow_window_costs(
date_from: datetime,
date_to: datetime | None,
branch: str | None,
+ run_scope: WorkflowHealthRunScope,
) -> dict[str, PRCostAggregate]:
- """Per-workflow billable cost over [date_from, date_to] (optional branch), keyed by workflow_name.
+ """Per-workflow billable cost over [date_from, date_to] (optional branch/run_scope), keyed by workflow_name.
Empty when the jobs source isn't synced. Mirrors the PR-list cost: grouped per workflow×label in SQL,
expanded back through aggregate_pr_cost.
@@ -188,21 +195,16 @@ def query_workflow_window_costs(
jobs_source = curated.jobs_source()
if jobs_source is None:
return {}
- branch = branch.strip() if branch else None
placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}
- date_to_clause = ""
- if date_to is not None:
- date_to_clause = "AND r.run_started_at <= {date_to}"
- placeholders["date_to"] = ast.Constant(value=date_to)
- branch_clause = ""
- if branch:
- branch_clause = "AND r.head_branch = {branch}"
- placeholders["branch"] = ast.Constant(value=branch)
+ date_to_clause = date_to_filter_clause(date_to, placeholders)
+ branch_clause = branch_filter_clause(branch, placeholders)
+ run_scope_clause = run_scope_filter_clause(run_scope)
sql = (
_WINDOW_COST_SELECT.replace("__JOBS_SOURCE__", jobs_source)
.replace("__RUNS_SOURCE__", curated.run_source())
.replace("__DATE_TO__", date_to_clause)
.replace("__BRANCH__", branch_clause)
+ .replace("__RUN_SCOPE__", run_scope_clause)
)
response = curated.run(sql, query_type="engineering_analytics.workflow_window_costs", placeholders=placeholders)
by_workflow: dict[str, list[tuple[list[str], float | None]]] = defaultdict(list)
@@ -500,16 +502,8 @@ def query_workflow_runner_costs(
"workflow_name": ast.Constant(value=workflow_name),
"date_from": ast.Constant(value=date_from),
}
- date_to_clause = ""
- if date_to is not None:
- date_to_clause = "AND r.run_started_at <= {date_to}"
- placeholders["date_to"] = ast.Constant(value=date_to)
- # An empty/whitespace branch is "no filter", not a literal match on '' — mirrors workflow_health.
- branch = branch.strip() if branch else None
- branch_clause = ""
- if branch:
- branch_clause = "AND r.head_branch = {branch}"
- placeholders["branch"] = ast.Constant(value=branch)
+ date_to_clause = date_to_filter_clause(date_to, placeholders)
+ branch_clause = branch_filter_clause(branch, placeholders)
sql = (
_RUNNER_COST_SELECT.replace("__JOBS_SOURCE__", jobs_source)
.replace("__RUNS_SOURCE__", curated.run_source())
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.py
index c805ebd92a2e..ab492dc5e831 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py
@@ -2,8 +2,11 @@
Run counts, success rate, and duration percentiles per ``workflow_name`` for runs
started within ``[date_from, date_to]`` (``date_to`` optional), optionally scoped to
-a single ``head_branch``. Rates and percentiles are over completed runs only, so they
-are ``None`` for a window with no completed runs.
+a single ``head_branch`` and/or attributed pull-request runs. Rates are over completed
+runs. Duration percentiles are over successful runs only — cancelled/skipped runs
+(common on PR branches, where a new push supersedes in-flight CI) and failed runs
+end early and would bias a "how long does CI take" percentile low — so they are
+``None`` for a window with no successful runs.
The per-bucket history adapts its granularity to the window length (hour / day / week)
so the trend sparkline keeps a readable number of points — per-day buckets are useless
@@ -14,7 +17,12 @@ from datetime import datetime
from posthog.hogql import ast
-from products.engineering_analytics.backend.facade.contracts import RepoRef, WorkflowHealthBucket, WorkflowHealthItem
+from products.engineering_analytics.backend.facade.contracts import (
+ RepoRef,
+ WorkflowHealthBucket,
+ WorkflowHealthItem,
+ WorkflowHealthRunScope,
+)
from products.engineering_analytics.backend.logic.queries._buckets import (
bucket_expr,
normalize_bucket,
@@ -22,6 +30,12 @@ from products.engineering_analytics.backend.logic.queries._buckets import (
window_buckets,
)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ DURATION_PERCENTILE_CONDITION,
+ branch_filter_clause,
+ date_to_filter_clause,
+ run_scope_filter_clause,
+)
from products.engineering_analytics.backend.logic.queries.pr_cost import query_workflow_window_costs
_LIMIT = 100
@@ -35,15 +49,15 @@ _SELECT = f"""
workflow_name,
count() AS run_count,
countIf(status = 'completed' AND conclusion = 'success') / nullIf(countIf(status = 'completed'), 0) AS success_rate,
- quantileIf(0.5)(duration_seconds, status = 'completed') AS p50_seconds,
- quantileIf(0.95)(duration_seconds, status = 'completed') AS p95_seconds,
+ quantileIf(0.5)(duration_seconds, {DURATION_PERCENTILE_CONDITION}) AS p50_seconds,
+ quantileIf(0.95)(duration_seconds, {DURATION_PERCENTILE_CONDITION}) AS p95_seconds,
max(if(conclusion IN ('failure', 'timed_out'), run_started_at, NULL)) AS last_failure_at,
countIf(status = 'completed') AS completed_count,
argMaxIf(conclusion IN ('failure', 'timed_out'), run_started_at, status = 'completed') AS latest_failed,
argMaxIf(conclusion, run_started_at, status = 'completed') AS latest_conclusion,
countIf(run_attempt > 1) AS rerun_cycles
FROM __RUNS_SOURCE__ AS r
- WHERE run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__
+ WHERE run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__ __RUN_SCOPE__
GROUP BY repo_owner, repo_name, workflow_name
ORDER BY run_count DESC
LIMIT {_LIMIT}
@@ -59,7 +73,7 @@ _PREV_SELECT = """
workflow_name,
countIf(status = 'completed' AND conclusion = 'success') / nullIf(countIf(status = 'completed'), 0) AS success_rate
FROM __RUNS_SOURCE__ AS r
- WHERE run_started_at >= {prev_from} AND run_started_at < {date_from} __BRANCH__
+ WHERE run_started_at >= {prev_from} AND run_started_at < {date_from} __BRANCH__ __RUN_SCOPE__
GROUP BY repo_owner, repo_name, workflow_name
"""
@@ -74,7 +88,7 @@ _BUCKET_SELECT = f"""
countIf(status = 'completed' AND conclusion = 'success') AS successes,
countIf(status = 'completed' AND conclusion IN ('failure', 'timed_out')) AS failures
FROM __RUNS_SOURCE__ AS r
- WHERE run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__
+ WHERE run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__ __RUN_SCOPE__
GROUP BY repo_owner, repo_name, workflow_name, bucket_start
LIMIT {_BUCKET_LIMIT}
"""
@@ -85,18 +99,14 @@ def query_workflow_health(
curated: CuratedGitHubSource,
date_from: datetime,
date_to: datetime | None,
- branch: str | None = None,
+ branch: str | None,
+ run_scope: WorkflowHealthRunScope,
) -> list[WorkflowHealthItem]:
granularity = pick_granularity(date_from, date_to)
- date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""
- # An empty/whitespace branch is "no filter", not a literal match on ''.
- branch = branch.strip() if branch else None
- branch_clause = "AND head_branch = {branch}" if branch else ""
placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}
- if date_to is not None:
- placeholders["date_to"] = ast.Constant(value=date_to)
- if branch:
- placeholders["branch"] = ast.Constant(value=branch)
+ date_to_clause = date_to_filter_clause(date_to, placeholders)
+ branch_clause = branch_filter_clause(branch, placeholders)
+ run_scope_clause = run_scope_filter_clause(run_scope)
runs_source = curated.run_source()
@@ -105,6 +115,7 @@ def query_workflow_health(
template.replace("__RUNS_SOURCE__", runs_source)
.replace("__DATE_TO__", date_to_clause)
.replace("__BRANCH__", branch_clause)
+ .replace("__RUN_SCOPE__", run_scope_clause)
.replace("__BUCKET_FN__", bucket_expr(granularity))
)
@@ -142,7 +153,9 @@ def query_workflow_health(
bucket_start=key, run_count=run_count, completed=completed, successes=successes, failures=failures
)
- cost_by_workflow = query_workflow_window_costs(curated=curated, date_from=date_from, date_to=date_to, branch=branch)
+ cost_by_workflow = query_workflow_window_costs(
+ curated=curated, date_from=date_from, date_to=date_to, branch=branch, run_scope=run_scope
+ )
window = window_buckets(date_from, date_to, granularity)
return [
WorkflowHealthItem(
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py b/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py
index 62a7043c86d9..8950ae393c44 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py
@@ -18,6 +18,10 @@ from posthog.hogql import ast
from products.engineering_analytics.backend.facade.contracts import WorkflowRunActivity, WorkflowRunActivityPoint
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ branch_filter_clause,
+ date_to_filter_clause,
+)
# The chart plots a point per run and needs enough span to cover the window: an order of magnitude
# above the run-detail table's cap (workflow_run_list._LIMIT = 200) so the scatter and focus-lens
@@ -52,16 +56,8 @@ def query_workflow_run_activity(
"workflow_name": ast.Constant(value=workflow_name),
"date_from": ast.Constant(value=date_from),
}
- date_to_clause = ""
- if date_to is not None:
- date_to_clause = "AND run_started_at <= {date_to}"
- placeholders["date_to"] = ast.Constant(value=date_to)
- # An empty/whitespace branch is "no filter", not a literal match on '' — mirrors workflow_run_list.
- branch = branch.strip() if branch else None
- branch_clause = ""
- if branch:
- branch_clause = "AND head_branch = {branch}"
- placeholders["branch"] = ast.Constant(value=branch)
+ date_to_clause = date_to_filter_clause(date_to, placeholders)
+ branch_clause = branch_filter_clause(branch, placeholders)
response = curated.run(
_SELECT.replace("__RUNS_SOURCE__", curated.run_source())
.replace("__DATE_TO__", date_to_clause)
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_run_list.py b/products/engineering_analytics/backend/logic/queries/workflow_run_list.py
index d803c6055af6..7b6a7c8dccb4 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_run_list.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_run_list.py
@@ -13,6 +13,10 @@ from posthog.hogql import ast
from products.engineering_analytics.backend.facade.contracts import WorkflowRunDetail
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries._run_detail import RUN_DETAIL_COLUMNS, to_run_detail
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ branch_filter_clause,
+ date_to_filter_clause,
+)
# Safety bound on the runs list (mirrors the PR table's cap philosophy).
_LIMIT = 200
@@ -44,16 +48,8 @@ def query_workflow_run_list(
"workflow_name": ast.Constant(value=workflow_name),
"date_from": ast.Constant(value=date_from),
}
- date_to_clause = ""
- if date_to is not None:
- date_to_clause = "AND run_started_at <= {date_to}"
- placeholders["date_to"] = ast.Constant(value=date_to)
- # An empty/whitespace branch is "no filter", not a literal match on '' — mirrors workflow_health.
- branch = branch.strip() if branch else None
- branch_clause = ""
- if branch:
- branch_clause = "AND head_branch = {branch}"
- placeholders["branch"] = ast.Constant(value=branch)
+ date_to_clause = date_to_filter_clause(date_to, placeholders)
+ branch_clause = branch_filter_clause(branch, placeholders)
response = curated.run(
_SELECT.replace("__RUNS_SOURCE__", curated.run_source())
.replace("__DATE_TO__", date_to_clause)
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index f5aab00183ae..57816a77acba 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -655,11 +655,14 @@ class WorkflowHealthItemSerializer(DataclassSerializer):
"allow_null": True,
},
"p50_seconds": {
- "help_text": "Median duration of completed runs, in seconds. Null if none completed.",
+ "help_text": "Median duration in seconds over successful runs only — cancelled (superseded) and "
+ "failed runs end early and would bias the percentile. Null if no run succeeded in the window.",
"allow_null": True,
},
"p95_seconds": {
- "help_text": "95th-percentile duration of completed runs, in seconds. Null if none completed.",
+ "help_text": "95th-percentile duration in seconds over successful runs only — cancelled "
+ "(superseded) and failed runs end early and would bias the percentile. Null if no run succeeded "
+ "in the window.",
"allow_null": True,
},
"last_failure_at": {
@@ -839,11 +842,13 @@ class WorkflowJobAggregateSerializer(DataclassSerializer):
"allow_null": True,
},
"p50_seconds": {
- "help_text": "Median duration of completed job instances, in seconds. Null if none completed.",
+ "help_text": "Median duration of successful job instances, in seconds — cancelled and failed "
+ "instances end early and would bias the percentile. Null if none succeeded.",
"allow_null": True,
},
"p95_seconds": {
- "help_text": "95th-percentile duration of completed job instances, in seconds. Null if none completed.",
+ "help_text": "95th-percentile duration of successful job instances, in seconds — cancelled and "
+ "failed instances end early and would bias the percentile. Null if none succeeded.",
"allow_null": True,
},
"failure_rate": {
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index 3148bf85d712..b2bd8deec4e6 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -28,6 +28,7 @@ from products.engineering_analytics.backend.facade.contracts import (
GitHubSourceNotConnectedError,
QuarantineRequest,
QuarantineWriteError,
+ WorkflowHealthRunScope,
)
from products.engineering_analytics.backend.presentation.serializers import (
CICardSummarySerializer,
@@ -89,6 +90,17 @@ _BRANCH = OpenApiParameter(
"Omit or leave blank to aggregate across all branches.",
)
+_RUN_SCOPE = OpenApiParameter(
+ name="run_scope",
+ type=OpenApiTypes.STR,
+ 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.",
+)
+
_SOURCE_ID = OpenApiParameter(
name="source_id",
type=OpenApiTypes.UUID,
@@ -248,19 +260,20 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
@extend_schema(
operation_id="engineering_analytics_workflow_health",
- parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _SOURCE_ID],
+ parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _RUN_SCOPE, _SOURCE_ID],
responses={
200: WorkflowHealthItemSerializer(many=True),
400: OpenApiResponse(
- description="Invalid date_from, date_to, or source_id, or a window longer than 366 days."
+ description="Invalid date_from, date_to, run_scope, or source_id, or a window longer than 366 days."
),
},
description=(
"Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success "
- "rate, p50/p95 duration over completed runs, last failure time, latest-run status, and a zero-filled "
- "run history bucketed by hour/day/week to fit the window. Optionally scope to a single git branch via "
- "`branch`. Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two "
- "windows to get a trend."
+ "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. 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."
),
)
@action(detail=False, methods=["get"], pagination_class=None)
@@ -271,6 +284,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
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,
)
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index aee919b0cfda..c12b8209df82 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -67,9 +67,16 @@ def _dt(value: str) -> datetime:
def _ago(days: int) -> str:
+ return _ago_with_duration(days, 0)[0]
+
+
+def _ago_with_duration(days: int, duration_seconds: int) -> tuple[str, str]:
# Seed dates relative to real time: HogQL now() runs server-side and ignores
# freezegun, so window/age assertions must share the clock the query uses.
- return (timezone.now() - timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")
+ started_at = timezone.now() - timedelta(days=days)
+ updated_at = started_at + timedelta(seconds=duration_seconds)
+ fmt = "%Y-%m-%d %H:%M:%S"
+ return started_at.strftime(fmt), updated_at.strftime(fmt)
def _job_row(
@@ -793,6 +800,75 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):
assert ci.last_failure_at is not None
assert ci.billable_minutes is None # no jobs source seeded → no cost figure
+ def test_workflow_health_duration_percentiles_exclude_cancelled_and_failed_runs(self) -> None:
+ self._create_table(
+ "github_pull_requests",
+ _PULL_REQUESTS_COLUMNS,
+ [_pr_row(90, "alice", "open", 0, _ago(1), head_sha="sha90")],
+ )
+ # Every success shares one duration, so success-only p50/p95 are exactly 100; any leaked
+ # cancel (1s) or failure (1000s) in the percentile population moves them off 100.
+ conclusions = [("success", 100)] * 2 + [("cancelled", 1)] * 3 + [("failure", 1000)]
+ self._create_table(
+ "github_workflow_runs",
+ _WORKFLOW_RUNS_COLUMNS,
+ [
+ _run_row(
+ 9000 + index,
+ "CI",
+ f"{conclusion}-{index}",
+ "completed",
+ conclusion,
+ *_ago_with_duration(1, duration_seconds),
+ pr_number=90,
+ head_branch="feature/ci",
+ )
+ for index, (conclusion, duration_seconds) in enumerate(conclusions)
+ ],
+ )
+
+ ci = next(
+ item for item in api.list_workflow_health(team=self.team, date_from="-30d") if item.workflow_name == "CI"
+ )
+
+ # Counts and rate stay over all/completed runs; only the duration population narrows.
+ assert ci.run_count == 6
+ assert ci.success_rate == pytest.approx(2 / 6)
+ assert ci.p50_seconds == pytest.approx(100)
+ assert ci.p95_seconds == pytest.approx(100)
+
+ def test_workflow_health_pull_request_scope_excludes_default_branch_and_unattributed_runs(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"),
+ ]
+ ],
+ )
+
+ pull_request = next(
+ item
+ for item in api.list_workflow_health(team=self.team, date_from="-30d", run_scope="pull_request")
+ 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
+
def test_workflow_health_includes_cost_when_jobs_synced(self) -> None:
# With the jobs source synced, each workflow carries its windowed billable cost + minutes.
self._create_table(
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 4e48712c3f37..754d26c2a80b 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -191,12 +191,16 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()[0]["workflow_name"] == "CI"
- def test_workflow_health_passes_branch_through(self) -> None:
+ def test_workflow_health_passes_filters_through(self) -> None:
with mock.patch(f"{_VIEWS}.list_workflow_health", return_value=[]) as list_health:
- response = self.client.get(self._url("workflow_health"), {"branch": "main"})
+ response = self.client.get(
+ self._url("workflow_health"),
+ {"branch": "main", "run_scope": "pull_request"},
+ )
assert response.status_code == status.HTTP_200_OK
assert list_health.call_args.kwargs["branch"] == "main"
+ assert list_health.call_args.kwargs["run_scope"] == "pull_request"
def test_repo_run_activity_serializes_and_forwards_branch(self) -> None:
result = contracts.WorkflowRunActivity(
@@ -386,6 +390,13 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "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"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "run_scope must be one of" in response.json()["detail"]
+
@parameterized.expand(["sources", "ci_cards", "pull_requests", "workflow_health", "pr_lifecycle", "quarantine"])
def test_requires_authentication(self, action: str) -> None:
self.client.logout()
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 452c18aa9722..e1de9c86bf3b 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -137,12 +137,12 @@ export interface WorkflowJobAggregateApi {
*/
queue_p50_seconds: number | null
/**
- * Median duration of completed job instances, in seconds. Null if none completed.
+ * Median duration of successful job instances, in seconds — cancelled and failed instances end early and would bias the percentile. Null if none succeeded.
* @nullable
*/
p50_seconds: number | null
/**
- * 95th-percentile duration of completed job instances, in seconds. Null if none completed.
+ * 95th-percentile duration of successful job instances, in seconds — cancelled and failed instances end early and would bias the percentile. Null if none succeeded.
* @nullable
*/
p95_seconds: number | null
@@ -756,12 +756,12 @@ export interface WorkflowHealthItemApi {
*/
success_rate: number | null
/**
- * Median duration of completed runs, in seconds. Null if none completed.
+ * Median duration in seconds over successful runs only — cancelled (superseded) and failed runs end early and would bias the percentile. Null if no run succeeded in the window.
* @nullable
*/
p50_seconds: number | null
/**
- * 95th-percentile duration of completed runs, in seconds. Null if none completed.
+ * 95th-percentile duration in seconds over successful runs only — cancelled (superseded) and failed runs end early and would bias the percentile. Null if no run succeeded in the window.
* @nullable
*/
p95_seconds: number | null
@@ -1096,12 +1096,24 @@ export type EngineeringAnalyticsWorkflowHealthParams = {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: 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.
+ */
+ run_scope?: EngineeringAnalyticsWorkflowHealthRunScope
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
source_id?: string
}
+export type EngineeringAnalyticsWorkflowHealthRunScope =
+ (typeof EngineeringAnalyticsWorkflowHealthRunScope)[keyof typeof EngineeringAnalyticsWorkflowHealthRunScope]
+
+export const EngineeringAnalyticsWorkflowHealthRunScope = {
+ All: 'all',
+ PullRequest: 'pull_request',
+} as const
+
export type EngineeringAnalyticsWorkflowJobsParams = {
/**
* Which re-run attempt to scope jobs to. Omit to use the run's latest attempt; pass an explicit attempt to avoid mixing jobs across a re-run's attempts.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 65d8b97f5cdf..0cc2361c9510 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -563,7 +563,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 over completed runs, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Optionally scope to a single git branch via `branch`. 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. 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.
*/
export const engineeringAnalyticsWorkflowHealth = async (
projectId: string,
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index 924b509001b5..c5c1f055e464 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -221,12 +221,17 @@ tools:
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. Rates and percentiles are over completed runs only and are null for a window with no
- completed runs; to get a trend, call this over two adjacent windows and compare.
+ and CI duration trends. 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.
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-analytics
url_prefix: /engineering-analytics/workflows
diff --git a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md
index 6714369e974c..9f07c41b58e1 100644
--- a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md
+++ b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md
@@ -26,12 +26,14 @@ autonomous agents (e.g. PostHog Code) reasoning about their own PRs.
which PRs have failing or pending CI, which are stuck open longest, per-author or per-repo triage, and
time-to-merge stats (aggregate `open_to_merge_seconds` over the returned merged rows yourself — median and p95,
never a mean).
-- **`workflow-health`** — per-workflow CI health over a window (`date_from` / `date_to`, default last 30 days):
+- **`workflow-health`** — per-workflow CI health over a window (`date_from` / `date_to`, default last 24 hours):
`run_count`, `success_rate`, `p50_seconds`, `p95_seconds`, `last_failure_at`. Answers "is CI getting faster or
slower" and "which workflow is the slow or flaky long pole". There is no built-in trend — call it over two
- adjacent windows and compare. `success_rate` / `p50_seconds` / `p95_seconds` cover completed runs only and are
- `null` when a window has no completed runs — guard for null before comparing two windows (a workflow can have
- runs in one and none in the other).
+ adjacent windows and compare. `success_rate` covers completed runs; `p50_seconds` / `p95_seconds` cover
+ successful runs only (cancelled and failed runs end early and would bias the duration trend). Each is `null`
+ when a window has no qualifying runs — guard for null before comparing two windows (a workflow can have runs
+ in one and none in the other). `run_scope=pull_request` scopes to PR-attributed runs, excluding master/main
+ (same-repo PRs only — fork runs carry no PR attribution).
- **`pr-lifecycle`** — a single PR's timeline: a header plus ordered events — opened, then a CI started/finished
pair **per workflow run** (many on a multi-workflow repo, interleaved by time), then merged/closed. Answers
"where is PR N stuck". `metric_quality` is `partial`.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a3a5843aa398..08dce455edfe 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8744,7 +8744,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. Rates and percentiles are over completed runs only and are null for a window with no completed runs; 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. 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.",
"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.json
index 0dc548fde15a..eec9b5fd39ff 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -9283,7 +9283,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. Rates and percentiles are over completed runs only and are null for a window with no completed runs; 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. 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.",
"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.ts
index 409415fc5fab..aee5415264c3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -56214,12 +56214,12 @@ export namespace Schemas {
*/
success_rate: number | null;
/**
- * Median duration of completed runs, in seconds. Null if none completed.
+ * Median duration in seconds over successful runs only — cancelled (superseded) and failed runs end early and would bias the percentile. Null if no run succeeded in the window.
* @nullable
*/
p50_seconds: number | null;
/**
- * 95th-percentile duration of completed runs, in seconds. Null if none completed.
+ * 95th-percentile duration in seconds over successful runs only — cancelled (superseded) and failed runs end early and would bias the percentile. Null if no run succeeded in the window.
* @nullable
*/
p95_seconds: number | null;
@@ -56319,12 +56319,12 @@ export namespace Schemas {
*/
queue_p50_seconds: number | null;
/**
- * Median duration of completed job instances, in seconds. Null if none completed.
+ * Median duration of successful job instances, in seconds — cancelled and failed instances end early and would bias the percentile. Null if none succeeded.
* @nullable
*/
p50_seconds: number | null;
/**
- * 95th-percentile duration of completed job instances, in seconds. Null if none completed.
+ * 95th-percentile duration of successful job instances, in seconds — cancelled and failed instances end early and would bias the percentile. Null if none succeeded.
* @nullable
*/
p95_seconds: number | null;
@@ -65400,12 +65400,24 @@ export namespace Schemas {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: 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.
+ */
+ run_scope?: EngineeringAnalyticsWorkflowHealthRunScope;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
source_id?: string;
};
+ export type EngineeringAnalyticsWorkflowHealthRunScope = typeof EngineeringAnalyticsWorkflowHealthRunScope[keyof typeof EngineeringAnalyticsWorkflowHealthRunScope];
+
+
+ export const EngineeringAnalyticsWorkflowHealthRunScope = {
+ All: 'all',
+ PullRequest: 'pull_request',
+ } as const;
+
export type EngineeringAnalyticsWorkflowJobsParams = {
/**
* Which re-run attempt to scope jobs to. Omit to use the run's latest attempt; pass an explicit attempt to avoid mixing jobs across a re-run's attempts.
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index e4fee7de52ab..457e4eef2afb 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -148,7 +148,7 @@ export const EngineeringAnalyticsSourcesParams = /* @__PURE__ */ zod.object({
})
/**
- * Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration over completed runs, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Optionally scope to a single git branch via `branch`. 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. 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.
*/
export const EngineeringAnalyticsWorkflowHealthParams = /* @__PURE__ */ zod.object({
project_id: zod
@@ -167,6 +167,12 @@ export const EngineeringAnalyticsWorkflowHealthQueryParams = /* @__PURE__ */ zod
),
date_from: zod.string().optional().describe("Window start: relative ('-24h', '-7d') or ISO8601. Defaults to -24h."),
date_to: zod.string().optional().describe('Window end: relative or ISO8601. Defaults to now.'),
+ run_scope: zod
+ .enum(['all', '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."
+ ),
source_id: zod
.string()
.optional()
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index ead0a8c5f7b4..9cecccec56f5 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -203,6 +203,9 @@ const WorkflowHealthSchema = EngineeringAnalyticsWorkflowHealthQueryParams.exten
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.'
+ ),
})
const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<Schemas.WorkflowHealthItem[]>> => ({
@@ -217,6 +220,7 @@ const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<
branch: params.branch,
date_from: params.date_from,
date_to: params.date_to,
+ run_scope: params.run_scope,
source_id: params.source_id,
},
})