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(devex): lens-stack ux overhaul for engineering analytics (#67764)

Julian Bezeed0591cca62
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 7d0030aff313..522c93bbc23e 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -114,8 +114,6 @@ export const productScenes: Record<string, () => Promise<any>> = {
import('../../products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene'),
EngineeringAnalyticsWorkflowRuns: () =>
import('../../products/engineering_analytics/frontend/scenes/WorkflowRunsScene'),
- EngineeringAnalyticsAuthor: () =>
- import('../../products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene'),
ErrorTracking: () => import('../../products/error_tracking/frontend/scenes/ErrorTrackingScene/ErrorTrackingScene'),
ErrorTrackingIssue: () =>
import('../../products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene'),
@@ -245,6 +243,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/endpoints': ['EndpointsScene', 'endpoints'],
'/endpoints/:name': ['EndpointScene', 'endpoint'],
'/engineering-analytics': ['EngineeringAnalytics', 'engineeringAnalytics'],
+ '/engineering-analytics/pulls': ['EngineeringAnalytics', 'engineeringAnalyticsPullRequestList'],
'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],
'/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],
'/engineering-analytics/:repoOwner/:repoName/pull/:number': [
@@ -259,7 +258,6 @@ export const productRoutes: Record<string, [string, string]> = {
'EngineeringAnalyticsWorkflowRuns',
'engineeringAnalyticsWorkflowRuns',
],
- '/engineering-analytics/author/:handle': ['EngineeringAnalyticsAuthor', 'engineeringAnalyticsAuthor'],
'/error_tracking': ['ErrorTracking', 'errorTracking'],
'/error_tracking/:id': ['ErrorTrackingIssue', 'errorTrackingIssue'],
'/error_tracking/:id/fingerprints': ['ErrorTrackingIssueFingerprints', 'errorTrackingIssueFingerprints'],
@@ -454,6 +452,8 @@ export const productRedirects: Record<
},
'/data-warehouse/sources/:id': ({ id }) => urls.dataWarehouseSource(id, 'schemas'),
'/data-warehouse/sources/:id/:tab': ({ id, tab }) => urls.dataWarehouseSource(id, tab as SourceSceneTab),
+ '/engineering-analytics/authors': '/engineering-analytics',
+ '/engineering-analytics/author/:handle': '/engineering-analytics',
'/error_tracking/configuration': (_params, searchParams, hashParams) => {
const { tab, ...restSearchParams } = searchParams
return combineUrl(
@@ -692,13 +692,6 @@ export const productConfiguration: Record<string, any> = {
description: "A single workflow's recent runs across the connected repo.",
iconType: 'health',
},
- EngineeringAnalyticsAuthor: {
- projectBased: true,
- name: 'Author CI',
- layout: 'app-container',
- description: "One author's pull requests and the CI cost they incurred.",
- iconType: 'health',
- },
ErrorTracking: {
projectBased: true,
name: 'Error tracking',
@@ -1084,6 +1077,7 @@ export const productUrls = {
return combineUrl('/endpoints', { tab: 'usage', ...searchParams }).url
},
engineeringAnalytics: (): string => '/engineering-analytics',
+ engineeringAnalyticsPullRequestList: (): string => '/engineering-analytics/pulls',
engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',
engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',
engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>
@@ -1092,8 +1086,6 @@ export const productUrls = {
`/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/runs/${runId}`,
engineeringAnalyticsWorkflowRuns: (repoOwner: string, repoName: string, workflowName: string): string =>
`/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/workflows/${encodeURIComponent(workflowName)}`,
- engineeringAnalyticsAuthor: (handle: string): string =>
- `/engineering-analytics/author/${encodeURIComponent(handle)}`,
errorTracking: (params = {}): string => combineUrl('/error_tracking', params).url,
errorTrackingConfiguration: (params = {}): string =>
combineUrl('/error_tracking', { ...params, activeTab: 'configuration' }).url,
@@ -1819,7 +1811,6 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
'EngineeringAnalyticsPullRequest',
'EngineeringAnalyticsWorkflowRun',
'EngineeringAnalyticsWorkflowRuns',
- 'EngineeringAnalyticsAuthor',
],
},
{
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 32ced233e5e5..68b6c9d32f54 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -147,6 +147,7 @@ SCENE_TO_TAGS: dict[str, FallbackTags | None] = {
"Cohort": {"product": Product.COHORTS, "feature": Feature.COHORT},
"EndpointScene": {"product": Product.ENDPOINTS, "feature": Feature.QUERY},
"EndpointsScene": {"product": Product.ENDPOINTS, "feature": Feature.QUERY},
+ "EngineeringAnalytics": {"product": Product.ENGINEERING_ANALYTICS, "feature": Feature.QUERY},
"Logs": {"product": Product.LOGS, "feature": Feature.QUERY},
"Metrics": {"product": Product.METRICS, "feature": Feature.QUERY},
"EventDefinition": {"product": Product.PRODUCT_ANALYTICS, "feature": Feature.EVENT_DEFINITION_SCENE},
diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.md
index 058c0ad1adb1..6cd6d8c8ae1c 100644
--- a/products/engineering_analytics/README.md
+++ b/products/engineering_analytics/README.md
@@ -19,7 +19,7 @@ If you understand PostHog product analytics, you understand this. Map it one-to-
| "How long from signup to purchase?" | "How long from opened to merged?" |
| "What % of signups convert?" (funnel) | "What % of PRs make it to prod?" (funnel) |
| "Is conversion getting better?" (trend) | "Is CI getting faster?" (trend) |
-| Segment by country, plan, browser | Segment by repo, author, file path |
+| Segment by country, plan, browser | Segment by repo, workflow, file path |
Same product, different noun.
@@ -145,6 +145,7 @@ Change one only in a separate PR with a written reason. Engineering-level decisi
- UI = read-only analytics surface on the **same** endpoints (PR list, CI health, workflow health) — a real read surface, not only a design-system showcase. No saved views or stateful filters in this phase; persisted/stateful surfaces are a later, separate decision.
- v1 data path = HogQL on warehouse. Event ingestion deferred. Product Postgres DB stays empty.
- Author identity = `Author{handle, display_name, avatar_url, is_bot}`. No PostHog-user mapping in v1.
+- **Analytics aggregate at team/repo level only.** Author is display metadata on a PR — attribution, never a unit of analysis. No author-level pages, tabs, leaderboards, rankings, or per-author cost, ever. This is a non-goal (per-developer surveillance), not a deferred feature.
- Bots and drafts excluded by default in throughput / cycle-time tools; bots are first-class in bot-impact analysis (don't strip them everywhere).
- Bot detection = `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist for v1.
- Time to merge v1 = the read layer's `open_to_merge_seconds` column = `merged_at - created_at` (draft + ready-for-review combined). Coarse — encoded in the column name, never named cycle/review time.
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 2c61c20717ac..b0de206a547e 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -11,7 +11,7 @@ The **goal** is to surface these as **Signals** for PostHog Code: valuable CI co
## 2. Non-goals
-- Per-developer surveillance metrics or rankings. Filters operate at cohort level by default.
+- Per-developer surveillance metrics or rankings. Analytics aggregate at team/repo level only; author is display metadata on a PR (attribution), never a unit of analysis. No author-level pages, tabs, leaderboards, rankings, or per-author cost, ever.
- Real-time alerting on individual PRs. That's notification surface, not analytics.
- Replacing GitHub's own UI. We surface signal, not the raw PR thread.
- Code-quality static analysis. Different product space.
@@ -184,6 +184,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- Cardinality: a run ↔ PR is **0..N** (push-only runs and fork PRs have no association; one commit can head several PRs). Treat pr_number attribution as a possibly-empty, possibly-multi set, never a guaranteed single value. v1 credits a run to the **first** PR in its association (see `pr_runs`).
- **The Logs surface inherits this.** Emitted CI failure logs carry `attributes['run_id']` (plus `job_id` / `branch` / `conclusion`); `ci_failure_logs` resolves a PR to its run_ids through the same `pull_requests` attribution (reusing `pr_runs`), then filters the Logs product by `run_id` — no head-SHA join, no merge SHA, all pushes captured. Fork PRs (no association) degrade to a run_id / branch lookup.
- **Warehouse columns are strings + Nullable JSON; the builders parse and `ifNull`-guard.** The real GitHub source lands timestamps as strings and the nested objects (`user`/`head`/`base`/`labels`/`repository`/`pull_requests`) as Nullable. Curated builders therefore parse every timestamp with HogQL `parseDateTimeBestEffort` (which maps to ClickHouse `parseDateTime64BestEffortOrNull` — that raw CH name is not exposed in HogQL) and `ifNull`-unwrap any Nullable column before an array function (`JSONExtractArrayRaw` / `splitByChar`), because ClickHouse rejects an Array nested inside a Nullable. `source_schema.py` mirrors these exact types so the seed and tests exercise the real path — violating this contract 500'd every endpoint on real data while idealized-fixture tests stayed green.
+- **Analytics aggregate at team/repo level only — no author-level surface, ever.** _(Changed — reason:)_ the v1 UI grew an authors tab, author list/detail pages, hub leaderboards, and an `author_workflow_costs` endpoint; all were removed. Per-author aggregation is per-developer surveillance (§2), and every such surface invites ranking people. Author stays on the `PullRequest` contract as display metadata (attribution on a PR row) and as a list _filter_ for finding work — never as an aggregation level, a page, or a cost rollup. Don't re-add an author-scoped aggregate endpoint or UI surface.
- **Bot detection** defined once in the read layer: `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist for v1; per-team config deferred.
- **Bots and drafts excluded by default** in throughput / cycle-time recipes (an explicit column flag + a default filter the skill applies). First-class in any future bot-impact analysis — don't strip them at the substrate.
- **Time to merge v1** = `open_to_merge_seconds` = `merged_at - created_at`, coarse (combines draft + ready-for-review time). The precise companion lands with state-transition data.
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 977eb556c852..acb332e7cb46 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -26,14 +26,18 @@ from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
CIFailureLogs,
GitHubSource,
+ MasterFailureGroup,
PRCostSummary,
PRLifecycle,
PullRequestList,
QuarantineFile,
QuarantineRequest,
QuarantineRequestResult,
+ RepoOverview,
+ RunFailureLogs,
WorkflowHealthItem,
WorkflowJob,
+ WorkflowJobAggregate,
WorkflowRunActivity,
WorkflowRunDetail,
WorkflowRunnerCost,
@@ -254,3 +258,64 @@ def request_quarantine(
user_access_control: "UserAccessControl | None" = None,
) -> QuarantineRequestResult:
return logic.request_quarantine(team=team, request=request, user_access_control=user_access_control)
+
+
+def get_repo_overview(
+ *,
+ team: Team,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> RepoOverview:
+ return logic.build_repo_overview(
+ curated=_authorized_source(team, source_id, user_access_control),
+ date_from=date_from,
+ date_to=date_to,
+ )
+
+
+def list_master_failures(
+ *,
+ team: Team,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ branch: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> list[MasterFailureGroup]:
+ return logic.build_master_failures(
+ curated=_authorized_source(team, source_id, user_access_control),
+ date_from=date_from,
+ date_to=date_to,
+ branch=branch,
+ )
+
+
+def get_run_failure_logs(
+ *,
+ team: Team,
+ run_id: int,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> RunFailureLogs:
+ return logic.build_run_failure_logs(curated=_authorized_source(team, source_id, user_access_control), run_id=run_id)
+
+
+def list_job_aggregates(
+ *,
+ team: Team,
+ workflow_name: str,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ branch: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> list[WorkflowJobAggregate]:
+ return logic.build_job_aggregates(
+ curated=_authorized_source(team, source_id, user_access_control),
+ workflow_name=workflow_name,
+ date_from=date_from,
+ date_to=date_to,
+ branch=branch,
+ )
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 4547720f5bd4..e7578ac209a5 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -21,6 +21,7 @@ read layer maps them into these types. Reviewers, deploys, and file paths are
intentionally absent until the warehouse data that backs them lands.
"""
+from dataclasses import field
from datetime import date, datetime
from enum import StrEnum
@@ -433,6 +434,8 @@ class CIStatusRollup:
passing: int
failing: int
pending: int
+ # The workflow names behind `failing`, sorted — what the UI names under the CI tag.
+ failing_workflows: list[str] = field(default_factory=list)
@dataclass(frozen=True)
@@ -611,3 +614,90 @@ class WorkflowHealthItem:
# the job-level source isn't synced (run-level health alone carries no runner tier).
billable_minutes: float | None = None
estimated_cost_usd: float | None = None
+ # Runs in the window that were a 2nd+ attempt.
+ rerun_cycles: int = 0
+ # Success rate over the equal-length window before date_from; None when it had no completed runs.
+ success_rate_prev: float | None = None
+
+
+@dataclass(frozen=True)
+class RepoOverview:
+ """Repo-level headline aggregates for the landing page, each with its previous-window twin
+ so the UI renders honest deltas. The previous window has the same length as the current one
+ and ends where it starts. Cost figures are None when the job-level source isn't synced
+ (``jobs_available``); the PR merge median excludes bots and drafts per the locked recipe.
+ """
+
+ run_count: int
+ run_count_prev: int
+ success_rate: float | None
+ success_rate_prev: float | None
+ rerun_cycles: int
+ rerun_cycles_prev: int
+ # Coarse by design: merged_at - created_at (draft + ready time fused), median over PRs merged in the window.
+ median_open_to_merge_seconds: float | None
+ median_open_to_merge_seconds_prev: float | None
+ billable_minutes: float | None
+ billable_minutes_prev: float | None
+ estimated_cost_usd: float | None
+ estimated_cost_usd_prev: float | None
+ jobs_available: bool
+ # 'master' or 'main', picked by observed run volume in the current window.
+ default_branch: str
+
+
+@dataclass(frozen=True)
+class MasterFailureGroup:
+ """One group of default-branch failures: a (workflow, de-sharded failing job) signature with
+ its run count and first/last seen — the error-tracking-style triage row. ``failed_job`` is ''
+ when the job-level source isn't synced and the group degrades to workflow level.
+ """
+
+ repo: RepoRef
+ workflow_name: str
+ failed_job: str
+ run_count: int
+ first_seen: datetime
+ last_seen: datetime
+ # The most recent failing run in the group — the drill-down anchor.
+ latest_run_id: int
+
+
+@dataclass(frozen=True)
+class RunFailureLogs:
+ """Thinned CI failure logs for a single workflow run, grouped by failed job. Same log substrate
+ as ``CIFailureLogs`` but keyed directly by run id, for surfaces that aren't PR-scoped (the
+ default-branch failures feed and the run page). ``logs_available`` is False when no failure-log
+ records exist for the run — it didn't fail, or the logs aged out of the short Logs retention.
+ """
+
+ run_id: int
+ logs_available: bool
+ jobs: list[CIJobFailureLog]
+ truncated: bool
+
+
+@dataclass(frozen=True)
+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."""
+
+ job_name: str
+ # Job instances observed in the window (all shards, all attempts).
+ job_count: int
+ # Distinct raw job names inside the group — the observed matrix width.
+ shard_count: int
+ # Distinct workflow runs the job appeared in.
+ runs_in: int
+ # runs_in / the workflow's total runs in the window — below 1.0 means the job is conditional.
+ run_share: float | None
+ queue_p50_seconds: float | None
+ p50_seconds: float | None
+ p95_seconds: float | None
+ failure_rate: float | None
+ # Job instances that ran on a 2nd+ run attempt.
+ retry_job_count: int
+ billable_minutes: float | None
+ estimated_cost_usd: float | None
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index 2ca6f3f9eeaf..bcde691abd8d 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -17,11 +17,15 @@ from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
CIFailureLogs,
GitHubSource,
+ MasterFailureGroup,
PRCostSummary,
PRLifecycle,
PullRequestList,
+ RepoOverview,
+ RunFailureLogs,
WorkflowHealthItem,
WorkflowJob,
+ WorkflowJobAggregate,
WorkflowRunActivity,
WorkflowRunDetail,
WorkflowRunnerCost,
@@ -32,11 +36,17 @@ from products.engineering_analytics.backend.logic.quarantine import (
)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries.ci_cards import query_ci_cards
-from products.engineering_analytics.backend.logic.queries.ci_failure_logs import query_ci_failure_logs
+from products.engineering_analytics.backend.logic.queries.ci_failure_logs import (
+ query_ci_failure_logs,
+ query_run_failure_logs,
+)
+from products.engineering_analytics.backend.logic.queries.job_aggregates import query_job_aggregates
+from products.engineering_analytics.backend.logic.queries.master_failures import query_master_failures
from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_cost, query_workflow_runner_costs
from products.engineering_analytics.backend.logic.queries.pr_lifecycle import query_pr_lifecycle
from products.engineering_analytics.backend.logic.queries.pr_runs import query_pr_runs
from products.engineering_analytics.backend.logic.queries.pull_request_list import query_pull_request_list
+from products.engineering_analytics.backend.logic.queries.repo_overview import query_default_branch, query_repo_overview
from products.engineering_analytics.backend.logic.queries.workflow_health import query_workflow_health
from products.engineering_analytics.backend.logic.queries.workflow_jobs import query_workflow_jobs
from products.engineering_analytics.backend.logic.queries.workflow_run import query_workflow_run
@@ -113,8 +123,7 @@ def build_workflow_run_list(
owner, name = _split_repo(repo)
if not (owner and name):
raise ValueError("repo must be in 'owner/name' format")
- parsed_from = _parse_date(curated.team, date_from or _DEFAULT_WINDOW)
- parsed_to = _parse_date(curated.team, date_to) if date_to else None
+ parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)
return query_workflow_run_list(
curated=curated,
repo_owner=owner,
@@ -138,8 +147,7 @@ def build_workflow_run_activity(
owner, name = _split_repo(repo)
if not (owner and name):
raise ValueError("repo must be in 'owner/name' format")
- parsed_from = _parse_date(curated.team, date_from or _DEFAULT_WINDOW)
- parsed_to = _parse_date(curated.team, date_to) if date_to else None
+ parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)
return query_workflow_run_activity(
curated=curated,
repo_owner=owner,
@@ -163,8 +171,7 @@ def build_workflow_runner_costs(
owner, name = _split_repo(repo)
if not (owner and name):
raise ValueError("repo must be in 'owner/name' format")
- parsed_from = _parse_date(curated.team, date_from or _DEFAULT_WINDOW)
- parsed_to = _parse_date(curated.team, date_to) if date_to else None
+ parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)
return query_workflow_runner_costs(
curated=curated,
repo_owner=owner,
@@ -200,11 +207,7 @@ def build_workflow_health(
date_to: str | None = None,
branch: str | None = None,
) -> list[WorkflowHealthItem]:
- parsed_from = _parse_date(curated.team, date_from or _DEFAULT_WORKFLOW_WINDOW)
- parsed_to = _parse_date(curated.team, date_to) if date_to else None
- span_days = ((parsed_to or datetime.now(tz=parsed_from.tzinfo)) - parsed_from).days
- if span_days > _MAX_WINDOW_DAYS:
- raise ValueError(f"date window spans {span_days} days; the maximum is {_MAX_WINDOW_DAYS}")
+ 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)
@@ -212,6 +215,18 @@ def _parse_date(team: Team, value: str) -> datetime:
return relative_date_parse(value, team.timezone_info)
+def _parse_window(
+ team: Team, date_from: str | None, date_to: str | None, *, default: str
+) -> tuple[datetime, datetime | None]:
+ """Resolve a caller's date window against the team timezone, capping the span at _MAX_WINDOW_DAYS."""
+ parsed_from = _parse_date(team, date_from or default)
+ parsed_to = _parse_date(team, date_to) if date_to else None
+ span_days = ((parsed_to or datetime.now(tz=parsed_from.tzinfo)) - parsed_from).days
+ if span_days > _MAX_WINDOW_DAYS:
+ raise ValueError(f"date window spans {span_days} days; the maximum is {_MAX_WINDOW_DAYS}")
+ return parsed_from, parsed_to
+
+
def _split_repo(repo: str | None) -> tuple[str | None, str | None]:
if not repo:
return None, None
@@ -221,3 +236,46 @@ def _split_repo(repo: str | None) -> tuple[str | None, str | None]:
if not (owner and name):
raise ValueError(f"repo must be in 'owner/name' format, got: {repo!r}")
return owner, name
+
+
+def build_repo_overview(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: str | None = None,
+ date_to: str | None = None,
+) -> RepoOverview:
+ parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)
+ return query_repo_overview(curated=curated, date_from=parsed_from, date_to=parsed_to)
+
+
+def build_master_failures(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ branch: str | None = None,
+) -> list[MasterFailureGroup]:
+ parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WORKFLOW_WINDOW)
+ resolved_branch = (branch or "").strip()
+ if not resolved_branch:
+ # No branch given: use the repo's default branch as observed in the window.
+ resolved_branch = query_default_branch(curated=curated, date_from=parsed_from, date_to=parsed_to)
+ return query_master_failures(curated=curated, date_from=parsed_from, date_to=parsed_to, branch=resolved_branch)
+
+
+def build_run_failure_logs(*, curated: CuratedGitHubSource, run_id: int) -> RunFailureLogs:
+ return query_run_failure_logs(curated=curated, run_id=run_id)
+
+
+def build_job_aggregates(
+ *,
+ curated: CuratedGitHubSource,
+ workflow_name: str,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ branch: 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
+ )
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 7a60d1edda3d..0b98b5a0bff6 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -13,6 +13,7 @@ flow through ``ast.Constant`` placeholders in the calling query, never be string
into these fragments.
"""
+import math
from typing import TYPE_CHECKING
from posthog.schema import HogQLQueryResponse
@@ -102,7 +103,10 @@ class CuratedGitHubSource:
countIf(s = 'completed' AND c IN ('failure', 'timed_out')) AS failing,
-- s IS NULL: run_started_at parses to NULL on a bad/missing timestamp, and argMax
-- over an all-NULL group returns NULL — count those as pending, not vanished.
- countIf(s IS NULL OR s != 'completed') AS pending
+ countIf(s IS NULL OR s != 'completed') AS pending,
+ -- The names behind `failing`, sorted for a stable order — the UI shows what is
+ -- failing under the CI tag instead of a bare count.
+ arraySort(groupArrayIf(workflow_name, s = 'completed' AND c IN ('failure', 'timed_out'))) AS failing_workflows
FROM (
SELECT
head_sha,
@@ -205,3 +209,10 @@ class CuratedGitHubSource:
# strip the tables — bypass is set ONLY in this genuinely userless case.
bypass_warehouse_access_control=uac is None,
)
+
+
+def opt_float(value: float | None) -> float | None:
+ """ClickHouse aggregate → optional float: quantile/avg over an empty set returns NaN, nullIf None."""
+ if value is None or (isinstance(value, float) and math.isnan(value)):
+ return None
+ return float(value)
diff --git a/products/engineering_analytics/backend/logic/queries/ci_failure_logs.py b/products/engineering_analytics/backend/logic/queries/ci_failure_logs.py
index 173301777057..4d7776c26686 100644
--- a/products/engineering_analytics/backend/logic/queries/ci_failure_logs.py
+++ b/products/engineering_analytics/backend/logic/queries/ci_failure_logs.py
@@ -24,6 +24,7 @@ from products.engineering_analytics.backend.facade.contracts import (
CIFailureLogs,
CIJobFailureLog,
RepoRef,
+ RunFailureLogs,
)
from products.engineering_analytics.backend.logic.job_logs.constants import CI_LOGS_SERVICE_NAME as _SERVICE_NAME
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
@@ -132,3 +133,43 @@ def query_ci_failure_logs(
jobs=jobs,
truncated=overall_truncated,
)
+
+
+# Existence probe for the source-authorization check below.
+_RUN_IN_SOURCE = """
+ SELECT 1
+ FROM __RUNS_SOURCE__ AS r
+ WHERE id = {run_id}
+ LIMIT 1
+"""
+
+
+def query_run_failure_logs(*, curated: CuratedGitHubSource, run_id: int) -> RunFailureLogs:
+ """Same log substrate as ``query_ci_failure_logs``, keyed directly by one run id — for surfaces
+ that aren't PR-scoped (the default-branch failures feed and the run page)."""
+ # The Logs table is team-scoped, not source-scoped — prove the run exists in the caller's
+ # authorized source before reading its logs, or a known run id would leak another source's logs.
+ in_source = curated.run(
+ _RUN_IN_SOURCE.replace("__RUNS_SOURCE__", curated.run_source()),
+ query_type="engineering_analytics.run_failure_logs_source_check",
+ placeholders={"run_id": ast.Constant(value=run_id)},
+ )
+ if not in_source.results:
+ return RunFailureLogs(run_id=run_id, logs_available=False, jobs=[], truncated=False)
+
+ response = curated.run(
+ _SELECT,
+ query_type="engineering_analytics.run_failure_logs",
+ placeholders={
+ "service_name": ast.Constant(value=_SERVICE_NAME),
+ "run_ids": ast.Constant(value=[str(run_id)]),
+ "line_cap": ast.Constant(value=_LINE_CAP + 1),
+ },
+ workload=Workload.LOGS,
+ )
+ rows = response.results or []
+ overall_truncated = len(rows) > _LINE_CAP
+ jobs = _group_jobs(rows[:_LINE_CAP])
+ if overall_truncated and jobs:
+ jobs[-1] = dataclasses.replace(jobs[-1], truncated=True)
+ return RunFailureLogs(run_id=run_id, logs_available=bool(rows), jobs=jobs, truncated=overall_truncated)
diff --git a/products/engineering_analytics/backend/logic/queries/job_aggregates.py b/products/engineering_analytics/backend/logic/queries/job_aggregates.py
new file mode 100644
index 000000000000..c03711603350
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/job_aggregates.py
@@ -0,0 +1,157 @@
+"""Curated query: per-job aggregates for one workflow over a window.
+
+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,
+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
+denominator comes from a cheap runs count.
+
+Unexpanded ``${{ matrix.* }}`` template names (skipped matrices) are collapsed for
+grouping the same way the frontend does.
+"""
+
+from datetime import datetime
+
+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.pr_cost import _parse_labels
+
+_LIMIT = 200
+
+# De-shard + de-template in SQL so grouping happens server-side over millions of job rows.
+# Mirrors jobGroups.stripShardSuffix / collapseTemplates on the frontend and
+# master_failures.strip_shard_suffix in Python — keep the three in sync.
+_JOB_NAME = (
+ "replaceRegexpOne(replaceRegexpAll(name, '\\\\$\\\\{\\\\{[^}]*\\\\}\\\\}', '…'),"
+ " '\\\\s*\\\\((\\\\d+)/(\\\\d+)\\\\)(\\\\))?$', '\\\\3')"
+)
+
+_AGGREGATE_SELECT = f"""
+ SELECT
+ {_JOB_NAME} AS job_name,
+ count() AS job_count,
+ 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,
+ 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
+ WHERE workflow_name = {{workflow_name}} AND created_at >= {{date_from}} __DATE_TO__ __BRANCH__
+ GROUP BY job_name
+ ORDER BY job_count DESC
+ LIMIT {_LIMIT}
+"""
+
+_COST_SELECT = f"""
+ SELECT
+ {_JOB_NAME} AS job_name,
+ labels,
+ sumIf(greatest(duration_seconds, 0), duration_seconds IS NOT NULL) AS elapsed_seconds,
+ countIf(duration_seconds IS NOT NULL) AS settled_jobs
+ FROM __JOBS_SOURCE__ AS j
+ WHERE workflow_name = {{workflow_name}} AND created_at >= {{date_from}} __DATE_TO__ __BRANCH__
+ GROUP BY job_name, labels
+"""
+
+_RUN_COUNT_SELECT = """
+ SELECT count() AS total_runs
+ FROM __RUNS_SOURCE__ AS r
+ WHERE workflow_name = {workflow_name} AND run_started_at >= {date_from} __RUNS_DATE_TO__ __RUNS_BRANCH__
+"""
+
+
+def query_job_aggregates(
+ *,
+ curated: CuratedGitHubSource,
+ workflow_name: str,
+ date_from: datetime,
+ date_to: datetime | None,
+ branch: str | None,
+) -> list[WorkflowJobAggregate]:
+ jobs_source = curated.jobs_source()
+ if jobs_source is None:
+ return []
+
+ branch = branch.strip() if branch else None
+ placeholders: dict[str, ast.Expr] = {
+ "workflow_name": ast.Constant(value=workflow_name),
+ "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)
+
+ def fill(template: str) -> str:
+ return (
+ template.replace("__JOBS_SOURCE__", jobs_source)
+ .replace("__RUNS_SOURCE__", curated.run_source())
+ .replace("__DATE_TO__", "AND created_at <= {date_to}" if date_to is not None else "")
+ .replace("__RUNS_DATE_TO__", "AND run_started_at <= {date_to}" if date_to is not None else "")
+ .replace("__BRANCH__", "AND head_branch = {branch}" if branch else "")
+ .replace("__RUNS_BRANCH__", "AND head_branch = {branch}" if branch else "")
+ )
+
+ response = curated.run(
+ fill(_AGGREGATE_SELECT), query_type="engineering_analytics.job_aggregates", placeholders=placeholders
+ )
+ if not response.results:
+ return []
+
+ run_count_response = curated.run(
+ fill(_RUN_COUNT_SELECT), query_type="engineering_analytics.job_aggregates_runs", placeholders=placeholders
+ )
+ total_runs = run_count_response.results[0][0] if run_count_response.results else 0
+
+ # Billable cost per job name, folded over its (labels) groups via the shared cost model.
+ cost_response = curated.run(
+ fill(_COST_SELECT), query_type="engineering_analytics.job_aggregates_cost", placeholders=placeholders
+ )
+ billable_by_job: dict[str, tuple[float, float]] = {}
+ for job_name, labels_raw, elapsed_seconds, settled_jobs in cost_response.results or []:
+ # An all-unsettled group (every instance still queued/running) sums to 0 elapsed — pass None
+ # so its cost stays unknown instead of billing a not-yet-finished job as $0.
+ elapsed = float(elapsed_seconds or 0.0) if settled_jobs else None
+ cost = estimate_job_cost_usd(_parse_labels(labels_raw), elapsed)
+ if cost is None:
+ continue
+ seconds, usd = billable_by_job.get(job_name, (0.0, 0.0))
+ billable_by_job[job_name] = (seconds + (elapsed or 0.0), usd + cost)
+
+ items: list[WorkflowJobAggregate] = []
+ for (
+ job_name,
+ job_count,
+ shard_count,
+ runs_in,
+ queue_p50_seconds,
+ p50_seconds,
+ p95_seconds,
+ failure_rate,
+ retry_job_count,
+ ) in response.results:
+ billable = billable_by_job.get(job_name)
+ items.append(
+ WorkflowJobAggregate(
+ job_name=job_name,
+ job_count=job_count,
+ shard_count=shard_count,
+ runs_in=runs_in,
+ run_share=(runs_in / total_runs) if total_runs else None,
+ queue_p50_seconds=opt_float(queue_p50_seconds),
+ p50_seconds=opt_float(p50_seconds),
+ p95_seconds=opt_float(p95_seconds),
+ failure_rate=opt_float(failure_rate),
+ retry_job_count=retry_job_count,
+ billable_minutes=billable[0] / 60 if billable else None,
+ estimated_cost_usd=billable[1] if billable else None,
+ )
+ )
+ return items
diff --git a/products/engineering_analytics/backend/logic/queries/master_failures.py b/products/engineering_analytics/backend/logic/queries/master_failures.py
new file mode 100644
index 000000000000..86cc74ee451a
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/master_failures.py
@@ -0,0 +1,123 @@
+"""Curated query: default-branch failures grouped by workflow + failing job.
+
+At this repo's volume a flat failure feed is a firehose (thousands of failing runs a
+day across all branches), so the triage view groups instead — error-tracking style:
+one row per (workflow, de-sharded failing job name) on the default branch, with a run
+count and first/last seen. PR-branch failures are deliberately out of scope here; they
+surface on their PR pages.
+
+Two-step like the failure-logs query: fetch the window's failed default-branch runs
+first (small — the branch filter does the heavy lifting), then their failed jobs by
+``run_id IN``, then group in Python where the shard-stripping regex lives.
+"""
+
+import re
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.facade.contracts import MasterFailureGroup, RepoRef
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+
+# Failed default-branch runs in the window is a triage view, not an archive — cap it.
+_RUN_CAP = 500
+
+_FAILED_RUNS_SELECT = f"""
+ SELECT id, repo_owner, repo_name, workflow_name, run_started_at
+ FROM __RUNS_SOURCE__ AS r
+ WHERE run_started_at >= {{date_from}} __DATE_TO__
+ AND head_branch = {{branch}}
+ AND status = 'completed' AND conclusion IN ('failure', 'timed_out')
+ ORDER BY run_started_at DESC
+ LIMIT {_RUN_CAP}
+"""
+
+_FAILED_JOBS_SELECT = """
+ SELECT run_id, name
+ FROM __JOBS_SOURCE__ AS j
+ WHERE run_id IN {run_ids} AND conclusion IN ('failure', 'timed_out')
+"""
+
+# Trailing "(G/N)" shard suffix, incl. nested parens ("Product tests (experiments (1/2))") —
+# same rule as the frontend's jobGroups.stripShardSuffix, so both sides group identically.
+_SHARD_SUFFIX = re.compile(r"\s*\((\d+)/(\d+)\)(\))?$")
+
+
+def strip_shard_suffix(name: str) -> str:
+ return _SHARD_SUFFIX.sub(lambda m: ")" if m.group(3) else "", name)
+
+
+def query_master_failures(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+ branch: str,
+) -> list[MasterFailureGroup]:
+ date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""
+ placeholders: dict[str, ast.Expr] = {
+ "date_from": ast.Constant(value=date_from),
+ "branch": ast.Constant(value=branch),
+ }
+ if date_to is not None:
+ placeholders["date_to"] = ast.Constant(value=date_to)
+
+ runs_response = curated.run(
+ _FAILED_RUNS_SELECT.replace("__RUNS_SOURCE__", curated.run_source()).replace("__DATE_TO__", date_to_clause),
+ query_type="engineering_analytics.master_failures_runs",
+ placeholders=placeholders,
+ )
+ runs = runs_response.results or []
+ if not runs:
+ return []
+
+ # Failed job names per run — empty when the jobs source isn't synced, in which case
+ # groups degrade to workflow-level (failed_job = '').
+ jobs_by_run: dict[int, list[str]] = {}
+ jobs_source = curated.jobs_source()
+ if jobs_source is not None:
+ jobs_response = curated.run(
+ _FAILED_JOBS_SELECT.replace("__JOBS_SOURCE__", jobs_source),
+ query_type="engineering_analytics.master_failures_jobs",
+ placeholders={"run_ids": ast.Constant(value=[run_id for run_id, *_ in runs])},
+ )
+ for run_id, job_name in jobs_response.results or []:
+ jobs_by_run.setdefault(run_id, []).append(job_name)
+
+ groups: dict[tuple[str, str, str, str], dict] = {}
+ for run_id, repo_owner, repo_name, workflow_name, run_started_at in runs:
+ failed_jobs = {strip_shard_suffix(name) for name in jobs_by_run.get(run_id, [])} or {""}
+ for failed_job in failed_jobs:
+ key = (repo_owner, repo_name, workflow_name, failed_job)
+ group = groups.setdefault(
+ key,
+ {
+ "run_ids": set(),
+ "first_seen": run_started_at,
+ "last_seen": run_started_at,
+ "latest_run_id": run_id,
+ },
+ )
+ group["run_ids"].add(run_id)
+ if run_started_at < group["first_seen"]:
+ group["first_seen"] = run_started_at
+ if run_started_at > group["last_seen"]:
+ group["last_seen"] = run_started_at
+ group["latest_run_id"] = run_id
+
+ return sorted(
+ (
+ MasterFailureGroup(
+ repo=RepoRef(provider="github", owner=repo_owner, name=repo_name),
+ workflow_name=workflow_name,
+ failed_job=failed_job,
+ run_count=len(group["run_ids"]),
+ first_seen=group["first_seen"],
+ last_seen=group["last_seen"],
+ latest_run_id=group["latest_run_id"],
+ )
+ for (repo_owner, repo_name, workflow_name, failed_job), group in groups.items()
+ ),
+ key=lambda g: g.last_seen,
+ reverse=True,
+ )
diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.py
index 10648ea1bab8..20b712b80509 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py
@@ -205,6 +205,78 @@ def query_workflow_window_costs(
return {workflow: aggregate_pr_cost(jobs) for workflow, jobs in by_workflow.items()}
+# The window-cost shape twice over — the current window and the equal-length one before it — as
+# per-window conditional aggregates on one jobs⋈runs scan, so the repo hub's delta doesn't pay the
+# (largest-table) join twice. Window predicates mirror the two separate calls exactly.
+_WINDOW_COST_WITH_PREV_SELECT = """
+ SELECT
+ r.workflow_name, j.labels,
+ countIf(j.duration_seconds IS NOT NULL AND __CUR__) AS finished,
+ sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL AND __CUR__) AS elapsed,
+ countIf(j.duration_seconds IS NULL AND __CUR__) AS unfinished,
+ countIf(j.duration_seconds IS NOT NULL AND __PREV__) AS finished_prev,
+ sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL AND __PREV__) AS elapsed_prev,
+ countIf(j.duration_seconds IS NULL AND __PREV__) AS unfinished_prev
+ 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 >= {prev_from} __DATE_TO__
+ GROUP BY r.workflow_name, j.labels
+ LIMIT 1000000
+"""
+
+
+def query_workflow_window_costs_with_prev(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+ prev_from: datetime,
+) -> tuple[dict[str, PRCostAggregate], dict[str, PRCostAggregate]]:
+ """``query_workflow_window_costs`` for [date_from, date_to] and [prev_from, date_from] in one scan.
+
+ Returns ``(current, previous)``, both keyed by workflow_name; empty when the jobs source isn't synced.
+ """
+ jobs_source = curated.jobs_source()
+ if jobs_source is None:
+ return {}, {}
+ placeholders: dict[str, ast.Expr] = {
+ "date_from": ast.Constant(value=date_from),
+ "prev_from": ast.Constant(value=prev_from),
+ }
+ cur = "(r.run_started_at >= {date_from}" + (" AND r.run_started_at <= {date_to})" if date_to else ")")
+ prev = "(r.run_started_at >= {prev_from} AND r.run_started_at <= {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)
+ sql = (
+ _WINDOW_COST_WITH_PREV_SELECT.replace("__JOBS_SOURCE__", jobs_source)
+ .replace("__RUNS_SOURCE__", curated.run_source())
+ .replace("__CUR__", cur)
+ .replace("__PREV__", prev)
+ .replace("__DATE_TO__", date_to_clause)
+ )
+ response = curated.run(
+ sql, query_type="engineering_analytics.workflow_window_costs_with_prev", placeholders=placeholders
+ )
+ by_workflow_cur: dict[str, list[tuple[list[str], float | None]]] = defaultdict(list)
+ by_workflow_prev: dict[str, list[tuple[list[str], float | None]]] = defaultdict(list)
+ for workflow_name, labels, finished, elapsed, unfinished, finished_prev, elapsed_prev, unfinished_prev in (
+ response.results or []
+ ):
+ parsed = _parse_labels(labels)
+ by_workflow_cur[workflow_name or ""].extend(
+ _expand_jobs(parsed, int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))
+ )
+ by_workflow_prev[workflow_name or ""].extend(
+ _expand_jobs(parsed, int(finished_prev or 0), float(elapsed_prev or 0.0), int(unfinished_prev or 0))
+ )
+ return (
+ {workflow: aggregate_pr_cost(jobs) for workflow, jobs in by_workflow_cur.items() if jobs},
+ {workflow: aggregate_pr_cost(jobs) for workflow, jobs in by_workflow_prev.items() if jobs},
+ )
+
+
# Per-runner-tier cost for one workflow (single-workflow page "where the spend goes" breakdown), scoped
# to the page's run window (and optional branch) so the figure always answers "spend over [window]",
# never an unbounded all-time.
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
index 2c9b0f991e5a..abfcf6288349 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_list.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
@@ -35,6 +35,7 @@ _SELECT = f"""
coalesce(ci.passing, 0) AS passing,
coalesce(ci.failing, 0) AS failing,
coalesce(ci.pending, 0) AS pending,
+ ci.failing_workflows AS failing_workflows,
coalesce(rp.pushes, 0) AS pushes,
coalesce(rp.rerun_cycles, 0) AS rerun_cycles
FROM __PR_SOURCE__ AS pr
@@ -94,6 +95,7 @@ def _map_row(row: tuple, cost_by_pr: dict[tuple[str, str, int], PRCostAggregate]
passing,
failing,
pending,
+ failing_workflows,
pushes,
rerun_cycles,
) = row
@@ -114,7 +116,15 @@ def _map_row(row: tuple, cost_by_pr: dict[tuple[str, str, int], PRCostAggregate]
merged_at=merged_at,
open_to_merge_seconds=open_to_merge_seconds,
labels=list(labels),
- ci=CIStatusRollup(runs=runs, passing=passing, failing=failing, pending=pending),
+ # A PR with no CI misses the LEFT JOIN; the array column then comes back empty or NULL
+ # depending on join_use_nulls — normalize both to [].
+ ci=CIStatusRollup(
+ runs=runs,
+ passing=passing,
+ failing=failing,
+ pending=pending,
+ failing_workflows=list(failing_workflows or []),
+ ),
pushes=pushes,
rerun_cycles=rerun_cycles,
estimated_cost_usd=cost.estimated_cost_usd if cost else None,
diff --git a/products/engineering_analytics/backend/logic/queries/repo_overview.py b/products/engineering_analytics/backend/logic/queries/repo_overview.py
new file mode 100644
index 000000000000..01992878be33
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/repo_overview.py
@@ -0,0 +1,136 @@
+"""Curated query: repo-level headline aggregates for the repo hub landing page.
+
+One runs scan covers the current window and the equal-length window before it, so
+every headline number ships with its previous-window twin and the UI can render an
+honest delta instead of a server-baked percentage. The PR medians (bots and drafts
+excluded, per the locked cycle-time recipe) come from the PR snapshot the same way.
+"""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.facade.contracts import RepoOverview
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float
+from products.engineering_analytics.backend.logic.queries.pr_cost import query_workflow_window_costs_with_prev
+
+_RUNS_SELECT = """
+ SELECT
+ countIf(__CUR__) AS run_count,
+ countIf(__PREV__) AS run_count_prev,
+ countIf(status = 'completed' AND conclusion = 'success' AND __CUR__)
+ / nullIf(countIf(status = 'completed' AND __CUR__), 0) AS success_rate,
+ countIf(status = 'completed' AND conclusion = 'success' AND __PREV__)
+ / nullIf(countIf(status = 'completed' AND __PREV__), 0) AS success_rate_prev,
+ countIf(run_attempt > 1 AND __CUR__) AS rerun_cycles,
+ countIf(run_attempt > 1 AND __PREV__) AS rerun_cycles_prev,
+ countIf(head_branch = 'master' AND __CUR__) AS master_runs,
+ countIf(head_branch = 'main' AND __CUR__) AS main_runs
+ FROM __RUNS_SOURCE__ AS r
+ WHERE run_started_at >= {prev_from} __DATE_TO__
+"""
+
+_PR_SELECT = """
+ SELECT
+ quantileIf(0.5)(open_to_merge_seconds, __CUR_MERGED__ AND NOT is_bot AND NOT is_draft) AS median_cur,
+ quantileIf(0.5)(open_to_merge_seconds, __PREV_MERGED__ AND NOT is_bot AND NOT is_draft) AS median_prev
+ FROM __PR_SOURCE__ AS pr
+ WHERE merged_at IS NOT NULL AND merged_at >= {prev_from}
+"""
+
+_DEFAULT_BRANCH_SELECT = """
+ SELECT countIf(head_branch = 'master') AS master_runs, countIf(head_branch = 'main') AS main_runs
+ FROM __RUNS_SOURCE__ AS r
+ WHERE run_started_at >= {date_from} __DATE_TO__
+"""
+
+
+def query_default_branch(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+) -> str:
+ """'master' or 'main', by observed run volume in the window — the cheap standalone variant of the
+ detection the overview aggregate gets for free."""
+ date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""
+ placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}
+ if date_to is not None:
+ placeholders["date_to"] = ast.Constant(value=date_to)
+ response = curated.run(
+ _DEFAULT_BRANCH_SELECT.replace("__RUNS_SOURCE__", curated.run_source()).replace("__DATE_TO__", date_to_clause),
+ query_type="engineering_analytics.default_branch",
+ placeholders=placeholders,
+ )
+ master_runs, main_runs = response.results[0] if response.results else (0, 0)
+ return "main" if (main_runs or 0) > (master_runs or 0) else "master"
+
+
+def query_repo_overview(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+) -> RepoOverview:
+ end = date_to or datetime.now(tz=date_from.tzinfo)
+ prev_from = date_from - (end - date_from)
+ date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""
+ cur = "(run_started_at >= {date_from}" + (" AND run_started_at <= {date_to})" if date_to is not None else ")")
+ prev = "(run_started_at >= {prev_from} AND run_started_at < {date_from})"
+
+ placeholders: dict[str, ast.Expr] = {
+ "date_from": ast.Constant(value=date_from),
+ "prev_from": ast.Constant(value=prev_from),
+ }
+ if date_to is not None:
+ placeholders["date_to"] = ast.Constant(value=date_to)
+
+ runs_sql = (
+ _RUNS_SELECT.replace("__CUR__", cur)
+ .replace("__PREV__", prev)
+ .replace("__RUNS_SOURCE__", curated.run_source())
+ .replace("__DATE_TO__", date_to_clause)
+ )
+ runs_response = curated.run(
+ runs_sql, query_type="engineering_analytics.repo_overview_runs", placeholders=placeholders
+ )
+ row = runs_response.results[0] if runs_response.results else (0, 0, None, None, 0, 0, 0, 0)
+ run_count, run_count_prev, success_rate, success_rate_prev, reruns, reruns_prev, master_runs, main_runs = row
+ default_branch = "main" if (main_runs or 0) > (master_runs or 0) else "master"
+
+ pr_cur = "(merged_at >= {date_from}" + (" AND merged_at <= {date_to})" if date_to is not None else ")")
+ pr_prev = "(merged_at >= {prev_from} AND merged_at < {date_from})"
+ pr_sql = (
+ _PR_SELECT.replace("__CUR_MERGED__", pr_cur)
+ .replace("__PREV_MERGED__", pr_prev)
+ .replace("__PR_SOURCE__", curated.pr_source())
+ )
+ pr_response = curated.run(pr_sql, query_type="engineering_analytics.repo_overview_prs", placeholders=placeholders)
+ median_cur, median_prev = pr_response.results[0] if pr_response.results else (None, None)
+
+ jobs_available = curated.jobs_source() is not None
+ cost_cur, cost_prev = query_workflow_window_costs_with_prev(
+ curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from
+ )
+ # Per-workflow figures can be None (billable time on an unknown tier) — sum what's known.
+ billable_seconds = sum(c.billable_seconds or 0.0 for c in cost_cur.values()) if cost_cur else None
+ billable_seconds_prev = sum(c.billable_seconds or 0.0 for c in cost_prev.values()) if cost_prev else None
+ cost_usd = sum(c.estimated_cost_usd or 0.0 for c in cost_cur.values()) if cost_cur else None
+ cost_usd_prev = sum(c.estimated_cost_usd or 0.0 for c in cost_prev.values()) if cost_prev else None
+
+ return RepoOverview(
+ run_count=run_count,
+ run_count_prev=run_count_prev,
+ success_rate=opt_float(success_rate),
+ success_rate_prev=opt_float(success_rate_prev),
+ rerun_cycles=reruns,
+ rerun_cycles_prev=reruns_prev,
+ median_open_to_merge_seconds=opt_float(median_cur),
+ median_open_to_merge_seconds_prev=opt_float(median_prev),
+ billable_minutes=billable_seconds / 60 if billable_seconds is not None else None,
+ billable_minutes_prev=billable_seconds_prev / 60 if billable_seconds_prev is not None else None,
+ estimated_cost_usd=opt_float(cost_usd),
+ estimated_cost_usd_prev=opt_float(cost_usd_prev),
+ jobs_available=jobs_available,
+ default_branch=default_branch,
+ )
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.py
index 896dfea7128d..c1fc1b56befc 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py
@@ -10,14 +10,13 @@ so the trend sparkline keeps a readable number of points — per-day buckets are
for a 24h window and far too many for a year.
"""
-import math
from datetime import date, datetime, timedelta
from typing import Literal
from posthog.hogql import ast
from products.engineering_analytics.backend.facade.contracts import RepoRef, WorkflowHealthBucket, WorkflowHealthItem
-from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float
from products.engineering_analytics.backend.logic.queries.pr_cost import query_workflow_window_costs
Granularity = Literal["hour", "day", "week"]
@@ -50,7 +49,8 @@ _SELECT = f"""
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
+ 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__
GROUP BY repo_owner, repo_name, workflow_name
@@ -58,6 +58,20 @@ _SELECT = f"""
LIMIT {_LIMIT}
"""
+# Success rate over the equal-length window before date_from — the delta baseline the UI renders as
+# an honest Δpp instead of a server-baked percentage. Kept as its own slim scan so the main query's
+# window (and its LIMIT semantics) stay untouched.
+_PREV_SELECT = """
+ SELECT
+ repo_owner,
+ repo_name,
+ 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__
+ GROUP BY repo_owner, repo_name, workflow_name
+"""
+
_BUCKET_SELECT = f"""
SELECT
repo_owner,
@@ -116,6 +130,18 @@ def query_workflow_health(
query_type="engineering_analytics.workflow_health_buckets",
placeholders=placeholders,
)
+
+ end = date_to or datetime.now(tz=date_from.tzinfo)
+ prev_from = date_from - (end - date_from)
+ prev_response = curated.run(
+ fill(_PREV_SELECT),
+ query_type="engineering_analytics.workflow_health_prev",
+ placeholders={**placeholders, "prev_from": ast.Constant(value=prev_from)},
+ )
+ prev_rate_by_workflow: dict[tuple[str, str, str], float | None] = {
+ (repo_owner, repo_name, workflow_name): opt_float(success_rate)
+ for repo_owner, repo_name, workflow_name, success_rate in prev_response.results or []
+ }
buckets_by_workflow: dict[tuple[str, str, str], dict[datetime, WorkflowHealthBucket]] = {}
for repo_owner, repo_name, workflow_name, bucket_start, run_count, completed, successes, failures in (
bucket_response.results or []
@@ -132,9 +158,9 @@ def query_workflow_health(
repo=RepoRef(provider="github", owner=repo_owner, name=repo_name),
workflow_name=workflow_name,
run_count=run_count,
- success_rate=_to_opt_float(success_rate),
- p50_seconds=_to_opt_float(p50_seconds),
- p95_seconds=_to_opt_float(p95_seconds),
+ success_rate=opt_float(success_rate),
+ p50_seconds=opt_float(p50_seconds),
+ p95_seconds=opt_float(p95_seconds),
last_failure_at=last_failure_at,
# argMaxIf defaults to 0 when nothing completed; the completed_count guard tells
# "latest run passed" apart from "no completed run yet".
@@ -155,8 +181,10 @@ def query_workflow_health(
estimated_cost_usd=(
cost_by_workflow[workflow_name].estimated_cost_usd if workflow_name in cost_by_workflow else None
),
+ rerun_cycles=rerun_cycles,
+ success_rate_prev=prev_rate_by_workflow.get((repo_owner, repo_name, workflow_name)),
)
- for repo_owner, repo_name, workflow_name, run_count, success_rate, p50_seconds, p95_seconds, last_failure_at, completed_count, latest_failed, latest_conclusion in response.results
+ for repo_owner, repo_name, workflow_name, run_count, success_rate, p50_seconds, p95_seconds, last_failure_at, completed_count, latest_failed, latest_conclusion, rerun_cycles in response.results
]
@@ -199,10 +227,3 @@ def _normalize(value: datetime | date, granularity: Granularity) -> datetime:
if granularity == "week":
return midnight - timedelta(days=midnight.weekday())
return midnight
-
-
-def _to_opt_float(value: float | None) -> float | None:
- # quantileIf over an empty window returns NaN; nullIf division returns None.
- if value is None or (isinstance(value, float) and math.isnan(value)):
- return None
- return float(value)
diff --git a/products/engineering_analytics/backend/logic/views/workflow_jobs.py b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
index 3a4961aa2da1..88ae93413aa6 100644
--- a/products/engineering_analytics/backend/logic/views/workflow_jobs.py
+++ b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
@@ -22,25 +22,33 @@ def build_query(table_name: str) -> str:
run_id,
run_attempt,
name,
+ workflow_name,
+ head_branch,
status,
conclusion,
labels,
runner_name,
+ created_at,
started_at,
completed_at,
- if(status = 'completed', dateDiff('second', started_at, completed_at), NULL) AS duration_seconds
+ if(status = 'completed', dateDiff('second', started_at, completed_at), NULL) AS duration_seconds,
+ -- Queue wait: webhook creation to first execution. NULL while still queued.
+ if(started_at IS NOT NULL, dateDiff('second', created_at, started_at), NULL) AS queue_seconds
FROM (
SELECT
id,
run_id,
run_attempt,
name,
+ ifNull(workflow_name, '') AS workflow_name,
+ ifNull(head_branch, '') AS head_branch,
status,
conclusion,
ifNull(labels, '[]') AS labels,
ifNull(runner_name, '') AS runner_name,
-- HogQL maps parseDateTimeBestEffort to the OrNull variant, so an empty/queued '' lands
-- as NULL with no explicit nullIf — same as the runs builder.
+ parseDateTimeBestEffort(created_at) AS created_at,
parseDateTimeBestEffort(started_at) AS started_at,
parseDateTimeBestEffort(completed_at) AS completed_at
FROM {table_name}
diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
index ad7e3780c38f..6992b8432d95 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -66,6 +66,9 @@ RUN_DATE_FIELDS = ("created_at", "run_started_at", "updated_at")
# Marks the GitHub source this command owns, so re-seeding never clobbers a real source.
SEED_SOURCE_ID = "engineering_analytics_seed"
+# Matches the fixtures' repository.full_name; without it the UI's repo header/picker fall back to
+# placeholders (a real source stores the repo in job_inputs at connect time).
+SEED_REPOSITORY = "PostHog/posthog"
# Default prefix is non-trivial on purpose: it proves the product resolves the real
# per-team table name rather than assuming the bare ``github_*`` names.
DEFAULT_PREFIX = "eng_analytics_seed"
@@ -366,10 +369,17 @@ class Command(BaseCommand):
status=ExternalDataSource.Status.COMPLETED,
source_type=ExternalDataSourceType.GITHUB,
prefix=prefix,
+ job_inputs={"repository": SEED_REPOSITORY},
)
+ update_fields = []
if source.prefix != prefix:
source.prefix = prefix
- source.save(update_fields=["prefix", "updated_at"])
+ update_fields.append("prefix")
+ if (source.job_inputs or {}).get("repository") != SEED_REPOSITORY:
+ source.job_inputs = {**(source.job_inputs or {}), "repository": SEED_REPOSITORY}
+ update_fields.append("job_inputs")
+ if update_fields:
+ source.save(update_fields=[*update_fields, "updated_at"])
return source
def _upsert_schema_table(
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index 8bc1923eeaae..b072a033b90a 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -17,6 +17,7 @@ from products.engineering_analytics.backend.facade.contracts import (
CIJobFailureLog,
CIStatusRollup,
GitHubSource,
+ MasterFailureGroup,
PRCostSummary,
PRLifecycle,
PRLifecycleEvent,
@@ -27,12 +28,15 @@ from products.engineering_analytics.backend.facade.contracts import (
QuarantineFile,
QuarantineRequest,
QuarantineRequestResult,
+ RepoOverview,
RepoRef,
RunCost,
+ RunFailureLogs,
WorkflowCost,
WorkflowHealthBucket,
WorkflowHealthItem,
WorkflowJob,
+ WorkflowJobAggregate,
WorkflowRunActivity,
WorkflowRunActivityPoint,
WorkflowRunDetail,
@@ -366,6 +370,10 @@ class CIStatusRollupSerializer(DataclassSerializer):
"passing": {"help_text": "Latest runs that completed with conclusion 'success'."},
"failing": {"help_text": "Latest runs that completed with conclusion 'failure' or 'timed_out'."},
"pending": {"help_text": "Latest runs not yet completed (queued or in progress)."},
+ "failing_workflows": {
+ "help_text": "The workflow names behind `failing`, sorted - names what is failing instead of "
+ "leaving a bare count."
+ },
}
@@ -625,4 +633,146 @@ class WorkflowHealthItemSerializer(DataclassSerializer):
"was costable or the job source isn't synced.",
"allow_null": True,
},
+ "rerun_cycles": {
+ "help_text": "Runs in the window that were a 2nd+ attempt - retry pressure, a flakiness proxy."
+ },
+ "success_rate_prev": {
+ "help_text": "Success rate over the equal-length window before date_from - the delta baseline. "
+ "Null when that window had no completed runs.",
+ "allow_null": True,
+ },
+ }
+
+
+class RepoOverviewSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = RepoOverview
+ extra_kwargs = {
+ "run_count": {"help_text": "Workflow runs started in the window, all branches and workflows."},
+ "run_count_prev": {
+ "help_text": "Same count over the equal-length window immediately before date_from — the delta baseline."
+ },
+ "success_rate": {
+ "help_text": "Fraction of completed runs that succeeded (0-1) in the window. Null if none completed.",
+ "allow_null": True,
+ },
+ "success_rate_prev": {
+ "help_text": "Success rate over the previous window. Null if none completed.",
+ "allow_null": True,
+ },
+ "rerun_cycles": {"help_text": "Runs in the window that were a 2nd+ attempt (attempt > 1)."},
+ "rerun_cycles_prev": {"help_text": "Re-run cycles over the previous window."},
+ "median_open_to_merge_seconds": {
+ "help_text": "Median merged_at - created_at over PRs merged in the window, bots and drafts excluded. "
+ "Coarse by design: draft and ready-for-review time are fused. Null when nothing merged.",
+ "allow_null": True,
+ },
+ "median_open_to_merge_seconds_prev": {
+ "help_text": "The same median over the previous window. Null when nothing merged.",
+ "allow_null": True,
+ },
+ "billable_minutes": {
+ "help_text": "Billable (self-hosted) job minutes in the window; null when the job-level source "
+ "isn't synced.",
+ "allow_null": True,
+ },
+ "billable_minutes_prev": {
+ "help_text": "Billable minutes over the previous window; null when the job-level source isn't synced.",
+ "allow_null": True,
+ },
+ "estimated_cost_usd": {
+ "help_text": "Estimated CI cost in USD (billable minutes x runner-tier rate); null when the "
+ "job-level source isn't synced.",
+ "allow_null": True,
+ },
+ "estimated_cost_usd_prev": {
+ "help_text": "Estimated cost over the previous window; null when the job-level source isn't synced.",
+ "allow_null": True,
+ },
+ "jobs_available": {"help_text": "Whether the job-level source is synced (cost and queue figures exist)."},
+ "default_branch": {"help_text": "'master' or 'main', picked by observed run volume in the window."},
+ }
+
+
+class MasterFailureGroupSerializer(DataclassSerializer):
+ repo = RepoRefSerializer(help_text="Repository the failures occurred in.")
+
+ class Meta:
+ dataclass = MasterFailureGroup
+ extra_kwargs = {
+ "workflow_name": {"help_text": "GitHub Actions workflow name the failing runs belong to."},
+ "failed_job": {
+ "help_text": "De-sharded failing job name (matrix '(G/N)' suffix stripped) — the group's failure "
+ "signature together with the workflow. '' when the job-level source isn't synced and the group "
+ "degrades to workflow level."
+ },
+ "run_count": {"help_text": "Distinct failing default-branch runs in this group within the window."},
+ "first_seen": {"help_text": "When the oldest failing run in the group started."},
+ "last_seen": {"help_text": "When the newest failing run in the group started."},
+ "latest_run_id": {"help_text": "Run id of the newest failing run — the drill-down anchor."},
+ }
+
+
+class RunFailureLogsSerializer(DataclassSerializer):
+ jobs = CIJobFailureLogSerializer(
+ many=True, help_text="Failed CI jobs of this run with their thinned failure logs, grouped by job."
+ )
+
+ class Meta:
+ dataclass = RunFailureLogs
+ extra_kwargs = {
+ "run_id": {"help_text": "Workflow run id the failure logs are for."},
+ "logs_available": {
+ "help_text": "False when no failure logs were found — the run didn't fail, or its logs aged out of "
+ "the short Logs retention.",
+ },
+ "truncated": {"help_text": "True when the overall line cap across all jobs was hit."},
+ }
+
+
+class WorkflowJobAggregateSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = WorkflowJobAggregate
+ extra_kwargs = {
+ "job_name": {
+ "help_text": "De-sharded job name: the matrix '(G/N)' suffix is stripped and unexpanded "
+ "'${{ matrix.* }}' templates are collapsed, so shards of one matrix aggregate together."
+ },
+ "job_count": {"help_text": "Job instances observed in the window (all shards, all attempts)."},
+ "shard_count": {"help_text": "Distinct raw job names inside the group - the observed matrix width."},
+ "runs_in": {"help_text": "Distinct workflow runs the job appeared in."},
+ "run_share": {
+ "help_text": "runs_in divided by the workflow's total runs in the window; below 1.0 means the "
+ "job is conditional and skips some runs. Null when the workflow had no runs.",
+ "allow_null": True,
+ },
+ "queue_p50_seconds": {
+ "help_text": "Median queue wait (created to started) in seconds - where runner-capacity problems "
+ "hide. Null when nothing started.",
+ "allow_null": True,
+ },
+ "p50_seconds": {
+ "help_text": "Median duration of completed job instances, in seconds. Null if none completed.",
+ "allow_null": True,
+ },
+ "p95_seconds": {
+ "help_text": "95th-percentile duration of completed job instances, in seconds. Null if none completed.",
+ "allow_null": True,
+ },
+ "failure_rate": {
+ "help_text": "Decisive failures ('failure', 'timed_out') over completed instances (0-1). Null if "
+ "none completed.",
+ "allow_null": True,
+ },
+ "retry_job_count": {"help_text": "Job instances that ran on a 2nd+ run attempt - retry pressure."},
+ "billable_minutes": {
+ "help_text": "Billable (self-hosted) minutes across the group's instances; null when every "
+ "instance ran on an unknown tier.",
+ "allow_null": True,
+ },
+ "estimated_cost_usd": {
+ "help_text": "Estimated cost in USD via the runner-tier rate ladder; null when every instance ran "
+ "on an unknown tier.",
+ "allow_null": True,
+ },
}
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index bbe05d815c50..53409d8c23bb 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -31,13 +31,17 @@ from products.engineering_analytics.backend.presentation.serializers import (
CICardSummarySerializer,
CIFailureLogsSerializer,
GitHubSourceSerializer,
+ MasterFailureGroupSerializer,
PRCostSummarySerializer,
PRLifecycleSerializer,
PullRequestListSerializer,
QuarantineFileSerializer,
QuarantineRequestResultSerializer,
QuarantineRequestSerializer,
+ RepoOverviewSerializer,
+ RunFailureLogsSerializer,
WorkflowHealthItemSerializer,
+ WorkflowJobAggregateSerializer,
WorkflowJobSerializer,
WorkflowRunActivitySerializer,
WorkflowRunDetailSerializer,
@@ -137,6 +141,10 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"workflow_run_activity",
"workflow_runner_costs",
"workflow_jobs",
+ "repo_overview",
+ "master_failures",
+ "run_failure_logs",
+ "job_aggregates",
]
scope_object_write_actions: list[str] = ["quarantine_request"]
@@ -699,6 +707,146 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
return _bad_request(exc, fallback="Invalid source_id")
return Response(WorkflowJobSerializer(instance=jobs, many=True).data)
+ @extend_schema(
+ operation_id="engineering_analytics_repo_overview",
+ parameters=[_DATE_FROM, _DATE_TO, _SOURCE_ID],
+ responses={
+ 200: RepoOverviewSerializer,
+ 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),
+ },
+ description=(
+ "Repo-level headline aggregates over a window (default -30d): run count, success rate, re-run "
+ "cycles, median PR open-to-merge (bots and drafts excluded; coarse — draft and ready time fused), "
+ "and billable minutes + estimated cost — each with its equal-length previous-window twin so a "
+ "caller can render honest deltas. Also carries the detected default branch and its completed-run "
+ "history series. Cost figures are null until the job-level source is synced."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def repo_overview(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_repo_overview(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")
+ return Response(RepoOverviewSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_master_failures",
+ parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _SOURCE_ID],
+ responses={
+ 200: MasterFailureGroupSerializer(many=True),
+ 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),
+ },
+ description=(
+ "Default-branch failures over a window (default -24h), grouped error-tracking style by "
+ "(workflow, de-sharded failing job) with a run count and first/last seen, newest group first. "
+ "`branch` overrides the detected default branch. PR-branch failures are deliberately excluded — "
+ "at monorepo volume a flat feed is a firehose; those surface per PR. Groups degrade to workflow "
+ "level (failed_job '') when the job-level source isn't synced."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def master_failures(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.list_master_failures(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")
+ return Response(MasterFailureGroupSerializer(instance=result, many=True).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_run_failure_logs",
+ parameters=[
+ OpenApiParameter(
+ name="run_id",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Workflow run id whose failure logs to fetch.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: RunFailureLogsSerializer,
+ 400: OpenApiResponse(description="Missing or non-integer run_id, or invalid source_id."),
+ },
+ description=(
+ "The thinned CI failure logs of one workflow run, grouped by failed job — the run-scoped twin of "
+ "ci_failure_logs for surfaces that aren't PR-scoped (default-branch failures, the run page). "
+ "logs_available is false when the run didn't fail or its logs aged out of the short Logs retention."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def run_failure_logs(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_run_failure_logs(
+ team=self.team,
+ run_id=_require_int_param(request, "run_id"),
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid source_id")
+ return Response(RunFailureLogsSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_job_aggregates",
+ parameters=[
+ OpenApiParameter(
+ name="workflow_name",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Workflow name to aggregate jobs for.",
+ ),
+ _DATE_FROM,
+ _DATE_TO,
+ _BRANCH,
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: WorkflowJobAggregateSerializer(many=True),
+ 400: OpenApiResponse(description="Missing workflow_name, or invalid date 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 "
+ "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."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def job_aggregates(self, request: Request, **kwargs) -> Response:
+ workflow_name = request.query_params.get("workflow_name")
+ if not workflow_name:
+ return Response({"detail": "workflow_name is required"}, status=status.HTTP_400_BAD_REQUEST)
+ try:
+ result = api.list_job_aggregates(
+ team=self.team,
+ workflow_name=workflow_name,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date, workflow_name, or source_id")
+ return Response(WorkflowJobAggregateSerializer(instance=result, many=True).data)
+
@extend_schema(
operation_id="engineering_analytics_quarantine",
summary="Flaky-test quarantine file",
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index bef66a6072d4..1f2158a306f9 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -272,6 +272,7 @@ class TestEndpointMapping(BaseTest):
2,
1,
0,
+ ["E2E CI"],
5,
2,
)
@@ -288,6 +289,7 @@ class TestEndpointMapping(BaseTest):
assert item.labels == ["bug", "p1"]
assert item.open_to_merge_seconds is None
assert (item.ci.runs, item.ci.passing, item.ci.failing, item.ci.pending) == (3, 2, 1, 0)
+ assert item.ci.failing_workflows == ["E2E CI"]
assert (item.pushes, item.rerun_cycles) == (5, 2)
assert item.estimated_cost_usd is None
@@ -312,6 +314,7 @@ class TestEndpointMapping(BaseTest):
0,
0,
0,
+ list[str](),
0,
0,
)
@@ -324,18 +327,20 @@ class TestEndpointMapping(BaseTest):
def test_workflow_health_maps_and_nulls_empty_window(self) -> None:
# Columns: owner, name, workflow, run_count, success_rate, p50, p95, last_failure_at,
- # completed_count, latest_failed, latest_conclusion.
+ # completed_count, latest_failed, latest_conclusion, rerun_cycles.
rows = [
- ("PostHog", "posthog", "CI", 10, 0.9, 120.0, 600.0, _dt("2026-01-20T00:00:00"), 8, 0, "success"),
+ ("PostHog", "posthog", "CI", 10, 0.9, 120.0, 600.0, _dt("2026-01-20T00:00:00"), 8, 0, "success", 3),
# 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, None, float("nan"), float("nan"), None, 0, 0, ""),
+ ("PostHog", "posthog", "Deploy", 2, None, float("nan"), float("nan"), None, 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.
bucket_rows = [("PostHog", "posthog", "CI", datetime.now(tz=UTC) - timedelta(days=1), 10, 8, 7, 1)]
- with mock.patch(_RUN_QUERY, side_effect=[_resp(rows), _resp(bucket_rows)]):
+ # Third response: the previous-window success rate (the Δ baseline); Deploy had no prior runs.
+ prev_rows = [("PostHog", "posthog", "CI", 0.95)]
+ with mock.patch(_RUN_QUERY, side_effect=[_resp(rows), _resp(bucket_rows), _resp(prev_rows)]):
items = api.list_workflow_health(team=self.team, date_from="-30d", date_to=None)
assert items[0].workflow_name == "CI" and items[0].success_rate == 0.9
@@ -343,6 +348,9 @@ class TestEndpointMapping(BaseTest):
assert items[0].granularity == "day"
assert items[0].latest_run_failed is False
assert items[0].latest_run_conclusion == "success"
+ assert items[0].rerun_cycles == 3
+ assert items[0].success_rate_prev == 0.95
+ assert items[1].success_rate_prev is None
# The series spans the whole window, zero-filled except the bucket with runs.
assert len(items[0].buckets) >= 30
seeded_bucket = next(entry for entry in items[0].buckets if entry.run_count > 0)
diff --git a/products/engineering_analytics/frontend/components/BranchFilter.tsx b/products/engineering_analytics/frontend/components/BranchFilter.tsx
deleted file mode 100644
index 7db2c69c054f..000000000000
--- a/products/engineering_analytics/frontend/components/BranchFilter.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { LemonButton, LemonInput } from '@posthog/lemon-ui'
-
-import { engineeringAnalyticsFiltersLogic } from '../scenes/engineeringAnalyticsFiltersLogic'
-
-// Quick presets for the default branch. We can't tell main from master without another query, so offer
-// both — clicking the active one clears back to all branches.
-const DEFAULT_BRANCHES = ['main', 'master']
-
-/** Branch scope control (server-side head_branch filter), shared by the Workflows tab and a single
- * workflow's detail page so the scope carries between them. Reads/writes the shared filters logic; typing
- * stages the value and Enter/blur (or a chip) applies it. */
-export function BranchFilter(): JSX.Element {
- const { branchInput, appliedBranch } = useValues(engineeringAnalyticsFiltersLogic)
- const { setBranchFilter, applyBranchFilter } = useActions(engineeringAnalyticsFiltersLogic)
-
- // Stage + apply a branch in one click (the chips). Clicking the active chip clears back to all branches.
- const selectBranch = (branch: string): void => {
- setBranchFilter(branch)
- applyBranchFilter()
- }
-
- return (
- <>
- <LemonInput
- type="search"
- size="small"
- className="w-56"
- placeholder="Branch: all (e.g. main)"
- value={branchInput}
- onChange={setBranchFilter}
- onPressEnter={applyBranchFilter}
- onBlur={applyBranchFilter}
- data-attr="engineering-analytics-branch-filter"
- />
- {DEFAULT_BRANCHES.map((branch) => (
- <LemonButton
- key={branch}
- size="xsmall"
- type={appliedBranch === branch ? 'primary' : 'secondary'}
- // Keep focus on the input so its onBlur doesn't fire first and apply whatever was
- // staged there — a chip should apply exactly its own branch, in one reload.
- onMouseDown={(e) => e.preventDefault()}
- onClick={() => selectBranch(appliedBranch === branch ? '' : branch)}
- >
- {branch}
- </LemonButton>
- ))}
- </>
- )
-}
diff --git a/products/engineering_analytics/frontend/components/CIAnalyticsLoadError.tsx b/products/engineering_analytics/frontend/components/CIAnalyticsLoadError.tsx
index 07c22cc9af1b..0cefe93c8180 100644
--- a/products/engineering_analytics/frontend/components/CIAnalyticsLoadError.tsx
+++ b/products/engineering_analytics/frontend/components/CIAnalyticsLoadError.tsx
@@ -9,8 +9,7 @@ export function CIAnalyticsLoadError({ onRetry }: { onRetry: () => void }): JSX.
<div className="flex flex-col items-center gap-2 py-12 text-center">
<span className="font-medium text-danger">Couldn't load engineering analytics</span>
<span className="max-w-md text-sm text-secondary">
- A GitHub source is connected, but its data endpoints returned an error — this isn't a missing source.
- Retry, or check the source's sync status.
+ A GitHub source is connected, but loading its data failed. Retry, or check the source's sync status.
</span>
<LemonButton type="primary" size="small" onClick={onRetry}>
Retry
diff --git a/products/engineering_analytics/frontend/components/CIStatusTag.tsx b/products/engineering_analytics/frontend/components/CIStatusTag.tsx
index 2e1fec3a7a59..027bb8bc889d 100644
--- a/products/engineering_analytics/frontend/components/CIStatusTag.tsx
+++ b/products/engineering_analytics/frontend/components/CIStatusTag.tsx
@@ -26,7 +26,7 @@ export function CIStatusTag({ rollup }: { rollup: CIRollup }): JSX.Element {
<LemonTag type={config.type}>{config.label}</LemonTag>
{rollup.runs > 0 && (
<Tooltip
- title={`${rollup.passing} passed, ${rollup.failing} failed, ${rollup.pending} still running — workflow-level rollup over the PR's head commit, not per-check.`}
+ title={`${rollup.passing} passed, ${rollup.failing} failed, ${rollup.pending} still running. Workflow-level status for the PR's latest commit, not per-check.`}
>
<span className="flex items-center gap-1.5">
{rollup.passing > 0 && (
diff --git a/products/engineering_analytics/frontend/components/ConnectGitHubSource.tsx b/products/engineering_analytics/frontend/components/ConnectGitHubSource.tsx
index 7e0ec06ca6f2..b979cd430e92 100644
--- a/products/engineering_analytics/frontend/components/ConnectGitHubSource.tsx
+++ b/products/engineering_analytics/frontend/components/ConnectGitHubSource.tsx
@@ -12,7 +12,7 @@ export function ConnectGitHubSource(): JSX.Element {
productKey={ProductKey.ENGINEERING_ANALYTICS}
thingName="GitHub source"
titleOverride="Connect a GitHub source to get started"
- description="Engineering analytics reads pull requests and workflow runs from a GitHub data warehouse source — once connected, you'll see CI health, throughput, and where engineering hours go."
+ description="Engineering analytics reads pull requests and workflow runs from a GitHub data warehouse source. Connect one to see CI health, pull request throughput, and cost."
isEmpty
actionElementOverride={
<LemonButton
diff --git a/products/engineering_analytics/frontend/components/DistributionBar.tsx b/products/engineering_analytics/frontend/components/DistributionBar.tsx
deleted file mode 100644
index bc5598bdf164..000000000000
--- a/products/engineering_analytics/frontend/components/DistributionBar.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { ReactNode } from 'react'
-
-import { Tooltip } from '@posthog/lemon-ui'
-
-import { cn } from 'lib/utils/css-classes'
-
-export interface DistributionSegment {
- key: string
- label: ReactNode
- value: number
- /** Any CSS color (e.g. a `getSeriesColor(i)` result). */
- color: string
- /** Extra tooltip line under the label (e.g. the formatted amount). */
- caption?: ReactNode
-}
-
-/**
- * One horizontal bar split into colored segments sized by share of the total (cost by runner tier, jobs
- * by status, …), each hover-able for its share. Segments under 0.5% are dropped as noise.
- */
-export function DistributionBar({
- segments,
- className,
-}: {
- segments: DistributionSegment[]
- className?: string
-}): JSX.Element | null {
- const total = segments.reduce((sum, seg) => sum + Math.max(0, seg.value), 0)
- if (total <= 0) {
- return null
- }
- return (
- <div className={cn('flex h-2.5 w-full overflow-hidden rounded-sm bg-border-light', className)}>
- {segments.map((seg) => {
- const percent = (Math.max(0, seg.value) / total) * 100
- if (percent < 0.5) {
- return null
- }
- return (
- <Tooltip
- key={seg.key}
- title={
- <div className="text-xs">
- <div className="font-semibold">{seg.label}</div>
- <div>
- {seg.caption != null && <>{seg.caption} · </>}
- {Math.round(percent)}%
- </div>
- </div>
- }
- >
- {/* eslint-disable-next-line react/forbid-dom-props */}
- <div
- className="h-full transition-all hover:opacity-80"
- style={{ width: `${percent}%`, backgroundColor: seg.color }}
- />
- </Tooltip>
- )
- })}
- </div>
- )
-}
diff --git a/products/engineering_analytics/frontend/components/EntityHeader.tsx b/products/engineering_analytics/frontend/components/EntityHeader.tsx
new file mode 100644
index 000000000000..c1fad97c97b2
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/EntityHeader.tsx
@@ -0,0 +1,76 @@
+// Shared entity header: icon square · title (+muted suffix) · mono slug line · verdict pill.
+
+import { ReactNode } from 'react'
+
+import { cn } from 'lib/utils/css-classes'
+
+export type VerdictKind = 'success' | 'danger' | 'warning' | 'muted'
+
+const PILL_CLASS: Record<VerdictKind, string> = {
+ success: 'bg-fill-success-tertiary text-success',
+ danger: 'bg-fill-error-tertiary text-danger',
+ warning: 'bg-fill-warning-tertiary text-warning-dark',
+ muted: 'bg-fill-secondary text-secondary',
+}
+
+const PILL_DOT: Record<VerdictKind, string> = {
+ success: 'var(--success)',
+ danger: 'var(--danger)',
+ warning: 'var(--warning)',
+ muted: 'var(--muted)',
+}
+
+/** One-glance verdict for the entity: "Failing on master · 38m", "CI passing", "3 open PRs". */
+export function VerdictPill({ kind, children }: { kind: VerdictKind; children: ReactNode }): JSX.Element {
+ return (
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold whitespace-nowrap',
+ PILL_CLASS[kind]
+ )}
+ >
+ <span
+ className="inline-block size-2 shrink-0 rounded-full"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ backgroundColor: PILL_DOT[kind] }}
+ />
+ {children}
+ </span>
+ )
+}
+
+export function EntityHeader({
+ icon,
+ title,
+ titleSuffix,
+ slug,
+ right,
+}: {
+ icon?: ReactNode
+ title: string
+ /** Muted addition after the title (e.g. the run id). */
+ titleSuffix?: ReactNode
+ /** Mono context line under the title: repo/path, links, attempt, "View on GitHub". */
+ slug: ReactNode
+ right?: ReactNode
+}): JSX.Element {
+ return (
+ <div className="flex items-start gap-3.5">
+ {icon && (
+ <span className="flex size-10 shrink-0 items-center justify-center rounded-lg border border-primary bg-surface-primary text-lg">
+ {icon}
+ </span>
+ )}
+ <div className="min-w-0">
+ <h1 className="m-0 text-xl font-bold leading-tight tracking-tight">
+ {title}
+ {titleSuffix && <span className="ml-2 font-normal text-tertiary">{titleSuffix}</span>}
+ </h1>
+ <div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 font-mono text-[11.5px] text-tertiary">
+ {slug}
+ </div>
+ </div>
+ {right && <div className="ml-auto flex shrink-0 items-center gap-2">{right}</div>}
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/FailureLogs.tsx b/products/engineering_analytics/frontend/components/FailureLogs.tsx
new file mode 100644
index 000000000000..5af4586db284
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/FailureLogs.tsx
@@ -0,0 +1,82 @@
+// CI failure log excerpts grouped by failed job. Lines come pre-thinned from the backend; omission
+// markers (original_line == null) render muted so the elision is visible, never silent.
+
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { CIJobFailureLogApi } from '../generated/api.schemas'
+
+function JobFailureLog({ job, jobName }: { job: CIJobFailureLogApi; jobName?: string }): JSX.Element {
+ return (
+ <div className="overflow-hidden rounded border border-primary bg-surface-primary">
+ <div className="flex items-center gap-2 border-b border-primary px-3 py-2 text-xs font-semibold">
+ <LemonTag type="danger" size="small">
+ {job.conclusion === 'timed_out' ? 'TIMED OUT' : 'FAILED'}
+ </LemonTag>
+ <span className="truncate font-mono">{jobName ?? `job ${job.job_id}`}</span>
+ {job.branch && <span className="font-mono font-normal text-tertiary">· {job.branch}</span>}
+ <span className="ml-auto font-normal text-tertiary">
+ {job.line_count} of {job.original_total_lines || '?'} lines
+ {job.truncated ? ' · truncated' : ''}
+ </span>
+ </div>
+ <table className="w-full border-collapse">
+ <tbody>
+ {job.lines.map((line, i) => (
+ <tr key={i} className={cn(i > 0 && 'border-t border-primary')}>
+ <td className="w-14 px-3 py-1 align-top text-right font-mono text-[11px] tabular-nums text-tertiary whitespace-nowrap">
+ {line.original_line ?? '⋯'}
+ </td>
+ <td
+ className={cn(
+ 'px-3 py-1 align-top font-mono text-[11.5px] leading-relaxed break-all',
+ line.original_line == null && 'italic text-tertiary'
+ )}
+ >
+ {line.text}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )
+}
+
+/**
+ * A set of failed jobs with their log excerpts, straight from the loader's union: ``null`` is the
+ * not-loaded state, ``'unavailable'`` a failed fetch, and ``logs_available === false`` means the run
+ * didn't fail or its logs aged out of retention.
+ */
+export function FailureLogGroups({
+ logs,
+ loading,
+ jobNames,
+}: {
+ logs: { jobs: CIJobFailureLogApi[]; logs_available: boolean } | 'unavailable' | null | undefined
+ loading: boolean
+ /** job_id → display name, when the caller has the run's jobs loaded — logs only carry ids. */
+ jobNames?: Record<number, string>
+}): JSX.Element {
+ if (logs === 'unavailable') {
+ return <div className="px-1 py-2 text-xs text-secondary">Failure logs are unavailable.</div>
+ }
+ if (logs == null) {
+ return <div className="px-1 py-2 text-xs text-secondary">{loading ? 'Loading failure logs…' : '—'}</div>
+ }
+ if (!logs.logs_available || logs.jobs.length === 0) {
+ return (
+ <div className="px-1 py-2 text-xs text-secondary">
+ No failure logs. Nothing failed, or the logs have aged out of retention.
+ </div>
+ )
+ }
+ return (
+ <div className="flex flex-col gap-2">
+ {logs.jobs.map((job) => (
+ <JobFailureLog key={`${job.run_id}:${job.job_id}`} job={job} jobName={jobNames?.[job.job_id]} />
+ ))}
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/GroupedJobsTable.tsx b/products/engineering_analytics/frontend/components/GroupedJobsTable.tsx
new file mode 100644
index 000000000000..c620bf4efc76
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/GroupedJobsTable.tsx
@@ -0,0 +1,273 @@
+// A run's jobs with matrix shards rolled up (lib/jobGroups, the same rule as the backend's SQL
+// de-shard); failing groups sort first and name their failed shards. Groups expand via the caret only —
+// links inside rows must stay clickable.
+
+import { LemonTable, LemonTag } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+
+import type { WorkflowJobApi } from '../generated/api.schemas'
+import { JobGroup, JobGroupConclusion, failedShardsLabel, groupJobs } from '../lib/jobGroups'
+import { BillableBadge } from './BillableBadge'
+import { RunConclusionTag, StatusDot } from './runTables'
+
+type WorkflowJobGroup = JobGroup<WorkflowJobApi>
+
+const GROUP_DOT_COLOR: Record<JobGroupConclusion, string> = {
+ success: 'var(--success)',
+ failure: 'var(--danger)',
+ running: 'var(--brand-blue)',
+ cancelled: 'var(--muted)',
+ skipped: 'var(--muted)',
+}
+
+function GroupConclusionDot({ conclusion }: { conclusion: JobGroupConclusion }): JSX.Element {
+ return (
+ <span
+ className="inline-block size-2 shrink-0 rounded-full"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ backgroundColor: GROUP_DOT_COLOR[conclusion], opacity: conclusion === 'skipped' ? 0.5 : 1 }}
+ />
+ )
+}
+
+interface GroupSpan {
+ startMs: number | null
+ endMs: number | null
+}
+
+function groupSpan(group: WorkflowJobGroup): GroupSpan {
+ const starts = group.jobs.map((j) => j.started_at).filter((at): at is string => !!at)
+ const ends = group.jobs
+ .map((j) => j.completed_at ?? (j.started_at ? dayjs().toISOString() : null))
+ .filter((at): at is string => !!at)
+ return {
+ startMs: starts.length ? Math.min(...starts.map((at) => dayjs(at).valueOf())) : null,
+ endMs: ends.length ? Math.max(...ends.map((at) => dayjs(at).valueOf())) : null,
+ }
+}
+
+/** Earliest-start → latest-finish envelope of the group's shards on the run's shared time axis. */
+function TimingEnvelope({
+ span,
+ conclusion,
+ axisStart,
+ axisEnd,
+}: {
+ span: GroupSpan
+ conclusion: JobGroupConclusion
+ axisStart: number
+ axisEnd: number
+}): JSX.Element {
+ if (span.startMs == null || span.endMs == null) {
+ return <span className="text-xs text-secondary">—</span>
+ }
+ const total = Math.max(1, axisEnd - axisStart)
+ const left = Math.max(0, Math.min(100, ((span.startMs - axisStart) / total) * 100))
+ const width = Math.max(1, Math.min(100 - left, ((span.endMs - span.startMs) / total) * 100))
+ return (
+ <span className="relative block h-2 w-full min-w-36">
+ <span className="absolute top-[3px] h-0.5 w-full rounded-full bg-fill-secondary" />
+ <span
+ className="absolute top-0.5 h-1 rounded-full opacity-80"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: `${left}%`, width: `${width}%`, backgroundColor: GROUP_DOT_COLOR[conclusion] }}
+ />
+ </span>
+ )
+}
+
+function durationRange(group: WorkflowJobGroup): JSX.Element {
+ const durations = group.jobs
+ .map((j) => j.duration_seconds)
+ .filter((d): d is number => d != null)
+ .sort((a, b) => a - b)
+ if (!durations.length) {
+ return <span className="text-xs text-secondary">—</span>
+ }
+ const min = durations[0]
+ const max = durations[durations.length - 1]
+ return (
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {durations.length > 1 && min !== max ? (
+ <>
+ {humanFriendlyDuration(min)} <span className="text-tertiary">→ {humanFriendlyDuration(max)}</span>
+ </>
+ ) : (
+ humanFriendlyDuration(max)
+ )}
+ </span>
+ )
+}
+
+function runnerLabel(group: WorkflowJobGroup): JSX.Element {
+ const labels = Array.from(new Set(group.jobs.map((j) => j.runner_label).filter(Boolean)))
+ if (!labels.length) {
+ return <span className="text-xs text-secondary">—</span>
+ }
+ return (
+ <span className="font-mono text-[11px] text-tertiary whitespace-nowrap">
+ {labels[0]}
+ {labels.length > 1 && <span> +{labels.length - 1}</span>}
+ </span>
+ )
+}
+
+function groupCost(group: WorkflowJobGroup): JSX.Element {
+ if (group.jobs.every((j) => j.runner_provider === 'github_hosted')) {
+ return <span className="text-xs text-secondary">Free</span>
+ }
+ const billable = group.jobs.filter((j) => j.runner_provider === 'self_hosted' && j.duration_seconds != null)
+ const minutes = billable.length ? billable.reduce((sum, j) => sum + (j.duration_seconds ?? 0), 0) / 60 : null
+ const costed = group.jobs.filter((j) => j.estimated_cost_usd != null)
+ const cost = costed.length ? costed.reduce((sum, j) => sum + (j.estimated_cost_usd ?? 0), 0) : null
+ return <BillableBadge minutes={minutes} costUsd={cost} />
+}
+
+function resultTag(group: WorkflowJobGroup): JSX.Element {
+ if (group.failed.length > 0 && group.jobs.length > 1) {
+ return (
+ <LemonTag type="danger">
+ {group.failed.length}/{group.jobs.length} failed
+ </LemonTag>
+ )
+ }
+ // The shared conclusion→tag convention; RunConclusionTag renders null as Running.
+ return <RunConclusionTag conclusion={group.conclusion === 'running' ? null : group.conclusion} />
+}
+
+/**
+ * Grouped jobs of one workflow-run attempt. ``jobs == null`` is the not-loaded state; ``[]`` means the
+ * job-level source isn't synced for this team (mirrors RunJobsTable's contract).
+ */
+export function GroupedJobsTable({
+ jobs,
+ loading,
+ embedded = false,
+}: {
+ jobs: WorkflowJobApi[] | null | undefined
+ loading: boolean
+ embedded?: boolean
+}): JSX.Element {
+ if (jobs == null) {
+ return <div className="px-3 py-2 text-xs text-secondary">{loading ? 'Loading jobs…' : 'No job data yet.'}</div>
+ }
+ if (jobs.length === 0) {
+ return (
+ <div className="px-3 py-2 text-xs text-secondary">
+ No job data yet. The job-level source isn't synced for this team.
+ </div>
+ )
+ }
+ const groups = groupJobs(jobs).sort((a, b) => Number(b.failed.length > 0) - Number(a.failed.length > 0))
+ const spans = new Map(groups.map((group) => [group.base, groupSpan(group)]))
+ const startValues = Array.from(spans.values())
+ .map((s) => s.startMs)
+ .filter((v): v is number => v != null)
+ const endValues = Array.from(spans.values())
+ .map((s) => s.endMs)
+ .filter((v): v is number => v != null)
+ const axisStart = startValues.length ? Math.min(...startValues) : 0
+ const axisEnd = endValues.length ? Math.max(...endValues) : 1
+
+ return (
+ <LemonTable<WorkflowJobGroup>
+ dataSource={groups}
+ size="small"
+ embedded={embedded}
+ loading={loading}
+ rowKey={(group) => group.base}
+ useURLForSorting={false}
+ expandable={{
+ noIndent: true,
+ // Only matrix groups expand, straight to their individual shards.
+ rowExpandable: (group) => group.jobs.length > 1,
+ expandedRowRender: (group) => (
+ <div className="px-3 py-2">
+ {[...group.jobs]
+ .sort(
+ (a, b) =>
+ Number(b.conclusion === 'failure' || b.conclusion === 'timed_out') -
+ Number(a.conclusion === 'failure' || a.conclusion === 'timed_out')
+ )
+ .map((job) => (
+ <div key={job.id} className="flex items-center gap-2 py-0.5 text-[11px]">
+ <StatusDot conclusion={job.conclusion} />
+ <span className="truncate font-mono">{job.name}</span>
+ <span className="ml-auto tabular-nums text-tertiary whitespace-nowrap">
+ {job.duration_seconds != null
+ ? humanFriendlyDuration(job.duration_seconds)
+ : '—'}
+ </span>
+ </div>
+ ))}
+ </div>
+ ),
+ }}
+ columns={[
+ {
+ title: 'Job',
+ key: 'job',
+ render: (_, group) => (
+ <span className="overflow-hidden">
+ <span className="flex items-center gap-1.5">
+ <GroupConclusionDot conclusion={group.conclusion} />
+ <span className="truncate font-mono text-[11px]">{group.base}</span>
+ {group.jobs.length > 1 && (
+ <LemonTag type="muted">
+ ×{group.jobs.length}
+ {group.variants > 1 ? ` · ${group.variants} variants` : ''}
+ </LemonTag>
+ )}
+ </span>
+ {group.failed.length > 0 && (
+ <span className="mt-0.5 block pl-3.5 font-mono text-[10.5px] text-danger">
+ {failedShardsLabel(group)} failed
+ </span>
+ )}
+ </span>
+ ),
+ },
+ {
+ title: 'Timing',
+ key: 'timing',
+ width: 220,
+ render: (_, group) => (
+ <TimingEnvelope
+ span={spans.get(group.base) ?? { startMs: null, endMs: null }}
+ conclusion={group.conclusion}
+ axisStart={axisStart}
+ axisEnd={axisEnd}
+ />
+ ),
+ },
+ {
+ title: 'Duration',
+ key: 'duration',
+ align: 'right',
+ render: (_, group) => durationRange(group),
+ },
+ {
+ title: 'Runner',
+ key: 'runner',
+ render: (_, group) => runnerLabel(group),
+ },
+ {
+ title: 'Cost',
+ key: 'cost',
+ align: 'right',
+ render: (_, group) => groupCost(group),
+ },
+ {
+ title: 'Result',
+ key: 'result',
+ width: 110,
+ render: (_, group) => resultTag(group),
+ },
+ ]}
+ emptyState="No jobs."
+ nouns={['job group', 'job groups']}
+ />
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/JobAggregatesTable.tsx b/products/engineering_analytics/frontend/components/JobAggregatesTable.tsx
new file mode 100644
index 000000000000..2ed333b2797e
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/JobAggregatesTable.tsx
@@ -0,0 +1,160 @@
+// One row per de-sharded job name (the backend strips the matrix "(G/N)" suffix with the same rule as
+// jobGroups). Jobs get no standalone pages — a job always needs its run as context.
+
+import { LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { WorkflowJobAggregateApi } from '../generated/api.schemas'
+import { compactUsd, percent } from '../lib/format'
+import { BillableBadge } from './BillableBadge'
+
+function formatSeconds(seconds: number | null): string {
+ return seconds == null ? '—' : humanFriendlyDuration(seconds)
+}
+
+export function JobAggregatesTable({
+ aggregates,
+ loading,
+ totalCostUsd,
+}: {
+ aggregates: WorkflowJobAggregateApi[]
+ loading: boolean
+ /** The workflow's total window cost — the denominator of each job's cost share. */
+ totalCostUsd: number | null
+}): JSX.Element {
+ return (
+ <LemonTable<WorkflowJobAggregateApi>
+ dataSource={aggregates}
+ loading={loading}
+ size="small"
+ rowKey={(row) => row.job_name}
+ useURLForSorting={false}
+ columns={[
+ {
+ title: 'Job',
+ key: 'job',
+ sorter: (a, b) => a.job_name.localeCompare(b.job_name),
+ render: (_, row) => (
+ <span className="flex items-center gap-2">
+ <span className="font-mono text-xs">{row.job_name}</span>
+ {row.shard_count > 1 && <LemonTag type="muted">×{row.shard_count} matrix</LemonTag>}
+ </span>
+ ),
+ },
+ {
+ title: 'Runs in',
+ key: 'runShare',
+ align: 'right',
+ tooltip: 'Share of workflow runs this job ran in. Below 100% means the job is conditional.',
+ sorter: (a, b) => (a.run_share ?? -1) - (b.run_share ?? -1),
+ render: (_, row) => (
+ <span
+ className={
+ row.run_share != null && row.run_share < 0.995
+ ? 'text-xs tabular-nums text-secondary'
+ : 'text-xs tabular-nums'
+ }
+ >
+ {row.run_share != null ? `${percent(Math.min(1, row.run_share))} of runs` : '—'}
+ </span>
+ ),
+ },
+ {
+ title: 'Queue p50',
+ key: 'queue',
+ align: 'right',
+ tooltip: 'Median wait from job created to started. Long waits point to runner capacity problems.',
+ sorter: (a, b) => (a.queue_p50_seconds ?? -1) - (b.queue_p50_seconds ?? -1),
+ render: (_, row) => (
+ <span className="text-xs tabular-nums text-tertiary">
+ {formatSeconds(row.queue_p50_seconds)}
+ </span>
+ ),
+ },
+ {
+ title: 'P50',
+ key: 'duration',
+ align: 'right',
+ tooltip: 'Median job duration over completed instances.',
+ sorter: (a, b) => (a.p50_seconds ?? -1) - (b.p50_seconds ?? -1),
+ render: (_, row) => (
+ <span className="text-xs tabular-nums whitespace-nowrap">{formatSeconds(row.p50_seconds)}</span>
+ ),
+ },
+ {
+ title: 'P95',
+ key: 'p95',
+ align: 'right',
+ tooltip: '95th-percentile job duration over completed instances.',
+ sorter: (a, b) => (a.p95_seconds ?? -1) - (b.p95_seconds ?? -1),
+ render: (_, row) => (
+ <span className="text-xs tabular-nums whitespace-nowrap text-secondary">
+ {formatSeconds(row.p95_seconds)}
+ </span>
+ ),
+ },
+ {
+ title: 'Failure rate',
+ key: 'failureRate',
+ align: 'right',
+ tooltip: 'Decisive failures (failure / timed out) over completed job instances.',
+ sorter: (a, b) => (a.failure_rate ?? -1) - (b.failure_rate ?? -1),
+ render: (_, row) => (
+ <span
+ className={
+ (row.failure_rate ?? 0) > 0.05
+ ? 'text-xs font-semibold tabular-nums text-danger'
+ : 'text-xs tabular-nums'
+ }
+ >
+ {row.failure_rate != null ? percent(row.failure_rate) : '—'}
+ </span>
+ ),
+ },
+ {
+ title: 'Retries',
+ key: 'retries',
+ align: 'right',
+ tooltip:
+ 'Job instances that ran on a second or later attempt. Frequent re-runs usually point to flaky checks.',
+ sorter: (a, b) => a.retry_job_count - b.retry_job_count,
+ render: (_, row) => (
+ <span className="text-xs tabular-nums">{humanFriendlyNumber(row.retry_job_count)}</span>
+ ),
+ },
+ {
+ title: 'Cost',
+ key: 'cost',
+ align: 'right',
+ tooltip:
+ 'Estimated cost over billable (self-hosted) runners. "—" when there is no billable figure: GitHub-hosted, an unrecognized runner, or no finished instance yet.',
+ sorter: (a, b) => (a.estimated_cost_usd ?? -1) - (b.estimated_cost_usd ?? -1),
+ render: (_, row) => {
+ if (row.estimated_cost_usd == null) {
+ return <span className="text-xs text-tertiary">—</span>
+ }
+ const share = totalCostUsd && totalCostUsd > 0 ? row.estimated_cost_usd / totalCostUsd : null
+ return (
+ <Tooltip
+ title={
+ <BillableBadge minutes={row.billable_minutes} costUsd={row.estimated_cost_usd} />
+ }
+ >
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {compactUsd(row.estimated_cost_usd)}
+ {share != null && <span className="ml-1 text-tertiary">{percent(share)}</span>}
+ </span>
+ </Tooltip>
+ )
+ },
+ },
+ ]}
+ defaultSorting={{ columnKey: 'cost', order: -1 }}
+ pagination={{ pageSize: 50 }}
+ emptyState="No jobs in the window. The job-level source may not be synced."
+ nouns={['job', 'jobs']}
+ />
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/MetricTile.tsx b/products/engineering_analytics/frontend/components/MetricTile.tsx
new file mode 100644
index 000000000000..3404121218be
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/MetricTile.tsx
@@ -0,0 +1,108 @@
+// Headline-metric tile: label · value (+suffix) · delta vs the previous window · caption.
+// Every entity page builds its stat strip from this tile.
+
+import { ReactNode } from 'react'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { cn } from 'lib/utils/css-classes'
+
+/** Relative change in percent, or null when there's no meaningful baseline. */
+export function percentChange(current: number | null | undefined, previous: number | null | undefined): number | null {
+ if (current == null || previous == null || previous === 0) {
+ return null
+ }
+ return ((current - previous) / previous) * 100
+}
+
+/** Percentage-point change for 0–1 rates, or null when either window has no signal. */
+export function pointChange(current: number | null | undefined, previous: number | null | undefined): number | null {
+ if (current == null || previous == null) {
+ return null
+ }
+ return (current - previous) * 100
+}
+
+export function DeltaBadge({
+ value,
+ unit = '%',
+ goodWhenDown = false,
+ precision = 0,
+ vs = 'vs the previous window',
+}: {
+ /** The delta to show; null hides the badge (no baseline to compare against). */
+ value: number | null
+ unit?: string
+ /** For costs, durations, failures — a drop is the good direction. */
+ goodWhenDown?: boolean
+ precision?: number
+ vs?: string
+}): JSX.Element | null {
+ if (value == null) {
+ return null
+ }
+ const rounded = Number(value.toFixed(precision))
+ if (rounded === 0) {
+ return (
+ <Tooltip title={vs}>
+ <span className="text-xs font-medium text-tertiary whitespace-nowrap">±0{unit}</span>
+ </Tooltip>
+ )
+ }
+ const up = rounded > 0
+ const good = goodWhenDown ? !up : up
+ // A near-zero baseline turns growth into a meaningless five-digit percentage — clamp the display.
+ const display = Math.abs(rounded) > 999 ? '>999' : Math.abs(rounded).toFixed(precision)
+ return (
+ <Tooltip title={vs}>
+ <span className={cn('text-xs font-semibold whitespace-nowrap', good ? 'text-success' : 'text-danger')}>
+ {up ? '▲' : '▼'} {display}
+ {unit}
+ </span>
+ </Tooltip>
+ )
+}
+
+export function MetricTile({
+ label,
+ tooltip,
+ value,
+ valueSuffix,
+ delta,
+ sub,
+ className,
+}: {
+ label: string
+ /** Definition or methodology, shown on label hover. */
+ tooltip?: ReactNode
+ /** Pre-formatted headline value; '—' for no data. */
+ value: string
+ valueSuffix?: string
+ delta?: ReactNode
+ /** Visible caption — only for an answer worth a glance (what's failing, why there's no value). */
+ sub?: ReactNode
+ className?: string
+}): JSX.Element {
+ const labelSpan = <span className="text-xs text-secondary">{label}</span>
+ return (
+ <LemonCard
+ hoverEffect={false}
+ className={cn('flex min-w-44 flex-1 flex-col justify-center gap-1 px-5 py-4', className)}
+ >
+ {tooltip ? (
+ <Tooltip title={tooltip}>
+ <span className="self-start cursor-default">{labelSpan}</span>
+ </Tooltip>
+ ) : (
+ labelSpan
+ )}
+ <span className="flex items-baseline gap-2">
+ <span className="text-2xl font-semibold leading-none tabular-nums">{value}</span>
+ {valueSuffix && <span className="text-xs font-medium text-tertiary">{valueSuffix}</span>}
+ {delta}
+ </span>
+ {sub && <span className="text-xs text-tertiary">{sub}</span>}
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/PullRequestTable.tsx b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
index 4147949ca6ab..cef561565ae6 100644
--- a/products/engineering_analytics/frontend/components/PullRequestTable.tsx
+++ b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
@@ -1,17 +1,17 @@
-// The PR list table, shared by the main PR list (Overview tab) and the author page (scoped to one
-// author). Only the author column and default sort differ per caller.
+// Shared by the repo hub and the PR list. Author renders as plain metadata and links nowhere
+// in-product (attribution, never a unit of analysis — see SPEC §2).
import { combineUrl, router } from 'kea-router'
import { ReactNode } from 'react'
-import { LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
+import { LemonTable, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
-import { TZLabel } from 'lib/components/TZLabel'
-import { humanFriendlyDuration } from 'lib/utils/durations'
+import { dayjs } from 'lib/dayjs'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
+import { compactHoursLabel } from '../lib/format'
import { githubPrUrl } from '../lib/github'
import { PullRequestRow, prKeyOf } from '../scenes/engineeringAnalyticsLogic'
import { BillableBadge } from './BillableBadge'
@@ -26,6 +26,17 @@ function detailUrlOf(row: PullRequestRow, sourceId: string | null): string {
).url
}
+/** How long the PR has been (or was) open, in the shared hours/days headline format.
+ * Null for closed-unmerged PRs: the list carries no closed_at, so their open time is unknown. */
+function openTimeOf(row: PullRequestRow): { seconds: number; label: string } | null {
+ const end = row.mergedAt ?? (row.state === 'open' ? dayjs().toISOString() : null)
+ if (!end) {
+ return null
+ }
+ const seconds = dayjs(end).diff(dayjs(row.createdAt), 'second')
+ return { seconds, label: compactHoursLabel(seconds) }
+}
+
export interface PullRequestTableProps {
rows: PullRequestRow[]
loading: boolean
@@ -33,9 +44,8 @@ export interface PullRequestTableProps {
sourceId: string | null
/** Show the pushes / re-runs / CI cost columns. */
costLensEnabled: boolean
- /** Author column is redundant on the author page (every row is the same author) — hide it there. */
- showAuthor?: boolean
- defaultSorting?: { columnKey: string; order: 1 | -1 }
+ /** Rows per page — the list page's 50 by default; the hub passes a small page to stay scannable. */
+ pageSize?: number
emptyState?: ReactNode
dataAttr?: string
}
@@ -45,8 +55,7 @@ export function PullRequestTable({
loading,
sourceId,
costLensEnabled,
- showAuthor = true,
- defaultSorting,
+ pageSize = 50,
emptyState,
dataAttr = 'engineering-analytics-pr-table',
}: PullRequestTableProps): JSX.Element {
@@ -56,18 +65,15 @@ export function PullRequestTable({
key: 'title',
render: (_, row) => (
<div className="flex flex-col gap-0.5">
- <div className="flex items-center gap-2">
- <PullRequestStateTag state={row.state} isDraft={row.isDraft} />
- <Link to={detailUrlOf(row, sourceId)} className="font-medium">
- {row.title}
- </Link>
- </div>
+ <Link to={detailUrlOf(row, sourceId)} className="font-medium">
+ {row.title}
+ </Link>
<div className="flex items-center gap-1.5 text-xs text-secondary">
<Link
to={githubPrUrl(row.repoOwner, row.repoName, row.number)}
target="_blank"
targetBlankIcon
- className="font-mono text-secondary"
+ className="font-mono text-[11px] text-tertiary"
>
{row.repoOwner}/{row.repoName} #{row.number}
</Link>
@@ -81,61 +87,39 @@ export function PullRequestTable({
),
},
{
- title: 'CI',
- key: 'ci',
- width: 190,
- render: (_, row) => <CIStatusTag rollup={row} />,
+ title: 'State',
+ key: 'state',
+ width: 104,
+ render: (_, row) => <PullRequestStateTag state={row.state} isDraft={row.isDraft} />,
},
- ...(showAuthor
- ? ([
- {
- title: 'Author',
- key: 'author',
- width: 190,
- render: (_, row) => (
- <div className="flex items-center gap-1.5">
- {row.authorAvatarUrl && (
- <img src={row.authorAvatarUrl} alt="" className="h-5 w-5 shrink-0 rounded-full" />
- )}
- <Link
- to={
- combineUrl(
- urls.engineeringAnalyticsAuthor(row.authorHandle),
- sourceId ? { source: sourceId } : {}
- ).url
- }
- className="text-xs"
- >
- {row.authorHandle}
- </Link>
- {row.isBot && <LemonTag type="muted">bot</LemonTag>}
- </div>
- ),
- },
- ] as LemonTableColumns<PullRequestRow>)
- : []),
{
- title: 'Opened',
- key: 'age',
- width: 130,
- align: 'right',
- sorter: (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
+ title: 'Author',
+ key: 'author',
+ width: 170,
render: (_, row) => (
- <span className="text-xs whitespace-nowrap">
- <TZLabel time={row.createdAt} />
- </span>
+ <div className="flex items-center gap-1.5">
+ {row.authorAvatarUrl && (
+ <img src={row.authorAvatarUrl} alt="" className="size-5 shrink-0 rounded-full" />
+ )}
+ <span className="text-xs font-medium">{row.authorHandle}</span>
+ {row.isBot && <LemonTag type="muted">bot</LemonTag>}
+ </div>
),
},
{
- title: 'Open→merge',
- key: 'openToMerge',
- width: 130,
- align: 'right',
- sorter: (a, b) => (a.openToMergeSeconds ?? -1) - (b.openToMergeSeconds ?? -1),
+ title: 'CI',
+ key: 'ci',
+ width: 190,
render: (_, row) => (
- <span className="text-xs whitespace-nowrap text-secondary">
- {row.openToMergeSeconds == null ? '—' : humanFriendlyDuration(row.openToMergeSeconds)}
- </span>
+ <div className="flex flex-col gap-0.5">
+ <CIStatusTag rollup={row} />
+ {row.failingWorkflows.length > 0 && (
+ <span className="text-[10.5px] leading-tight text-tertiary">
+ {row.failingWorkflows.slice(0, 3).join(' · ')}
+ {row.failingWorkflows.length > 3 && ` +${row.failingWorkflows.length - 3}`}
+ </span>
+ )}
+ </div>
),
},
...(costLensEnabled
@@ -143,25 +127,19 @@ export function PullRequestTable({
{
title: 'Pushes',
key: 'pushes',
- width: 90,
+ width: 100,
align: 'right',
tooltip:
- 'Distinct head commits that triggered CI for this PR (all-time, not windowed). Fork PRs are unattributed.',
+ 'Distinct head commits that triggered CI for this PR, with re-run cycles as the amber tag. Fork PRs are unattributed.',
sorter: (a, b) => a.pushes - b.pushes,
render: (_, row) => (
- <span className="text-xs tabular-nums">{humanFriendlyNumber(row.pushes)}</span>
- ),
- },
- {
- title: 'Re-runs',
- key: 'rerunCycles',
- width: 90,
- align: 'right',
- tooltip: 'Workflow runs on this PR that were a 2nd+ attempt (a re-run).',
- sorter: (a, b) => a.rerunCycles - b.rerunCycles,
- render: (_, row) => (
- <span className="text-xs tabular-nums">
- {row.rerunCycles > 0 ? humanFriendlyNumber(row.rerunCycles) : '—'}
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {humanFriendlyNumber(row.pushes)}
+ {row.rerunCycles > 0 && (
+ <LemonTag type="warning" className="ml-1.5">
+ +{row.rerunCycles}
+ </LemonTag>
+ )}
</span>
),
},
@@ -179,6 +157,19 @@ export function PullRequestTable({
},
] as LemonTableColumns<PullRequestRow>)
: []),
+ {
+ title: 'Open time',
+ key: 'age',
+ width: 100,
+ align: 'right',
+ tooltip: 'How long the pull request has been open (or was, until it merged).',
+ sorter: (a, b) => (openTimeOf(a)?.seconds ?? -1) - (openTimeOf(b)?.seconds ?? -1),
+ render: (_, row) => (
+ <Tooltip title={<>opened {dayjs(row.createdAt).format('MMM D, HH:mm')}</>}>
+ <span className="text-xs tabular-nums whitespace-nowrap">{openTimeOf(row)?.label ?? '—'}</span>
+ </Tooltip>
+ ),
+ },
]
return (
@@ -189,11 +180,10 @@ export function PullRequestTable({
dataSource={rows}
rowKey={prKeyOf}
loading={loading}
- defaultSorting={defaultSorting}
onRow={(row) => {
const detailUrl = detailUrlOf(row, sourceId)
return {
- // Inner links (#id → GitHub, author → author page) keep their own behavior.
+ // Inner links (#id → GitHub) keep their own behavior.
onClick: (e: React.MouseEvent) => {
if ((e.target as HTMLElement).closest('a, button')) {
return
@@ -214,8 +204,8 @@ export function PullRequestTable({
}
}}
useURLForSorting={false}
- pagination={{ pageSize: 50 }}
- emptyState={emptyState ?? 'No pull requests yet — they show up as soon as CI events arrive.'}
+ pagination={{ pageSize }}
+ emptyState={emptyState ?? "No pull requests yet. They'll appear once the GitHub source syncs."}
nouns={['pull request', 'pull requests']}
/>
)
diff --git a/products/engineering_analytics/frontend/components/RangeBar.tsx b/products/engineering_analytics/frontend/components/RangeBar.tsx
deleted file mode 100644
index 318a1ac28aac..000000000000
--- a/products/engineering_analytics/frontend/components/RangeBar.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { ReactNode } from 'react'
-
-import { Tooltip } from '@posthog/lemon-ui'
-
-import { cn } from 'lib/utils/css-classes'
-
-/**
- * Compact horizontal bar with a fill and an optional tick marker (e.g. median duration as the fill, p95
- * as the tick). Tick triangle and fill width are inline styles because they're data-driven.
- */
-export function RangeBar({
- fraction,
- tickFraction,
- fillColor = 'var(--brand-blue)',
- tickColor = 'var(--muted)',
- className,
- tooltip,
-}: {
- /** 0–1 — how far the bar fills. */
- fraction: number
- /** 0–1 — optional marker (a small triangle above the bar); omit for a plain fill. */
- tickFraction?: number | null
- fillColor?: string
- tickColor?: string
- className?: string
- tooltip?: ReactNode
-}): JSX.Element {
- const fill = Math.max(0, Math.min(100, fraction * 100))
- const tick = tickFraction == null ? null : Math.max(0, Math.min(100, tickFraction * 100))
- const bar = (
- <span className={cn('relative inline-block', className)}>
- <span className="block h-1.5 overflow-hidden rounded-full bg-border-light">
- {/* eslint-disable-next-line react/forbid-dom-props */}
- <span className="block h-full rounded-full" style={{ width: `${fill}%`, backgroundColor: fillColor }} />
- </span>
- {tick != null && (
- <span
- className="absolute"
- // eslint-disable-next-line react/forbid-dom-props
- style={{
- left: `${tick}%`,
- top: -4,
- marginLeft: -3,
- width: 0,
- height: 0,
- borderLeft: '3px solid transparent',
- borderRight: '3px solid transparent',
- borderTop: `4px solid ${tickColor}`,
- }}
- />
- )}
- </span>
- )
- return tooltip ? <Tooltip title={tooltip}>{bar}</Tooltip> : bar
-}
diff --git a/products/engineering_analytics/frontend/components/RunActivityChart.tsx b/products/engineering_analytics/frontend/components/RunActivityChart.tsx
index 534af6790b85..5a28e5f80e54 100644
--- a/products/engineering_analytics/frontend/components/RunActivityChart.tsx
+++ b/products/engineering_analytics/frontend/components/RunActivityChart.tsx
@@ -59,11 +59,9 @@ const MIN_POINTS = 2
const LENS_MS = 24 * 60 * 60 * 1000
// The lens never narrows below 15 min, so it stays grabbable and the zoomed axis keeps a readable span.
const MIN_LENS_MS = 15 * 60 * 1000
-// A run with no final duration is treated as in flight up to now — but only up to this cap. A run that
-// started longer ago than this and still hasn't settled almost certainly never will (its completion webhook
-// was missed); without the cap its interval would stretch to now and inflate the in-flight band — and the
-// time axis — by hours or days. Capping bounds that phantom load while still counting a genuinely-running
-// recent run right up to now.
+// A run with no final duration counts as in flight up to now, capped here: one that started longer ago
+// and never settled almost certainly lost its completion webhook, and uncapped it would inflate the
+// in-flight band and time axis by days.
const MAX_IN_FLIGHT_MS = 60 * 60 * 1000
/** Round up to a "nice" number (1/2/5 × 10ⁿ) so axis ticks land on readable values. */
@@ -397,9 +395,7 @@ export function RunActivityChart({
<h3 className="mb-0">{title}</h3>
<Tooltip
title={
- truncated
- ? `Over the most recent ${plottable.length} runs — the list is capped, so this isn't the full window.`
- : undefined
+ truncated ? `Covers the most recent ${plottable.length} runs, not the full window.` : undefined
}
>
<span className="text-xs whitespace-nowrap text-secondary tabular-nums">
diff --git a/products/engineering_analytics/frontend/components/ScopeBar.tsx b/products/engineering_analytics/frontend/components/ScopeBar.tsx
new file mode 100644
index 000000000000..a988069ac701
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/ScopeBar.tsx
@@ -0,0 +1,219 @@
+// 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.
+
+import { useActions, useValues } from 'kea'
+import { Fragment, ReactNode, useState } from 'react'
+
+import { IconX } from '@posthog/icons'
+import { LemonButton, LemonDropdown, LemonInput, LemonSelect, Link } from '@posthog/lemon-ui'
+
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { cn } from 'lib/utils/css-classes'
+import { dateMapping } from 'lib/utils/dateFilters'
+
+import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from '../scenes/engineeringAnalyticsFiltersLogic'
+import { engineeringAnalyticsLogic } from '../scenes/engineeringAnalyticsLogic'
+
+// The endpoints require a window start (no "all time") — relative windows + Custom only.
+export const SCOPE_DATE_OPTIONS = dateMapping.filter(({ key }) =>
+ [
+ 'Custom',
+ 'Last 24 hours',
+ 'Last 7 days',
+ 'Last 14 days',
+ 'Last 30 days',
+ 'Last 90 days',
+ 'Last 180 days',
+ ].includes(key)
+)
+
+export interface ScopeCrumb {
+ label: string
+ to?: string
+}
+
+export interface LensChip {
+ label: string
+ /** Where dismissing the chip navigates. */
+ to: string
+}
+
+const CHIP_CLASS =
+ 'inline-flex items-center gap-1.5 rounded border border-primary bg-surface-primary px-2.5 py-1 text-xs text-secondary'
+
+/** A source picker on multi-source teams, otherwise the repo name. `pickerOnly` skips the static chip
+ * on pages that already state the repo elsewhere (the hub's entity header). */
+export function SourceScopeChip({ pickerOnly = false }: { pickerOnly?: boolean }): JSX.Element | null {
+ const { hasMultipleSources, sourceOptions, sourceId, activeSource } = useValues(engineeringAnalyticsLogic)
+ const { setSourceId } = useActions(engineeringAnalyticsLogic)
+ const repoLabel = activeSource?.repo
+ if (hasMultipleSources) {
+ return (
+ <LemonSelect
+ size="small"
+ value={sourceId}
+ onChange={setSourceId}
+ options={sourceOptions}
+ placeholder={repoLabel || 'Repository'}
+ allowClear
+ dropdownMatchSelectWidth={false}
+ data-attr="engineering-analytics-source-select"
+ />
+ )
+ }
+ // No repo name yet — render nothing rather than a dead "Repository" pill.
+ if (pickerOnly || !repoLabel) {
+ return null
+ }
+ return (
+ <span className={CHIP_CLASS}>
+ <strong className="font-semibold text-primary">{repoLabel}</strong>
+ </span>
+ )
+}
+
+/** Repo chip on detail pages: links back to the hub without mounting the hub's loaders. */
+export function RepoScopeChip({ label, to }: { label: string; to: string }): JSX.Element {
+ return (
+ <Link to={to}>
+ <span className={cn(CHIP_CLASS, 'cursor-pointer')}>
+ <strong className="font-semibold text-primary">{label}</strong>
+ </span>
+ </Link>
+ )
+}
+
+// Quick presets for the default branch. We can't tell main from master without another query, so offer
+// both — picking the active one clears back to all branches.
+const DEFAULT_BRANCHES = ['main', 'master']
+
+/** Branch chip opening a small picker — a server-side head_branch filter shared across pages. */
+function BranchScopeChip(): JSX.Element {
+ const { branchInput, appliedBranch } = useValues(engineeringAnalyticsFiltersLogic)
+ const { setBranchFilter, applyBranchFilter } = useActions(engineeringAnalyticsFiltersLogic)
+ const [visible, setVisible] = useState(false)
+
+ // Stage + apply a branch in one click; picking the active preset clears back to all branches.
+ const selectBranch = (branch: string): void => {
+ setBranchFilter(branch)
+ applyBranchFilter()
+ setVisible(false)
+ }
+
+ return (
+ <LemonDropdown
+ visible={visible}
+ onVisibilityChange={setVisible}
+ closeOnClickInside={false}
+ overlay={
+ <div className="flex w-64 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">
+ {DEFAULT_BRANCHES.map((branch) => (
+ <LemonButton
+ key={branch}
+ size="xsmall"
+ type={appliedBranch === branch ? 'primary' : 'secondary'}
+ onClick={() => selectBranch(appliedBranch === branch ? '' : branch)}
+ >
+ {branch}
+ </LemonButton>
+ ))}
+ <LemonButton
+ size="xsmall"
+ type={appliedBranch === '' ? 'primary' : 'secondary'}
+ onClick={() => selectBranch('')}
+ >
+ all branches
+ </LemonButton>
+ </div>
+ </div>
+ }
+ >
+ <span className={cn(CHIP_CLASS, 'cursor-pointer')} title="One branch scope for every section below">
+ branch:{' '}
+ <strong className={cn('font-semibold', appliedBranch ? 'text-primary' : 'text-tertiary')}>
+ {appliedBranch || 'all'}
+ </strong>
+ <span className="text-[8px] text-tertiary">▼</span>
+ </span>
+ </LemonDropdown>
+ )
+}
+
+export function ScopeBar({
+ repoSlot,
+ crumbs = [],
+ lensFilter,
+ showBranch = false,
+ showDate = true,
+ extra,
+}: {
+ /** The repo chip: <SourceScopeChip /> on hub/list pages, <RepoScopeChip /> on detail pages. */
+ repoSlot: ReactNode
+ /** Hierarchy below the repo (workflow › run); empty on the repo hub itself. */
+ crumbs?: ScopeCrumb[]
+ /** The active cross-cutting lens (pr: #N) — dismissible, zooms out to `to`. */
+ lensFilter?: LensChip
+ showBranch?: boolean
+ showDate?: boolean
+ extra?: ReactNode
+}): JSX.Element {
+ const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
+ const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
+
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ {repoSlot}
+ {crumbs.map((crumb) => (
+ <Fragment key={crumb.label}>
+ <span className="text-xs text-tertiary">›</span>
+ {crumb.to ? (
+ <Link to={crumb.to} className="text-[13px] font-medium">
+ {crumb.label}
+ </Link>
+ ) : (
+ <span className="text-[13px] font-semibold">{crumb.label}</span>
+ )}
+ </Fragment>
+ ))}
+ <span className="ml-auto flex flex-wrap items-center gap-2">
+ {lensFilter && (
+ <span
+ className={cn(CHIP_CLASS, 'border-accent-highlight-secondary bg-fill-highlight-50')}
+ title="A filter is applied to this page. Remove it to see the whole repo."
+ >
+ <strong className="font-semibold text-primary">{lensFilter.label}</strong>
+ <Link to={lensFilter.to} className="px-0.5 text-tertiary hover:text-primary">
+ <IconX />
+ </Link>
+ </span>
+ )}
+ {showBranch && <BranchScopeChip />}
+ {showDate && (
+ <DateFilter
+ dateFrom={dateFrom}
+ dateTo={dateTo}
+ onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
+ dateOptions={SCOPE_DATE_OPTIONS}
+ size="small"
+ />
+ )}
+ {extra}
+ </span>
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/Section.tsx b/products/engineering_analytics/frontend/components/Section.tsx
new file mode 100644
index 000000000000..387a34ba1682
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/Section.tsx
@@ -0,0 +1,53 @@
+// Anchored page sections with a compact title row, plus a sticky jumper that scrolls between them.
+
+import { ReactNode } from 'react'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+function sectionDomId(id: string): string {
+ return `ea-section-${id}`
+}
+
+export function scrollToSection(id: string): void {
+ document.getElementById(sectionDomId(id))?.scrollIntoView({ behavior: 'smooth', block: 'start' })
+}
+
+export function Section({
+ id,
+ title,
+ note,
+ right,
+ children,
+}: {
+ id: string
+ title: string
+ /** Muted caveat after the title. Only for load-bearing context the data can't show (scope, inclusion
+ * criteria, a legend) — never a restatement of the title or an interaction hint. */
+ note?: ReactNode
+ right?: ReactNode
+ children: ReactNode
+}): JSX.Element {
+ return (
+ <section id={sectionDomId(id)} className="scroll-mt-14">
+ <div className="mb-2 flex items-baseline gap-2.5">
+ <h2 className="m-0 text-base font-semibold">{title}</h2>
+ {note && <span className="text-xs text-tertiary">{note}</span>}
+ {right && <span className="ml-auto text-xs">{right}</span>}
+ </div>
+ {children}
+ </section>
+ )
+}
+
+export function SectionNav({ items }: { items: { id: string; label: string }[] }): JSX.Element {
+ return (
+ <div className="sticky top-0 z-10 -mx-1 flex flex-wrap items-center gap-0.5 bg-primary px-1 py-1.5">
+ <span className="mr-1.5 text-xs text-tertiary">Jump to</span>
+ {items.map((item) => (
+ <LemonButton key={item.id} size="xsmall" onClick={() => scrollToSection(item.id)}>
+ {item.label}
+ </LemonButton>
+ ))}
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/ShareRow.tsx b/products/engineering_analytics/frontend/components/ShareRow.tsx
new file mode 100644
index 000000000000..86246bd468cd
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/ShareRow.tsx
@@ -0,0 +1,65 @@
+// A leaderboard row: rank · label/sub · share bar · value/value-sub. The cost section builds its
+// "where does it go" list from this, so every breakdown reads the same.
+
+import { ReactNode } from 'react'
+
+import { Link } from '@posthog/lemon-ui'
+
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { Lettermark } from 'lib/lemon-ui/Lettermark'
+import { cn } from 'lib/utils/css-classes'
+
+export function ShareRow({
+ rank,
+ label,
+ sub,
+ value,
+ valueSub,
+ share,
+ color,
+ to,
+ avatar,
+}: {
+ rank?: number
+ label: ReactNode
+ sub?: ReactNode
+ value: ReactNode
+ valueSub?: ReactNode
+ /** 0–1 — the share bar's fill. Omit for a bar-less row. */
+ share?: number
+ color?: string
+ to?: string
+ avatar?: string
+}): JSX.Element {
+ const row = (
+ <div
+ className={cn(
+ 'flex items-center gap-3 border-b border-primary px-1 py-2 last:border-b-0',
+ to && 'cursor-pointer hover:bg-fill-button-tertiary-hover'
+ )}
+ >
+ {rank !== undefined && (
+ <span className="w-4 shrink-0 text-right text-xs tabular-nums text-tertiary">{rank}.</span>
+ )}
+ {avatar && <Lettermark name={avatar} />}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-semibold text-primary">{label}</span>
+ {sub && <span className="block truncate text-[11px] text-tertiary">{sub}</span>}
+ </span>
+ {share !== undefined && (
+ <LemonProgress
+ percent={share * 100}
+ strokeColor={color ?? 'var(--brand-blue)'}
+ bgColor="var(--color-bg-fill-tertiary)"
+ smoothing={false}
+ className="w-40 max-w-[30%] shrink-0"
+ />
+ )}
+ <span className="shrink-0 text-right">
+ <span className="block text-[13px] font-semibold tabular-nums text-primary">{value}</span>
+ {valueSub && <span className="block text-[10px] text-tertiary">{valueSub}</span>}
+ </span>
+ </div>
+ )
+ return to ? <Link to={to}>{row}</Link> : row
+}
diff --git a/products/engineering_analytics/frontend/components/StatCard.tsx b/products/engineering_analytics/frontend/components/StatCard.tsx
index 2b7fb02d14c5..9a0b3d7d41dc 100644
--- a/products/engineering_analytics/frontend/components/StatCard.tsx
+++ b/products/engineering_analytics/frontend/components/StatCard.tsx
@@ -15,7 +15,8 @@ export function StatCard({
}: {
label: string
value: string
- caption: string
+ /** Visible definition — only when the label alone doesn't explain the count. */
+ caption?: string
loading: boolean
onClick: () => void
active?: boolean
@@ -47,7 +48,7 @@ export function StatCard({
) : (
<div className="text-2xl font-bold leading-tight">{value}</div>
)}
- <div className="text-xs text-tertiary">{caption}</div>
+ {caption && <div className="text-xs text-tertiary">{caption}</div>}
</button>
</Tooltip>
)
diff --git a/products/engineering_analytics/frontend/components/StatTile.tsx b/products/engineering_analytics/frontend/components/StatTile.tsx
deleted file mode 100644
index b24304d4191b..000000000000
--- a/products/engineering_analytics/frontend/components/StatTile.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { ReactNode } from 'react'
-
-import { LemonCard } from 'lib/lemon-ui/LemonCard'
-import { cn } from 'lib/utils/css-classes'
-
-/** Plain headline metric tile. For the clickable filter-toggle variant, use StatCard. */
-export function StatTile({
- label,
- value,
- sub,
- className,
-}: {
- label: string
- value: string
- sub: ReactNode
- className?: string
-}): JSX.Element {
- return (
- <LemonCard hoverEffect={false} className={cn('flex min-w-44 flex-1 flex-col gap-1 px-5 py-4', className)}>
- <span className="text-xs text-secondary">{label}</span>
- <span className="text-2xl font-semibold leading-none tabular-nums">{value}</span>
- <span className="text-xs text-tertiary">{sub}</span>
- </LemonCard>
- )
-}
diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthHeader.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthHeader.tsx
deleted file mode 100644
index d8bc2de4593f..000000000000
--- a/products/engineering_analytics/frontend/components/WorkflowHealthHeader.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { LemonTag, Tooltip } from '@posthog/lemon-ui'
-
-import { TZLabel } from 'lib/components/TZLabel'
-import { LemonCard } from 'lib/lemon-ui/LemonCard'
-import { cn } from 'lib/utils/css-classes'
-import { humanFriendlyDuration } from 'lib/utils/durations'
-import { percentage } from 'lib/utils/numbers'
-
-import type { CostSummary, HealthSummary } from '../lib/runHealth'
-import { HealthKpi, STATE_META } from './healthVerdict'
-import { RangeBar } from './RangeBar'
-import { formatCost } from './runTables'
-
-function formatDuration(seconds: number | null): string {
- return seconds == null ? '—' : humanFriendlyDuration(seconds, { maxUnits: 2 })
-}
-
-/** Duration spread as a range bar: median is the fill, p95 the tick. */
-function DurationRange({ median, p95 }: { median: number | null; p95: number | null }): JSX.Element {
- // Scale a touch past p95 so its tick sits inside the bar rather than hard against the end.
- const scale = p95 ? p95 * 1.25 : 0
- return (
- <div className="flex flex-col gap-1">
- <span className="text-xs text-tertiary">Duration p50 → p95</span>
- <div className="flex items-center gap-2">
- <RangeBar
- className="w-20"
- fraction={scale ? Math.min(1, (median ?? 0) / scale) : 0}
- tickFraction={scale ? p95! / scale : null}
- tooltip={`median ${formatDuration(median)} · p95 ${formatDuration(p95)}`}
- />
- <span className="text-xs whitespace-nowrap tabular-nums text-secondary">
- {formatDuration(median)} → {formatDuration(p95)}
- </span>
- </div>
- </div>
- )
-}
-
-interface WorkflowHealthHeaderProps {
- summary: HealthSummary
- /** Cost rollup for the window; null (or all-null fields) hides the cost KPI when jobs aren't synced. */
- cost: CostSummary | null
- /** Runs list was capped server-side — run rollups are over the most recent runs, not the full window. */
- truncated?: boolean
- className?: string
-}
-
-/**
- * Verdict strip above a workflow's runs: colored state word + pass rate, plus rollups the chart can't
- * show (re-run rate, total CI cost).
- */
-export function WorkflowHealthHeader({ summary, cost, truncated, className }: WorkflowHealthHeaderProps): JSX.Element {
- const meta = STATE_META[summary.state]
- const passRateLabel = summary.passRate == null ? '—' : percentage(summary.passRate, 0)
- const hasCost = cost?.estimatedCostUsd != null
-
- return (
- <LemonCard
- hoverEffect={false}
- // Left accent in the state color so the strip reads healthy/degraded/failing at the edge.
- className={cn(
- 'flex flex-wrap items-center gap-x-6 gap-y-4 border-l-4 px-5 py-4',
- meta.borderClass,
- className
- )}
- >
- <div className="flex flex-col">
- <div className="flex items-center gap-2">
- <span className={cn('h-2.5 w-2.5 shrink-0 rounded-full', meta.dotClass)} />
- <span className={cn('text-xl font-semibold leading-none', meta.wordClass)}>{meta.word}</span>
- {summary.running > 0 && <LemonTag type={meta.tag}>{summary.running} running</LemonTag>}
- </div>
- <span className="mt-1.5 text-xs text-secondary">
- {summary.state === 'unknown' ? (
- 'No completed runs in this window'
- ) : summary.state === 'failing' ? (
- <>
- Latest run failed
- {summary.lastFailureAt && (
- <>
- {' · '}
- <TZLabel time={summary.lastFailureAt} />
- </>
- )}
- </>
- ) : (
- `${summary.passedRuns} of ${summary.completedRuns}${truncated ? ' recent' : ''} runs passed`
- )}
- </span>
- </div>
-
- <div className="flex flex-col border-l border-primary pl-6">
- <span className="text-2xl font-semibold leading-7 tabular-nums">{passRateLabel}</span>
- <span className="text-xs text-tertiary">
- pass rate · {truncated ? 'recent ' : ''}
- {summary.completedRuns} {truncated ? 'runs' : 'completed'}
- </span>
- </div>
-
- <div className="flex-1" />
-
- {/* Rollups not on the chart: median is the chart's dashed line (omitted); p95, re-run rate,
- and cost aren't. */}
- <div className="flex flex-wrap items-start gap-x-6 gap-y-3">
- <HealthKpi
- label="Runs"
- value={
- truncated ? (
- <Tooltip
- title={`Showing the most recent ${summary.totalRuns} runs. Failures and pass rate cover these; CI cost reflects the full window.`}
- >
- <span>{summary.totalRuns.toLocaleString()}+</span>
- </Tooltip>
- ) : (
- summary.totalRuns.toLocaleString()
- )
- }
- />
- <HealthKpi label="Failures" value={summary.failures.toLocaleString()} danger={summary.failures > 0} />
- <HealthKpi label="Re-runs" value={summary.reruns.toLocaleString()} danger={summary.reruns > 0} />
- <DurationRange median={summary.medianSeconds} p95={summary.p95Seconds} />
- {hasCost && <HealthKpi label="CI cost" value={`≈ ${formatCost(cost?.estimatedCostUsd ?? null)}`} />}
- </div>
- </LemonCard>
- )
-}
diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
index fb57db645ec6..3b30a8d5023e 100644
--- a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
+++ b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
@@ -1,36 +1,22 @@
-// Per-workflow CI health table, shared by the Workflows tab (time-bucketed) and the PR detail page
-// (per-push buckets, rows expandable to runs). Only the bucket axis and row expansion differ per caller.
+// Per-workflow CI health table, shared by the Workflows tab and the repo hub.
import { useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
import { ReactNode } from 'react'
-import { IconTrending } from '@posthog/icons'
-import { LemonTable, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
-import { getSeriesColorPalette } from 'lib/colors'
import { TZLabel } from 'lib/components/TZLabel'
-import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
-import type { ExpandableConfig } from 'lib/lemon-ui/LemonTable/types'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
-import {
- WorkflowHealthRow,
- WorkflowTrendDirection,
- workflowFailureSeries,
- workflowFailureTrend,
-} from '../scenes/engineeringAnalyticsLogic'
+import { WorkflowHealthRow, workflowFailureSeries } from '../scenes/engineeringAnalyticsLogic'
import { BillableBadge } from './BillableBadge'
import { FailureSparkline } from './FailureSparkline'
-import { CI_GRID } from './runTables'
-
-// Floor on bar slots for push-bucketed sparklines (PR view) so a single push stays narrow, but low
-// enough that 2-3 pushes read as separate bars. Time-bucketed sparklines (Workflows tab) fill.
-const PUSH_MIN_SLOTS = 10
+import { DeltaBadge, pointChange } from './MetricTile'
function formatSeconds(seconds: number | null): string {
return seconds == null ? '—' : humanFriendlyDuration(seconds)
@@ -40,11 +26,15 @@ function formatRate(rate: number | null): string {
return rate == null ? '—' : `${humanFriendlyNumber(rate * 100)}%`
}
-/** Color only what needs attention — red rare, amber occasional, everything else plain. */
-function successRateClass(rate: number | null): string {
+/** Color only what needs attention — red rare, amber occasional, everything else plain. A low rate
+ * without any decisive failure (skip/cancel-heavy workflows) stays plain: nothing is broken. */
+function successRateClass(rate: number | null, hasFailures: boolean): string {
if (rate == null) {
return 'text-secondary'
}
+ if (!hasFailures) {
+ return ''
+ }
if (rate < 0.8) {
return 'font-semibold text-danger'
}
@@ -54,17 +44,6 @@ function successRateClass(rate: number | null): string {
return ''
}
-/** Stable per-name color so each workflow keeps the same dot across renders and sorts. */
-function WorkflowDot({ name }: { name: string }): JSX.Element {
- const palette = getSeriesColorPalette()
- let hash = 0
- for (let i = 0; i < name.length; i++) {
- hash = (hash * 31 + name.charCodeAt(i)) | 0
- }
- const color = palette[Math.abs(hash) % palette.length]
- return <span className="inline-block h-2 w-2 rounded-full shrink-0" style={{ backgroundColor: color }} />
-}
-
/** Sort key so a Status sort surfaces failing workflows first. */
function statusRank(failed: boolean | null): number {
if (failed === true) {
@@ -89,40 +68,17 @@ function StatusTag({ failed, conclusion }: { failed: boolean | null; conclusion:
return <LemonTag type="muted">{capitalizeFirstLetter(conclusion.replace('_', ' '))}</LemonTag>
}
-function TrendArrow({ direction }: { direction: WorkflowTrendDirection }): JSX.Element {
- // Arrow tracks health, not failures: rising failures = declining health = red down arrow, and vice versa.
- if (direction === 'up') {
- return (
- <Tooltip title="Health declining — failures rising">
- <IconTrendingDown className="text-danger shrink-0" />
- </Tooltip>
- )
- }
- if (direction === 'down') {
- return (
- <Tooltip title="Health improving — failures falling">
- <IconTrending className="text-success shrink-0" />
- </Tooltip>
- )
- }
- return (
- <Tooltip title="Health steady — no change in failures">
- <IconTrendingFlat className="text-muted shrink-0" />
- </Tooltip>
- )
-}
-
export interface WorkflowHealthTableProps {
rows: WorkflowHealthRow[]
loading?: boolean
/** Threaded into the Workflow-name link so it preserves the active source. */
sourceId?: string | null
- /** Optional row expansion (the PR page expands a workflow to its runs). */
- expandable?: ExpandableConfig<WorkflowHealthRow>
/** Default column sort. Alphabetical by workflow name by default; click Status for failing-first. */
defaultSorting?: { columnKey: string; order: 1 | -1 }
- /** Show the billable cost column (needs per-workflow cost on the rows; PR page only for now). */
+ /** Show the billable cost column (needs per-workflow cost on the rows). */
showCost?: boolean
+ /** Rows per page — 50 by default; the hub passes a small page to stay scannable. */
+ pageSize?: number
emptyState?: ReactNode
dataAttr?: string
}
@@ -131,16 +87,15 @@ export function WorkflowHealthTable({
rows,
loading,
sourceId,
- expandable,
defaultSorting = { columnKey: 'workflowName', order: 1 },
showCost = false,
+ pageSize = 50,
emptyState,
dataAttr = 'engineering-analytics-workflow-table',
}: WorkflowHealthTableProps): JSX.Element {
const { searchParams } = useValues(router)
- // Carry the active CI-analytics window and branch scope into the drill-down so opening a workflow from a
- // non-default window/branch keeps it instead of snapping back to defaults (the tab links preserve them
- // the same way). Without the branch (`q`), the detail page would widen to all branches and show more runs.
+ // Carry the active window/branch scope into the drill-down; without `q` the detail page would
+ // silently widen to all branches.
const windowParams: Record<string, string> = {
...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),
...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
@@ -153,7 +108,6 @@ export function WorkflowHealthTable({
sorter: (a, b) => a.workflowName.localeCompare(b.workflowName),
render: (_, row) => (
<div className="flex items-center gap-2">
- <WorkflowDot name={row.workflowName} />
<Link
to={
combineUrl(
@@ -172,7 +126,7 @@ export function WorkflowHealthTable({
{
title: 'Status',
key: 'status',
- width: CI_GRID.status,
+ width: 90,
// Failing first when sorted: failing (2) > unknown (1) > passing (0).
sorter: (a, b) => statusRank(a.latestRunFailed) - statusRank(b.latestRunFailed),
render: (_, row) => <StatusTag failed={row.latestRunFailed} conclusion={row.latestRunConclusion} />,
@@ -180,19 +134,27 @@ export function WorkflowHealthTable({
{
title: 'Runs',
key: 'runCount',
- width: CI_GRID.runs,
+ width: 60,
align: 'right',
sorter: (a, b) => a.runCount - b.runCount,
render: (_, row) => <span className="text-xs tabular-nums">{humanFriendlyNumber(row.runCount)}</span>,
},
{
- title: 'Success rate',
+ title: 'Pass rate',
key: 'successRate',
- width: CI_GRID.successRate,
+ width: 96,
align: 'right',
sorter: (a, b) => (a.successRate ?? -1) - (b.successRate ?? -1),
render: (_, row) => (
- <span className={cn('text-xs tabular-nums', successRateClass(row.successRate))}>
+ <span
+ className={cn(
+ 'text-xs tabular-nums',
+ successRateClass(
+ row.successRate,
+ row.buckets.some((bucket) => bucket.failures > 0)
+ )
+ )}
+ >
{formatRate(row.successRate)}
</span>
),
@@ -202,9 +164,9 @@ export function WorkflowHealthTable({
{
title: 'Cost',
tooltip:
- "CI minutes spent (each job's time summed — parallel jobs add up) plus the estimated $ at the reference rate. This is compute spent, not wall-clock run time. Excludes still-running jobs, so it can rise as they settle.",
+ "CI minutes spent (each job's time summed, so parallel jobs add up) and the estimated cost at the reference rate. This is compute time, not wall-clock run time. Still-running jobs are excluded, so the figure can rise as they settle.",
key: 'cost',
- width: CI_GRID.cost,
+ width: 130,
align: 'right',
sorter: (a, b) => (a.estimatedCostUsd ?? -1) - (b.estimatedCostUsd ?? -1),
render: (_, row) => (
@@ -214,57 +176,89 @@ export function WorkflowHealthTable({
]
: []) as LemonTableColumns<WorkflowHealthRow>),
{
- title: 'Health',
- key: 'trend',
- // Pinned so the layout doesn't shift when sorting reorders rows with and without history.
- width: CI_GRID.health,
- render: function RenderTrend(_, row) {
- if (row.buckets.length === 0) {
- return <span className="text-xs text-secondary">—</span>
- }
- const { completed, failures, labels } = workflowFailureSeries(row.buckets, row.granularity)
- return (
- <div className="flex items-center gap-2">
- <FailureSparkline
- className="flex-1"
- completed={completed}
- failures={failures}
- labels={labels}
- ariaLabel={`${row.workflowName} failure history`}
- // Push buckets are few — keep bars narrow and right-aligned instead of fat.
- minSlots={row.granularity === 'push' ? PUSH_MIN_SLOTS : undefined}
- />
- <TrendArrow direction={workflowFailureTrend(row.buckets)} />
- </div>
+ title: 'Δ',
+ key: 'successRateDelta',
+ width: 76,
+ align: 'right',
+ tooltip: 'Success-rate change in percentage points vs the equal-length window before this one.',
+ sorter: (a, b) =>
+ (pointChange(a.successRate, a.successRatePrev) ?? -Infinity) -
+ (pointChange(b.successRate, b.successRatePrev) ?? -Infinity),
+ render: (_, row) => {
+ const delta = pointChange(row.successRate, row.successRatePrev)
+ return delta == null ? (
+ <span className="text-xs text-secondary">—</span>
+ ) : (
+ <DeltaBadge value={delta} unit="pp" />
)
},
},
{
- title: 'p50',
- tooltip: 'Median run duration (wall-clock) over completed runs in the window.',
+ title: 'P50',
key: 'p50Seconds',
- width: CI_GRID.p50,
+ width: 88,
align: 'right',
+ tooltip: 'Median run duration (wall-clock) over completed runs.',
sorter: (a, b) => (a.p50Seconds ?? -1) - (b.p50Seconds ?? -1),
render: (_, row) => (
- <span className="text-xs whitespace-nowrap tabular-nums">{formatSeconds(row.p50Seconds)}</span>
+ <span className="text-xs tabular-nums whitespace-nowrap">{formatSeconds(row.p50Seconds)}</span>
),
},
{
- title: 'p95',
- tooltip: '95th-percentile run duration (wall-clock) over completed runs in the window.',
+ title: 'P95',
key: 'p95Seconds',
- width: CI_GRID.p95,
+ width: 88,
align: 'right',
+ tooltip: '95th-percentile run duration (wall-clock) over completed runs.',
sorter: (a, b) => (a.p95Seconds ?? -1) - (b.p95Seconds ?? -1),
render: (_, row) => (
- <span className="text-xs whitespace-nowrap tabular-nums">{formatSeconds(row.p95Seconds)}</span>
+ <span className="text-xs tabular-nums whitespace-nowrap text-secondary">
+ {formatSeconds(row.p95Seconds)}
+ </span>
),
},
+ {
+ title: 'Re-runs',
+ key: 'rerunCycles',
+ width: 76,
+ align: 'right',
+ tooltip: 'Runs with attempt > 1 in the window. Frequent re-runs usually point to flaky checks.',
+ sorter: (a, b) => (a.rerunCycles ?? 0) - (b.rerunCycles ?? 0),
+ render: (_, row) => (
+ <span
+ className={cn(
+ 'text-xs tabular-nums',
+ (row.rerunCycles ?? 0) > 50 && 'font-semibold text-warning-dark'
+ )}
+ >
+ {row.rerunCycles ?? '—'}
+ </span>
+ ),
+ },
+ {
+ title: 'Health',
+ key: 'trend',
+ // Pinned so the layout doesn't shift when sorting reorders rows with and without history.
+ width: 132,
+ render: function RenderTrend(_, row) {
+ if (row.buckets.length === 0) {
+ return <span className="text-xs text-secondary">—</span>
+ }
+ const { completed, failures, labels } = workflowFailureSeries(row.buckets, row.granularity)
+ return (
+ <FailureSparkline
+ completed={completed}
+ failures={failures}
+ labels={labels}
+ ariaLabel={`${row.workflowName} failure history`}
+ />
+ )
+ },
+ },
{
title: 'Last failure',
key: 'lastFailureAt',
- width: CI_GRID.lastFailure,
+ width: 100,
align: 'right',
render: (_, row) =>
row.lastFailureAt ? (
@@ -279,15 +273,6 @@ export function WorkflowHealthTable({
return (
<LemonTable
- // Fixed layout honors the CI_GRID widths exactly (auto layout lets empty spacer cells collapse),
- // so the run/job tables nested inside line their columns up to the pixel. Cascades to them too.
- // Fixed layout collapses the expand-toggle <col> (LemonTable sizes it width:1%, an auto-layout
- // shrink-to-content trick), clipping the chevron — re-widen just that col to the width auto-layout
- // would give it: the toggle cell is the row's first child, so 1rem + 0.5rem padding around a
- // 1.5rem icon button = 3rem (w-12). A narrower col leaves the chevron clipped by the padding.
- // Match on '1%' alone (not 'width: 1%'): a Tailwind arbitrary variant can't contain the space,
- // and within this table the toggle is the only col with a % width, so there's no false match.
- className="[&_table]:table-fixed [&_col[style*='1%']]:!w-12"
data-attr={dataAttr}
size="small"
columns={columns}
@@ -298,8 +283,7 @@ export function WorkflowHealthTable({
loading={loading}
useURLForSorting={false}
defaultSorting={defaultSorting}
- expandable={expandable}
- pagination={{ pageSize: 50 }}
+ pagination={{ pageSize }}
emptyState={emptyState ?? 'No workflow runs.'}
nouns={['workflow', 'workflows']}
/>
diff --git a/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx b/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx
index 32412eb3eefa..734fc5241887 100644
--- a/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx
+++ b/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx
@@ -2,8 +2,8 @@ import { Tooltip } from '@posthog/lemon-ui'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { cn } from 'lib/utils/css-classes'
-import { percentage } from 'lib/utils/numbers'
+import { percent } from '../lib/format'
import type { FleetSummary } from '../lib/runHealth'
import { HealthKpi, STATE_META } from './healthVerdict'
import { formatCost } from './runTables'
@@ -15,20 +15,18 @@ interface WorkflowsHealthHeaderProps {
className?: string
}
-/**
- * Fleet verdict strip above the all-workflows table: colored state word + "% green" headline rolled up
- * across every workflow in the window (how many are red now, total runs, total CI spend).
- */
+/** Verdict strip above the all-workflows table: state word, failing-now count, pass rate, re-runs,
+ * total runs, and CI spend rolled up across every workflow in the window. */
export function WorkflowsHealthHeader({ summary, truncated, className }: WorkflowsHealthHeaderProps): JSX.Element {
const meta = STATE_META[summary.state]
const greenNow = summary.settledWorkflows - summary.failingNow
- const greenRateLabel = summary.settledWorkflows > 0 ? percentage(greenNow / summary.settledWorkflows, 0) : '—'
+ const greenRateLabel = summary.settledWorkflows > 0 ? percent(greenNow / summary.settledWorkflows) : '—'
const hasCost = summary.estimatedCostUsd != null
return (
<LemonCard
hoverEffect={false}
- // Left accent in the state color.
+ // Left accent in the state color (border-l-4 + the state's token class).
className={cn(
'flex flex-wrap items-center gap-x-6 gap-y-4 border-l-4 px-5 py-4',
meta.borderClass,
@@ -44,22 +42,24 @@ export function WorkflowsHealthHeader({ summary, truncated, className }: Workflo
{summary.workflowCount === 0
? 'No workflow runs in this window'
: summary.settledWorkflows === 0
- ? `${summary.workflowCount} workflows · none settled yet`
+ ? `${summary.workflowCount} workflows · no completed runs yet`
: summary.failingNow > 0
? `${summary.failingNow} of ${summary.workflowCount} workflows failing right now`
: summary.flakyNow > 0
? `${summary.flakyNow} flaky · below 90% pass rate`
- : summary.settledWorkflows < summary.workflowCount
- ? `${summary.settledWorkflows} of ${summary.workflowCount} settled · all green`
- : truncated
- ? `Top ${summary.workflowCount} by runs · all green`
- : `All ${summary.workflowCount} workflows healthy`}
+ : truncated
+ ? `Top ${summary.workflowCount} by runs · all green`
+ : `All ${summary.workflowCount} workflows healthy`}
</span>
</div>
<div className="flex flex-col border-l border-primary pl-6">
+ <Tooltip
+ title={`Share of workflows currently green, of the ${summary.settledWorkflows} whose latest run completed.`}
+ >
+ <span className="self-start cursor-default text-xs text-tertiary">Green now</span>
+ </Tooltip>
<span className="text-2xl font-semibold leading-7 tabular-nums">{greenRateLabel}</span>
- <span className="text-xs text-tertiary">green now · {summary.settledWorkflows} settled</span>
</div>
<div className="flex-1" />
@@ -70,7 +70,7 @@ export function WorkflowsHealthHeader({ summary, truncated, className }: Workflo
value={
truncated ? (
<Tooltip
- title={`Showing the top ${summary.workflowCount} workflows by run count. Total runs, CI cost, and the verdict cover these — lower-volume workflows beyond the cap aren't included.`}
+ title={`Showing the top ${summary.workflowCount} workflows by run count. Total runs, CI cost, and the verdict cover these only; lower-volume workflows aren't included.`}
>
<span>{summary.workflowCount.toLocaleString()}+</span>
</Tooltip>
@@ -84,6 +84,26 @@ export function WorkflowsHealthHeader({ summary, truncated, className }: Workflo
value={summary.failingNow.toLocaleString()}
danger={summary.failingNow > 0}
/>
+ <HealthKpi
+ label="Run pass rate"
+ value={
+ summary.passRate != null ? (
+ <Tooltip title="Passes ÷ completed runs across all workflows, weighted by run volume, so busier workflows count for more.">
+ <span>{percent(summary.passRate)}</span>
+ </Tooltip>
+ ) : (
+ '—'
+ )
+ }
+ />
+ <HealthKpi
+ label="Re-runs"
+ value={
+ <Tooltip title="Runs with attempt > 1 in the window. Frequent re-runs usually point to flaky checks.">
+ <span>{summary.rerunCycles.toLocaleString()}</span>
+ </Tooltip>
+ }
+ />
<HealthKpi label="Total runs" value={summary.totalRuns.toLocaleString()} />
{hasCost && <HealthKpi label="CI cost" value={`≈ ${formatCost(summary.estimatedCostUsd)}`} />}
</div>
diff --git a/products/engineering_analytics/frontend/components/runTables.tsx b/products/engineering_analytics/frontend/components/runTables.tsx
index c97a4d5f5048..b2b241735d96 100644
--- a/products/engineering_analytics/frontend/components/runTables.tsx
+++ b/products/engineering_analytics/frontend/components/runTables.tsx
@@ -1,22 +1,10 @@
-// Shared building blocks for the CI run/job tables (PR detail page and single workflow-run page) so the
-// two surfaces read identically — a job row looks the same expanded under a run or on its own page.
+// Shared status tags and cost formatters for the CI run/job tables (PR detail and workflow-run pages).
-import { ReactNode } from 'react'
+import { LemonTag } from '@posthog/lemon-ui'
-import { LemonTable, LemonTableColumns, LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'
-
-import { TZLabel } from 'lib/components/TZLabel'
-import { dayjs } from 'lib/dayjs'
import { cn } from 'lib/utils/css-classes'
-import { humanFriendlyDuration } from 'lib/utils/durations'
-import type { WorkflowJobApi } from '../generated/api.schemas'
-import { jobCacheKey } from '../lib/jobs'
import { verdictTag } from '../lib/runStatus'
-import { BillableBadge } from './BillableBadge'
-
-// A short item still shows next to a long one (durations span seconds → minutes).
-const MIN_BAR_PCT = 4
const STATUS_DOT: Record<string, string> = {
success: 'bg-success',
@@ -25,23 +13,15 @@ const STATUS_DOT: Record<string, string> = {
muted: 'bg-muted',
}
-/** Earliest start → latest finish (running items extend to now) over a set of start/finish pairs. */
-export function timeAxis(items: { startedAt: string | null; finishedAt: string | null }[]): {
- axisStart: number | null
- axisEnd: number | null
-} {
- const starts = items
- .map((i) => i.startedAt)
- .filter((at): at is string => !!at)
- .map((at) => dayjs(at).valueOf())
- const ends = items
- .map((i) => i.finishedAt ?? (i.startedAt ? dayjs().toISOString() : null))
- .filter((at): at is string => !!at)
- .map((at) => dayjs(at).valueOf())
- return { axisStart: starts.length ? Math.min(...starts) : null, axisEnd: ends.length ? Math.max(...ends) : null }
+export function RunConclusionTag({ conclusion }: { conclusion: string | null }): JSX.Element {
+ if (conclusion == null) {
+ return <LemonTag type="completion">Running</LemonTag>
+ }
+ const tag = verdictTag(conclusion)
+ return <LemonTag type={tag.type}>{tag.label}</LemonTag>
}
-/** Compact status: a colored dot + label rather than a boxed tag — far less noise down a long list. */
+/** Dot + label status — quieter than a boxed tag down a long list. */
export function StatusDot({ conclusion }: { conclusion: string | null }): JSX.Element {
const tag = verdictTag(conclusion)
return (
@@ -52,460 +32,17 @@ export function StatusDot({ conclusion }: { conclusion: string | null }): JSX.El
)
}
-/**
- * Gantt bar anchored to start time on a shared axis, sized by duration, red when failed. Running bars
- * extend to now; a min width keeps short items visible. The duration prints to the right.
- */
-export function GanttBar({
- startedAt,
- finishedAt,
- durationSeconds,
- conclusion,
- axisStart,
- axisEnd,
- showDuration = true,
-}: {
- startedAt: string | null
- finishedAt: string | null
- durationSeconds: number | null
- conclusion: string | null
- axisStart: number | null
- axisEnd: number | null
- // Hidden in the aligned grid, where duration has its own column under p50.
- showDuration?: boolean
-}): JSX.Element {
- if (!startedAt || axisStart == null || axisEnd == null) {
- return <span className="text-xs text-secondary">—</span>
- }
- const start = dayjs(startedAt).valueOf()
- const end = finishedAt ? dayjs(finishedAt).valueOf() : dayjs().valueOf()
- const span = Math.max(1, axisEnd - axisStart)
- const left = Math.max(0, Math.min(100, ((start - axisStart) / span) * 100))
- const width = Math.max(MIN_BAR_PCT, Math.min(100 - left, ((end - start) / span) * 100))
- const isFailure = conclusion === 'failure' || conclusion === 'timed_out'
- return (
- <div className="flex items-center gap-2">
- <div className="relative h-1.5 flex-1 overflow-hidden rounded-sm bg-border">
- <div
- className={cn('absolute top-0 h-1.5 rounded-sm', isFailure ? 'bg-danger' : 'bg-muted')}
- style={{ left: `${left}%`, width: `${width}%` }}
- />
- </div>
- {showDuration && (
- <span className="w-14 shrink-0 text-right text-xs whitespace-nowrap tabular-nums text-secondary">
- {durationSeconds == null ? '—' : humanFriendlyDuration(durationSeconds)}
- </span>
- )}
- </div>
- )
-}
-
export function formatCost(usd: number | null): string {
if (usd == null) {
return '—'
}
- // Sub-cent costs would round to "$0.00" and read as free (and jobs wouldn't sum to the run total),
- // so show positives under a cent as "<$0.01"; only a measured zero is "$0.00".
+ // Positives under a cent show as "<$0.01" — "$0.00" would read as free.
if (usd > 0 && usd < 0.01) {
return '<$0.01'
}
- return `$${usd.toFixed(2)}`
+ return `$${usd.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}
export function formatMinutes(minutes: number | null): string {
return minutes == null ? '—' : `${Math.round(minutes).toLocaleString()} min`
}
-
-// Canonical CI grid: the L1 (workflow), L2 (run), and L3 (job) tables reuse these exact widths so every
-// column lines up vertically as you drill in. Each level fills the slots it has an analog for, blanks the
-// rest. Single source of truth shared by WorkflowHealthTable, RunsTable, RunJobsTable; change a width
-// once, all levels move. Widths fit the widest header in each slot (fixed layout clips overflow).
-export const CI_GRID = {
- status: 116, // L1 Passing/Failing tag · L3 runner tier
- runs: 80, // L1 run count · blank below
- successRate: 140, // L1 "Success rate" · L2/L3 verdict/status dot
- cost: 132, // shared "min · $" billable badge
- health: 220, // L1 failure sparkline · L3 job timeline
- p50: 108, // L1 p50 · L2/L3 "Duration"
- p95: 92, // L1 p95 · blank below
- lastFailure: 124, // L1 last-failure time · L2/L3 started
-} as const
-
-// Grey for GitHub-hosted (free), blue for self-hosted — off the green/red verdict palette so a runner
-// badge never reads as a pass/fail status.
-const RUNNER_BADGE: Record<string, { label: string; type: LemonTagType }> = {
- github_hosted: { label: 'GitHub', type: 'muted' },
- self_hosted: { label: 'Self-hosted', type: 'primary' },
- unknown: { label: 'Unknown', type: 'muted' },
-}
-
-/** Runner type badge: GitHub-hosted (free) vs self-hosted (billable), plus the tier (e.g. 16-core). */
-export function RunnerBadge({ provider, label }: { provider: string; label: string }): JSX.Element {
- const badge = RUNNER_BADGE[provider] ?? RUNNER_BADGE.unknown
- return (
- <span className="flex items-center gap-1.5 whitespace-nowrap">
- <LemonTag type={badge.type} size="small">
- {badge.label}
- </LemonTag>
- {label && provider !== 'unknown' && <span className="font-mono text-xs text-secondary">{label}</span>}
- </span>
- )
-}
-
-/** GitHub-hosted runners are free; self-hosted shows the modeled estimate in the same "min · $" badge as
- * the run/workflow rows. */
-function jobCostCell(job: WorkflowJobApi): JSX.Element {
- if (job.runner_provider === 'github_hosted') {
- return <span className="text-xs text-secondary">Free</span>
- }
- const minutes = job.duration_seconds != null ? job.duration_seconds / 60 : null
- return <BillableBadge minutes={minutes} costUsd={job.estimated_cost_usd} />
-}
-
-function formatSeconds(seconds: number | null): string {
- return seconds == null ? '—' : humanFriendlyDuration(seconds)
-}
-
-/** Runner in the aligned grid: just the tier tag (full name on hover) — the verbose badge won't fit the
- * Status slot. */
-function compactRunnerCell(job: WorkflowJobApi): JSX.Element {
- const badge = RUNNER_BADGE[job.runner_provider] ?? RUNNER_BADGE.unknown
- if (job.runner_provider === 'unknown' && !job.runner_label) {
- return <span className="text-xs text-secondary">—</span>
- }
- return (
- <Tooltip title={`${badge.label}${job.runner_label ? ` · ${job.runner_label}` : ''}`}>
- <LemonTag type={badge.type} size="small">
- {job.runner_label || badge.label}
- </LemonTag>
- </Tooltip>
- )
-}
-
-/**
- * A workflow run's jobs: runner tier, Gantt timeline on the jobs' own axis, est. cost. Used as the
- * expanded-row content under a run (`embedded`) and as the single workflow-run page. `undefined`/`null`
- * jobs = not loaded; `[]` = the job-level source isn't synced for this team.
- */
-export function RunJobsTable({
- jobs,
- loading,
- embedded = false,
- aligned = false,
-}: {
- // null/undefined = not loaded (kea coerces an undefined loader default to null); [] = source unsynced.
- jobs: WorkflowJobApi[] | null | undefined
- loading: boolean
- embedded?: boolean
- // Render onto the canonical CI_GRID so columns line up under the run/workflow tables (PR detail).
- aligned?: boolean
-}): JSX.Element {
- if (jobs == null) {
- return <div className="px-3 py-2 text-xs text-secondary">{loading ? 'Loading jobs…' : 'No job data yet.'}</div>
- }
- if (jobs.length === 0) {
- return (
- <div className="px-3 py-2 text-xs text-secondary">
- No job data yet — the job-level source isn't synced for this team.
- </div>
- )
- }
- // Jobs of one run share the run's window; anchor their bars to the jobs' own start→finish span.
- const { axisStart, axisEnd } = timeAxis(
- jobs.map((job) => ({ startedAt: job.started_at, finishedAt: job.completed_at }))
- )
- const nameColumn = {
- title: 'Job',
- key: 'name',
- sorter: (a: WorkflowJobApi, b: WorkflowJobApi) => a.name.localeCompare(b.name),
- render: (_: unknown, job: WorkflowJobApi) => <span className="font-medium">{job.name}</span>,
- }
- const timelineCell = (job: WorkflowJobApi): JSX.Element => (
- <GanttBar
- startedAt={job.started_at}
- finishedAt={job.completed_at}
- durationSeconds={job.duration_seconds}
- conclusion={job.conclusion}
- axisStart={axisStart}
- axisEnd={axisEnd}
- showDuration={!aligned}
- />
- )
- // Aligned: job data drops into the canonical L1 slots (Runner→Status, dot→Success rate, timeline→
- // Health, duration→p50, started→Last failure). Natural: the standalone run page's own layout.
- const jobColumns: LemonTableColumns<WorkflowJobApi> = aligned
- ? [
- nameColumn,
- { title: 'Runner', key: 'status', width: CI_GRID.status, render: (_, job) => compactRunnerCell(job) },
- { title: '', key: 'runs', width: CI_GRID.runs, render: () => null },
- {
- title: 'Status',
- key: 'successRate',
- width: CI_GRID.successRate,
- render: (_, job) => <StatusDot conclusion={job.conclusion} />,
- },
- {
- title: 'Cost',
- key: 'cost',
- width: CI_GRID.cost,
- align: 'right',
- render: (_, job) => jobCostCell(job),
- },
- {
- title: 'Timeline',
- key: 'health',
- width: CI_GRID.health,
- sorter: (a, b) => (a.started_at ?? '').localeCompare(b.started_at ?? ''),
- render: (_, job) => timelineCell(job),
- },
- {
- title: 'Duration',
- key: 'p50',
- width: CI_GRID.p50,
- align: 'right',
- render: (_, job) => (
- <span className="text-xs tabular-nums">{formatSeconds(job.duration_seconds)}</span>
- ),
- },
- { title: '', key: 'p95', width: CI_GRID.p95, render: () => null },
- {
- title: 'Started',
- key: 'lastFailure',
- width: CI_GRID.lastFailure,
- align: 'right',
- render: (_, job) =>
- job.started_at ? (
- <span className="text-xs whitespace-nowrap">
- <TZLabel time={job.started_at} />
- </span>
- ) : (
- <span className="text-xs text-secondary">—</span>
- ),
- },
- ]
- : [
- nameColumn,
- {
- title: 'Status',
- key: 'status',
- width: 110,
- sorter: (a, b) => (a.conclusion ?? '').localeCompare(b.conclusion ?? ''),
- render: (_, job) => <StatusDot conclusion={job.conclusion} />,
- },
- {
- title: 'Runner',
- key: 'runner',
- width: 180,
- sorter: (a, b) => a.runner_label.localeCompare(b.runner_label),
- render: (_, job) => <RunnerBadge provider={job.runner_provider} label={job.runner_label} />,
- },
- {
- title: 'Timeline',
- key: 'timeline',
- width: 200,
- sorter: (a, b) => (a.started_at ?? '').localeCompare(b.started_at ?? ''),
- render: (_, job) => timelineCell(job),
- },
- {
- title: 'Cost',
- key: 'cost',
- width: 110,
- align: 'right',
- sorter: (a, b) => (a.estimated_cost_usd ?? -1) - (b.estimated_cost_usd ?? -1),
- render: (_, job) => jobCostCell(job),
- },
- ]
- const table = (
- <LemonTable
- embedded={embedded}
- size="small"
- columns={jobColumns}
- dataSource={jobs}
- rowKey={(job) => job.id}
- useURLForSorting={false}
- // Sort by start (the timeline column, keyed 'health' when aligned) so bars read top-to-bottom.
- defaultSorting={{ columnKey: aligned ? 'health' : 'timeline', order: 1 }}
- nouns={['job', 'jobs']}
- />
- )
- // No indent: the job table has no expand toggle, so rows read flush-left under the parent run instead
- // of behind a stray gap.
- return table
-}
-
-// The minimum a run row needs to drive the shared columns + job expansion. Callers add their own lead
-// columns (the PR page leads with the commit; the workflow page leads with run id / branch / PR).
-export interface RunRowBase {
- runId: number | null
- runAttempt: number | null
- conclusion: string | null
- durationSeconds: number | null
- startedAt: string | null
-}
-
-export interface RunsTableProps<T extends RunRowBase> {
- runs: T[]
- rowKey: (row: T) => string
- /** Columns shown before the shared Verdict / Duration / Started / Cost columns. */
- leadColumns: LemonTableColumns<T>
- loading: boolean
- // null/undefined per key = that run's jobs aren't loaded yet; lazily fetched on first expand.
- runJobs: Record<string, WorkflowJobApi[]>
- runJobsLoading: boolean
- expandedKeys: string[]
- setExpanded: (rowKey: string, expanded: boolean, runId: number | null, runAttempt: number | null) => void
- /** Per-run cost keyed by jobCacheKey; pass with showCost to add the trailing Cost column. */
- runCostByKey?: Record<string, { minutes: number | null; cost: number | null }>
- showCost?: boolean
- /** Render onto the canonical CI_GRID so columns line up under the workflow table (PR detail). */
- aligned?: boolean
- defaultSorting?: { columnKey: string; order: 1 | -1 }
- emptyState?: ReactNode
- dataAttr?: string
-}
-
-/**
- * A list of workflow runs, each expandable to its jobs (RunJobsTable). Shared trailing columns (verdict,
- * duration, started, optional cost) and expand-to-jobs behavior; only the leading columns differ per caller.
- */
-export function RunsTable<T extends RunRowBase>({
- runs,
- rowKey,
- leadColumns,
- loading,
- runJobs,
- runJobsLoading,
- expandedKeys,
- setExpanded,
- runCostByKey,
- showCost = false,
- aligned = false,
- defaultSorting = { columnKey: 'started', order: 1 },
- emptyState = 'No CI runs match.',
- dataAttr = 'engineering-analytics-runs-table',
-}: RunsTableProps<T>): JSX.Element {
- const verdictColumn = {
- title: 'Verdict',
- key: 'verdict',
- sorter: (a: T, b: T) => verdictTag(a.conclusion).label.localeCompare(verdictTag(b.conclusion).label),
- render: (_: unknown, run: T) => <StatusDot conclusion={run.conclusion} />,
- }
- const durationCell = (run: T): JSX.Element => (
- <span className="text-xs tabular-nums whitespace-nowrap">
- {run.durationSeconds == null ? '—' : humanFriendlyDuration(run.durationSeconds)}
- </span>
- )
- const startedCell = (run: T): JSX.Element =>
- run.startedAt ? (
- <span className="text-xs whitespace-nowrap">
- <TZLabel time={run.startedAt} />
- </span>
- ) : (
- <span className="text-xs text-secondary">—</span>
- )
- const costCell = (run: T): JSX.Element => {
- const cost = run.runId != null ? runCostByKey?.[jobCacheKey(run.runId, run.runAttempt)] : null
- return <BillableBadge minutes={cost?.minutes ?? null} costUsd={cost?.cost ?? null} />
- }
- // Aligned: run data drops into the canonical L1 slots (verdict→Success rate, cost→Cost, duration→p50,
- // started→Last failure), with blank spacers under the slots a run has no analog for (Status, Runs,
- // Health, p95). Natural: the standalone workflow-runs page's own compact layout.
- const columns: LemonTableColumns<T> = aligned
- ? [
- ...leadColumns,
- { title: '', key: 'slotStatus', width: CI_GRID.status, render: () => null },
- { title: '', key: 'slotRuns', width: CI_GRID.runs, render: () => null },
- { ...verdictColumn, width: CI_GRID.successRate },
- { title: 'Cost', key: 'cost', width: CI_GRID.cost, align: 'right', render: (_, run) => costCell(run) },
- { title: '', key: 'slotHealth', width: CI_GRID.health, render: () => null },
- {
- title: 'Duration',
- key: 'duration',
- width: CI_GRID.p50,
- align: 'right',
- sorter: (a, b) => (a.durationSeconds ?? -1) - (b.durationSeconds ?? -1),
- render: (_, run) => durationCell(run),
- },
- { title: '', key: 'slotP95', width: CI_GRID.p95, render: () => null },
- {
- title: 'Started',
- key: 'started',
- width: CI_GRID.lastFailure,
- align: 'right',
- sorter: (a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''),
- render: (_, run) => startedCell(run),
- },
- ]
- : [
- ...leadColumns,
- { ...verdictColumn, width: 110 },
- {
- title: 'Duration',
- key: 'duration',
- width: 90,
- align: 'right',
- sorter: (a, b) => (a.durationSeconds ?? -1) - (b.durationSeconds ?? -1),
- render: (_, run) => durationCell(run),
- },
- {
- title: 'Started',
- key: 'started',
- width: 130,
- align: 'right',
- sorter: (a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''),
- render: (_, run) => startedCell(run),
- },
- ...((showCost
- ? [
- {
- title: 'Cost',
- key: 'cost',
- width: 110,
- align: 'right',
- render: (_: unknown, run: T) => costCell(run),
- },
- ]
- : []) as LemonTableColumns<T>),
- ]
-
- return (
- <LemonTable
- data-attr={dataAttr}
- size="small"
- columns={columns}
- dataSource={runs}
- rowKey={rowKey}
- loading={loading}
- useURLForSorting={false}
- defaultSorting={defaultSorting}
- // Whole-row click toggles the job breakdown (the logs-viewer pattern); in-row links
- // stopPropagation so they still navigate.
- onRow={(run) =>
- run.runId != null
- ? {
- className: 'cursor-pointer',
- onClick: () =>
- setExpanded(rowKey(run), !expandedKeys.includes(rowKey(run)), run.runId, run.runAttempt),
- }
- : {}
- }
- expandable={{
- // Compact chevron toggle + whole-row click; no onRowExpand/onRowCollapse so the toggle
- // bubbles to onRow — one toggle, not two.
- noIndent: true,
- rowExpandable: (run) => run.runId != null,
- isRowExpanded: (run) => expandedKeys.includes(rowKey(run)),
- expandedRowRender: (run) => (
- <RunJobsTable
- jobs={run.runId != null ? runJobs[jobCacheKey(run.runId, run.runAttempt)] : undefined}
- loading={runJobsLoading}
- embedded
- aligned={aligned}
- />
- ),
- }}
- emptyState={emptyState}
- nouns={['workflow run', 'workflow runs']}
- />
- )
-}
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 71e40d732082..896202e37d70 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -71,6 +71,71 @@ export interface CIFailureLogsApi {
truncated: boolean
}
+export interface WorkflowJobAggregateApi {
+ /** De-sharded job name: the matrix '(G/N)' suffix is stripped and unexpanded '${{ matrix.* }}' templates are collapsed, so shards of one matrix aggregate together. */
+ job_name: string
+ /** Job instances observed in the window (all shards, all attempts). */
+ job_count: number
+ /** Distinct raw job names inside the group - the observed matrix width. */
+ shard_count: number
+ /** Distinct workflow runs the job appeared in. */
+ runs_in: number
+ /**
+ * runs_in divided by the workflow's total runs in the window; below 1.0 means the job is conditional and skips some runs. Null when the workflow had no runs.
+ * @nullable
+ */
+ run_share: number | null
+ /**
+ * Median queue wait (created to started) in seconds - where runner-capacity problems hide. Null when nothing started.
+ * @nullable
+ */
+ queue_p50_seconds: number | null
+ /**
+ * Median duration of completed job instances, in seconds. Null if none completed.
+ * @nullable
+ */
+ p50_seconds: number | null
+ /**
+ * 95th-percentile duration of completed job instances, in seconds. Null if none completed.
+ * @nullable
+ */
+ p95_seconds: number | null
+ /**
+ * Decisive failures ('failure', 'timed_out') over completed instances (0-1). Null if none completed.
+ * @nullable
+ */
+ failure_rate: number | null
+ /** Job instances that ran on a 2nd+ run attempt - retry pressure. */
+ retry_job_count: number
+ /**
+ * Billable (self-hosted) minutes across the group's instances; null when every instance ran on an unknown tier.
+ * @nullable
+ */
+ billable_minutes: number | null
+ /**
+ * Estimated cost in USD via the runner-tier rate ladder; null when every instance ran on an unknown tier.
+ * @nullable
+ */
+ estimated_cost_usd: number | null
+}
+
+export interface MasterFailureGroupApi {
+ /** Repository the failures occurred in. */
+ repo: RepoRefApi
+ /** GitHub Actions workflow name the failing runs belong to. */
+ workflow_name: string
+ /** De-sharded failing job name (matrix '(G/N)' suffix stripped) — the group's failure signature together with the workflow. '' when the job-level source isn't synced and the group degrades to workflow level. */
+ failed_job: string
+ /** Distinct failing default-branch runs in this group within the window. */
+ run_count: number
+ /** When the oldest failing run in the group started. */
+ first_seen: string
+ /** When the newest failing run in the group started. */
+ last_seen: string
+ /** Run id of the newest failing run — the drill-down anchor. */
+ latest_run_id: number
+}
+
export interface WorkflowCostApi {
/** GitHub Actions workflow name this cost is for. */
workflow_name: string
@@ -297,6 +362,8 @@ export interface CIStatusRollupApi {
failing: number
/** Latest runs not yet completed (queued or in progress). */
pending: number
+ /** The workflow names behind `failing`, sorted - names what is failing instead of leaving a bare count. */
+ failing_workflows?: string[]
}
export interface PullRequestListItemApi {
@@ -507,6 +574,72 @@ export interface QuarantineRequestResultApi {
branch: string
}
+export interface RepoOverviewApi {
+ /** Workflow runs started in the window, all branches and workflows. */
+ run_count: number
+ /** Same count over the equal-length window immediately before date_from — the delta baseline. */
+ run_count_prev: number
+ /**
+ * Fraction of completed runs that succeeded (0-1) in the window. Null if none completed.
+ * @nullable
+ */
+ success_rate: number | null
+ /**
+ * Success rate over the previous window. Null if none completed.
+ * @nullable
+ */
+ success_rate_prev: number | null
+ /** Runs in the window that were a 2nd+ attempt (attempt > 1). */
+ rerun_cycles: number
+ /** Re-run cycles over the previous window. */
+ rerun_cycles_prev: number
+ /**
+ * Median merged_at - created_at over PRs merged in the window, bots and drafts excluded. Coarse by design: draft and ready-for-review time are fused. Null when nothing merged.
+ * @nullable
+ */
+ median_open_to_merge_seconds: number | null
+ /**
+ * The same median over the previous window. Null when nothing merged.
+ * @nullable
+ */
+ median_open_to_merge_seconds_prev: number | null
+ /**
+ * Billable (self-hosted) job minutes in the window; null when the job-level source isn't synced.
+ * @nullable
+ */
+ billable_minutes: number | null
+ /**
+ * Billable minutes over the previous window; null when the job-level source isn't synced.
+ * @nullable
+ */
+ billable_minutes_prev: number | null
+ /**
+ * Estimated CI cost in USD (billable minutes x runner-tier rate); null when the job-level source isn't synced.
+ * @nullable
+ */
+ estimated_cost_usd: number | null
+ /**
+ * Estimated cost over the previous window; null when the job-level source isn't synced.
+ * @nullable
+ */
+ estimated_cost_usd_prev: number | null
+ /** Whether the job-level source is synced (cost and queue figures exist). */
+ jobs_available: boolean
+ /** 'master' or 'main', picked by observed run volume in the window. */
+ default_branch: string
+}
+
+export interface RunFailureLogsApi {
+ /** Failed CI jobs of this run with their thinned failure logs, grouped by job. */
+ jobs: CIJobFailureLogApi[]
+ /** Workflow run id the failure logs are for. */
+ run_id: number
+ /** False when no failure logs were found — the run didn't fail, or its logs aged out of the short Logs retention. */
+ logs_available: boolean
+ /** True when the overall line cap across all jobs was hit. */
+ truncated: boolean
+}
+
export interface GitHubSourceApi {
/** Source id — pass as `source_id` to the other endpoints to read this source. */
id: string
@@ -580,6 +713,13 @@ export interface WorkflowHealthItemApi {
* @nullable
*/
estimated_cost_usd?: number | null
+ /** Runs in the window that were a 2nd+ attempt - retry pressure, a flakiness proxy. */
+ rerun_cycles?: number
+ /**
+ * Success rate over the equal-length window before date_from - the delta baseline. Null when that window had no completed runs.
+ * @nullable
+ */
+ success_rate_prev?: number | null
}
export interface WorkflowJobApi {
@@ -690,6 +830,48 @@ export type EngineeringAnalyticsCiFailureLogsParams = {
source_id?: string
}
+export type EngineeringAnalyticsJobAggregatesParams = {
+ /**
+ * Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
+ */
+ branch?: string
+ /**
+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
+ */
+ date_from?: string
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
+ /**
+ * Workflow name to aggregate jobs for.
+ */
+ workflow_name: string
+}
+
+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.
+ */
+ branch?: string
+ /**
+ * Window start: relative ('-24h', '-7d') or ISO8601. Defaults to -24h.
+ */
+ date_from?: string
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
+}
+
export type EngineeringAnalyticsPrCostParams = {
/**
* Pull request number to estimate cost for.
@@ -761,6 +943,32 @@ export type EngineeringAnalyticsQuarantineParams = {
source_id?: string
}
+export type EngineeringAnalyticsRepoOverviewParams = {
+ /**
+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
+ */
+ date_from?: string
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
+}
+
+export type EngineeringAnalyticsRunFailureLogsParams = {
+ /**
+ * Workflow run id whose failure logs to fetch.
+ */
+ run_id: number
+ /**
+ * 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 EngineeringAnalyticsWorkflowHealthParams = {
/**
* Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 9143cd527b48..7689881ab4df 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -13,11 +13,15 @@ import type {
CIFailureLogsApi,
EngineeringAnalyticsCiCardsParams,
EngineeringAnalyticsCiFailureLogsParams,
+ EngineeringAnalyticsJobAggregatesParams,
+ EngineeringAnalyticsMasterFailuresParams,
EngineeringAnalyticsPrCostParams,
EngineeringAnalyticsPrLifecycleParams,
EngineeringAnalyticsPrRunsParams,
EngineeringAnalyticsPullRequestsParams,
EngineeringAnalyticsQuarantineParams,
+ EngineeringAnalyticsRepoOverviewParams,
+ EngineeringAnalyticsRunFailureLogsParams,
EngineeringAnalyticsWorkflowHealthParams,
EngineeringAnalyticsWorkflowJobsParams,
EngineeringAnalyticsWorkflowRunActivityParams,
@@ -25,13 +29,17 @@ import type {
EngineeringAnalyticsWorkflowRunnerCostsParams,
EngineeringAnalyticsWorkflowRunsParams,
GitHubSourceApi,
+ MasterFailureGroupApi,
PRCostSummaryApi,
PRLifecycleApi,
PullRequestListApi,
QuarantineFileApi,
QuarantineRequestApi,
QuarantineRequestResultApi,
+ RepoOverviewApi,
+ RunFailureLogsApi,
WorkflowHealthItemApi,
+ WorkflowJobAggregateApi,
WorkflowJobApi,
WorkflowRunActivityApi,
WorkflowRunDetailApi,
@@ -101,6 +109,72 @@ export const engineeringAnalyticsCiFailureLogs = async (
})
}
+export const getEngineeringAnalyticsJobAggregatesUrl = (
+ projectId: string,
+ params: EngineeringAnalyticsJobAggregatesParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/job_aggregates/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/job_aggregates/`
+}
+
+/**
+ * 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.
+ */
+export const engineeringAnalyticsJobAggregates = async (
+ projectId: string,
+ params: EngineeringAnalyticsJobAggregatesParams,
+ options?: RequestInit
+): Promise<WorkflowJobAggregateApi[]> => {
+ return apiMutator<WorkflowJobAggregateApi[]>(getEngineeringAnalyticsJobAggregatesUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getEngineeringAnalyticsMasterFailuresUrl = (
+ projectId: string,
+ params?: EngineeringAnalyticsMasterFailuresParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/master_failures/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/master_failures/`
+}
+
+/**
+ * Default-branch failures over a window (default -24h), grouped error-tracking style by (workflow, de-sharded failing job) with a run count and first/last seen, newest group first. `branch` overrides the detected default branch. PR-branch failures are deliberately excluded — at monorepo volume a flat feed is a firehose; those surface per PR. Groups degrade to workflow level (failed_job '') when the job-level source isn't synced.
+ */
+export const engineeringAnalyticsMasterFailures = async (
+ projectId: string,
+ params?: EngineeringAnalyticsMasterFailuresParams,
+ options?: RequestInit
+): Promise<MasterFailureGroupApi[]> => {
+ return apiMutator<MasterFailureGroupApi[]>(getEngineeringAnalyticsMasterFailuresUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsPrCostUrl = (projectId: string, params: EngineeringAnalyticsPrCostParams) => {
const normalizedParams = new URLSearchParams()
@@ -282,6 +356,72 @@ export const engineeringAnalyticsQuarantineRequest = async (
})
}
+export const getEngineeringAnalyticsRepoOverviewUrl = (
+ projectId: string,
+ params?: EngineeringAnalyticsRepoOverviewParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/repo_overview/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/repo_overview/`
+}
+
+/**
+ * Repo-level headline aggregates over a window (default -30d): run count, success rate, re-run cycles, median PR open-to-merge (bots and drafts excluded; coarse — draft and ready time fused), and billable minutes + estimated cost — each with its equal-length previous-window twin so a caller can render honest deltas. Also carries the detected default branch and its completed-run history series. Cost figures are null until the job-level source is synced.
+ */
+export const engineeringAnalyticsRepoOverview = async (
+ projectId: string,
+ params?: EngineeringAnalyticsRepoOverviewParams,
+ options?: RequestInit
+): Promise<RepoOverviewApi> => {
+ return apiMutator<RepoOverviewApi>(getEngineeringAnalyticsRepoOverviewUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getEngineeringAnalyticsRunFailureLogsUrl = (
+ projectId: string,
+ params: EngineeringAnalyticsRunFailureLogsParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/run_failure_logs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/run_failure_logs/`
+}
+
+/**
+ * The thinned CI failure logs of one workflow run, grouped by failed job — the run-scoped twin of ci_failure_logs for surfaces that aren't PR-scoped (default-branch failures, the run page). logs_available is false when the run didn't fail or its logs aged out of the short Logs retention.
+ */
+export const engineeringAnalyticsRunFailureLogs = async (
+ projectId: string,
+ params: EngineeringAnalyticsRunFailureLogsParams,
+ options?: RequestInit
+): Promise<RunFailureLogsApi> => {
+ return apiMutator<RunFailureLogsApi>(getEngineeringAnalyticsRunFailureLogsUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsSourcesUrl = (projectId: string) => {
return `/api/projects/${projectId}/engineering_analytics/sources/`
}
diff --git a/products/engineering_analytics/frontend/lib/format.ts b/products/engineering_analytics/frontend/lib/format.ts
new file mode 100644
index 000000000000..b0bc9cb2dfef
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/format.ts
@@ -0,0 +1,66 @@
+// Compact headline formatting for stat tiles and share rows. Tables keep the precise formats from
+// runTables (formatCost) and lib/utils — these are for the big numbers where "$11.4k" beats "$11,400.00".
+
+export function compactUsd(usd: number | null | undefined): string {
+ if (usd == null) {
+ return '—'
+ }
+ if (usd >= 10000) {
+ return `$${(usd / 1000).toFixed(1)}k`
+ }
+ if (usd >= 100) {
+ return `$${Math.round(usd).toLocaleString()}`
+ }
+ return `$${usd.toFixed(2)}`
+}
+
+export function compactCount(count: number | null | undefined): string {
+ if (count == null) {
+ return '—'
+ }
+ if (count >= 10000) {
+ return `${(count / 1000).toFixed(count >= 100000 ? 0 : 1)}k`
+ }
+ return Math.round(count).toLocaleString()
+}
+
+// Below this many hours the PR-timing format stays in hours; above, one-decimal days.
+const HOURS_BEFORE_DAYS = 48
+
+/** Hours below two days, one-decimal days above — the PR-timing headline format. */
+export function compactHours(seconds: number | null | undefined): string {
+ if (seconds == null) {
+ return '—'
+ }
+ const hours = seconds / 3600
+ return hours < HOURS_BEFORE_DAYS ? `${Math.round(hours)}` : `${(hours / 24).toFixed(1)}`
+}
+
+export function compactHoursUnit(seconds: number | null | undefined): string {
+ if (seconds == null) {
+ return ''
+ }
+ return seconds / 3600 < HOURS_BEFORE_DAYS ? 'hours' : 'days'
+}
+
+/** The compactHours ladder as one short label: "17h" below two days, "3.2d" above. */
+export function compactHoursLabel(seconds: number | null | undefined): string {
+ if (seconds == null) {
+ return '—'
+ }
+ return `${compactHours(seconds)}${seconds / 3600 < HOURS_BEFORE_DAYS ? 'h' : 'd'}`
+}
+
+export function compactMinutes(minutes: number | null | undefined): string {
+ if (minutes == null) {
+ return '—'
+ }
+ if (minutes >= 1000) {
+ return `${(minutes / 1000).toFixed(0)}k min`
+ }
+ return `${Math.round(minutes)} min`
+}
+
+export function percent(rate: number | null | undefined, precision: number = 0): string {
+ return rate == null ? '—' : `${(rate * 100).toFixed(precision)}%`
+}
diff --git a/products/engineering_analytics/frontend/lib/jobGroups.test.ts b/products/engineering_analytics/frontend/lib/jobGroups.test.ts
new file mode 100644
index 000000000000..20f6d17b6d13
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/jobGroups.test.ts
@@ -0,0 +1,81 @@
+import { failedShardsLabel, groupJobs, jobBaseName, stripShardSuffix } from './jobGroups'
+
+// Names below are taken verbatim from real PostHog/posthog runs (see run 28576193541: a
+// master push carries ~80 jobs across a multi-dimension Django matrix, sharded and
+// list-valued product-test groups, and unexpanded templates when a matrix was skipped).
+const DJANGO_CORE = 'Django tests – Core (persons-on-events off), Py 3.13.13, clickhouse:26.3.10'
+const DJANGO_TEMPORAL = 'Django tests – Temporal (persons-on-events off), Py 3.13.13, clickhouse:26.3.10'
+const DJANGO_TEMPLATE =
+ "Django tests – ${{ matrix.segment }}${{ ((matrix.compat && ' compat') || '') }} (persons-on-events ${{ ((matrix.person-on-events && 'on') || 'off') }}), Py ${{ matrix.python-version }} (${{ matrix.group }}/${{ matrix.concurrency }})"
+
+describe('jobGroups', () => {
+ test.each([
+ // the nested-paren shard: the closing paren must survive the strip
+ ['Product tests (experiments (1/2))', 'Product tests (experiments)'],
+ ['Product tests (web-analytics)', 'Product tests (web-analytics)'],
+ [`${DJANGO_CORE} (3/23)`, DJANGO_CORE],
+ ['Lint & types', 'Lint & types'],
+ // a bare "(G/N)" suffix without an outer paren group
+ ['e2e (chromium) (5/8)', 'e2e (chromium)'],
+ ])('stripShardSuffix(%s)', (name, expected) => {
+ expect(stripShardSuffix(name)).toBe(expected)
+ })
+
+ test.each([
+ [`${DJANGO_CORE} (3/23)`, 'Django tests'],
+ ['Product tests (experiments (1/2))', 'Product tests'],
+ ['Product tests (logs, ai-observability)', 'Product tests'],
+ ['Repo checks (depot-ubuntu-latest)', 'Repo checks'],
+ ['Django Tests Pass', 'Django Tests Pass'],
+ // unexpanded template from a skipped matrix must not crash or leak "${{"
+ [DJANGO_TEMPLATE, 'Django tests'],
+ ])('jobBaseName(%s)', (name, expected) => {
+ expect(jobBaseName(name)).toBe(expected)
+ })
+
+ it('groups multi-variant matrices into one base with variant count and shard attribution', () => {
+ const jobs = [
+ { name: 'Select tests', conclusion: 'success' },
+ ...Array.from({ length: 23 }, (_, i) => ({
+ name: `${DJANGO_CORE} (${i + 1}/23)`,
+ conclusion: i === 2 || i === 16 ? 'failure' : 'success',
+ })),
+ ...Array.from({ length: 13 }, (_, i) => ({
+ name: `${DJANGO_TEMPORAL} (${i + 1}/13)`,
+ conclusion: 'success',
+ })),
+ { name: 'Product tests (experiments (1/2))', conclusion: 'success' },
+ { name: 'Product tests (experiments (2/2))', conclusion: 'success' },
+ { name: 'Django Tests Pass', conclusion: 'failure' },
+ ]
+ const groups = groupJobs(jobs)
+ expect(groups.map((g) => [g.base, g.jobs.length, g.variants, g.conclusion])).toEqual([
+ ['Select tests', 1, 1, 'success'],
+ ['Django tests', 36, 2, 'failure'],
+ ['Product tests', 2, 1, 'success'],
+ ['Django Tests Pass', 1, 1, 'failure'],
+ ])
+ expect(failedShardsLabel(groups[1])).toBe('shards 3, 17 of 23')
+ })
+
+ test.each([
+ // any running job keeps the group open, but a failure wins over running
+ [[null, 'success'], 'running'],
+ [['failure', null], 'failure'],
+ [['timed_out', 'success'], 'failure'],
+ [['cancelled', 'success'], 'cancelled'],
+ [['skipped', 'skipped'], 'skipped'],
+ ] as [Array<string | null>, string][])('group conclusion precedence %s → %s', (conclusions, expected) => {
+ const groups = groupJobs(
+ conclusions.map((c, i) => ({ name: `job (${i + 1}/${conclusions.length})`, conclusion: c }))
+ )
+ expect(groups).toHaveLength(1)
+ expect(groups[0].conclusion).toBe(expected)
+ })
+
+ it('labels non-shard failures by cleaned name', () => {
+ const groups = groupJobs([{ name: DJANGO_TEMPLATE, conclusion: 'failure' }])
+ expect(failedShardsLabel(groups[0])).toContain('Django tests – …')
+ expect(failedShardsLabel(groups[0])).not.toContain('${{')
+ })
+})
diff --git a/products/engineering_analytics/frontend/lib/jobGroups.ts b/products/engineering_analytics/frontend/lib/jobGroups.ts
new file mode 100644
index 000000000000..eabefd23568d
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/jobGroups.ts
@@ -0,0 +1,104 @@
+/** Matrix grouping for GitHub Actions jobs, derived from real PostHog run shapes.
+ *
+ * A master-push Backend CI run carries ~80 jobs; most are matrix shards. Grouping rules:
+ * - a trailing "(G/N)" shard suffix is stripped — including when nested inside another paren
+ * group, e.g. "Product tests (experiments (1/2))" → "Product tests (experiments)"
+ * - jobs group by the base name before the first " – " or " (" of the de-sharded name,
+ * so "Django tests – Core (persons-on-events off), Py 3.13 (3/23)" and its Temporal
+ * sibling land in one "Django tests" group with two variants
+ * - a skipped matrix never expands, so its single job keeps the raw workflow-file template
+ * name ("Django tests – ${{ matrix.segment }} …"); templates are collapsed to "…" for
+ * display but still group by their base
+ */
+
+export interface GroupableJob {
+ name: string
+ /** null while the job is still running */
+ conclusion: string | null
+}
+
+export type JobGroupConclusion = 'failure' | 'running' | 'cancelled' | 'skipped' | 'success'
+
+export interface JobGroup<T extends GroupableJob> {
+ /** grouping key and display name: de-sharded, de-templated base */
+ base: string
+ jobs: T[]
+ /** distinct matrix variants inside the group (segment/python/etc. combos) */
+ variants: number
+ failed: T[]
+ conclusion: JobGroupConclusion
+}
+
+/** Strip a trailing "(G/N)" shard suffix, preserving a closing paren that wrapped it. */
+export function stripShardSuffix(name: string): string {
+ return name.replace(/\s*\((\d+)\/(\d+)\)(\))?$/, (_, __, ___, close: string | undefined) => (close ? ')' : ''))
+}
+
+/** Collapse unexpanded workflow-file templates ("${{ matrix.foo }}") for display. */
+export function collapseTemplates(name: string): string {
+ return name
+ .replace(/\$\{\{[^}]*\}\}/g, '…')
+ .replace(/\s+/g, ' ')
+ .trim()
+}
+
+/** The grouping key: de-sharded, de-templated, cut before the first " – " or " (". */
+export function jobBaseName(name: string): string {
+ const cleaned = collapseTemplates(stripShardSuffix(name))
+ const cuts = [cleaned.indexOf(' – '), cleaned.indexOf(' (')].filter((i) => i > 0)
+ return (cuts.length ? cleaned.slice(0, Math.min(...cuts)) : cleaned).trim()
+}
+
+function groupConclusion(jobs: GroupableJob[]): JobGroupConclusion {
+ const conclusions = jobs.map((j) => j.conclusion)
+ if (conclusions.some((c) => c === 'failure' || c === 'timed_out')) {
+ return 'failure'
+ }
+ if (conclusions.some((c) => c === null)) {
+ return 'running'
+ }
+ if (conclusions.some((c) => c === 'cancelled')) {
+ return 'cancelled'
+ }
+ if (conclusions.every((c) => c === 'skipped')) {
+ return 'skipped'
+ }
+ return 'success'
+}
+
+/** Group jobs by matrix base, preserving first-appearance order of the groups. */
+export function groupJobs<T extends GroupableJob>(jobs: T[]): JobGroup<T>[] {
+ const order: string[] = []
+ const byBase = new Map<string, T[]>()
+ for (const job of jobs) {
+ const base = jobBaseName(job.name)
+ if (!byBase.has(base)) {
+ byBase.set(base, [])
+ order.push(base)
+ }
+ byBase.get(base)!.push(job)
+ }
+ return order.map((base) => {
+ const group = byBase.get(base)!
+ return {
+ base,
+ jobs: group,
+ variants: new Set(group.map((j) => collapseTemplates(stripShardSuffix(j.name)))).size,
+ failed: group.filter((j) => j.conclusion === 'failure' || j.conclusion === 'timed_out'),
+ conclusion: groupConclusion(group),
+ }
+ })
+}
+
+/** Short human form of which shards failed inside a group: "shards 3, 17 of 23". */
+export function failedShardsLabel<T extends GroupableJob>(group: JobGroup<T>): string {
+ const shardMatches = group.failed
+ .map((j) => j.name.match(/\((\d+)\/(\d+)\)\)?$/))
+ .filter((m): m is RegExpMatchArray => m !== null)
+ if (!shardMatches.length) {
+ return group.failed.map((j) => collapseTemplates(j.name)).join(' · ')
+ }
+ const nums = shardMatches.map((m) => m[1])
+ const total = shardMatches[0][2]
+ return `shard${nums.length > 1 ? 's' : ''} ${nums.join(', ')} of ${total}`
+}
diff --git a/products/engineering_analytics/frontend/lib/runHealth.test.ts b/products/engineering_analytics/frontend/lib/runHealth.test.ts
index 396a958c8fdd..b2f64f870126 100644
--- a/products/engineering_analytics/frontend/lib/runHealth.test.ts
+++ b/products/engineering_analytics/frontend/lib/runHealth.test.ts
@@ -86,17 +86,62 @@ describe('runHealth', () => {
expect(computeFleetSummary(rows).state).toBe(expected)
})
- it('sums runs and cost across workflows', () => {
+ it('sums runs, re-runs, and cost across workflows', () => {
const summary = computeFleetSummary([
- { runCount: 10, successRate: 1, latestRunFailed: false, billableMinutes: 100, estimatedCostUsd: 4 },
+ {
+ runCount: 10,
+ successRate: 1,
+ latestRunFailed: false,
+ billableMinutes: 100,
+ estimatedCostUsd: 4,
+ rerunCycles: 3,
+ },
{ runCount: 5, successRate: 1, latestRunFailed: true, billableMinutes: 50, estimatedCostUsd: 2 },
])
expect(summary.totalRuns).toBe(15)
expect(summary.failingNow).toBe(1)
+ expect(summary.rerunCycles).toBe(3)
expect(summary.estimatedCostUsd).toBe(6)
expect(summary.billableMinutes).toBe(150)
})
+ it.each([
+ // Weighted by completed runs — an unweighted mean of per-row rates would say 0.75 here.
+ [
+ 'weights the fleet rate by completed runs, not per-row average',
+ [
+ { runCount: 2, successRate: 1, latestRunFailed: false, buckets: [{ completed: 2, successes: 2 }] },
+ {
+ runCount: 6,
+ successRate: 0.5,
+ latestRunFailed: true,
+ buckets: [
+ { completed: 3, successes: 2 },
+ { completed: 3, successes: 1 },
+ ],
+ },
+ ],
+ 0.625,
+ ],
+ // Nothing settled anywhere → null, never a misleading 0%.
+ [
+ 'null when nothing has completed',
+ [{ runCount: 3, successRate: null, latestRunFailed: null, buckets: [{ completed: 0, successes: 0 }] }],
+ null,
+ ],
+ // Rows without buckets (per-push rows) contribute nothing rather than crashing or zeroing the rate.
+ [
+ 'rows without buckets are tolerated',
+ [
+ { runCount: 4, successRate: 0.5, latestRunFailed: false, buckets: [{ completed: 4, successes: 2 }] },
+ { runCount: 9, successRate: 1, latestRunFailed: false },
+ ],
+ 0.5,
+ ],
+ ])('computes the fleet pass rate: %s', (_name, rows, expected) => {
+ expect(computeFleetSummary(rows).passRate).toBe(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.ts
index b24d87422e86..a75135131a6f 100644
--- a/products/engineering_analytics/frontend/lib/runHealth.ts
+++ b/products/engineering_analytics/frontend/lib/runHealth.ts
@@ -1,9 +1,6 @@
-// Rolls a flat list of one workflow's runs into the health facts the verdict header renders. Separate
-// from the kea logic so both pages can share it and the math is unit-testable.
-
import { isDecisiveFailure } from './lifecycle'
-// The minimum a run needs to score its health. Both WorkflowRunRow and PrRunRow satisfy this.
+/** Minimal run shape; WorkflowRunRow and PrRunRow both satisfy it. */
export interface HealthRun {
conclusion: string | null
startedAt: string | null
@@ -39,7 +36,7 @@ export interface HealthSummary {
passedRuns: number
failures: number
running: number
- /** Runs that were a 2nd+ attempt — re-runs, a flakiness signal the chart doesn't show. */
+ /** Runs that were a 2nd+ attempt. */
reruns: number
/** Passes ÷ completed runs (null when nothing has settled). */
passRate: number | null
@@ -55,7 +52,7 @@ const DEGRADED_FAILURE_RATE = 0.1
// Below this success rate a currently-green workflow counts as flaky in the fleet rollup.
const FLAKY_SUCCESS_RATE = 0.9
-// One workflow's row in the all-workflows table, reduced to what the fleet rollup needs.
+// One workflow's row, reduced to what the fleet rollup needs.
export interface FleetRow {
runCount: number
successRate: number | null
@@ -66,6 +63,10 @@ export interface FleetRow {
lastFailureAt?: string | null
billableMinutes?: number | null
estimatedCostUsd?: number | null
+ /** Per-bucket completed/success counts — the weights behind the fleet-wide pass rate. */
+ buckets?: { completed: number; successes: number }[]
+ /** Runs in the window that were a 2nd+ attempt. */
+ rerunCycles?: number
}
export interface FleetSummary {
@@ -77,6 +78,10 @@ export interface FleetSummary {
/** Currently green but below the success-rate floor — flaky. */
flakyNow: number
totalRuns: number
+ /** Passes ÷ completed runs across every row's buckets; null when nothing has completed. */
+ passRate: number | null
+ /** Re-runs (attempt > 1) summed across workflows. */
+ rerunCycles: number
billableMinutes: number | null
estimatedCostUsd: number | null
}
@@ -90,15 +95,13 @@ export function percentileSorted(sortedAsc: number[], q: number): number | null
}
/**
- * Verdict + headline stats for one workflow's runs. State: latest settled run failing → "failing";
- * elevated decisive-failure rate → "degraded"; else "healthy". Durations and rates are over completed
- * runs only — an unsettled run is excluded, never counted as a failure.
+ * Verdict + headline stats for one workflow's runs. Durations and rates are over completed runs only —
+ * an unsettled run is excluded, never counted as a failure.
*/
export function computeHealthSummary(runs: HealthRun[]): HealthSummary {
const completed = runs.filter((run) => run.conclusion !== null)
const running = runs.length - completed.length
- // Strictly conclusion === 'success', mirroring the workflow-health endpoint's success_rate
- // (skipped/neutral don't count as passes) so this header and the Workflows table agree.
+ // Strictly 'success' (not skipped/neutral), mirroring the endpoint's success_rate so surfaces agree.
const passed = completed.filter((run) => run.conclusion === 'success').length
const failures = completed.filter((run) => isDecisiveFailure(run.conclusion)).length
const reruns = runs.filter((run) => (run.runAttempt ?? 1) > 1).length
@@ -146,11 +149,8 @@ export function computeHealthSummary(runs: HealthRun[]): HealthSummary {
}
}
-/**
- * Fleet verdict + rollups across all workflows in the window. State is the worst the fleet is now: every
- * settled workflow red → "failing"; any red or flaky → "degraded"; else "healthy". Runs and cost are
- * summed across workflows; cost is null until a row carries it.
- */
+/** Fleet verdict + rollups across all workflows: every settled workflow red → "failing"; any red or
+ * flaky → "degraded"; else "healthy". */
export function computeFleetSummary(rows: FleetRow[]): FleetSummary {
const workflowCount = rows.length
const settledWorkflows = rows.filter((row) => row.latestRunFailed != null).length
@@ -166,8 +166,19 @@ export function computeFleetSummary(rows: FleetRow[]): FleetSummary {
).length
const totalRuns = rows.reduce((sum, row) => sum + row.runCount, 0)
- // Gate each cost field on whether any row carries a real value — free runners report null, and a
- // bare sum would turn "no cost data" into a misleading $0.00 / 0 min.
+ // Completed-run-weighted, so a 3-run workflow can't move the fleet as much as a 3,000-run one.
+ let completedRuns = 0
+ let passedRuns = 0
+ for (const row of rows) {
+ for (const bucket of row.buckets ?? []) {
+ completedRuns += bucket.completed
+ passedRuns += bucket.successes
+ }
+ }
+ const passRate = completedRuns > 0 ? passedRuns / completedRuns : null
+ const rerunCycles = rows.reduce((sum, row) => sum + (row.rerunCycles ?? 0), 0)
+
+ // Free runners report null — a bare sum would turn "no cost data" into a misleading $0.00.
const hasBillable = rows.some((row) => row.billableMinutes != null)
const hasEstimatedCost = rows.some((row) => row.estimatedCostUsd != null)
const billableMinutes = hasBillable ? rows.reduce((sum, row) => sum + (row.billableMinutes ?? 0), 0) : null
@@ -175,7 +186,6 @@ export function computeFleetSummary(rows: FleetRow[]): FleetSummary {
let state: WorkflowState
if (workflowCount === 0 || settledWorkflows === 0) {
- // Workflows exist but none settled yet — no evidence either way, same as single-workflow "unknown".
state = 'unknown'
} else if (failingNow > 0 && failingNow === settledWorkflows) {
state = 'failing'
@@ -192,35 +202,28 @@ export function computeFleetSummary(rows: FleetRow[]): FleetSummary {
failingNow,
flakyNow,
totalRuns,
+ passRate,
+ rerunCycles,
billableMinutes,
estimatedCostUsd,
}
}
/**
- * Roll a run's jobs up to a single cost figure, mirroring the backend cost model (logic/cost.py): only
- * self-hosted runners are billable, and a job contributes once it has settled (a non-null estimated cost).
- * `unsettledJobs` counts only billable jobs that haven't finished yet (no duration) — excluded from the
- * total and surfaced as a caveat so the number never silently inflates. A finished self-hosted job with no
- * cost is an excluded tier (the backend doesn't price non-Linux Depot runners), not "unsettled", so it's
- * left out of both. Returns null when there's nothing to show — no priced jobs and nothing still running
- * (every job free, or every billable job finished on an unpriced tier) — so the caller omits the tile rather
- * than render a dangling "—".
+ * 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's
+ * nothing to show, so the caller omits the tile.
*/
export function summarizeRunCost(jobs: CostableJob[]): RunCostSummary | null {
const billable = jobs.filter((job) => job.runner_provider === 'self_hosted')
const costed = billable.filter((job) => job.estimated_cost_usd != null)
- // A null cost on a finished job means an unpriced tier (excluded), not "still running" — only a job
- // with no duration is genuinely unsettled.
+ // Null cost on a finished job = unpriced tier, not "still running" — only no-duration jobs are unsettled.
const unsettledJobs = billable.filter((job) => job.duration_seconds == null).length
if (costed.length === 0 && unsettledJobs === 0) {
- // Nothing to report: no priced jobs and nothing still running (all free, or every billable job
- // finished on an unpriced tier). Omit the tile rather than render a dangling "—".
return null
}
if (costed.length === 0) {
- // Billable jobs are still running but none has settled yet — keep the tile (with a "—" value +
- // caveat) rather than reporting a misleading $0.00 / 0 min for a run whose cost hasn't landed.
+ // Billable jobs still running, none settled — keep the tile rather than report a misleading $0.00.
return { billableMinutes: null, estimatedCostUsd: null, unsettledJobs }
}
const billableMinutes = costed.reduce((sum, job) => sum + (job.duration_seconds ?? 0) / 60, 0)
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
deleted file mode 100644
index 8666504534b8..000000000000
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { DateFilter } from 'lib/components/DateFilter/DateFilter'
-import { dateMapping } from 'lib/utils/dateFilters'
-import { pluralize } from 'lib/utils/strings'
-import { SceneExport } from 'scenes/sceneTypes'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-
-import { PullRequestTable } from '../components/PullRequestTable'
-import { formatCost, formatMinutes } from '../components/runTables'
-import { StatTile } from '../components/StatTile'
-import { AuthorLogicProps, authorLogic } from './authorLogic'
-import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
-
-// date_from only (the list floors on it); "all time" / week+month snaps are out. All options are within
-// the list's load window so the tile scope is always a subset of the visible PRs.
-const AUTHOR_DATE_OPTIONS = dateMapping.filter(({ key }) =>
- ['Custom', 'Last 7 days', 'Last 14 days', 'Last 30 days', 'Last 90 days', 'Last 180 days', 'Year to date'].includes(
- key
- )
-)
-
-export const scene: SceneExport<AuthorLogicProps> = {
- component: EngineeringAnalyticsAuthorScene,
- logic: authorLogic,
- paramsToProps: ({ params: { handle }, searchParams: { source } }) => ({
- handle: decodeURIComponent(handle),
- sourceId: source ?? null,
- }),
-}
-
-export function EngineeringAnalyticsAuthorScene(): JSX.Element {
- const { handle, prs, prsLoading, windowedRows, totalCostUsd, totalBillableMinutes, sourceId } =
- useValues(authorLogic)
- const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
- const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
-
- return (
- <SceneContent>
- <SceneTitleSection name={handle} resourceType={{ type: 'health' }} />
- <div className="flex flex-col gap-4">
- {/* The picker scopes the cost tiles only — the PR list below stays the author's recent PRs. */}
- <div className="flex flex-col gap-2">
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-xs font-semibold tracking-wide text-secondary uppercase">CI cost</span>
- <span className="text-xs text-tertiary">for PRs opened in</span>
- <DateFilter
- dateFrom={dateFrom}
- dateTo={dateTo}
- onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
- dateOptions={AUTHOR_DATE_OPTIONS}
- size="small"
- />
- </div>
- <div className="flex flex-wrap gap-3">
- <StatTile
- label="Pull requests opened"
- value={windowedRows.length.toLocaleString()}
- sub="in the selected window"
- />
- <StatTile
- label="Billable CI minutes"
- value={formatMinutes(totalBillableMinutes)}
- sub={totalCostUsd != null ? `≈ ${formatCost(totalCostUsd)} estimated` : 'no cost data yet'}
- />
- <StatTile
- label="Estimated CI cost"
- value={formatCost(totalCostUsd)}
- sub="self-hosted runners; excludes still-running jobs"
- />
- </div>
- </div>
-
- <div className="flex flex-col gap-2">
- <div className="flex items-baseline gap-2">
- <h3 className="mb-0">Pull requests</h3>
- {!prsLoading && <span className="text-xs text-secondary">{pluralize(prs.length, 'PR')}</span>}
- </div>
- <PullRequestTable
- rows={prs}
- loading={prsLoading}
- sourceId={sourceId}
- costLensEnabled
- showAuthor={false}
- defaultSorting={{ columnKey: 'age', order: -1 }}
- dataAttr="engineering-analytics-author-pr-table"
- emptyState={`No pull requests for ${handle} in the last year.`}
- />
- </div>
- </div>
- </SceneContent>
- )
-}
-
-export default EngineeringAnalyticsAuthorScene
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
index c090de07086b..154a471b541b 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
@@ -10,11 +10,11 @@ import {
} from '@posthog/lemon-ui'
import { humanFriendlyNumber } from 'lib/utils/numbers'
-import { pluralize } from 'lib/utils/strings'
import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
import { PullRequestTable } from '../components/PullRequestTable'
+import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
import { StatCard } from '../components/StatCard'
import { CIStatusFilter, PRStateFilter, engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
@@ -61,15 +61,15 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
}
const failingPct =
- cards && cards.openPrs > 0 ? `${humanFriendlyNumber((cards.failingCi / cards.openPrs) * 100)}% of open` : '—'
+ cards && cards.openPrs > 0 ? `${Math.round((cards.failingCi / cards.openPrs) * 100)}% of open` : undefined
return (
<div className="flex flex-col gap-4">
+ <ScopeBar repoSlot={<SourceScopeChip />} showDate={false} />
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
<StatCard
label="Open PRs"
value={cards ? humanFriendlyNumber(cards.openPrs) : '—'}
- caption={cards ? `across ${pluralize(cards.repos, 'repo')}` : ' '}
loading={cardsLoading}
onClick={() => applyCardFilter('open')}
active={activeCard === 'open'}
@@ -78,7 +78,7 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
<StatCard
label="Failing CI"
value={cards ? humanFriendlyNumber(cards.failingCi) : '—'}
- caption={`${failingPct} · workflow-level`}
+ caption={failingPct}
loading={cardsLoading}
onClick={() => applyCardFilter('failing')}
active={activeCard === 'failing'}
@@ -87,7 +87,7 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
<StatCard
label="Stuck > 7d"
value={cards ? humanFriendlyNumber(cards.stuck) : '—'}
- caption="open > 7d, not draft, not bot"
+ caption="excludes drafts and bots"
loading={cardsLoading}
onClick={() => applyCardFilter('stuck')}
active={activeCard === 'stuck'}
@@ -147,7 +147,7 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
/>
</div>
<LemonSwitch
- label="Cost & performance lens"
+ label="Cost columns"
checked={costLensEnabled}
onChange={setCostLensEnabled}
size="small"
@@ -170,15 +170,15 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
</LemonButton>
</div>
) : (
- 'No pull requests yet — they show up as soon as CI events arrive.'
+ "No pull requests yet. They'll appear once the GitHub source syncs."
)
}
/>
<div className="text-xs text-tertiary">
- CI is a workflow-level rollup via the head-commit join, not per-check — a run that hasn't completed
- shows as Running, not a pass or fail. "Open→merge" is created-to-merged time (merged PRs only), never
- review or cycle time.
+ CI status is workflow-level for each pull request's latest commit, not per-check. A run that hasn't
+ completed shows as Running, not a pass or fail. "Open→merge" is created-to-merged time (merged PRs
+ only), never review or cycle time.
{tableTruncated && ' Showing the most recent 1000 PRs.'}
</div>
</div>
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
index c6e2b781edfb..d232ce5eaeb2 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
@@ -1,7 +1,7 @@
import { BindLogic, useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { LemonBanner, LemonButton, LemonSelect, LemonTab, LemonTabs } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonTab, LemonTabs } from '@posthog/lemon-ui'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -12,12 +12,13 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
import { EngineeringAnalyticsPullRequests } from './EngineeringAnalyticsPullRequests'
import {
- EngineeringAnalyticsTab,
- TAB_DESCRIPTIONS,
+ EngineeringAnalyticsView,
+ VIEW_DESCRIPTIONS,
engineeringAnalyticsSceneLogic,
} from './engineeringAnalyticsSceneLogic'
import { EngineeringAnalyticsTestHealth } from './EngineeringAnalyticsTestHealth'
import { EngineeringAnalyticsWorkflows } from './EngineeringAnalyticsWorkflows'
+import { RepoOverviewScene } from './RepoOverviewScene'
export const scene: SceneExport = {
component: EngineeringAnalyticsScene,
@@ -25,32 +26,40 @@ export const scene: SceneExport = {
}
export function EngineeringAnalyticsScene(): JSX.Element {
- const { searchParams } = useValues(router)
- const { activeTab } = useValues(engineeringAnalyticsSceneLogic)
+ const { searchParams: linkParams } = useValues(router)
+ const { activeView } = useValues(engineeringAnalyticsSceneLogic)
const logic = engineeringAnalyticsLogic()
- const { anyLoading, hasMultipleSources, sourceOptions, sourceId } = useValues(logic)
- const { refresh, setSourceId } = useActions(logic)
+ const { anyLoading } = useValues(logic)
+ const { refresh } = useActions(logic)
- const tabs: LemonTab<EngineeringAnalyticsTab>[] = [
+ // The general areas of the product. Drill-down pages (workflow, run, PR) live below the Overview.
+ const tabs: LemonTab<EngineeringAnalyticsView>[] = [
+ {
+ key: 'hub',
+ label: 'Overview',
+ content: <RepoOverviewScene />,
+ link: combineUrl(urls.engineeringAnalytics(), linkParams).url,
+ 'data-attr': 'engineering-analytics-overview-tab',
+ },
{
key: 'pull-requests',
label: 'Pull requests',
content: <EngineeringAnalyticsPullRequests />,
- link: combineUrl(urls.engineeringAnalytics(), searchParams).url,
+ link: combineUrl(urls.engineeringAnalyticsPullRequestList(), linkParams).url,
'data-attr': 'engineering-analytics-pull-requests-tab',
},
{
key: 'workflows',
label: 'Workflows',
content: <EngineeringAnalyticsWorkflows />,
- link: combineUrl(urls.engineeringAnalyticsWorkflows(), searchParams).url,
+ link: combineUrl(urls.engineeringAnalyticsWorkflows(), linkParams).url,
'data-attr': 'engineering-analytics-workflows-tab',
},
{
key: 'test-health',
label: 'Test health',
content: <EngineeringAnalyticsTestHealth />,
- link: combineUrl(urls.engineeringAnalyticsTestHealth(), searchParams).url,
+ link: combineUrl(urls.engineeringAnalyticsTestHealth(), linkParams).url,
'data-attr': 'engineering-analytics-test-health-tab',
},
]
@@ -60,38 +69,24 @@ export function EngineeringAnalyticsScene(): JSX.Element {
<SceneContent>
<SceneTitleSection
name="Engineering analytics"
- description={TAB_DESCRIPTIONS[activeTab]}
+ description={VIEW_DESCRIPTIONS[activeView]}
resourceType={{ type: 'health' }}
actions={
- <div className="flex items-center gap-2">
- {hasMultipleSources && (
- <LemonSelect
- size="small"
- value={sourceId}
- onChange={setSourceId}
- options={sourceOptions}
- placeholder="Source: default"
- allowClear
- dropdownMatchSelectWidth={false}
- data-attr="engineering-analytics-source-select"
- />
- )}
- <LemonButton
- type="secondary"
- size="small"
- onClick={refresh}
- loading={anyLoading}
- disabledReason={anyLoading ? 'Loading…' : undefined}
- >
- Refresh
- </LemonButton>
- </div>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={refresh}
+ loading={anyLoading}
+ disabledReason={anyLoading ? 'Loading…' : undefined}
+ >
+ Refresh
+ </LemonButton>
}
/>
<LemonBanner type="info" dismissKey="engineering-analytics-alpha">
Engineering analytics is in alpha. Metrics are limited to CI events, and details may change.
</LemonBanner>
- <LemonTabs activeKey={activeTab} data-attr="engineering-analytics-tabs" tabs={tabs} sceneInset />
+ <LemonTabs activeKey={activeView} data-attr="engineering-analytics-tabs" tabs={tabs} sceneInset />
</SceneContent>
</BindLogic>
)
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
index d5c9082515ec..59f549dd69a9 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
@@ -23,6 +23,7 @@ import { pluralize } from 'lib/utils/strings'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
import { QuarantineTestModal } from '../components/QuarantineTestModal'
+import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
import { StatCard } from '../components/StatCard'
import {
QuarantineEntryRow,
@@ -47,14 +48,14 @@ function LifecycleTag({ lifecycle }: { lifecycle: QuarantineLifecycle }): JSX.El
return <LemonTag type="warning">Expiring soon</LemonTag>
case 'in_grace':
return (
- <Tooltip title="Expired, but inside the 7-day grace — the quarantine check only warns for now.">
+ <Tooltip title="Expired, but inside the 7-day grace period. The quarantine check only warns for now.">
<LemonTag type="warning">In grace</LemonTag>
</Tooltip>
)
default:
return (
- <Tooltip title="Expired beyond the grace period — the quarantine check workflow fails until it is removed or re-triaged.">
- <LemonTag type="danger">Overdue — blocks CI</LemonTag>
+ <Tooltip title="Expired beyond the grace period. The quarantine check workflow fails until the entry is removed or re-triaged.">
+ <LemonTag type="danger">Overdue · blocks CI</LemonTag>
</Tooltip>
)
}
@@ -152,6 +153,10 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
/>
)
+ // Rendered on every data-bearing branch: the quarantine file is per-repo, so multi-source teams
+ // need the source picker here too — including on the wrong-repo empty states.
+ const scopeBar = <ScopeBar repoSlot={<SourceScopeChip />} showDate={false} />
+
// Production with no GitHub source and no local checkout: the endpoint 400s, same as the other tabs.
if (quarantineLoadFailed) {
return <ConnectGitHubSource />
@@ -161,25 +166,28 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
// parse_errors set — surface those instead of the "no file" explainer, which only fits a true 404.
if (quarantine && !quarantine.available && quarantine.parseErrors.length > 0) {
return (
- <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">
- <IconShieldLock className="size-8 text-tertiary" />
- <div className="text-lg font-semibold">Couldn't read the quarantine file</div>
- <div className="w-full max-w-xl">
- <LemonBanner type="warning">
- <ul className="ml-4 list-disc text-left">
- {quarantine.parseErrors.map((error, index) => (
- <li key={index} className="font-mono text-xs">
- {error}
- </li>
- ))}
- </ul>
- </LemonBanner>
+ <div className="flex flex-col gap-4">
+ {scopeBar}
+ <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">
+ <IconShieldLock className="size-8 text-tertiary" />
+ <div className="text-lg font-semibold">Couldn't read the quarantine file</div>
+ <div className="w-full max-w-xl">
+ <LemonBanner type="warning">
+ <ul className="ml-4 list-disc text-left">
+ {quarantine.parseErrors.map((error, index) => (
+ <li key={index} className="font-mono text-xs">
+ {error}
+ </li>
+ ))}
+ </ul>
+ </LemonBanner>
+ </div>
+ {quarantine.repoFullName && (
+ <p className="text-sm text-secondary">
+ Repository: <span className="font-mono">{quarantine.repoFullName}</span>
+ </p>
+ )}
</div>
- {quarantine.repoFullName && (
- <p className="text-sm text-secondary">
- Repository: <span className="font-mono">{quarantine.repoFullName}</span>
- </p>
- )}
</div>
)
}
@@ -187,20 +195,23 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
// A file that does not exist is a normal state, not an error — offer to start one.
if (quarantine && !quarantine.available) {
return (
- <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">
- <IconShieldLock className="size-8 text-tertiary" />
- <div className="text-lg font-semibold">No test quarantine yet</div>
- <p className="max-w-xl text-sm text-secondary">
- {quarantine.repoFullName
- ? `${quarantine.repoFullName} has no .test_quarantine.json. `
- : 'This repo has no .test_quarantine.json. '}
- Quarantine masks a flaky test in CI with a hard expiry, so it stops blocking merges while its owner
- fixes it. The first quarantine opens a PR that creates the file.
- </p>
- <LemonButton type="primary" onClick={openNewQuarantine} data-attr="eng-analytics-quarantine-open">
- Quarantine a test
- </LemonButton>
- {modalElement}
+ <div className="flex flex-col gap-4">
+ {scopeBar}
+ <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">
+ <IconShieldLock className="size-8 text-tertiary" />
+ <div className="text-lg font-semibold">No test quarantine yet</div>
+ <p className="max-w-xl text-sm text-secondary">
+ {quarantine.repoFullName
+ ? `${quarantine.repoFullName} has no .test_quarantine.json. `
+ : 'This repo has no .test_quarantine.json. '}
+ Quarantine masks a flaky test in CI with a hard expiry, so it stops blocking merges while its
+ owner fixes it. The first quarantine opens a PR that creates the file.
+ </p>
+ <LemonButton type="primary" onClick={openNewQuarantine} data-attr="eng-analytics-quarantine-open">
+ Quarantine a test
+ </LemonButton>
+ {modalElement}
+ </div>
</div>
)
}
@@ -219,7 +230,7 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
{row.selectorKind}
</LemonTag>
{row.runner !== 'pytest' && (
- <Tooltip title="No enforcement adapter yet — entry is informational.">
+ <Tooltip title="No enforcement adapter yet. This entry is informational.">
<LemonTag type="muted" size="small">
{row.runner}
</LemonTag>
@@ -320,6 +331,7 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
return (
<div className="flex flex-col gap-4">
+ {scopeBar}
<div className="flex items-start justify-between gap-2">
<div className="flex flex-col gap-0.5">
<h3 className="m-0 text-base font-semibold">Quarantine register</h3>
@@ -464,7 +476,7 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
</LemonButton>
</div>
) : (
- 'No quarantined tests — nothing is masked right now.'
+ 'No quarantined tests. Nothing is masked right now.'
)
}
nouns={['quarantined test', 'quarantined tests']}
@@ -472,8 +484,8 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
<div className="text-xs text-tertiary">
Quarantine is checked into <span className="font-mono">.test_quarantine.json</span> and enforced by CI.
- Quarantining, extending, or removing opens a pull request — the file stays the source of truth. A merged
- edit only affects CI runs that start after it lands.
+ Quarantining, extending, or removing opens a pull request, so the file stays the source of truth. A
+ merged edit only affects CI runs that start after it lands.
</div>
{modalElement}
</div>
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
index 78810d9d0da0..de44d6f79c65 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
@@ -1,43 +1,32 @@
+// The full workflow list behind the hub's capped workflows section. Every row opens the workflow page.
+
import { useActions, useValues } from 'kea'
-import { DateFilter } from 'lib/components/DateFilter/DateFilter'
-import { dateFilterToText, dateMapping } from 'lib/utils/dateFilters'
+import { LemonButton, LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui'
-import { BranchFilter } from '../components/BranchFilter'
import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
+import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
import { WorkflowsHealthHeader } from '../components/WorkflowsHealthHeader'
-import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
-import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
-
-// The endpoint caps the window at 366 days, so "All time" and week/month snaps are out.
-const WORKFLOW_DATE_OPTIONS = dateMapping.filter(({ key }) =>
- [
- 'Custom',
- 'Last 24 hours',
- 'Last 7 days',
- 'Last 14 days',
- 'Last 30 days',
- 'Last 90 days',
- 'Last 180 days',
- 'Year to date',
- ].includes(key)
-)
+import { WORKFLOW_HEALTH_LIMIT, WorkflowStatusFilter, engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
export function EngineeringAnalyticsWorkflows(): JSX.Element {
const {
- workflowHealth,
+ fleetSummary,
+ fleetTruncated,
+ filteredWorkflowHealth,
workflowHealthLoading,
+ workflowSearch,
+ workflowStatusFilter,
+ hasActiveWorkflowFilters,
+ workflowCostAvailable,
+ sourceId,
notConnected,
workflowHealthLoadError,
- sourceId,
- fleetSummary,
- fleetTruncated,
} = useValues(engineeringAnalyticsLogic)
- const { refresh } = useActions(engineeringAnalyticsLogic)
- const { dateFrom, dateTo, appliedBranch } = useValues(engineeringAnalyticsFiltersLogic)
- const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
+ const { setWorkflowSearch, setWorkflowStatusFilter, resetWorkflowFilters, refresh } =
+ useActions(engineeringAnalyticsLogic)
if (notConnected) {
return <ConnectGitHubSource />
@@ -46,35 +35,60 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
return <CIAnalyticsLoadError onRetry={refresh} />
}
- const windowLabel = dateFilterToText(dateFrom, dateTo, 'Last 7 days') ?? 'Last 7 days'
-
return (
<div className="flex flex-col gap-4">
- <div className="flex items-center gap-2">
- <DateFilter
- dateFrom={dateFrom}
- dateTo={dateTo}
- onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
- dateOptions={WORKFLOW_DATE_OPTIONS}
+ <ScopeBar repoSlot={<SourceScopeChip />} showBranch />
+
+ <WorkflowsHealthHeader summary={fleetSummary} truncated={fleetTruncated} />
+
+ <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' },
+ ]}
/>
- <BranchFilter />
</div>
- {workflowHealth.length > 0 && <WorkflowsHealthHeader summary={fleetSummary} truncated={fleetTruncated} />}
+
<WorkflowHealthTable
- rows={workflowHealth}
+ rows={filteredWorkflowHealth}
loading={workflowHealthLoading}
sourceId={sourceId}
- showCost={workflowHealth.some((row) => row.billableMinutes != null || row.estimatedCostUsd != null)}
+ showCost={workflowCostAvailable}
+ defaultSorting={{ columnKey: 'runCount', order: -1 }}
emptyState={
- appliedBranch
- ? `No workflow runs on '${appliedBranch}' in this window.`
- : 'No workflow runs in this window.'
+ 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">
- Success rate and durations are computed over completed runs only — a run that hasn't settled is
- excluded, not counted as a failure. Window: {windowLabel}
- {appliedBranch ? ` · branch: ${appliedBranch}` : ''}.
+ Pass rate and durations cover completed runs only. A run that hasn't settled is excluded, never counted
+ as a failure. Health is workflow-level, not per-job.
+ {fleetTruncated && ` Showing the top ${WORKFLOW_HEALTH_LIMIT} workflows by run count.`}
</div>
</div>
)
diff --git a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
index ca0652abd036..aaa918d07f3f 100644
--- a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
@@ -2,8 +2,16 @@ import { useActions, useValues } from 'kea'
import { combineUrl } from 'kea-router'
import { Fragment, ReactNode } from 'react'
-import { IconExternal } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonSkeleton, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
+import { IconExternal, IconPullRequest } from '@posthog/icons'
+import {
+ LemonButton,
+ LemonInput,
+ LemonSkeleton,
+ LemonTable,
+ LemonTableColumns,
+ LemonTag,
+ Link,
+} from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
@@ -17,19 +25,26 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { EntityHeader, VerdictPill } from '../components/EntityHeader'
+import { FailureLogGroups } from '../components/FailureLogs'
+import { GroupedJobsTable } from '../components/GroupedJobsTable'
+import { MetricTile } from '../components/MetricTile'
import { PullRequestStateTag } from '../components/PullRequestStateTag'
-import { RunJobsTable, RunsTable, formatCost } from '../components/runTables'
-import { StatTile } from '../components/StatTile'
-import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
-import type { PRCostSummaryApi, PullRequestApi } from '../generated/api.schemas'
+import { RunConclusionTag } from '../components/runTables'
+import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
+import { Section, SectionNav } from '../components/Section'
+import type { WorkflowJobApi } from '../generated/api.schemas'
+import { compactUsd } from '../lib/format'
import { githubCommitUrl, githubPrUrl } from '../lib/github'
import { LifecycleSummary, WorkflowRun, isPassingConclusion } from '../lib/lifecycle'
import {
PrCommitRuns,
PrRunRow,
+ PrWorkflowRow,
PullRequestDetailLogicProps,
jobCacheKey,
pullRequestDetailLogic,
+ latestRunPerWorkflow,
} from './pullRequestDetailLogic'
export const scene: SceneExport<PullRequestDetailLogicProps> = {
@@ -172,8 +187,6 @@ function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps
// Not necessarily the last node's time: head-SHA runs can outlive the merge.
const totalTo = summary.mergedAt ?? summary.closedAt ?? nodes[nodes.length - 1].at
- const endLabel = summary.mergedAt ? 'merged' : summary.closedAt ? 'closed' : 'still open'
- const subtitle = commitGroups.length ? `opened → latest push → ${endLabel}` : `opened → ${endLabel}`
const connector = (dashed: boolean | undefined): string =>
dashed ? 'w-full border-t border-dashed border-border-bold' : 'h-px w-full bg-border-bold'
@@ -184,10 +197,6 @@ function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps
return (
<LemonCard hoverEffect={false} className="px-5 py-4">
- <div className="mb-3 flex items-baseline gap-2">
- <span className="text-xs font-semibold tracking-wide text-secondary uppercase">Lifecycle</span>
- <span className="text-xs text-tertiary">{subtitle}</span>
- </div>
<div className="flex items-center gap-6">
<div className="flex min-w-0 flex-1 items-stretch">
{nodes.map((node, index) => (
@@ -255,268 +264,322 @@ function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps
)
}
-function MetaRow({ pullRequest, sourceId }: { pullRequest: PullRequestApi; sourceId: string | null }): JSX.Element {
- return (
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
- <PullRequestStateTag state={pullRequest.state} isDraft={pullRequest.is_draft} />
- <span className="flex items-center gap-1.5">
- {pullRequest.author.avatar_url && (
- <img src={pullRequest.author.avatar_url} alt="" className="h-5 w-5 shrink-0 rounded-full" />
- )}
- <Link
- to={
- combineUrl(
- urls.engineeringAnalyticsAuthor(pullRequest.author.handle),
- sourceId ? { source: sourceId } : {}
- ).url
- }
- >
- {pullRequest.author.handle}
- </Link>
- {pullRequest.author.is_bot && <LemonTag type="muted">bot</LemonTag>}
- </span>
- <span className="font-mono text-xs text-secondary">
- {pullRequest.repo.owner}/{pullRequest.repo.name} #{pullRequest.number}
- </span>
- </div>
- )
-}
-
// Stable per-row key — re-runs share a runId, so start time disambiguates attempts. Used for rowKey and
// the expand-state set, so expanding one attempt doesn't open the others.
function runRowKey(run: WorkflowRun): string {
return `${run.workflow}@${run.startedAt ?? run.finishedAt ?? run.runId ?? ''}`
}
-function formatMinutes(minutes: number): string {
- return `${Math.round(minutes).toLocaleString()} min`
-}
-
-const VERDICT_LEGEND: { key: 'passed' | 'failed' | 'running'; dot: string; label: string }[] = [
- { key: 'passed', dot: 'bg-success', label: 'passed' },
- { key: 'failed', dot: 'bg-danger', label: 'failed' },
- { key: 'running', dot: 'bg-warning', label: 'running' },
-]
-
-// Stroke from the same CSS vars the verdict dots / LemonTags use, so the donut matches the legend dots
-// and the run-table StatusDots exactly.
-const DONUT_STROKE: Record<'passed' | 'failed' | 'running', string> = {
- passed: 'var(--success)',
- failed: 'var(--danger)',
- running: 'var(--warning)',
-}
-
-interface VerdictCounts {
- passed: number
- failed: number
- running: number
-}
-
-/** Donut of run verdicts with the pass rate (passed / settled) in the center. */
-function VerdictDonut({ counts }: { counts: VerdictCounts }): JSX.Element {
- const total = counts.passed + counts.failed + counts.running
- const settled = counts.passed + counts.failed
- const passRate = settled > 0 ? Math.round((counts.passed / settled) * 100) : null
- const radius = 40
- const circumference = 2 * Math.PI * radius
-
- let offset = 0
- const arcs = VERDICT_LEGEND.flatMap(({ key }) => {
- const value = counts[key]
- if (value <= 0 || total <= 0) {
- return []
- }
- const length = (value / total) * circumference
- const arc = (
- <circle
- key={key}
- cx="50"
- cy="50"
- r={radius}
- fill="none"
- strokeWidth="10"
- stroke={DONUT_STROKE[key]}
- strokeDasharray={`${length} ${circumference - length}`}
- strokeDashoffset={-offset}
- />
- )
- offset += length
- return [arc]
- })
-
- return (
- <div className="relative h-24 w-24 shrink-0">
- <svg viewBox="0 0 100 100" className="h-full w-full -rotate-90">
- <circle cx="50" cy="50" r={radius} fill="none" strokeWidth="10" stroke="var(--border)" />
- {arcs}
- </svg>
- <div className="absolute inset-0 flex flex-col items-center justify-center">
- <span className="text-xl leading-none font-semibold tabular-nums">
- {passRate == null ? '—' : `${passRate}%`}
+/** The runs of one workflow on this PR, one row per push × attempt — jobs live on the run page. */
+function PerPushRunsTable({
+ runs,
+ runCostByKey,
+ showCost,
+ repoOwner,
+ repoName,
+ sourceId,
+ runJobs,
+ runJobsLoading,
+ expandedRunKeys,
+ setRunExpanded,
+}: {
+ runs: PrRunRow[]
+ runCostByKey: Record<string, { minutes: number | null; cost: number | null }>
+ showCost: boolean
+ repoOwner: string
+ repoName: string
+ sourceId: string | null
+ runJobs: Record<string, WorkflowJobApi[]>
+ runJobsLoading: boolean
+ expandedRunKeys: string[]
+ setRunExpanded: (rowKey: string, expanded: boolean, runId: number | null, runAttempt: number | null) => void
+}): JSX.Element {
+ // Oldest push first so rows read in the same order as the timeline strip.
+ const ordered = [...runs].sort((a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''))
+ const columns: LemonTableColumns<PrRunRow> = [
+ {
+ title: 'Push',
+ key: 'push',
+ render: (_, run) =>
+ run.headSha ? (
+ <Link
+ to={githubCommitUrl(repoOwner, repoName, run.headSha)}
+ target="_blank"
+ className="font-mono text-xs"
+ >
+ {run.headSha.slice(0, 7)}
+ </Link>
+ ) : (
+ <span className="text-xs text-secondary">—</span>
+ ),
+ },
+ {
+ title: 'Run',
+ key: 'run',
+ render: (_, run) =>
+ run.runId != null ? (
+ <Link
+ to={
+ combineUrl(
+ urls.engineeringAnalyticsWorkflowRun(repoOwner, repoName, run.runId),
+ sourceId ? { source: sourceId } : {}
+ ).url
+ }
+ className="font-mono text-xs"
+ >
+ #{run.runId}
+ </Link>
+ ) : (
+ <span className="text-xs text-secondary">—</span>
+ ),
+ },
+ {
+ title: 'Attempt',
+ key: 'attempt',
+ align: 'right',
+ render: (_, run) =>
+ (run.runAttempt ?? 1) > 1 ? (
+ <LemonTag type="warning">{run.runAttempt}</LemonTag>
+ ) : (
+ <span className="text-xs tabular-nums text-tertiary">{run.runAttempt ?? 1}</span>
+ ),
+ },
+ {
+ title: 'Conclusion',
+ key: 'conclusion',
+ render: (_, run) => <RunConclusionTag conclusion={run.conclusion} />,
+ },
+ {
+ title: 'Duration',
+ key: 'duration',
+ align: 'right',
+ render: (_, run) => (
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {run.durationSeconds == null ? '—' : humanFriendlyDuration(run.durationSeconds)}
</span>
- <span className="text-xs text-tertiary">pass rate</span>
- </div>
- </div>
- )
-}
-
-interface PrSummaryCardsProps {
- cost: PRCostSummaryApi | null
- costLoading: boolean
- pushes: number
- rerunCycles: number
- counts: VerdictCounts
- runsTotal: number
- commits: number
- summary: LifecycleSummary | null
- openedAt: string
- // First load: three loaders (lifecycle / runs / cost) resolve at different times; without this the
- // cards pop in one at a time. Show a full skeleton row instead.
- loading: boolean
-}
-
-/**
- * Headline stats for a PR's CI: verdict donut over all commits, billable runner minutes + estimated cost
- * (when the job-level source is synced), CI triggers, and time open. Cost is an estimate — the chip spells
- * out the model (wall-clock × reference rate) and excludes unsettled jobs.
- */
-function PrSummaryCards({
- cost,
- costLoading,
- pushes,
- rerunCycles,
- counts,
- runsTotal,
- commits,
- summary,
- openedAt,
- loading,
-}: PrSummaryCardsProps): JSX.Element {
- if (loading) {
- // One skeleton per card (the verdict card is wider) so the whole row appears at once.
- return (
- <div className="flex flex-wrap items-stretch gap-3">
- <LemonSkeleton className="h-[104px] min-w-72 flex-1 rounded-lg" />
- <LemonSkeleton className="h-[104px] min-w-44 flex-1 rounded-lg" />
- <LemonSkeleton className="h-[104px] min-w-44 flex-1 rounded-lg" />
- <LemonSkeleton className="h-[104px] min-w-44 flex-1 rounded-lg" />
- </div>
- )
- }
- const showCost = cost?.jobs_available
- const openTo = summary?.mergedAt ?? summary?.closedAt ?? dayjs().toISOString()
- const openLabel = summary?.mergedAt ? 'Time to merge' : summary?.closedAt ? 'Time to close' : 'Open so far'
+ ),
+ },
+ ...((showCost
+ ? [
+ {
+ title: 'Cost',
+ key: 'cost',
+ align: 'right',
+ render: (_: unknown, run: PrRunRow) => {
+ const cost = run.runId != null ? runCostByKey[jobCacheKey(run.runId, run.runAttempt)] : null
+ return (
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {cost?.cost != null ? compactUsd(cost.cost) : '—'}
+ </span>
+ )
+ },
+ },
+ ]
+ : []) as LemonTableColumns<PrRunRow>),
+ {
+ title: 'Started',
+ key: 'started',
+ align: 'right',
+ render: (_, run) =>
+ run.startedAt ? (
+ <span className="text-xs whitespace-nowrap text-tertiary">
+ <TZLabel time={run.startedAt} />
+ </span>
+ ) : (
+ <span className="text-xs text-secondary">—</span>
+ ),
+ },
+ ]
return (
- <div className="flex flex-col gap-2">
- {showCost && (
- <div className="flex flex-wrap items-center gap-2">
- <LemonTag type="warning">estimate · wall-clock × reference rate</LemonTag>
- {cost.unsettled_jobs > 0 && (
- <LemonTag type="muted">{pluralize(cost.unsettled_jobs, 'unsettled job')} excluded</LemonTag>
- )}
- </div>
- )}
- <div className="flex flex-wrap items-stretch gap-3">
- {runsTotal > 0 && (
- <LemonCard hoverEffect={false} className="flex min-w-72 flex-1 flex-col gap-2 px-5 py-4">
- <span className="text-xs text-secondary">Run verdicts · all commits &amp; re-runs</span>
- <div className="flex items-center gap-4">
- <VerdictDonut counts={counts} />
- <div className="flex flex-col gap-0.5 text-xs">
- {VERDICT_LEGEND.map(({ key, dot, label }) => (
- <span key={key} className="flex items-center gap-1.5">
- <span className={cn('h-1.5 w-1.5 shrink-0 rounded-full', dot)} />
- <span className="font-medium tabular-nums">{counts[key]}</span>
- <span className="text-secondary">{label}</span>
- </span>
- ))}
- </div>
- </div>
- <span className="text-xs text-tertiary">
- {pluralize(runsTotal, 'run')} · {pluralize(commits, 'commit')}
- </span>
- </LemonCard>
- )}
- {costLoading && !cost ? (
- <LemonSkeleton className="h-24 w-44" />
- ) : showCost ? (
- <StatTile
- label="Billable CI minutes"
- value={formatMinutes(cost.billable_minutes)}
- sub={<>≈ {formatCost(cost.estimated_cost_usd)} estimated</>}
- />
- ) : null}
- <StatTile
- label="Pushes (CI triggers)"
- value={pushes.toLocaleString()}
- sub={rerunCycles > 0 ? pluralize(rerunCycles, 're-run cycle') : 'no re-runs'}
- />
- {openedAt && (
- <StatTile
- label={openLabel}
- value={gapBetween(openedAt, openTo)}
- sub={
- <>
- opened <TZLabel time={openedAt} />
- </>
- }
+ <LemonTable
+ dataSource={ordered}
+ columns={columns}
+ size="small"
+ embedded
+ rowKey={runRowKey}
+ useURLForSorting={false}
+ onRow={(run) =>
+ run.runId != null
+ ? {
+ className: 'cursor-pointer',
+ onClick: () =>
+ setRunExpanded(
+ runRowKey(run),
+ !expandedRunKeys.includes(runRowKey(run)),
+ run.runId,
+ run.runAttempt
+ ),
+ }
+ : {}
+ }
+ expandable={{
+ noIndent: true,
+ rowExpandable: (run) => run.runId != null,
+ isRowExpanded: (run) => expandedRunKeys.includes(runRowKey(run)),
+ expandedRowRender: (run) => (
+ <GroupedJobsTable
+ jobs={run.runId != null ? runJobs[jobCacheKey(run.runId, run.runAttempt)] : undefined}
+ loading={runJobsLoading}
+ embedded
/>
- )}
- </div>
- </div>
+ ),
+ }}
+ nouns={['run', 'runs']}
+ />
)
}
-/**
- * Lead columns for the PR runs table: the commit (which push) + re-run attempt. Re-runs share a runId,
- * so attempts are numbered by start order. The shared RunsTable appends verdict / duration / started / cost.
- */
-function commitLeadColumns(runs: PrRunRow[], repoOwner: string, repoName: string): LemonTableColumns<PrRunRow> {
- const attemptIndexByKey = new Map<string, number>()
- const runsByRunId = new Map<number, PrRunRow[]>()
- runs.forEach((run) => {
- if (run.runId != null) {
- const group = runsByRunId.get(run.runId) ?? []
- group.push(run)
- runsByRunId.set(run.runId, group)
- }
- })
- runsByRunId.forEach((group) => {
- if (group.length > 1) {
- ;[...group]
- .sort((a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''))
- .forEach((run, index) => attemptIndexByKey.set(runRowKey(run), index + 1))
- }
- })
- return [
+/** The PR's CI rolled up per workflow: latest state, what failed (by job name), runs / p50 / cost.
+ * Expands (caret only) to the per-push runs. */
+function PrWorkflowsTable({
+ rows,
+ filteredRuns,
+ failingJobLabelByWorkflow,
+ runCostByKey,
+ showCost,
+ loading,
+ repoOwner,
+ repoName,
+ sourceId,
+ runJobs,
+ runJobsLoading,
+ expandedRunKeys,
+ setRunExpanded,
+}: {
+ rows: PrWorkflowRow[]
+ filteredRuns: PrRunRow[]
+ failingJobLabelByWorkflow: Record<string, string>
+ runCostByKey: Record<string, { minutes: number | null; cost: number | null }>
+ showCost: boolean
+ loading: boolean
+ repoOwner: string
+ repoName: string
+ sourceId: string | null
+ runJobs: Record<string, WorkflowJobApi[]>
+ runJobsLoading: boolean
+ expandedRunKeys: string[]
+ setRunExpanded: (rowKey: string, expanded: boolean, runId: number | null, runAttempt: number | null) => void
+}): JSX.Element {
+ const latestByWorkflow = latestRunPerWorkflow(filteredRuns)
+ const columns: LemonTableColumns<PrWorkflowRow> = [
{
- // The workflow is already the parent row, so lead with the commit (which push) + attempt.
- title: 'Commit',
- key: 'commit',
- // Tiebreak by start so a commit's re-run attempts stay in order.
- sorter: (a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''),
- render: (_, run) => {
- const attempt = attemptIndexByKey.get(runRowKey(run))
+ title: 'Workflow',
+ key: 'workflow',
+ sorter: (a, b) => a.workflowName.localeCompare(b.workflowName),
+ render: (_, row) => {
+ const latest = latestByWorkflow.get(row.workflowName)
+ const failing = latest?.conclusion != null && !isPassingConclusion(latest.conclusion)
return (
- <div className="flex items-center gap-2">
- {run.headSha ? (
- <Link
- to={githubCommitUrl(repoOwner, repoName, run.headSha)}
- target="_blank"
- className="font-mono text-xs font-medium"
- onClick={(e) => e.stopPropagation()}
- >
- {run.headSha.slice(0, 7)}
- </Link>
- ) : (
- <span className="text-xs text-secondary">—</span>
- )}
- {attempt ? <span className="text-xs text-secondary">· attempt {attempt}</span> : null}
- </div>
+ <span className="flex items-center gap-2 font-medium">
+ <span
+ className={cn(
+ 'inline-block size-2 shrink-0 rounded-full',
+ failing ? 'bg-danger' : latest?.conclusion == null ? 'bg-brand-blue' : 'bg-success'
+ )}
+ />
+ <Link
+ to={
+ combineUrl(
+ urls.engineeringAnalyticsWorkflowRuns(repoOwner, repoName, row.workflowName),
+ sourceId ? { source: sourceId } : {}
+ ).url
+ }
+ >
+ {row.workflowName}
+ </Link>
+ </span>
)
},
},
+ {
+ title: 'Latest conclusion',
+ key: 'latest',
+ width: 130,
+ render: (_, row) => (
+ <RunConclusionTag conclusion={latestByWorkflow.get(row.workflowName)?.conclusion ?? null} />
+ ),
+ },
+ {
+ title: 'What failed',
+ key: 'failedJob',
+ render: (_, row) => {
+ const latest = latestByWorkflow.get(row.workflowName)
+ if (latest?.conclusion == null || isPassingConclusion(latest.conclusion)) {
+ return <span className="text-xs text-tertiary">—</span>
+ }
+ const label = failingJobLabelByWorkflow[row.workflowName]
+ return label ? (
+ <span className="font-mono text-[10.5px] text-secondary">{label}</span>
+ ) : (
+ <span className="text-xs text-tertiary">looking up the failing job…</span>
+ )
+ },
+ },
+ {
+ title: 'Runs',
+ key: 'runCount',
+ align: 'right',
+ sorter: (a, b) => a.runCount - b.runCount,
+ render: (_, row) => <span className="text-xs tabular-nums">{row.runCount}</span>,
+ },
+ {
+ title: 'P50',
+ key: 'p50',
+ align: 'right',
+ sorter: (a, b) => (a.p50Seconds ?? -1) - (b.p50Seconds ?? -1),
+ render: (_, row) => (
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {row.p50Seconds == null ? '—' : humanFriendlyDuration(row.p50Seconds)}
+ </span>
+ ),
+ },
+ ...((showCost
+ ? [
+ {
+ title: 'Cost',
+ key: 'cost',
+ align: 'right',
+ sorter: (a: PrWorkflowRow, b: PrWorkflowRow) =>
+ (a.estimatedCostUsd ?? -1) - (b.estimatedCostUsd ?? -1),
+ render: (_: unknown, row: PrWorkflowRow) => (
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {row.estimatedCostUsd != null ? compactUsd(row.estimatedCostUsd) : '—'}
+ </span>
+ ),
+ },
+ ]
+ : []) as LemonTableColumns<PrWorkflowRow>),
]
+ return (
+ <LemonTable
+ dataSource={rows}
+ columns={columns}
+ size="small"
+ loading={loading}
+ rowKey={(row) => row.workflowName}
+ useURLForSorting={false}
+ expandable={{
+ noIndent: true,
+ rowExpandable: (row) => filteredRuns.some((run) => run.workflow === row.workflowName),
+ expandedRowRender: (row) => (
+ <PerPushRunsTable
+ runs={filteredRuns.filter((run) => run.workflow === row.workflowName)}
+ runCostByKey={runCostByKey}
+ showCost={showCost}
+ repoOwner={repoOwner}
+ repoName={repoName}
+ sourceId={sourceId}
+ runJobs={runJobs}
+ runJobsLoading={runJobsLoading}
+ expandedRunKeys={expandedRunKeys}
+ setRunExpanded={setRunExpanded}
+ />
+ ),
+ }}
+ emptyState="No CI runs match."
+ nouns={['workflow', 'workflows']}
+ />
+ )
}
export function PullRequestDetailScene(): JSX.Element {
@@ -528,24 +591,26 @@ export function PullRequestDetailScene(): JSX.Element {
runs,
commitGroups,
filteredRuns,
- filteredWorkflowHealthRows,
+ filteredPrWorkflowRows,
prRunsLoading,
prRunsFailed,
prCost,
- prCostLoading,
pushes,
rerunCycles,
workflowFilter,
repoOwner,
repoName,
sourceId,
+ runCostByKey,
+ failureLogs,
+ failureLogsLoading,
+ latestPushStats,
+ failingJobLabelByWorkflow,
runJobs,
runJobsLoading,
expandedRunKeys,
- runCostByKey,
} = useValues(pullRequestDetailLogic)
- const { loadLifecycle, loadPrRuns, loadJobs, setRunExpanded, setWorkflowFilter } =
- useActions(pullRequestDetailLogic)
+ const { loadLifecycle, loadPrRuns, setWorkflowFilter, setRunExpanded } = useActions(pullRequestDetailLogic)
const pullRequest = lifecycle?.pull_request
const githubUrl = pullRequest
@@ -562,7 +627,7 @@ export function PullRequestDetailScene(): JSX.Element {
<SceneTitleSection name="Pull request" resourceType={{ type: 'health' }} />
<div className="flex items-center gap-3">
<span className="text-secondary">
- Couldn't load this pull request — it may not exist in the connected GitHub source.
+ Couldn't load this pull request. It may not exist in the connected GitHub source.
</span>
<LemonButton type="secondary" size="small" onClick={loadLifecycle} loading={lifecycleLoading}>
Retry
@@ -592,54 +657,147 @@ export function PullRequestDetailScene(): JSX.Element {
}
/>
+ <ScopeBar
+ repoSlot={
+ <RepoScopeChip
+ label={`${repoOwner}/${repoName}`}
+ to={combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url}
+ />
+ }
+ lensFilter={{
+ label: `pr: #${pullRequest?.number ?? ''}`,
+ to: combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url,
+ }}
+ showDate={false}
+ />
+
{pullRequest ? (
- <MetaRow pullRequest={pullRequest} sourceId={sourceId} />
+ <>
+ <EntityHeader
+ icon={<IconPullRequest />}
+ title={pullRequest.title}
+ slug={
+ <>
+ <PullRequestStateTag state={pullRequest.state} isDraft={pullRequest.is_draft} />
+ <span>
+ {pullRequest.repo.owner}/{pullRequest.repo.name} #{pullRequest.number}
+ </span>
+ <span>·</span>
+ <span className="flex items-center gap-1.5">
+ {pullRequest.author.avatar_url && (
+ <img
+ src={pullRequest.author.avatar_url}
+ alt=""
+ className="size-4 shrink-0 rounded-full"
+ />
+ )}
+ <span>{pullRequest.author.handle}</span>
+ {pullRequest.author.is_bot && <LemonTag type="muted">bot</LemonTag>}
+ </span>
+ <span>
+ · opened <TZLabel time={pullRequest.created_at} />
+ </span>
+ </>
+ }
+ right={
+ pullRequest.state === 'merged' ? (
+ <VerdictPill kind="muted">Merged</VerdictPill>
+ ) : latestPushStats && latestPushStats.failingWorkflows.length > 0 ? (
+ <VerdictPill kind="danger">CI failing</VerdictPill>
+ ) : latestPushStats && latestPushStats.running > 0 ? (
+ <VerdictPill kind="warning">CI running</VerdictPill>
+ ) : latestPushStats ? (
+ <VerdictPill kind="success">CI passing</VerdictPill>
+ ) : undefined
+ }
+ />
+ <div className="flex flex-wrap gap-2.5">
+ <MetricTile
+ label="Latest push"
+ tooltip="Workflows green on the newest commit, one verdict per workflow."
+ value={latestPushStats ? `${latestPushStats.green} / ${latestPushStats.total}` : '—'}
+ valueSuffix={latestPushStats ? 'passing' : undefined}
+ sub={
+ latestPushStats && latestPushStats.failingWorkflows.length > 0
+ ? `${latestPushStats.failingWorkflows.slice(0, 3).join(', ')} failing`
+ : latestPushStats && latestPushStats.running > 0
+ ? `${latestPushStats.running} still running`
+ : undefined
+ }
+ />
+ <MetricTile
+ label="Pushes"
+ tooltip="Commits that triggered CI on this pull request."
+ value={`${pushes}`}
+ delta={
+ rerunCycles > 0 ? (
+ <span className="text-xs font-semibold text-warning-dark">
+ +{rerunCycles} re-runs
+ </span>
+ ) : undefined
+ }
+ />
+ <MetricTile
+ label="CI cost"
+ tooltip={
+ prCost?.jobs_available
+ ? `${compactUsd(
+ (prCost.estimated_cost_usd ?? 0) / Math.max(1, pushes)
+ )} per push${prCost.unsettled_jobs > 0 ? ` · ${pluralize(prCost.unsettled_jobs, 'unsettled job')} excluded` : ''}.`
+ : 'Available once the job-level source is synced.'
+ }
+ value={prCost?.jobs_available ? compactUsd(prCost.estimated_cost_usd) : '—'}
+ sub={prCost?.jobs_available ? undefined : 'Job-level source not synced'}
+ />
+ <MetricTile
+ label={
+ summary?.mergedAt ? 'Open → merge' : summary?.closedAt ? 'Open → close' : 'Open so far'
+ }
+ value={gapBetween(
+ summary?.openedAt ?? pullRequest.created_at,
+ summary?.mergedAt ?? summary?.closedAt ?? dayjs().toISOString()
+ )}
+ />
+ </div>
+ </>
) : (
- <LemonSkeleton className="h-5 w-96" />
+ <LemonSkeleton className="h-24 w-full" />
)}
- <div>
- <PrSummaryCards
- cost={prCost}
- costLoading={prCostLoading}
- pushes={pushes}
- rerunCycles={rerunCycles}
- counts={{ passed, failed, running }}
- runsTotal={runs.length}
- commits={commitGroups.length}
- summary={summary}
- openedAt={summary?.openedAt ?? pullRequest?.created_at ?? ''}
- // Skeleton the whole row until lifecycle + runs are in (covers the frame before
- // afterMount fires). The cost card fills on its own once prCost resolves. loadFailed
- // returns earlier, so !lifecycle can't hang here.
- loading={!lifecycle || (prRunsLoading && runs.length === 0)}
- />
- </div>
+ <SectionNav
+ items={[
+ { id: 'pr-timeline', label: 'Lifecycle' },
+ { id: 'pr-runs', label: 'CI runs' },
+ { id: 'pr-failures', label: 'Failures' },
+ ]}
+ />
- {summary && pullRequest ? (
- <div>
+ <Section id="pr-timeline" title="Lifecycle">
+ {summary && pullRequest ? (
<LifecycleStrip
summary={summary}
openedAt={summary.openedAt ?? pullRequest.created_at}
commitGroups={commitGroups}
/>
- </div>
- ) : (
- <LemonSkeleton className="h-12 w-full" />
- )}
+ ) : (
+ <LemonSkeleton className="h-12 w-full" />
+ )}
+ </Section>
- <div>
- <div className="mb-2 flex items-baseline gap-3">
- <h3 className="mb-0">CI runs</h3>
- {runs.length > 0 && (
+ <Section
+ id="pr-runs"
+ title="CI runs"
+ right={
+ runs.length > 0 ? (
<span className="text-xs text-secondary">
Cumulative · {pluralize(passed, 'run')} passed
{failed > 0 && <> · {failed} failed</>}
{running > 0 && <> · {running} still running</>}
{commitGroups.length > 1 && <> · {pluralize(commitGroups.length, 'commit')}</>}
</span>
- )}
- </div>
+ ) : undefined
+ }
+ >
{commitGroups.length > 0 && (
<LemonInput
type="search"
@@ -660,74 +818,34 @@ export function PullRequestDetailScene(): JSX.Element {
</div>
) : commitGroups.length === 0 ? (
<div className="text-sm text-secondary">No CI runs attributed to this pull request yet.</div>
- ) : filteredWorkflowHealthRows.length === 0 ? (
+ ) : filteredPrWorkflowRows.length === 0 ? (
<div className="text-sm text-secondary">No workflows match “{workflowFilter}”.</div>
) : (
- <WorkflowHealthTable
- rows={filteredWorkflowHealthRows}
+ <PrWorkflowsTable
+ rows={filteredPrWorkflowRows}
+ filteredRuns={filteredRuns}
+ failingJobLabelByWorkflow={failingJobLabelByWorkflow}
+ runCostByKey={runCostByKey}
+ showCost={prCost?.jobs_available ?? false}
loading={prRunsLoading}
+ repoOwner={repoOwner}
+ repoName={repoName}
sourceId={sourceId}
- showCost={prCost?.jobs_available ?? false}
- dataAttr="engineering-analytics-pr-workflow-table"
- emptyState="No CI runs match."
- expandable={{
- noIndent: true,
- rowExpandable: (row) => filteredRuns.some((run) => run.workflow === row.workflowName),
- // Single run on the PR → load its jobs straight away (we skip the runs layer below).
- onRowExpand: (row) => {
- const wfRuns = filteredRuns.filter((run) => run.workflow === row.workflowName)
- const run = wfRuns.length === 1 ? wfRuns[0] : null
- if (run?.runId != null && !(jobCacheKey(run.runId, run.runAttempt) in runJobs)) {
- loadJobs({ runId: run.runId, runAttempt: run.runAttempt })
- }
- },
- expandedRowRender: (row) => {
- const wfRuns = filteredRuns.filter((run) => run.workflow === row.workflowName)
- // One run → no point in a one-row runs table; jump straight to its jobs.
- if (wfRuns.length === 1) {
- const run = wfRuns[0]
- return (
- <RunJobsTable
- jobs={
- run.runId != null
- ? runJobs[jobCacheKey(run.runId, run.runAttempt)]
- : undefined
- }
- loading={runJobsLoading}
- embedded
- aligned
- />
- )
- }
- // Multiple runs (re-runs / multi-push) → list them, each expandable to jobs.
- return (
- <RunsTable
- runs={wfRuns}
- rowKey={runRowKey}
- leadColumns={commitLeadColumns(wfRuns, repoOwner, repoName)}
- loading={prRunsLoading}
- runJobs={runJobs}
- runJobsLoading={runJobsLoading}
- expandedKeys={expandedRunKeys}
- setExpanded={setRunExpanded}
- runCostByKey={runCostByKey}
- showCost={prCost?.jobs_available ?? false}
- aligned
- // Oldest push first so rows read in the same order as the sparkline.
- defaultSorting={{ columnKey: 'started', order: 1 }}
- dataAttr="engineering-analytics-pr-runs-table"
- />
- )
- },
- }}
+ runJobs={runJobs}
+ runJobsLoading={runJobsLoading}
+ expandedRunKeys={expandedRunKeys}
+ setRunExpanded={setRunExpanded}
/>
)}
- </div>
+ </Section>
- <div className="text-xs text-tertiary">
- CI runs attributed to this pull request across all its commits — review and comment activity isn't
- tracked yet.
- </div>
+ {failed > 0 && (
+ <Section id="pr-failures" title="Failures">
+ <FailureLogGroups logs={failureLogs} loading={failureLogsLoading} />
+ </Section>
+ )}
+
+ <div className="text-xs text-tertiary">Review and comment activity isn't tracked yet.</div>
</SceneContent>
)
}
diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
new file mode 100644
index 000000000000..53bb2a650869
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
@@ -0,0 +1,501 @@
+// The repo hub landing page: stat tiles with deltas, then master health, failing runs, PRs needing
+// attention, workflows, and cost as sections on one page.
+
+import { useActions, useValues } from 'kea'
+import { combineUrl, router } from 'kea-router'
+
+import { IconBox } from '@posthog/icons'
+import { LemonCard, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { QueryCard } from 'lib/components/Cards/InsightCard/QueryCard'
+import { TZLabel } from 'lib/components/TZLabel'
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { urls } from 'scenes/urls'
+
+import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
+import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
+import { EntityHeader } from '../components/EntityHeader'
+import { FailureLogGroups } from '../components/FailureLogs'
+import { DeltaBadge, MetricTile, percentChange, pointChange } from '../components/MetricTile'
+import { PullRequestTable } from '../components/PullRequestTable'
+import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
+import { Section, SectionNav, scrollToSection } from '../components/Section'
+import { ShareRow } from '../components/ShareRow'
+import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
+import type { MasterFailureGroupApi } from '../generated/api.schemas'
+import { compactCount, compactHours, compactHoursUnit, compactMinutes, compactUsd, percent } from '../lib/format'
+import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
+import { repoOverviewLogic } from './repoOverviewLogic'
+
+const SHARE_COLORS = [
+ 'var(--data-color-1)',
+ 'var(--data-color-2)',
+ 'var(--data-color-3)',
+ 'var(--data-color-4)',
+ 'var(--data-color-5)',
+]
+
+// The hub shows capped tables; the dedicated list pages keep the full 50-per-page tables.
+const HUB_TABLE_PAGE_SIZE = 8
+
+function withSource(url: string, sourceId: string | null): string {
+ return combineUrl(url, sourceId ? { source: sourceId } : {}).url
+}
+
+function RepoEntityHeader({ repoFullName }: { repoFullName: string }): JSX.Element {
+ const name = repoFullName.split('/')[1] || repoFullName || 'GitHub repository'
+ return (
+ <EntityHeader
+ icon={<IconBox />}
+ title={name}
+ // No slug line when the source hasn't reported a repo name yet.
+ slug={
+ repoFullName ? (
+ <>
+ {repoFullName}
+ {' · '}
+ <Link to={`https://github.com/${repoFullName}`} target="_blank" targetBlankIcon>
+ View on GitHub
+ </Link>
+ </>
+ ) : undefined
+ }
+ />
+ )
+}
+
+/** Default-branch verdict tile: a calm dot when clean, a red "N failing" that jumps to the triage table. */
+function MasterStatusTile({
+ failingCount,
+ loading,
+ defaultBranch,
+}: {
+ failingCount: number
+ loading: boolean
+ defaultBranch: string
+}): JSX.Element {
+ const failing = failingCount > 0
+ const dotColor = loading ? 'var(--muted)' : failing ? 'var(--danger)' : 'var(--success)'
+ const status = loading ? 'Checking…' : failing ? `${failingCount} failing` : 'Passing'
+ return (
+ <LemonCard
+ hoverEffect={failing}
+ onClick={failing ? () => scrollToSection('now') : undefined}
+ className="flex min-w-44 flex-1 flex-col justify-center gap-1 px-5 py-4"
+ >
+ <Tooltip title="Workflows failing on the default branch in the last 24 hours.">
+ <span className="self-start cursor-default text-xs text-secondary">
+ {defaultBranch === 'main' ? 'Main' : 'Master'}
+ </span>
+ </Tooltip>
+ <span className="flex items-center gap-2">
+ <span
+ className="inline-block size-2.5 shrink-0 rounded-full"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ backgroundColor: dotColor }}
+ />
+ <span
+ className={cn(
+ 'text-2xl font-semibold leading-none',
+ loading ? 'text-tertiary' : failing ? 'text-danger' : 'text-primary'
+ )}
+ >
+ {status}
+ </span>
+ </span>
+ </LemonCard>
+ )
+}
+
+function MasterFailuresSection(): JSX.Element {
+ const { masterFailures, masterFailuresLoading, failureLogs, failureLogsLoading, defaultBranch } =
+ useValues(repoOverviewLogic)
+ const { loadLogsForRun } = useActions(repoOverviewLogic)
+ const { sourceId } = useValues(engineeringAnalyticsLogic)
+
+ return (
+ <Section id="now" title={`Failing on ${defaultBranch}`} note="Last 24 hours">
+ <LemonCard hoverEffect={false} className="p-0">
+ <LemonTable<MasterFailureGroupApi>
+ dataSource={masterFailures}
+ loading={masterFailuresLoading}
+ embedded
+ rowKey={(group) => `${group.workflow_name}:${group.failed_job}`}
+ expandable={{
+ noIndent: true,
+ onRowExpand: (group) => loadLogsForRun(group.latest_run_id),
+ expandedRowRender: (group) => {
+ const logs = failureLogs[group.latest_run_id]
+ return (
+ <div className="p-2">
+ <div className="mb-1.5 flex items-center gap-2 text-xs font-semibold">
+ Failure excerpt
+ <span className="font-mono font-normal text-tertiary">
+ latest run #{group.latest_run_id}
+ </span>
+ <span className="ml-auto font-normal">
+ <Link
+ to={withSource(
+ urls.engineeringAnalyticsWorkflowRun(
+ group.repo.owner,
+ group.repo.name,
+ group.latest_run_id
+ ),
+ sourceId
+ )}
+ >
+ Open run →
+ </Link>
+ </span>
+ </div>
+ <FailureLogGroups logs={logs} loading={failureLogsLoading} />
+ </div>
+ )
+ },
+ }}
+ columns={[
+ {
+ title: 'Workflow',
+ key: 'workflow',
+ render: (_, group) => (
+ <span className="flex items-center gap-2 font-medium">
+ <span className="inline-block size-2 shrink-0 rounded-full bg-danger" />
+ <Link
+ to={withSource(
+ urls.engineeringAnalyticsWorkflowRuns(
+ group.repo.owner,
+ group.repo.name,
+ group.workflow_name
+ ),
+ sourceId
+ )}
+ >
+ {group.workflow_name}
+ </Link>
+ </span>
+ ),
+ },
+ {
+ title: 'What failed',
+ key: 'failedJob',
+ render: (_, group) =>
+ group.failed_job ? (
+ <span className="font-mono text-[11px] text-secondary">{group.failed_job}</span>
+ ) : (
+ <span className="text-xs text-tertiary">workflow-level (jobs not synced)</span>
+ ),
+ },
+ {
+ title: 'Runs',
+ key: 'runs',
+ align: 'right',
+ render: (_, group) =>
+ group.run_count > 1 ? (
+ <LemonTag type="danger">×{group.run_count}</LemonTag>
+ ) : (
+ <span className="tabular-nums text-tertiary">1</span>
+ ),
+ },
+ {
+ title: 'First seen',
+ key: 'firstSeen',
+ align: 'right',
+ render: (_, group) => (
+ <span className="text-xs text-tertiary whitespace-nowrap">
+ <TZLabel time={group.first_seen} />
+ </span>
+ ),
+ },
+ {
+ title: 'Last seen',
+ key: 'lastSeen',
+ align: 'right',
+ render: (_, group) => (
+ <span className="text-xs text-tertiary whitespace-nowrap">
+ <TZLabel time={group.last_seen} />
+ </span>
+ ),
+ },
+ ]}
+ emptyState={`Nothing failing on ${defaultBranch} in the last 24 hours.`}
+ nouns={['failure group', 'failure groups']}
+ />
+ <div className="border-t border-primary px-4 py-2 text-[11px] text-tertiary">
+ PR-branch failures appear on each pull request's page.
+ </div>
+ </LemonCard>
+ </Section>
+ )
+}
+
+export function RepoOverviewScene(): JSX.Element {
+ const {
+ overview,
+ masterSuccessRateQuery,
+ masterFailedRunsQuery,
+ attentionPrs,
+ draftCount,
+ costByWorkflow,
+ otherCostWorkflowCount,
+ jobsAvailable,
+ defaultBranch,
+ notConnected,
+ overviewFailed,
+ failingWorkflowCount,
+ masterFailuresLoading,
+ } = useValues(repoOverviewLogic)
+ const {
+ cards,
+ pullRequestsLoading,
+ workflowHealth,
+ workflowHealthLoading,
+ sourceId,
+ costLensEnabled,
+ activeSource,
+ } = useValues(engineeringAnalyticsLogic)
+ const { loadOverview, loadMasterFailures } = useActions(repoOverviewLogic)
+ const { searchParams } = useValues(router)
+
+ if (notConnected) {
+ return <ConnectGitHubSource />
+ }
+ if (overviewFailed) {
+ return (
+ <CIAnalyticsLoadError
+ onRetry={() => {
+ loadOverview()
+ loadMasterFailures()
+ }}
+ />
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ {/* The entity header below is the repo identity — the scope bar only adds the source
+ picker (multi-source teams) so the repo name isn't stated twice on one screen. */}
+ <ScopeBar repoSlot={<SourceScopeChip pickerOnly />} />
+
+ <RepoEntityHeader repoFullName={activeSource?.repo || ''} />
+
+ <div className="flex flex-wrap gap-2.5">
+ <MasterStatusTile
+ failingCount={failingWorkflowCount}
+ loading={masterFailuresLoading}
+ defaultBranch={defaultBranch}
+ />
+ <MetricTile
+ label="Pass rate"
+ tooltip="Workflow-level, across all branches."
+ value={percent(overview?.success_rate)}
+ delta={
+ <DeltaBadge
+ value={pointChange(overview?.success_rate, overview?.success_rate_prev)}
+ unit="pp"
+ />
+ }
+ />
+ <MetricTile
+ label="Runs"
+ value={compactCount(overview?.run_count)}
+ delta={<DeltaBadge value={percentChange(overview?.run_count, overview?.run_count_prev)} />}
+ />
+ <MetricTile
+ label="CI cost"
+ tooltip={
+ jobsAvailable
+ ? `Estimated: ${compactMinutes(overview?.billable_minutes)} billable × runner-tier rate.`
+ : 'Available once the job-level source is synced.'
+ }
+ value={jobsAvailable ? compactUsd(overview?.estimated_cost_usd) : '—'}
+ delta={
+ jobsAvailable ? (
+ <DeltaBadge
+ value={percentChange(overview?.estimated_cost_usd, overview?.estimated_cost_usd_prev)}
+ goodWhenDown
+ />
+ ) : undefined
+ }
+ sub={jobsAvailable ? undefined : 'Job-level source not synced'}
+ />
+ <MetricTile
+ label="Median PR open→merge"
+ tooltip="Created to merged, over PRs merged in the window. Bots and drafts excluded."
+ value={compactHours(overview?.median_open_to_merge_seconds)}
+ valueSuffix={compactHoursUnit(overview?.median_open_to_merge_seconds)}
+ delta={
+ <DeltaBadge
+ value={
+ overview?.median_open_to_merge_seconds != null &&
+ overview?.median_open_to_merge_seconds_prev != null
+ ? (overview.median_open_to_merge_seconds -
+ overview.median_open_to_merge_seconds_prev) /
+ 3600
+ : null
+ }
+ unit="h"
+ goodWhenDown
+ />
+ }
+ />
+ <MetricTile
+ label="Re-run cycles"
+ tooltip="Runs with attempt > 1 in the window."
+ value={compactCount(overview?.rerun_cycles)}
+ delta={
+ <DeltaBadge
+ value={percentChange(overview?.rerun_cycles, overview?.rerun_cycles_prev)}
+ goodWhenDown
+ />
+ }
+ />
+ </div>
+
+ <SectionNav
+ items={[
+ { id: 'master', label: `${defaultBranch === 'main' ? 'Main' : 'Master'} health` },
+ { id: 'now', label: `Failing on ${defaultBranch}` },
+ { id: 'prs', label: 'Pull requests' },
+ { id: 'workflows', label: 'Workflows' },
+ { id: 'cost', label: 'Cost' },
+ ]}
+ />
+
+ <Section id="master" title={`${defaultBranch === 'main' ? 'Main' : 'Master'} health`}>
+ {masterSuccessRateQuery && masterFailedRunsQuery ? (
+ <div className="grid gap-2.5 lg:grid-cols-2">
+ <QueryCard
+ title={`Success rate on ${defaultBranch}`}
+ query={masterSuccessRateQuery}
+ uniqueKey="engineering-analytics-master-success-rate"
+ />
+ <QueryCard
+ title={`Failed runs on ${defaultBranch}`}
+ description={`Completed runs on ${defaultBranch} whose conclusion wasn't success.`}
+ query={masterFailedRunsQuery}
+ uniqueKey="engineering-analytics-master-failed-runs"
+ />
+ </div>
+ ) : (
+ <LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">
+ Loading…
+ </LemonCard>
+ )}
+ </Section>
+
+ <MasterFailuresSection />
+
+ <Section id="prs" title="Pull requests needing attention">
+ <div className="mb-2 flex flex-wrap gap-2 text-xs text-secondary">
+ <span>
+ <strong className="text-primary">{cards ? humanFriendlyNumber(cards.openPrs) : '…'}</strong>{' '}
+ open
+ </span>
+ <span>·</span>
+ <span>
+ <strong className="text-primary">{humanFriendlyNumber(draftCount)}</strong> drafts
+ </span>
+ <span>·</span>
+ <span>
+ <strong className="text-danger">{cards ? humanFriendlyNumber(cards.failingCi) : '…'}</strong>{' '}
+ failing CI
+ </span>
+ <span>·</span>
+ <span>
+ <strong className="text-warning-dark">{cards ? humanFriendlyNumber(cards.stuck) : '…'}</strong>{' '}
+ stuck &gt;7d
+ </span>
+ </div>
+ <LemonCard hoverEffect={false} className="p-0">
+ <PullRequestTable
+ rows={attentionPrs}
+ loading={pullRequestsLoading}
+ sourceId={sourceId}
+ costLensEnabled={costLensEnabled}
+ pageSize={HUB_TABLE_PAGE_SIZE}
+ emptyState="Nothing failing or stuck in the open backlog."
+ dataAttr="engineering-analytics-attention-prs"
+ />
+ <div className="border-t border-primary px-4 py-2 text-[11px] text-tertiary">
+ Showing {attentionPrs.length} of {cards ? humanFriendlyNumber(cards.openPrs) : '…'} open pull
+ requests ·{' '}
+ <Link to={withSource(urls.engineeringAnalyticsPullRequestList(), sourceId)}>View all</Link>
+ </div>
+ </LemonCard>
+ </Section>
+
+ <Section id="workflows" title="Workflows">
+ <LemonCard hoverEffect={false} className="p-0">
+ <WorkflowHealthTable
+ rows={workflowHealth}
+ loading={workflowHealthLoading}
+ sourceId={sourceId}
+ showCost={jobsAvailable}
+ defaultSorting={{ columnKey: 'runCount', order: -1 }}
+ pageSize={HUB_TABLE_PAGE_SIZE}
+ emptyState="No workflow runs in the window."
+ />
+ <div className="border-t border-primary px-4 py-2 text-[11px] text-tertiary">
+ Showing top {Math.min(HUB_TABLE_PAGE_SIZE, workflowHealth.length)} of {workflowHealth.length}{' '}
+ workflows ·{' '}
+ <Link
+ to={
+ // A bare link would reset the shared window/branch scope (the filters logic
+ // re-hydrates from the URL on every route) — carry it, plus the source.
+ combineUrl(urls.engineeringAnalyticsWorkflows(), {
+ ...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),
+ ...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
+ ...(searchParams.q ? { q: searchParams.q } : {}),
+ ...(sourceId ? { source: sourceId } : {}),
+ }).url
+ }
+ >
+ View all
+ </Link>
+ </div>
+ </LemonCard>
+ </Section>
+
+ <Section id="cost" title="Cost">
+ {jobsAvailable && costByWorkflow.length > 0 ? (
+ <LemonCard hoverEffect={false} className="p-4">
+ <h3 className="mb-1 text-xs font-semibold text-secondary">By workflow</h3>
+ {costByWorkflow.map((row, i) => (
+ <ShareRow
+ key={row.workflowName ?? 'other'}
+ label={row.workflowName ?? `Other (${otherCostWorkflowCount} workflows)`}
+ value={compactUsd(row.costUsd)}
+ valueSub={`${Math.round(row.share * 100)}% of total`}
+ share={row.share}
+ color={row.workflowName ? SHARE_COLORS[i % SHARE_COLORS.length] : 'var(--muted)'}
+ to={
+ row.workflowName && workflowHealth.length
+ ? withSource(
+ urls.engineeringAnalyticsWorkflowRuns(
+ workflowHealth[0].repoOwner,
+ workflowHealth[0].repoName,
+ row.workflowName
+ ),
+ sourceId
+ )
+ : undefined
+ }
+ />
+ ))}
+ <div className="mt-2 border-t border-primary pt-2 text-[11px] text-tertiary">
+ Estimated from billable job minutes × runner-tier rate. GitHub-hosted runners are free for
+ open source.
+ </div>
+ </LemonCard>
+ ) : (
+ <LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">
+ {jobsAvailable
+ ? 'No costable jobs in the window.'
+ : 'Cost data will appear once the job-level source (github_workflow_jobs) is synced.'}
+ </LemonCard>
+ )}
+ </Section>
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
index de6ab50f05f6..bfde0ccb2b88 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
@@ -1,11 +1,11 @@
import { useActions, useValues } from 'kea'
import { combineUrl } from 'kea-router'
-import { IconExternal } from '@posthog/icons'
-import { LemonButton, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'
+import { IconCheckCircle, IconExternal, IconHourglass, IconPause, IconXCircle } from '@posthog/icons'
+import { LemonButton, LemonSkeleton, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
-import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { dayjs } from 'lib/dayjs'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { pluralize } from 'lib/utils/strings'
import { SceneExport } from 'scenes/sceneTypes'
@@ -14,9 +14,14 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { RunJobsTable, formatCost, formatMinutes } from '../components/runTables'
-import { StatTile } from '../components/StatTile'
+import { EntityHeader, VerdictPill } from '../components/EntityHeader'
+import { FailureLogGroups } from '../components/FailureLogs'
+import { GroupedJobsTable } from '../components/GroupedJobsTable'
+import { MetricTile } from '../components/MetricTile'
+import { formatCost, formatMinutes } from '../components/runTables'
+import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
import { githubCommitUrl, githubRunUrl } from '../lib/github'
+import { isDecisiveFailure } from '../lib/lifecycle'
import { verdictTag } from '../lib/runStatus'
import { WorkflowRunDetailLogicProps, workflowRunDetailLogic } from './workflowRunDetailLogic'
@@ -31,18 +36,19 @@ export const scene: SceneExport<WorkflowRunDetailLogicProps> = {
}),
}
-function DetailRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {
- return (
- <div className="flex items-baseline gap-4 px-4 py-2.5">
- <span className="w-32 shrink-0 text-xs text-secondary">{label}</span>
- <span className="min-w-0 text-sm">{children}</span>
- </div>
- )
-}
-
export function WorkflowRunDetailScene(): JSX.Element {
- const { run, runLoading, loadFailed, sourceId, jobs, jobsLoading, runCost, isValidRunId } =
- useValues(workflowRunDetailLogic)
+ const {
+ run,
+ runLoading,
+ loadFailed,
+ sourceId,
+ jobs,
+ jobsLoading,
+ runCost,
+ isValidRunId,
+ failureLogs,
+ failureLogsLoading,
+ } = useValues(workflowRunDetailLogic)
const { loadRun } = useActions(workflowRunDetailLogic)
if (!isValidRunId) {
@@ -63,6 +69,28 @@ export function WorkflowRunDetailScene(): JSX.Element {
sourceId ? { source: sourceId } : {}
).url
: null
+ // Run started → first job started: the runner-capacity wait before anything executed.
+ const jobStarts = (jobs ?? []).map((job) => job.started_at).filter((at): at is string => !!at)
+ const queueSeconds =
+ run?.run_started_at && jobStarts.length
+ ? Math.max(
+ 0,
+ dayjs(jobStarts.reduce((min, at) => (at < min ? at : min))).diff(dayjs(run.run_started_at), 'second')
+ )
+ : null
+ const jobRollupLabel = jobs?.length
+ ? [
+ `${jobs.filter((job) => job.conclusion === 'success').length} passed`,
+ ...(jobs.some((job) => isDecisiveFailure(job.conclusion))
+ ? [`${jobs.filter((job) => isDecisiveFailure(job.conclusion)).length} failed`]
+ : []),
+ ...(jobs.some((job) => job.conclusion === 'skipped')
+ ? [`${jobs.filter((job) => job.conclusion === 'skipped').length} skipped`]
+ : []),
+ ].join(' · ')
+ : null
+ // The logs endpoint only carries job ids; the run's loaded jobs supply the names.
+ const jobNamesById = Object.fromEntries((jobs ?? []).map((job) => [job.id, job.name]))
if (loadFailed) {
return (
@@ -70,7 +98,7 @@ export function WorkflowRunDetailScene(): JSX.Element {
<SceneTitleSection name="Workflow run" resourceType={{ type: 'health' }} />
<div className="flex items-center gap-3">
<span className="text-secondary">
- Couldn't load this workflow run — it may not exist in the connected GitHub source.
+ Couldn't load this workflow run. It may not exist in the connected GitHub source.
</span>
<LemonButton type="secondary" size="small" onClick={loadRun} loading={runLoading}>
Retry
@@ -102,91 +130,128 @@ export function WorkflowRunDetailScene(): JSX.Element {
{run ? (
<>
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
- {verdict && <LemonTag type={verdict.type}>{verdict.label}</LemonTag>}
- {run.run_attempt > 1 && <LemonTag type="muted">attempt {run.run_attempt}</LemonTag>}
- <span className="font-mono text-xs text-secondary">
- {run.repo.owner}/{run.repo.name} · run #{run.id}
- </span>
- </div>
-
- {runCost && (
- <div className="flex flex-col gap-2">
- <div className="flex flex-wrap items-center gap-2">
- <LemonTag type="warning">estimate · wall-clock × reference rate</LemonTag>
- {runCost.unsettledJobs > 0 && (
- <LemonTag type="muted">
- {pluralize(runCost.unsettledJobs, 'unsettled job')} excluded
- </LemonTag>
- )}
- </div>
- <StatTile
- label="Billable CI minutes"
- value={formatMinutes(runCost.billableMinutes)}
- sub={<>≈ {formatCost(runCost.estimatedCostUsd)} estimated</>}
- className="max-w-72"
+ <ScopeBar
+ repoSlot={
+ <RepoScopeChip
+ label={`${run.repo.owner}/${run.repo.name}`}
+ to={combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url}
/>
- </div>
- )}
-
- <LemonCard hoverEffect={false} className="divide-y p-0">
- <DetailRow label="Status">
- <span className="capitalize">{run.status || '—'}</span>
- </DetailRow>
- <DetailRow label="Duration">
- <span className="tabular-nums">
- {run.duration_seconds == null ? '—' : humanFriendlyDuration(run.duration_seconds)}
- </span>
- </DetailRow>
- <DetailRow label="Started">
- {run.run_started_at ? (
- <TZLabel time={run.run_started_at} />
- ) : (
- <span className="text-secondary">—</span>
- )}
- </DetailRow>
- <DetailRow label="Updated">
- {run.updated_at ? (
- <TZLabel time={run.updated_at} />
+ }
+ crumbs={[
+ {
+ label: run.workflow_name,
+ to: combineUrl(
+ urls.engineeringAnalyticsWorkflowRuns(
+ run.repo.owner,
+ run.repo.name,
+ run.workflow_name
+ ),
+ sourceId ? { source: sourceId } : {}
+ ).url,
+ },
+ { label: `run #${run.id}` },
+ ]}
+ showDate={false}
+ />
+ <EntityHeader
+ icon={
+ run.conclusion == null ? (
+ <IconHourglass className="text-muted" />
+ ) : isDecisiveFailure(run.conclusion) ? (
+ <IconXCircle className="text-danger" />
+ ) : run.conclusion === 'success' ? (
+ <IconCheckCircle className="text-success" />
) : (
- <span className="text-secondary">—</span>
- )}
- </DetailRow>
- <DetailRow label="Branch">
- {run.head_branch ? (
- <span className="font-mono text-xs">{run.head_branch}</span>
- ) : (
- <span className="text-secondary">—</span>
- )}
- </DetailRow>
- <DetailRow label="Commit">
- {run.head_sha ? (
- <Link
- to={githubCommitUrl(run.repo.owner, run.repo.name, run.head_sha)}
- target="_blank"
- className="font-mono text-xs"
+ <IconPause className="text-muted" />
+ )
+ }
+ title={run.workflow_name}
+ titleSuffix={`#${run.id}`}
+ slug={
+ <>
+ {run.head_branch && <span>{run.head_branch}</span>}
+ {run.head_sha && (
+ <>
+ <span>· commit</span>
+ <Link
+ to={githubCommitUrl(run.repo.owner, run.repo.name, run.head_sha)}
+ target="_blank"
+ >
+ {run.head_sha.slice(0, 7)}
+ </Link>
+ </>
+ )}
+ {prUrl && (
+ <>
+ <span>· pull request</span>
+ <Link to={prUrl}>#{run.pr_number}</Link>
+ </>
+ )}
+ {run.run_attempt > 1 && <span>· attempt {run.run_attempt}</span>}
+ {run.run_started_at && (
+ <span>
+ · started <TZLabel time={run.run_started_at} />
+ </span>
+ )}
+ </>
+ }
+ right={
+ verdict ? (
+ <VerdictPill
+ kind={
+ run.conclusion == null
+ ? 'warning'
+ : isDecisiveFailure(run.conclusion)
+ ? 'danger'
+ : run.conclusion === 'success'
+ ? 'success'
+ : 'muted'
+ }
>
- {run.head_sha.slice(0, 7)}
- </Link>
- ) : (
- <span className="text-secondary">—</span>
- )}
- </DetailRow>
- <DetailRow label="Pull request">
- {prUrl ? (
- <Link to={prUrl} className="font-medium">
- #{run.pr_number}
- </Link>
- ) : (
- <span className="text-secondary">—</span>
- )}
- </DetailRow>
- </LemonCard>
+ {verdict.label}
+ </VerdictPill>
+ ) : undefined
+ }
+ />
+
+ <div className="flex flex-wrap gap-2.5">
+ <MetricTile
+ label="Duration"
+ tooltip="Wall-clock time of the run."
+ value={run.duration_seconds == null ? '—' : humanFriendlyDuration(run.duration_seconds)}
+ />
+ <MetricTile
+ label="Queue time"
+ tooltip="From run started to the first job starting."
+ value={queueSeconds != null ? humanFriendlyDuration(queueSeconds) : '—'}
+ />
+ <MetricTile label="Jobs" tooltip={jobRollupLabel} value={jobs ? `${jobs.length}` : '—'} />
+ <MetricTile
+ label="Estimated cost"
+ tooltip={
+ runCost
+ ? `${formatMinutes(runCost.billableMinutes)} billable × runner-tier rate${
+ runCost.unsettledJobs > 0
+ ? ` · ${pluralize(runCost.unsettledJobs, 'unsettled job')} excluded`
+ : ''
+ }.`
+ : 'Available once the job-level source is synced.'
+ }
+ value={runCost ? formatCost(runCost.estimatedCostUsd) : '—'}
+ />
+ </div>
<div className="flex flex-col gap-2">
<h3 className="mb-0">Jobs</h3>
- <RunJobsTable jobs={jobs} loading={jobsLoading} />
+ <GroupedJobsTable jobs={jobs} loading={jobsLoading} />
</div>
+
+ {isDecisiveFailure(run.conclusion) && (
+ <div className="flex flex-col gap-2">
+ <h3 className="mb-0">Failure logs</h3>
+ <FailureLogGroups logs={failureLogs} loading={failureLogsLoading} jobNames={jobNamesById} />
+ </div>
+ )}
</>
) : (
<LemonSkeleton className="h-64 w-full" />
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
index bb9ce21848fa..5d9890e39aeb 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
@@ -1,95 +1,74 @@
import { useActions, useValues } from 'kea'
import { combineUrl } from 'kea-router'
-import { IconExternal } from '@posthog/icons'
+import { IconExternal, IconGear } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
-import { getSeriesColor } from 'lib/colors'
-import { DateFilter } from 'lib/components/DateFilter/DateFilter'
-import { dateMapping } from 'lib/utils/dateFilters'
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { BillableBadge } from '../components/BillableBadge'
-import { BranchFilter } from '../components/BranchFilter'
-import { DistributionBar } from '../components/DistributionBar'
+import { EntityHeader, VerdictPill } from '../components/EntityHeader'
+import { GroupedJobsTable } from '../components/GroupedJobsTable'
+import { JobAggregatesTable } from '../components/JobAggregatesTable'
+import { MetricTile } from '../components/MetricTile'
import { RunActivityChart } from '../components/RunActivityChart'
-import { RunnerBadge, RunsTable, formatCost } from '../components/runTables'
-import { WorkflowHealthHeader } from '../components/WorkflowHealthHeader'
+import { RunConclusionTag } from '../components/runTables'
+import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
+import { Section, SectionNav } from '../components/Section'
+import { ShareRow } from '../components/ShareRow'
import type { WorkflowRunnerCostApi } from '../generated/api.schemas'
-import { githubWorkflowUrl } from '../lib/github'
-import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
+import { compactCount, compactMinutes, compactUsd, percent } from '../lib/format'
+import { githubCommitUrl, githubWorkflowUrl } from '../lib/github'
+import { jobCacheKey } from '../lib/jobs'
+import { isDecisiveFailure } from '../lib/lifecycle'
import { WorkflowRunRow, WorkflowRunsLogicProps, workflowRunsLogic } from './workflowRunsLogic'
-/** Where a workflow's CI spend goes, split by runner tier — a small table (not bespoke chips) so it reads
- * like every other table in the product. */
-function RunnerCostTable({ costs }: { costs: WorkflowRunnerCostApi[] }): JSX.Element {
- const columns: LemonTableColumns<WorkflowRunnerCostApi> = [
- {
- title: 'Runner',
- key: 'runner',
- render: (_, cost) => <RunnerBadge provider={cost.provider} label={cost.runner_label} />,
- },
- {
- title: 'Jobs',
- key: 'jobs',
- width: 90,
- align: 'right',
- render: (_, cost) => <span className="text-xs tabular-nums">{cost.job_count}</span>,
- },
- {
- title: 'Cost',
- key: 'cost',
- width: 140,
- align: 'right',
- render: (_, cost) => <BillableBadge minutes={cost.billable_minutes} costUsd={cost.estimated_cost_usd} />,
- },
- ]
- // One stacked bar over the table, a segment per tier sized by its $ share. Free (GitHub-hosted)
- // runners are $0, so they don't take a slice; the bar reads as "billable spend".
- const costSegments = costs.map((cost, i) => ({
- key: `${cost.provider}:${cost.runner_label}`,
- label: cost.runner_label || cost.provider,
- value: cost.estimated_cost_usd ?? 0,
- color: getSeriesColor(i),
- caption: formatCost(cost.estimated_cost_usd ?? null),
- }))
+/** Spend by runner tier: tier, job count, cost (or 'free'), share bar scaled to billable spend. */
+function RunnerTierCard({ costs }: { costs: WorkflowRunnerCostApi[] }): JSX.Element {
+ const totalCost = costs.reduce((sum, cost) => sum + (cost.estimated_cost_usd ?? 0), 0)
return (
- <div className="flex flex-col gap-2">
- <div className="flex flex-wrap items-baseline gap-2">
- <h3 className="mb-0">Cost by runner</h3>
+ <LemonCard hoverEffect={false} className="p-4">
+ <div className="mb-1 flex items-baseline gap-2">
+ <h3 className="mb-0 text-xs font-semibold text-secondary">By runner tier</h3>
<LemonTag type="warning">estimate · wall-clock × reference rate</LemonTag>
</div>
- <DistributionBar segments={costSegments} />
- <LemonTable
- data-attr="engineering-analytics-workflow-runner-costs"
- size="small"
- columns={columns}
- dataSource={costs}
- rowKey={(cost) => `${cost.provider}:${cost.runner_label}`}
- nouns={['runner tier', 'runner tiers']}
- />
- </div>
+ {costs.map((cost) => (
+ <ShareRow
+ key={`${cost.provider}:${cost.runner_label}`}
+ label={
+ <span className="font-mono text-xs">
+ {cost.runner_label || cost.provider}
+ {cost.provider === 'github_hosted' ? ' (GitHub-hosted)' : ''}
+ </span>
+ }
+ sub={`${humanFriendlyNumber(cost.job_count)} jobs`}
+ value={cost.estimated_cost_usd != null ? compactUsd(cost.estimated_cost_usd) : 'free'}
+ valueSub={
+ cost.estimated_cost_usd != null
+ ? `${compactMinutes(cost.billable_minutes)} billable`
+ : undefined
+ }
+ share={totalCost > 0 ? (cost.estimated_cost_usd ?? 0) / totalCost : 0}
+ color={cost.estimated_cost_usd != null ? 'var(--brand-blue)' : 'var(--muted)'}
+ />
+ ))}
+ <div className="mt-2 border-t border-primary pt-2 text-[11px] text-tertiary">
+ Tier parsed from job labels; rate ladder in the cost model. GitHub-hosted runners are free for open
+ source.
+ </div>
+ </LemonCard>
)
}
-// The endpoint requires a date_from (floors finished runs), so "all time" is out — relative windows +
-// Custom only, from a 24h "right now" view through a monthly-ish spend window.
-const WORKFLOW_DATE_OPTIONS = dateMapping.filter(({ key }) =>
- [
- 'Custom',
- 'Last 24 hours',
- 'Last 7 days',
- 'Last 14 days',
- 'Last 30 days',
- 'Last 90 days',
- 'Last 180 days',
- ].includes(key)
-)
-
export const scene: SceneExport<WorkflowRunsLogicProps> = {
component: WorkflowRunsScene,
logic: workflowRunsLogic,
@@ -119,16 +98,36 @@ export function WorkflowRunsScene(): JSX.Element {
runsTruncated,
activityRuns,
activityTruncated,
+ jobAggregates,
+ jobAggregatesLoading,
+ masterConclusion,
+ queueP50Seconds,
} = useValues(workflowRunsLogic)
const { loadRuns, setRunExpanded } = useActions(workflowRunsLogic)
- const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
- const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
const githubUrl = githubWorkflowUrl(repoOwner, repoName, workflowName)
+ // Master's own verdict when the window has master runs; the overall fleet state otherwise.
+ const verdictPill =
+ masterConclusion != null ? (
+ isDecisiveFailure(masterConclusion) ? (
+ <VerdictPill kind="danger">Failing on master</VerdictPill>
+ ) : masterConclusion === 'success' ? (
+ <VerdictPill kind="success">Passing on master</VerdictPill>
+ ) : (
+ <VerdictPill kind="muted">
+ {capitalizeFirstLetter(masterConclusion.replace('_', ' '))} on master
+ </VerdictPill>
+ )
+ ) : healthSummary.state === 'failing' ? (
+ <VerdictPill kind="danger">Failing</VerdictPill>
+ ) : healthSummary.state === 'degraded' ? (
+ <VerdictPill kind="warning">Degraded</VerdictPill>
+ ) : healthSummary.state === 'healthy' ? (
+ <VerdictPill kind="success">Passing</VerdictPill>
+ ) : undefined
- // Run id (→ the single-run page) + attempt, branch, attributed PR. The shared RunsTable appends
- // verdict / duration / started and the expand-to-jobs behavior.
- const leadColumns: LemonTableColumns<WorkflowRunRow> = [
+ // Lead columns for the runs table; rows expand (caret or row click) to the run's matrix-grouped jobs.
+ const runColumns: LemonTableColumns<WorkflowRunRow> = [
{
title: 'Run',
key: 'run',
@@ -140,22 +139,53 @@ export function WorkflowRunsScene(): JSX.Element {
sourceId ? { source: sourceId } : {}
).url
}
- className="font-medium tabular-nums"
+ className="font-mono text-xs font-medium tabular-nums"
onClick={(e) => e.stopPropagation()}
>
#{run.id}
- {(run.runAttempt ?? 1) > 1 && (
- <span className="ml-1 text-xs text-secondary">· attempt {run.runAttempt}</span>
- )}
</Link>
),
},
+ {
+ title: 'Conclusion',
+ key: 'conclusion',
+ width: 110,
+ render: (_, run) => <RunConclusionTag conclusion={run.conclusion} />,
+ },
{
title: 'Branch',
key: 'branch',
render: (_, run) =>
run.headBranch ? (
- <span className="font-mono text-xs">{run.headBranch}</span>
+ <span className="flex items-center gap-1.5 font-mono text-xs">
+ {(run.headBranch === 'master' || run.headBranch === 'main') && (
+ <span
+ className={cn(
+ 'inline-block size-1.5 shrink-0 rounded-full',
+ isDecisiveFailure(run.conclusion) ? 'bg-danger' : 'bg-success'
+ )}
+ />
+ )}
+ {run.headBranch}
+ </span>
+ ) : (
+ <span className="text-xs text-secondary">—</span>
+ ),
+ },
+ {
+ title: 'Commit',
+ key: 'commit',
+ width: 90,
+ render: (_, run) =>
+ run.headSha ? (
+ <Link
+ to={githubCommitUrl(run.repoOwner, run.repoName, run.headSha)}
+ target="_blank"
+ className="font-mono text-xs text-tertiary"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {run.headSha.slice(0, 7)}
+ </Link>
) : (
<span className="text-xs text-secondary">—</span>
),
@@ -181,6 +211,45 @@ export function WorkflowRunsScene(): JSX.Element {
<span className="text-xs text-secondary">—</span>
),
},
+ {
+ title: 'Attempt',
+ key: 'attempt',
+ width: 80,
+ align: 'right',
+ render: (_, run) =>
+ (run.runAttempt ?? 1) > 1 ? (
+ <LemonTag type="warning">{run.runAttempt}</LemonTag>
+ ) : (
+ <span className="text-xs tabular-nums text-tertiary">{run.runAttempt ?? 1}</span>
+ ),
+ },
+ {
+ title: 'Duration',
+ key: 'duration',
+ width: 90,
+ align: 'right',
+ sorter: (a, b) => (a.durationSeconds ?? -1) - (b.durationSeconds ?? -1),
+ render: (_, run) => (
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {run.durationSeconds == null ? '—' : humanFriendlyDuration(run.durationSeconds)}
+ </span>
+ ),
+ },
+ {
+ title: 'Started',
+ key: 'started',
+ width: 130,
+ align: 'right',
+ sorter: (a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''),
+ render: (_, run) =>
+ run.startedAt ? (
+ <span className="text-xs whitespace-nowrap text-tertiary">
+ <TZLabel time={run.startedAt} />
+ </span>
+ ) : (
+ <span className="text-xs text-secondary">—</span>
+ ),
+ },
]
if (loadFailed) {
@@ -189,7 +258,7 @@ export function WorkflowRunsScene(): JSX.Element {
<SceneTitleSection name="Workflow" resourceType={{ type: 'health' }} />
<div className="flex items-center gap-3">
<span className="text-secondary">
- Couldn't load this workflow's runs — it may not exist in the connected GitHub source.
+ Couldn't load this workflow's runs. It may not exist in the connected GitHub source.
</span>
<LemonButton type="secondary" size="small" onClick={loadRuns} loading={runsLoading}>
Retry
@@ -210,40 +279,147 @@ export function WorkflowRunsScene(): JSX.Element {
</LemonButton>
}
/>
- {/* One window + branch scope the cost breakdown and the runs list below — the same scope as the
- Workflows tab, so numbers match after drilling in (a missing branch filter here read as more
- runs than the tab showed). */}
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-xs font-semibold tracking-wide text-secondary uppercase">Window</span>
- <DateFilter
- dateFrom={dateFrom}
- dateTo={dateTo}
- onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
- dateOptions={WORKFLOW_DATE_OPTIONS}
- size="small"
+ {/* Same window + branch scope as the repo hub, so numbers match after drilling in. */}
+ <ScopeBar
+ repoSlot={
+ <RepoScopeChip
+ label={`${repoOwner}/${repoName}`}
+ to={combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url}
+ />
+ }
+ crumbs={[{ label: workflowName }]}
+ showBranch
+ />
+ <EntityHeader
+ icon={<IconGear />}
+ title={workflowName}
+ slug={
+ <>
+ {repoOwner}/{repoName}
+ {runsTruncated && <span> · run stats cover the most recent {runRows.length} runs</span>}
+ </>
+ }
+ right={verdictPill}
+ />
+ <div className="flex flex-wrap gap-2.5">
+ <MetricTile
+ label="Pass rate"
+ tooltip={`${humanFriendlyNumber(healthSummary.passedRuns)} of ${humanFriendlyNumber(
+ healthSummary.completedRuns
+ )} completed runs passed.`}
+ value={percent(healthSummary.passRate)}
/>
- <BranchFilter />
- </div>
- <WorkflowHealthHeader summary={healthSummary} cost={costSummary} truncated={runsTruncated} />
- <RunActivityChart runs={activityRuns} truncated={activityTruncated} />
- {runnerCosts.length > 0 && <RunnerCostTable costs={runnerCosts} />}
- <div className="flex flex-col gap-2">
- <h3 className="mb-0">Runs</h3>
- <RunsTable
- runs={runRows}
- rowKey={(run) => `${run.id}-${run.runAttempt}`}
- leadColumns={leadColumns}
- loading={runsLoading}
- runJobs={runJobs}
- runJobsLoading={runJobsLoading}
- expandedKeys={expandedRunKeys}
- setExpanded={setRunExpanded}
- // Newest run first on the workflow page.
- defaultSorting={{ columnKey: 'started', order: -1 }}
- dataAttr="engineering-analytics-workflow-runs-table"
- emptyState="No runs for this workflow in the connected source."
+ <MetricTile
+ label="Runs"
+ tooltip={
+ healthSummary.reruns > 0
+ ? `Includes ${humanFriendlyNumber(healthSummary.reruns)} re-run cycles.`
+ : undefined
+ }
+ value={compactCount(healthSummary.totalRuns)}
+ />
+ <MetricTile
+ label="Duration p50"
+ tooltip="Wall-clock, over completed runs."
+ value={
+ healthSummary.medianSeconds != null ? humanFriendlyDuration(healthSummary.medianSeconds) : '—'
+ }
+ valueSuffix={
+ healthSummary.p95Seconds != null
+ ? `→ ${humanFriendlyDuration(healthSummary.p95Seconds)} p95`
+ : undefined
+ }
+ />
+ <MetricTile
+ label="Queue time p50"
+ tooltip="From job created to started, weighted across the workflow's jobs."
+ value={queueP50Seconds != null ? humanFriendlyDuration(queueP50Seconds) : '—'}
+ />
+ <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'}
/>
</div>
+ <SectionNav
+ items={[
+ { id: 'health', label: 'Health' },
+ { id: 'jobs', label: 'Jobs' },
+ { id: 'cost', label: 'Cost' },
+ { id: 'runs', label: 'Runs' },
+ ]}
+ />
+ <Section id="health" title="Health">
+ <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">
+ {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="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 }}
+ 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>
</SceneContent>
)
}
diff --git a/products/engineering_analytics/frontend/scenes/authorLogic.ts b/products/engineering_analytics/frontend/scenes/authorLogic.ts
deleted file mode 100644
index ac60dab94592..000000000000
--- a/products/engineering_analytics/frontend/scenes/authorLogic.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { afterMount, connect, kea, key, path, props, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { ApiConfig } from 'lib/api'
-import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs } from 'lib/utils/dateFilters'
-import { urls } from 'scenes/urls'
-
-import { Breadcrumb } from '~/types'
-
-import { engineeringAnalyticsPullRequests } from '../generated/api'
-import type { authorLogicType } from './authorLogicType'
-import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
-import { PullRequestRow, toPullRequestRow } from './engineeringAnalyticsLogic'
-
-const projectId = (): string => String(ApiConfig.getCurrentProjectId())
-
-// The PR list isn't date-scoped (the picker only scopes the cost tiles), but the load needs a floor for
-// finished PRs — wide so the list reads as "this author's recent PRs", and wider than any tile window so
-// the tiles stay a subset. Open PRs come back regardless.
-const LIST_WINDOW = '-365d'
-
-export interface AuthorLogicProps {
- handle: string
- // Which GitHub source the list was scoped to, threaded from `?source=` via paramsToProps.
- sourceId: string | null
-}
-
-export const authorLogic = kea<authorLogicType>([
- path(['products', 'engineering_analytics', 'frontend', 'scenes', 'authorLogic']),
- props({} as AuthorLogicProps),
- key((props) => `author/${props.handle}@${props.sourceId ?? ''}`),
-
- // Shares the CI-analytics window, but only to scope the cost tiles (a client-side filter over the
- // already-loaded PRs) — the PR list below is never re-scoped, so changing the window never reloads here.
- connect(() => ({
- values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo']],
- })),
-
- loaders(({ props }) => ({
- prs: [
- [] as PullRequestRow[],
- {
- // Loaded once: the author's recent PRs, mapped to the shared table row shape. Stable across
- // date changes — the picker only scopes the tiles.
- loadPrs: async (): Promise<PullRequestRow[]> => {
- const result = await engineeringAnalyticsPullRequests(projectId(), {
- author: props.handle,
- date_from: LIST_WINDOW,
- source_id: props.sourceId ?? undefined,
- })
- return result.items.map(toPullRequestRow)
- },
- },
- ],
- })),
-
- selectors({
- sourceId: [() => [(_, p: AuthorLogicProps) => p.sourceId], (sourceId): string | null => sourceId],
- handle: [() => [(_, p: AuthorLogicProps) => p.handle], (handle): string => handle],
- // The tile scope: PRs opened within the selected window. The list shows every loaded PR; only the
- // cost KPIs narrow to this subset, so the date picker reads as "cost of PRs opened in the window".
- windowedRows: [
- (s) => [s.prs, s.dateFrom, s.dateTo],
- (prs: PullRequestRow[], dateFrom: string | null, dateTo: string | null): PullRequestRow[] => {
- const from = dateFrom ? dateStringToDayJs(dateFrom) : null
- const to = dateTo ? dateStringToDayJs(dateTo) : null
- return prs.filter((pr) => {
- const created = dayjs(pr.createdAt)
- return (!from || created.isAfter(from)) && (!to || created.isBefore(to))
- })
- },
- ],
- // Author totals across the in-window PRs — null when nothing was costable / the job source is unsynced.
- totalCostUsd: [
- (s) => [s.windowedRows],
- (rows: PullRequestRow[]): number | null => {
- const costs = rows.map((pr) => pr.estimatedCostUsd).filter((c): c is number => c != null)
- return costs.length ? costs.reduce((sum, c) => sum + c, 0) : null
- },
- ],
- totalBillableMinutes: [
- (s) => [s.windowedRows],
- (rows: PullRequestRow[]): number | null => {
- const minutes = rows.map((pr) => pr.billableMinutes).filter((m): m is number => m != null)
- return minutes.length ? minutes.reduce((sum, m) => sum + m, 0) : null
- },
- ],
- breadcrumbs: [
- (_, p) => [p.handle],
- (handle): Breadcrumb[] => [
- {
- key: 'EngineeringAnalytics',
- name: 'Engineering analytics',
- path: urls.engineeringAnalytics(),
- iconType: 'health',
- },
- { key: ['EngineeringAnalyticsAuthor', handle], name: handle, iconType: 'health' },
- ],
- ],
- }),
-
- afterMount(({ actions }) => {
- actions.loadPrs()
- }),
-])
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
index 875734dfb459..f45b0448d10d 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
@@ -3,18 +3,12 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import type { engineeringAnalyticsFiltersLogicType } from './engineeringAnalyticsFiltersLogicType'
-// One window shared by every CI-analytics surface that's scoped by time — the Workflows tab, a single
-// workflow's runs/cost page, and an author's cost tiles — so a window picked on one carries to the others
-// instead of each page snapping back to its own default. 7 days balances the two needs the pages used to
-// split on (-24h health vs -30d spend): long enough to read a week of spend, short enough that health still
-// reads as recent. Nothing live is lost — the "is CI red now" verdict is window-independent and bucket
-// granularity auto-follows the window, so narrowing to 24h still gives the live hourly view on demand.
+// One window shared by every time-scoped CI-analytics surface, so a window picked on one page carries
+// 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 branch scope is shared here too, alongside the window, so filtering to `master` on the Workflows tab
-// carries into a workflow's detail page instead of the detail silently widening back to all branches (which
-// read as "more runs" than the tab showed). It's a server-side filter (head_branch), so typing only stages
-// the value in branchInput; applyBranchFilter promotes it to appliedBranch, which the consuming logics send.
+// The branch scope is shared the same way. It's a server-side filter (head_branch): typing stages
+// branchInput; applyBranchFilter promotes it to appliedBranch, which the consuming logics send.
export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsFiltersLogic']),
@@ -36,9 +30,7 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
listeners(({ actions, values }) => ({
setBranchFilter: ({ branch }) => {
- // The search input's built-in clear (×) only fires onChange(''), never Enter/blur, so clearing it
- // would otherwise leave the tables scoped to the old branch. Apply on empty so the × resets to
- // all-branches immediately.
+ // The input's clear (×) only fires onChange('') — apply on empty so it resets to all branches.
if (branch.trim() === '') {
actions.applyBranchFilter()
}
@@ -54,9 +46,7 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
})),
actionToUrl(({ values }) => ({
- // Encode the window in the URL so tab links and drill-down links (which preserve query params) carry
- // it, and a shared link reopens it. Replace, not push — nudging a date shouldn't stack back-history.
- // The default is omitted so a pristine URL stays clean.
+ // Replace, not push — nudging a date shouldn't stack back-history. Defaults are omitted.
setDateRange: () => {
const { pathname, searchParams, hashParams } = router.values.currentLocation
const next = { ...searchParams }
@@ -72,8 +62,7 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
}
return [pathname, next, hashParams, { replace: true }]
},
- // Mirror the applied branch into `?q=` so a branch-scoped view is shareable, survives reload, and
- // carries through drill-down links into the workflow detail page. Empty is omitted to keep URLs clean.
+ // Mirror the applied branch into `?q=` so a branch-scoped view is shareable and survives reload.
setAppliedBranch: () => {
const { pathname, searchParams, hashParams } = router.values.currentLocation
const next = { ...searchParams }
@@ -87,10 +76,8 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
})),
urlToAction(({ actions, values }) => ({
- // Hydrate from the URL on any CI-analytics route — a shared link, a reload, or a drill-down link that
- // carried the params. Guarded so we only dispatch on a real change, which also breaks the actionToUrl
- // loop. '*' is safe here: the logic is only mounted while a CI-analytics scene connects it, so this
- // never fires for unrelated routes. Handler params are inferred (kea-router types them).
+ // Hydrate from the URL, dispatching only on real change (also breaks the actionToUrl loop).
+ // '*' is safe: the logic is only mounted while a CI-analytics scene connects it.
'*': (_, searchParams) => {
const dateFrom = searchParams.date_from ?? SHARED_DEFAULT_DATE_FROM
const dateTo = searchParams.date_to ?? null
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index 6e89f5614ef1..bc17bd6bd74b 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -1,7 +1,9 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { ApiConfig, ApiError } from 'lib/api'
import { dayjs } from 'lib/dayjs'
+import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
@@ -28,16 +30,18 @@ import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersL
import {
DEFAULT_FILTERS,
DEFAULT_QUARANTINE_FILTERS,
+ DEFAULT_WORKFLOW_FILTERS,
PullRequestRow,
QuarantineEntryRow,
+ WorkflowHealthRow,
engineeringAnalyticsLogic,
filterPullRequests,
+ filterWorkflowHealth,
workflowFailureSeries,
filterQuarantineEntries,
inferOwnerFromSelector,
quarantineCountsOf,
quarantineRequestErrorMessage,
- workflowFailureTrend,
} from './engineeringAnalyticsLogic'
import { engineeringAnalyticsSceneLogic } from './engineeringAnalyticsSceneLogic'
import { groupRunsByCommit, sortRunsForTriage } from './pullRequestDetailLogic'
@@ -141,6 +145,7 @@ function makePr(overrides: Partial<PullRequestRow> = {}): PullRequestRow {
passing: 0,
failing: 0,
pending: 0,
+ failingWorkflows: [],
pushes: 0,
rerunCycles: 0,
estimatedCostUsd: null,
@@ -199,6 +204,24 @@ const WORKFLOWS: WorkflowHealthItemApi[] = [
latest_run_conclusion: 'success',
},
]
+function makeWorkflow(overrides: Partial<WorkflowHealthRow> = {}): WorkflowHealthRow {
+ return {
+ repoOwner: 'posthog',
+ repoName: 'posthog',
+ workflowName: 'CI',
+ runCount: 10,
+ successRate: 1,
+ p50Seconds: 60,
+ p95Seconds: 120,
+ lastFailureAt: null,
+ latestRunFailed: false,
+ latestRunConclusion: 'success',
+ granularity: 'day',
+ buckets: [],
+ ...overrides,
+ }
+}
+
const SOURCES: GitHubSourceApi[] = [
{ id: 'src-older', repo: 'posthog/posthog', prefix: 'older' },
{ id: 'src-newer', repo: 'posthog/posthog.com', prefix: 'website' },
@@ -445,6 +468,62 @@ describe('engineeringAnalyticsLogic', () => {
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d', source_id: 'src-newer' })
})
+ it.each([
+ // 'failing'/'passing' key off the latest settled run; a row with nothing completed
+ // (latestRunFailed null) must show only under 'all' — it is neither green nor red.
+ ['failing keeps only rows whose latest run failed', { status: 'failing' as const }, ['E2E']],
+ ['passing keeps only settled green rows', { status: 'passing' as const }, ['CI']],
+ ['unsettled rows show only under all', {}, ['CI', 'E2E', 'Nightly']],
+ ['search is case-insensitive over the name', { search: 'NIGHT' }, ['Nightly']],
+ ])('filterWorkflowHealth: %s', (_label, overrides, expected) => {
+ const rows = [
+ makeWorkflow({ workflowName: 'CI', latestRunFailed: false }),
+ makeWorkflow({ workflowName: 'E2E', latestRunFailed: true }),
+ makeWorkflow({ workflowName: 'Nightly', latestRunFailed: null, latestRunConclusion: null }),
+ ]
+ expect(
+ filterWorkflowHealth(rows, { ...DEFAULT_WORKFLOW_FILTERS, ...overrides }).map((row) => row.workflowName)
+ ).toEqual(expected)
+ })
+
+ it('resetWorkflowFilters returns the workflow filters to defaults and clears hasActiveWorkflowFilters', () => {
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+ expect(logic.values.hasActiveWorkflowFilters).toBe(false)
+
+ logic.actions.setWorkflowSearch('e2e')
+ logic.actions.setWorkflowStatusFilter('failing')
+ expect(logic.values.hasActiveWorkflowFilters).toBe(true)
+
+ logic.actions.resetWorkflowFilters()
+ expect(logic.values.workflowFilters).toEqual(DEFAULT_WORKFLOW_FILTERS)
+ expect(logic.values.hasActiveWorkflowFilters).toBe(false)
+ })
+
+ it('workflowCostAvailable flips on once any row carries cost data', async () => {
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
+ expect(logic.values.workflowCostAvailable).toBe(false)
+
+ mockWorkflowHealth.mockResolvedValue([{ ...WORKFLOWS[0], billable_minutes: 12, estimated_cost_usd: 0.5 }])
+ logic.actions.loadWorkflowHealth()
+ await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
+ expect(logic.values.workflowCostAvailable).toBe(true)
+ })
+
+ it.each([
+ ['workflows', () => urls.engineeringAnalyticsWorkflows()],
+ ['test health', () => urls.engineeringAnalyticsTestHealth()],
+ ])('the %s route applies ?source like the other tabs', async (_label, url) => {
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+
+ router.actions.push(url(), { source: 'src-newer' })
+ await expectLogic(logic).toDispatchActions(['setSourceId'])
+ expect(logic.values.sourceId).toBe('src-newer')
+ })
+
it('resetFilters returns every filter to defaults and clears hasActiveFilters', async () => {
logic = engineeringAnalyticsLogic()
logic.mount()
@@ -492,22 +571,6 @@ describe('engineeringAnalyticsLogic', () => {
expect(series).toEqual({ completed: [completed], failures: [failures], labels: [label] })
})
- it.each([
- ['rising failures trend up', [0, 0, 2, 3], 'up'],
- ['falling failures trend down', [4, 3, 1, 0], 'down'],
- ['steady failures stay flat', [1, 1, 1, 1], 'flat'],
- ['a single bucket is flat', [5], 'flat'],
- ])('workflowFailureTrend: %s', (_label, failuresPerBucket, expected) => {
- const buckets = failuresPerBucket.map((failures, i) => ({
- bucketStart: `2026-06-0${i + 1}`,
- runCount: 10,
- completed: 10,
- successes: 10 - failures,
- failures,
- }))
- expect(workflowFailureTrend(buckets)).toBe(expected)
- })
-
it('summarizeLifecycle rolls events up into milestones and verdicts', () => {
const summary = summarizeLifecycle([
{ kind: 'opened', at: '2026-06-01T00:00:00Z' },
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index 8a6b213b7a6e..f0ee2732bffd 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -28,20 +28,18 @@ import { type FleetSummary, computeFleetSummary } from '../lib/runHealth'
import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import type { engineeringAnalyticsLogicType } from './engineeringAnalyticsLogicType'
-// Mirrors the endpoint's server-side limit; surfaced in copy when hit so a truncated list reads as truncated.
+// Mirrors the endpoint's server-side limit.
export const PR_TABLE_LIMIT = 1000
-// Top workflows by run count (`workflow_health.py` `_LIMIT`); when hit, the header labels totals "top N".
+// Mirrors `workflow_health.py` `_LIMIT` (top workflows by run count).
export const WORKFLOW_HEALTH_LIMIT = 100
-// Project-scoped endpoints; the generated client takes the id as a string.
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
export type PRState = 'open' | 'closed' | 'merged'
-/** 'draft' is a lens over open PRs; the other values mirror PRState. */
+/** 'draft' narrows open PRs; the other values mirror PRState. */
export type PRStateFilter = PRState | 'draft' | 'all'
export type CIStatusFilter = CIStatus | 'all'
-/** The stat cards double as quick views over the open backlog. */
export type CardFilter = 'open' | 'failing' | 'stuck'
/** Mirrors the ci_cards "stuck" rule: open, non-draft, non-bot, older than 7 days. */
@@ -66,11 +64,13 @@ export interface PullRequestRow {
passing: number
failing: number
pending: number
- /** CI triggers in the PR's window: distinct head SHAs across its workflow runs. Fork PRs unattributed. */
+ /** Workflow names behind `failing`, sorted. */
+ failingWorkflows: string[]
+ /** Distinct head SHAs across the PR's workflow runs. Fork PRs unattributed. */
pushes: number
/** Workflow runs attributed to this PR that were a 2nd+ attempt. */
rerunCycles: number
- /** Estimated CI cost (USD) over the PR's jobs (billable runners). Null when no cost / source unsynced. */
+ /** Estimated CI cost (USD) over the PR's billable jobs. Null when the job source isn't synced. */
estimatedCostUsd: number | null
/** Billable (self-hosted) minutes over the PR's jobs. Null when the job source isn't synced. */
billableMinutes: number | null
@@ -83,9 +83,8 @@ export interface CardsData {
failingCi: number
}
-/** Bucket width of a workflow's history series. 'hour'/'day'/'week' come from the server (time-bucketed
- * workflow health); 'push' is computed client-side for the PR view, where each bucket is one push. */
-export type WorkflowGranularity = 'hour' | 'day' | 'week' | 'push'
+/** Bucket width of a workflow's history series, picked by the server from the window length. */
+export type WorkflowGranularity = 'hour' | 'day' | 'week'
export interface WorkflowHealthBucket {
/** Bucket start (ISO), aligned to the granularity (top of hour / midnight / Monday). */
@@ -95,9 +94,6 @@ export interface WorkflowHealthBucket {
successes: number
/** Decisive failures only (failure / timed_out); excludes skipped, cancelled, action_required. */
failures: number
- /** Pre-formatted sparkline label; used verbatim when set — push buckets aren't time-aligned, so they
- * carry their own "Push N (sha)" label. */
- label?: string
}
export interface WorkflowHealthRow {
@@ -122,16 +118,15 @@ export interface WorkflowHealthRow {
billableMinutes?: number | null
/** Estimated $ cost for this workflow within the scope; null when nothing was costable. */
estimatedCostUsd?: number | null
+ /** Runs in the window that were a 2nd+ attempt. */
+ rerunCycles?: number
+ /** Success rate over the previous equal-length window. */
+ successRatePrev?: number | null
}
-export type WorkflowTrendDirection = 'up' | 'down' | 'flat'
-
export interface WorkflowFailureSeries {
- /** Completed runs per bucket — drives total (stacked) bar height, i.e. volume. */
completed: number[]
- /** Decisive failures per bucket — the red portion of each stacked bar. */
failures: number[]
- /** Per-bucket tooltip label. */
labels: string[]
}
@@ -146,11 +141,7 @@ function formatBucket(bucketStart: string, granularity: WorkflowGranularity): st
return at.format('MMM D')
}
-/**
- * Run-status sparkline series. Each bar is stacked: total height is completed runs (volume), the red
- * portion is decisive failures, so the red fraction reads as the failure rate. Skipped, cancelled, and
- * action_required runs are not failures.
- */
+/** Stacked sparkline series: bar height = completed runs, red portion = decisive failures. */
export function workflowFailureSeries(
buckets: WorkflowHealthBucket[],
granularity: WorkflowGranularity
@@ -158,37 +149,40 @@ export function workflowFailureSeries(
const completed = buckets.map((b) => b.completed)
const failures = buckets.map((b) => b.failures)
const labels = buckets.map((b) => {
- // Push buckets carry their own label (not time-aligned); time buckets format from bucketStart.
- const when = b.label ?? formatBucket(b.bucketStart, granularity)
+ const when = formatBucket(b.bucketStart, granularity)
return b.completed > 0 ? `${when} · ${b.failures} of ${b.completed} failed` : `${when} · no completed runs`
})
return { completed, failures, labels }
}
-/** Failure direction: are failures rising in the recent half of the window vs the prior half? */
-export function workflowFailureTrend(buckets: WorkflowHealthBucket[]): WorkflowTrendDirection {
- if (buckets.length < 2) {
- return 'flat'
- }
- const mid = Math.floor(buckets.length / 2)
- const sumFailures = (slice: WorkflowHealthBucket[]): number => slice.reduce((total, b) => total + b.failures, 0)
- const prior = sumFailures(buckets.slice(0, mid))
- const recent = sumFailures(buckets.slice(mid))
- if (recent > prior) {
- return 'up'
- }
- if (recent < prior) {
- return 'down'
- }
- return 'flat'
+/** 'failing'/'passing' key off the latest settled run; rows with nothing completed show only under 'all'. */
+export type WorkflowStatusFilter = 'all' | 'failing' | 'passing'
+
+export interface WorkflowFilters {
+ search: string
+ status: WorkflowStatusFilter
+}
+
+export const DEFAULT_WORKFLOW_FILTERS: WorkflowFilters = { search: '', status: 'all' }
+
+export function filterWorkflowHealth(rows: WorkflowHealthRow[], filters: WorkflowFilters): WorkflowHealthRow[] {
+ const search = filters.search.trim().toLowerCase()
+ return rows.filter((row) => {
+ if (filters.status === 'failing' && row.latestRunFailed !== true) {
+ return false
+ }
+ if (filters.status === 'passing' && row.latestRunFailed !== false) {
+ return false
+ }
+ return !search || row.workflowName.toLowerCase().includes(search)
+ })
}
export function prKeyOf(row: Pick<PullRequestRow, 'repoOwner' | 'repoName' | 'number'>): string {
return `${row.repoOwner}/${row.repoName}#${row.number}`
}
-/** Map an API PR list item to the table row — shared by the PR list and author page. ?? fallbacks degrade
- * gracefully when a new frontend hits an older backend predating the cost/push fields. */
+/** ?? fallbacks: a new frontend can briefly hit an older backend predating the cost/push fields. */
export function toPullRequestRow(it: PullRequestListItemApi): PullRequestRow {
return {
number: it.number,
@@ -208,6 +202,7 @@ export function toPullRequestRow(it: PullRequestListItemApi): PullRequestRow {
passing: it.ci.passing,
failing: it.ci.failing,
pending: it.ci.pending,
+ failingWorkflows: it.ci.failing_workflows ?? [],
pushes: it.pushes ?? 0,
rerunCycles: it.rerun_cycles ?? 0,
estimatedCostUsd: it.estimated_cost_usd ?? null,
@@ -253,8 +248,7 @@ export function filterPullRequests(
now: dayjs.Dayjs = dayjs()
): PullRequestRow[] {
const search = filters.search.trim().toLowerCase()
- // Hoisted out of the per-row check: this selector re-runs on every search keystroke
- // over up to 1000 rows, so the row loop should not allocate dayjs instances.
+ // Hoisted: re-runs per keystroke over up to 1000 rows — no dayjs allocation in the row loop.
const stuckCutoffMs = filters.stuckOnly ? now.subtract(STUCK_AFTER_DAYS, 'day').valueOf() : 0
return rows.filter((row) => {
if (!matchesStateFilter(row, filters.state)) {
@@ -290,7 +284,6 @@ export type QuarantineSelectorKind = 'product' | 'directory' | 'file' | 'test'
/** 'past_expiry' groups in_grace + overdue — the states the quarantine check warns or fails on. */
export type QuarantineLifecycleFilter = 'all' | 'active' | 'expiring_soon' | 'past_expiry'
export type QuarantineModeFilter = QuarantineMode | 'all'
-/** The stat cards double as quick filters over the entries, like the PR tab. */
export type QuarantineCard = 'active' | 'expiring_soon' | 'past_expiry' | 'skipped'
export interface QuarantineEntryRow {
@@ -430,11 +423,7 @@ export interface QuarantineModalState {
mode: QuarantineMode
}
-/**
- * Suggest an owning team from a product-scoped selector — a confirm-then-edit starting
- * point, since CODEOWNERS here is intentionally sparse. Returns '' when the selector is
- * not product-scoped, so the user just types the owner.
- */
+/** Suggest an owning team from a product-scoped selector; '' when the selector isn't product-scoped. */
export function inferOwnerFromSelector(selector: string): string {
const trimmed = selector.trim()
const product = trimmed.startsWith('product:')
@@ -448,8 +437,7 @@ function toRequestBody(input: QuarantineSubmitInput, repo: string | null): Quara
// Wire field is 'operation' (a bare 'action' enum collides in the OpenAPI spec).
operation: input.action,
selector: input.selector,
- // Write to the repo currently being viewed so the PR lands where the user expects —
- // and the backend skips the most-active-repo warehouse lookup. Null in local dev.
+ // The repo being viewed, so the PR lands there. Null in local dev.
repo,
reason: input.reason,
owner: input.owner,
@@ -465,10 +453,8 @@ export function quarantineRequestErrorMessage(error: unknown): string {
}
/**
- * Per-loader outcome. All endpoints resolve the same GitHub source, so a 400
- * (GitHubSourceNotConnectedError) means "connect a source" for every scene; any other failure is a
- * genuine error scoped to the loader that hit it, so a 500 on one endpoint doesn't error a scene that
- * doesn't read it.
+ * Per-loader outcome. A 400 means "no GitHub source" for every scene; any other failure stays scoped
+ * to the loader that hit it, so a 500 on one endpoint doesn't error a scene that doesn't read it.
*/
export type LoaderStatus = 'ok' | 'notConnected' | 'error'
@@ -480,8 +466,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
kea<engineeringAnalyticsLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsLogic']),
- // The Workflows tab reads the shared CI-analytics window and branch scope; the loader and reload
- // listeners use them.
connect(() => ({
values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'appliedBranch']],
})),
@@ -492,6 +476,9 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
setRepo: (repo: string | null) => ({ repo }),
setCiStatusFilter: (ciStatus: CIStatusFilter) => ({ ciStatus }),
setSearch: (search: string) => ({ search }),
+ setWorkflowSearch: (search: string) => ({ search }),
+ setWorkflowStatusFilter: (status: WorkflowStatusFilter) => ({ status }),
+ resetWorkflowFilters: true,
setStuckOnly: (stuckOnly: boolean) => ({ stuckOnly }),
applyCardFilter: (card: CardFilter) => ({ card }),
setSourceId: (sourceId: string | null) => ({ sourceId }),
@@ -556,22 +543,21 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
p50Seconds: it.p50_seconds,
p95Seconds: it.p95_seconds,
lastFailureAt: it.last_failure_at,
- // ?? fallbacks: a new frontend can briefly hit an older backend predating
- // these fields — degrade, don't crash.
+ // ?? fallbacks: a new frontend can briefly hit an older backend predating these fields.
latestRunFailed: it.latest_run_failed ?? null,
latestRunConclusion: it.latest_run_conclusion ?? null,
- // ?? 'day': older backends predate adaptive bucketing.
granularity: (it.granularity ?? 'day') as WorkflowGranularity,
buckets: (it.buckets ?? []).map((b) => ({
bucketStart: b.bucket_start,
runCount: b.run_count,
completed: b.completed,
successes: b.successes,
- // ?? 0: don't compute NaN bars when the field is absent.
failures: b.failures ?? 0,
})),
billableMinutes: it.billable_minutes ?? null,
estimatedCostUsd: it.estimated_cost_usd ?? null,
+ rerunCycles: it.rerun_cycles ?? 0,
+ successRatePrev: it.success_rate_prev ?? null,
})
)
},
@@ -651,7 +637,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
DEFAULT_FILTERS.search,
{ setSearch: (_, { search }) => search, resetFilters: () => DEFAULT_FILTERS.search },
],
- // Leaving the open backlog (e.g. switching to Merged) exits the stuck lens — stuck implies open.
+ // Changing the state filter exits stuck-only — stuck implies open.
stuckOnly: [
DEFAULT_FILTERS.stuckOnly,
{
@@ -660,11 +646,22 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
resetFilters: () => DEFAULT_FILTERS.stuckOnly,
},
],
- // Which GitHub source to read; null = backend default (oldest connected). URL-synced via
- // `?source=` so it survives tab switches and deep-links into a PR's detail.
+ workflowSearch: [
+ DEFAULT_WORKFLOW_FILTERS.search,
+ {
+ setWorkflowSearch: (_, { search }) => search,
+ resetWorkflowFilters: () => DEFAULT_WORKFLOW_FILTERS.search,
+ },
+ ],
+ workflowStatusFilter: [
+ DEFAULT_WORKFLOW_FILTERS.status,
+ {
+ setWorkflowStatusFilter: (_, { status }) => status,
+ resetWorkflowFilters: () => DEFAULT_WORKFLOW_FILTERS.status,
+ },
+ ],
+ // Which GitHub source to read; null = backend default (oldest connected). Synced to `?source=`.
sourceId: [null as string | null, { setSourceId: (_, { sourceId }) => sourceId }],
- // Per-loader status, tracked separately (not off cards alone) so notConnected and the per-scene
- // error states each react only to the loaders that feed them — see the selectors below.
cardsStatus: [
'ok' as LoaderStatus,
{
@@ -701,8 +698,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
resetQuarantineFilters: () => DEFAULT_QUARANTINE_FILTERS.owner,
},
],
- // The quarantine endpoint only 400s when there's no GitHub source AND no local checkout
- // (prod without a source); a failed load is that signal.
+ // The quarantine endpoint only 400s when there's no GitHub source and no local checkout.
quarantineLoadFailed: [
false,
{
@@ -711,13 +707,11 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
loadQuarantineFailure: () => true,
},
],
- // Drives the quarantine/extend modal; remove uses a confirm dialog instead.
quarantineModal: [
null as QuarantineModalState | null,
{
openQuarantineModal: (_, { state }) => state,
closeQuarantineModal: () => null,
- // A successful write closes the modal; a failure keeps it open so the user can retry.
submitQuarantineSuccess: () => null,
},
],
@@ -737,21 +731,41 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
loadWorkflowHealthFailure: (_, { errorObject }) => loaderStatusFromError(errorObject),
},
],
- // Cost & performance lens: surfaces per-PR pushes / re-runs / estimated cost. Transient (not persisted).
costLensEnabled: [true, { setCostLensEnabled: (_, { enabled }) => enabled }],
}),
selectors({
- // Fleet verdict + rollups across every workflow row, for the all-workflows health strip.
fleetSummary: [
(s) => [s.workflowHealth],
(workflowHealth): FleetSummary => computeFleetSummary(workflowHealth),
],
- // Endpoint caps at top workflows by run count; when hit, the header labels totals "top N", not fleet-wide.
fleetTruncated: [
(s) => [s.workflowHealth],
(workflowHealth): boolean => workflowHealth.length >= WORKFLOW_HEALTH_LIMIT,
],
+ workflowFilters: [
+ (s) => [s.workflowSearch, s.workflowStatusFilter],
+ (search, status): WorkflowFilters => ({ search, status }),
+ ],
+ filteredWorkflowHealth: [
+ (s) => [s.workflowHealth, s.workflowFilters],
+ (workflowHealth, workflowFilters): WorkflowHealthRow[] =>
+ filterWorkflowHealth(workflowHealth, workflowFilters),
+ ],
+ hasActiveWorkflowFilters: [
+ (s) => [s.workflowFilters],
+ (workflowFilters): boolean =>
+ !objectsEqual(
+ { ...workflowFilters, search: workflowFilters.search.trim() },
+ DEFAULT_WORKFLOW_FILTERS
+ ),
+ ],
+ // Until the job-level source syncs every cost field is null — scenes hide the column instead.
+ workflowCostAvailable: [
+ (s) => [s.workflowHealth],
+ (workflowHealth): boolean =>
+ workflowHealth.some((row) => row.billableMinutes != null || row.estimatedCostUsd != null),
+ ],
filters: [
(s) => [s.stateFilter, s.author, s.repo, s.ciStatusFilter, s.search, s.stuckOnly],
(stateFilter, author, repo, ciStatus, search, stuckOnly): PullRequestFilters => ({
@@ -801,23 +815,16 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
(cardsLoading, pullRequestsLoading, workflowHealthLoading, quarantineLoading): boolean =>
cardsLoading || pullRequestsLoading || workflowHealthLoading || quarantineLoading,
],
- // No GitHub source: a 400 from any endpoint (shared source resolution). Drives the "connect a
- // source" state on every scene, regardless of which loaders it renders.
notConnected: [
(s) => [s.cardsStatus, s.pullRequestsStatus, s.workflowHealthStatus],
(cardsStatus, pullRequestsStatus, workflowHealthStatus): boolean =>
[cardsStatus, pullRequestsStatus, workflowHealthStatus].includes('notConnected'),
],
- // Non-400 failure of a loader the PR scene renders (cards + PR list) → retryable error. A
- // workflow-health-only failure doesn't, so the PR list isn't hidden behind an error it
- // doesn't depend on.
+ // Each scene's error state reacts only to the loaders it renders (see LoaderStatus).
pullRequestsLoadError: [
(s) => [s.cardsStatus, s.pullRequestsStatus],
(cardsStatus, pullRequestsStatus): boolean => cardsStatus === 'error' || pullRequestsStatus === 'error',
],
- // Non-400 failure of the only loader the Workflows scene renders. Decoupled from cards so its
- // own failure shows an error (not a misleading empty table), and a cards-only failure doesn't
- // error a scene whose data loaded fine.
workflowHealthLoadError: [
(s) => [s.workflowHealthStatus],
(workflowHealthStatus): boolean => workflowHealthStatus === 'error',
@@ -861,8 +868,13 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
(filters): boolean =>
!objectsEqual({ ...filters, search: filters.search.trim() }, DEFAULT_QUARANTINE_FILTERS),
],
- // Only worth a picker when the team has more than one GitHub source connected.
hasMultipleSources: [(s) => [s.githubSources], (githubSources): boolean => githubSources.length > 1],
+ // The source reads resolve to: the picked one, else the backend default (oldest connected = first).
+ activeSource: [
+ (s) => [s.githubSources, s.sourceId],
+ (githubSources, sourceId): GitHubSourceApi | null =>
+ (sourceId ? githubSources.find((source) => source.id === sourceId) : githubSources[0]) ?? null,
+ ],
sourceOptions: [
(s) => [s.githubSources],
(githubSources): { value: string; label: string }[] =>
@@ -880,9 +892,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
actions.loadWorkflowHealth()
actions.loadQuarantine()
},
- // Cards, PR list, workflow health, and quarantine are all per-source — reload them all.
setSourceId: () => actions.refresh(),
- // The shared window and branch scope workflow health; reload it when either changes.
[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadWorkflowHealth()
},
@@ -920,7 +930,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
: 'Opened a PR. It takes effect once it merges.',
{ button: { label: 'View PR', action: () => window.open(quarantineSubmit.pr_url, '_blank') } }
)
- // Reflect the pending change once it lands; the file is still the source of truth.
actions.loadQuarantine()
},
submitQuarantineFailure: ({ error }) => {
@@ -941,8 +950,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
})),
urlToAction(({ actions, values }) => {
- // The chosen source rides in `?source=` so it survives tab switches and deep-links into a PR's detail.
- // (The shared branch scope in `?q=` is hydrated by engineeringAnalyticsFiltersLogic, not here.)
+ // `?q=` (branch scope) is hydrated by engineeringAnalyticsFiltersLogic, not here.
const applySource = (source: string | undefined): void => {
const next = source ?? null
if (next !== values.sourceId) {
@@ -951,7 +959,9 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
}
return {
[urls.engineeringAnalytics()]: (_, searchParams) => applySource(searchParams.source),
+ [urls.engineeringAnalyticsPullRequestList()]: (_, searchParams) => applySource(searchParams.source),
[urls.engineeringAnalyticsWorkflows()]: (_, searchParams) => applySource(searchParams.source),
+ [urls.engineeringAnalyticsTestHealth()]: (_, searchParams) => applySource(searchParams.source),
}
}),
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
index df352a34ed36..b9791a22e2b0 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
@@ -4,16 +4,19 @@ import { sceneLogic } from '~/scenes/sceneLogic'
import type { engineeringAnalyticsSceneLogicType } from './engineeringAnalyticsSceneLogicType'
-export type EngineeringAnalyticsTab = 'pull-requests' | 'workflows' | 'test-health'
+/** The root scene's views: the repo hub landing, the PR list page, the workflow list page, and test health. */
+export type EngineeringAnalyticsView = 'hub' | 'pull-requests' | 'workflows' | 'test-health'
-export const TAB_DESCRIPTIONS: Record<EngineeringAnalyticsTab, string> = {
+export const VIEW_DESCRIPTIONS: Record<EngineeringAnalyticsView, string> = {
+ hub: 'CI health, pull requests, workflows, and cost for the connected repo.',
'pull-requests': 'Pull requests and their CI status across connected repos.',
workflows: 'Run volume, success rate, and duration per workflow over the selected window.',
'test-health': 'Flaky tests under quarantine: what is masked, who owns it, and when it expires.',
}
-const SCENE_KEY_TO_TAB: Record<string, EngineeringAnalyticsTab> = {
- engineeringAnalytics: 'pull-requests',
+const SCENE_KEY_TO_VIEW: Record<string, EngineeringAnalyticsView> = {
+ engineeringAnalytics: 'hub',
+ engineeringAnalyticsPullRequestList: 'pull-requests',
engineeringAnalyticsWorkflows: 'workflows',
engineeringAnalyticsTestHealth: 'test-health',
}
@@ -24,9 +27,9 @@ export const engineeringAnalyticsSceneLogic = kea<engineeringAnalyticsSceneLogic
values: [sceneLogic, ['sceneKey']],
})),
selectors({
- activeTab: [
+ activeView: [
(s) => [s.sceneKey],
- (sceneKey: string): EngineeringAnalyticsTab => SCENE_KEY_TO_TAB[sceneKey] ?? 'pull-requests',
+ (sceneKey: string): EngineeringAnalyticsView => SCENE_KEY_TO_VIEW[sceneKey] ?? 'hub',
],
}),
])
diff --git a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
index b10983374412..95f0320aea7b 100644
--- a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
@@ -7,12 +7,20 @@ import { urls } from 'scenes/urls'
import { Breadcrumb } from '~/types'
import {
+ engineeringAnalyticsCiFailureLogs,
engineeringAnalyticsPrCost,
engineeringAnalyticsPrLifecycle,
engineeringAnalyticsPrRuns,
engineeringAnalyticsWorkflowJobs,
} from '../generated/api'
-import type { PRCostSummaryApi, PRLifecycleApi, WorkflowJobApi, WorkflowRunDetailApi } from '../generated/api.schemas'
+import type {
+ CIFailureLogsApi,
+ PRCostSummaryApi,
+ PRLifecycleApi,
+ WorkflowJobApi,
+ WorkflowRunDetailApi,
+} from '../generated/api.schemas'
+import { failedShardsLabel, groupJobs } from '../lib/jobGroups'
import { jobCacheKey } from '../lib/jobs'
import {
LifecycleSummary,
@@ -21,7 +29,6 @@ import {
isPassingConclusion,
summarizeLifecycle,
} from '../lib/lifecycle'
-import type { WorkflowHealthBucket, WorkflowHealthRow } from './engineeringAnalyticsLogic'
import type { pullRequestDetailLogicType } from './pullRequestDetailLogicType'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
@@ -41,6 +48,54 @@ export function sortRunsForTriage(runs: WorkflowRun[]): WorkflowRun[] {
return [...runs].sort((a, b) => rank(a) - rank(b) || a.workflow.localeCompare(b.workflow))
}
+// A broken push shouldn't fan the eager "what failed" job fetches out into dozens of requests.
+const MAX_FAILING_JOB_FETCHES = 6
+
+/** The latest run per workflow on the newest push — what the "CI verdict · latest push" tile counts. */
+export interface LatestPushStats {
+ headSha: string
+ total: number
+ green: number
+ running: number
+ failingWorkflows: string[]
+}
+
+export function computeLatestPushStats(group: PrCommitRuns | undefined): LatestPushStats | null {
+ if (!group) {
+ return null
+ }
+ const latestByWorkflow = new Map<string, WorkflowRun>()
+ for (const run of group.runs) {
+ const seen = latestByWorkflow.get(run.workflow)
+ if (!seen || (run.startedAt ?? '') > (seen.startedAt ?? '')) {
+ latestByWorkflow.set(run.workflow, run)
+ }
+ }
+ const latest = Array.from(latestByWorkflow.values())
+ return {
+ headSha: group.headSha,
+ total: latest.length,
+ green: latest.filter((run) => run.conclusion != null && isPassingConclusion(run.conclusion)).length,
+ running: latest.filter((run) => run.conclusion == null).length,
+ failingWorkflows: latest
+ .filter((run) => run.conclusion != null && !isPassingConclusion(run.conclusion))
+ .map((run) => run.workflow)
+ .sort(),
+ }
+}
+
+/** Each workflow's latest run on the PR (across pushes) — drives the CI-runs table's verdict column. */
+export function latestRunPerWorkflow(runs: PrRunRow[]): Map<string, PrRunRow> {
+ const latest = new Map<string, PrRunRow>()
+ for (const run of runs) {
+ const seen = latest.get(run.workflow)
+ if (!seen || (run.startedAt ?? '') > (seen.startedAt ?? '')) {
+ latest.set(run.workflow, run)
+ }
+ }
+ return latest
+}
+
/** A PR's runs for one commit (head SHA) — used to bucket the progression sparkline by push. */
export interface PrCommitRuns {
headSha: string
@@ -56,6 +111,14 @@ export interface PrRunRow extends WorkflowRun {
headBranch: string
}
+/** One row of the PR page's workflows table — its verdict/failed-job columns derive separately. */
+export interface PrWorkflowRow {
+ workflowName: string
+ runCount: number
+ p50Seconds: number | null
+ estimatedCostUsd: number | null
+}
+
/** Nearest-rank percentile over a small sample (the PR's per-workflow run durations). */
function percentile(values: number[], q: number): number | null {
if (values.length === 0) {
@@ -77,11 +140,9 @@ function toWorkflowRun(run: WorkflowRunDetailApi): WorkflowRun {
}
}
-// Re-exported for the PR detail scene; defined in lib/jobs so the shared RunsTable can read the cache
-// without importing scene logic.
export { jobCacheKey }
-/** Group a PR's runs by commit, newest push first — so the detail shows CI across all pushes. */
+/** Group a PR's runs by commit, newest push first. */
export function groupRunsByCommit(prRuns: WorkflowRunDetailApi[]): PrCommitRuns[] {
const byCommit = new Map<string, WorkflowRunDetailApi[]>()
for (const run of prRuns) {
@@ -116,7 +177,6 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
runId,
runAttempt,
}),
- // Free-text filter on workflow name, narrowing the per-round run tables.
setWorkflowFilter: (filter: string) => ({ filter }),
}),
@@ -154,12 +214,28 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
}),
},
],
+ // Fetched only once a decisive failure is known; 'unavailable' = the fetch itself failed.
+ failureLogs: [
+ null as CIFailureLogsApi | 'unavailable' | null,
+ {
+ loadFailureLogs: async (): Promise<CIFailureLogsApi | 'unavailable'> => {
+ try {
+ return await engineeringAnalyticsCiFailureLogs(projectId(), {
+ pr_number: props.number,
+ repo: `${props.repoOwner}/${props.repoName}`,
+ source_id: props.sourceId ?? undefined,
+ })
+ } catch {
+ return 'unavailable'
+ }
+ },
+ },
+ ],
runJobs: [
{} as Record<string, WorkflowJobApi[]>,
{
- // Lazy: fetched only on first expand. Keyed by run+attempt; the post-await read of
- // values.runJobs (not a pre-await snapshot) keeps two near-simultaneous first-expands
- // from clobbering each other.
+ // The post-await read of values.runJobs (not a pre-await snapshot) keeps two
+ // near-simultaneous first-expands from clobbering each other.
loadJobs: async ({
runId,
runAttempt,
@@ -187,8 +263,7 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
loadLifecycleFailure: () => true,
},
],
- // Separate from loadFailed (the header): a runs-load failure shows an error in the CI-runs section
- // instead of the misleading "no runs attributed" empty state, with its own retry.
+ // Separate from loadFailed so a runs-load failure errors the CI-runs section, not the header.
prRunsFailed: [
false,
{
@@ -209,15 +284,28 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
listeners(({ actions, values }) => ({
setRunExpanded: ({ expanded, runId, runAttempt }) => {
- // Fetch a run+attempt's jobs once, on first expand.
if (expanded && runId != null && !(jobCacheKey(runId, runAttempt) in values.runJobs)) {
actions.loadJobs({ runId, runAttempt })
}
},
+ // Failure logs only exist once something failed — skip the Logs query otherwise.
+ loadPrRunsSuccess: () => {
+ if (values.prRuns.some((run) => isDecisiveFailure(run.conclusion))) {
+ actions.loadFailureLogs()
+ }
+ // Eagerly fetch each failing workflow's latest run's jobs so the table can name what failed.
+ Array.from(latestRunPerWorkflow(values.filteredRuns).values())
+ .filter((run) => run.conclusion != null && !isPassingConclusion(run.conclusion))
+ .slice(0, MAX_FAILING_JOB_FETCHES)
+ .forEach((run) => {
+ if (run.runId != null && !(jobCacheKey(run.runId, run.runAttempt) in values.runJobs)) {
+ actions.loadJobs({ runId: run.runId, runAttempt: run.runAttempt })
+ }
+ })
+ },
})),
selectors({
- // Exposed so the scene can build links (commit/run) and preserve `?source=` without waiting on lifecycle.
sourceId: [() => [(_, p: PullRequestDetailLogicProps) => p.sourceId], (sourceId): string | null => sourceId],
repoOwner: [() => [(_, p: PullRequestDetailLogicProps) => p.repoOwner], (repoOwner): string => repoOwner],
repoName: [() => [(_, p: PullRequestDetailLogicProps) => p.repoName], (repoName): string => repoName],
@@ -225,11 +313,9 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
(s) => [s.lifecycle],
(lifecycle): LifecycleSummary | null => (lifecycle ? summarizeLifecycle(lifecycle.events) : null),
],
- // All of the PR's runs, flattened — for the header counts.
runs: [(s) => [s.prRuns], (prRuns): WorkflowRun[] => prRuns.map(toWorkflowRun)],
- // The PR's runs grouped by commit, newest push first — one collapsible round per commit in the UI.
commitGroups: [(s) => [s.prRuns], (prRuns): PrCommitRuns[] => groupRunsByCommit(prRuns)],
- // Rounds with their runs narrowed to the workflow filter; rounds with no match drop out.
+ // Groups with their runs narrowed to the workflow filter; groups with no match drop out.
filteredCommitGroups: [
(s) => [s.commitGroups, s.workflowFilter],
(commitGroups, workflowFilter): PrCommitRuns[] => {
@@ -245,8 +331,7 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
.filter((group) => group.runs.length > 0)
},
],
- // The PR's runs as one flat list (newest push first), each tagged with its commit, narrowed to
- // the workflow filter.
+ // Flat run list (newest push first), each run tagged with its commit.
filteredRuns: [
(s) => [s.filteredCommitGroups],
(groups): PrRunRow[] =>
@@ -254,15 +339,12 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
group.runs.map((run) => ({ ...run, headSha: group.headSha, headBranch: group.headBranch }))
),
],
- // The PR's runs rolled up per workflow, in the Workflows tab's WorkflowHealthRow shape so the PR
- // page reuses the shared WorkflowHealthTable. Sparkline buckets are the PR's pushes (oldest →
- // newest), zero-filled so every workflow row aligns.
- workflowHealthRows: [
- (s) => [s.commitGroups, s.repoOwner, s.repoName, s.prCost],
- (commitGroups, repoOwner, repoName, prCost): WorkflowHealthRow[] => {
+ // One row per workflow on the PR (first-seen order) — just what the workflows table renders;
+ // the verdict column derives from latestRunPerWorkflow separately.
+ prWorkflowRows: [
+ (s) => [s.commitGroups, s.prCost],
+ (commitGroups, prCost): PrWorkflowRow[] => {
const costByWorkflow = new Map((prCost?.by_workflow ?? []).map((cost) => [cost.workflow_name, cost]))
- const pushesOldestFirst = [...commitGroups].reverse()
- // Workflow names that ran on the PR, first-seen order (newest push first).
const workflowNames: string[] = []
const seen = new Set<string>()
for (const group of commitGroups) {
@@ -273,59 +355,24 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
}
}
}
- return workflowNames.map((workflowName): WorkflowHealthRow => {
- const buckets: WorkflowHealthBucket[] = pushesOldestFirst.map((group, index) => {
- const runs = group.runs.filter((run) => run.workflow === workflowName)
- return {
- bucketStart: group.headSha,
- label: `Push ${index + 1} (${group.headSha.slice(0, 7)})`,
- runCount: runs.length,
- completed: runs.filter((run) => run.conclusion !== null).length,
- successes: runs.filter((run) => run.conclusion === 'success').length,
- failures: runs.filter((run) => isDecisiveFailure(run.conclusion)).length,
- }
- })
+ return workflowNames.map((workflowName): PrWorkflowRow => {
const all = commitGroups.flatMap((group) =>
group.runs.filter((run) => run.workflow === workflowName)
)
- const completedRuns = all.filter((run) => run.conclusion !== null)
- const durations = completedRuns
+ const durations = all
+ .filter((run) => run.conclusion !== null)
.map((run) => run.durationSeconds)
.filter((d): d is number => d != null)
- // Latest completed run (by start) drives the status badge, same as workflow health.
- const latest = [...completedRuns].sort((a, b) =>
- (b.startedAt ?? '').localeCompare(a.startedAt ?? '')
- )[0]
- const failingStarts = all
- .filter((run) => isDecisiveFailure(run.conclusion))
- .map((run) => run.startedAt)
- .filter((at): at is string => !!at)
return {
- repoOwner,
- repoName,
workflowName,
runCount: all.length,
- successRate:
- completedRuns.length > 0
- ? all.filter((run) => run.conclusion === 'success').length / completedRuns.length
- : null,
p50Seconds: percentile(durations, 0.5),
- p95Seconds: percentile(durations, 0.95),
- lastFailureAt: failingStarts.length
- ? failingStarts.reduce((max, at) => (at > max ? at : max))
- : null,
- latestRunFailed: latest ? isDecisiveFailure(latest.conclusion) : null,
- latestRunConclusion: latest ? latest.conclusion : null,
- granularity: 'push',
- buckets,
- billableMinutes: costByWorkflow.get(workflowName)?.billable_minutes ?? null,
estimatedCostUsd: costByWorkflow.get(workflowName)?.estimated_cost_usd ?? null,
}
})
},
],
- // Per-run cost keyed by jobCacheKey(run_id, run_attempt) — so the expanded runs table shows a cost
- // column per attempt. Empty when the job source isn't synced (prCost.jobs_available false).
+ // Per-run cost keyed by jobCacheKey(run_id, run_attempt); empty when the job source isn't synced.
runCostByKey: [
(s) => [s.prCost],
(prCost): Record<string, { minutes: number | null; cost: number | null }> => {
@@ -339,17 +386,44 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
return map
},
],
- // Workflow health rows narrowed to the workflow-name filter.
- filteredWorkflowHealthRows: [
- (s) => [s.workflowHealthRows, s.workflowFilter],
- (rows: WorkflowHealthRow[], workflowFilter: string): WorkflowHealthRow[] => {
+ filteredPrWorkflowRows: [
+ (s) => [s.prWorkflowRows, s.workflowFilter],
+ (rows: PrWorkflowRow[], workflowFilter: string): PrWorkflowRow[] => {
const query = workflowFilter.trim().toLowerCase()
return query ? rows.filter((row) => row.workflowName.toLowerCase().includes(query)) : rows
},
],
- // CI triggers: distinct head SHAs across the PR's runs (matches the backend `pushes` definition).
+ latestPushStats: [
+ (s) => [s.commitGroups],
+ (commitGroups): LatestPushStats | null => computeLatestPushStats(commitGroups[0]),
+ ],
+ // workflow → "what failed" label (de-sharded failing job names); missing = jobs not loaded yet.
+ failingJobLabelByWorkflow: [
+ (s) => [s.filteredRuns, s.runJobs],
+ (filteredRuns, runJobs): Record<string, string> => {
+ const labels: Record<string, string> = {}
+ for (const [workflow, run] of latestRunPerWorkflow(filteredRuns)) {
+ if (run.conclusion == null || isPassingConclusion(run.conclusion) || run.runId == null) {
+ continue
+ }
+ const jobs = runJobs[jobCacheKey(run.runId, run.runAttempt)]
+ if (!jobs) {
+ continue
+ }
+ const failing = groupJobs(jobs).filter((group) => group.failed.length > 0)
+ if (failing.length) {
+ labels[workflow] = failing
+ .map((group) =>
+ group.jobs.length > 1 ? `${group.base} (${failedShardsLabel(group)})` : group.base
+ )
+ .join(' · ')
+ }
+ }
+ return labels
+ },
+ ],
+ // Both match the backend definitions (`pushes`, `rerun_cycles`).
pushes: [(s) => [s.prRuns], (prRuns): number => new Set(prRuns.map((run) => run.head_sha)).size],
- // Runs that were a 2nd+ attempt — re-run cycles (matches the backend `rerun_cycles` definition).
rerunCycles: [(s) => [s.prRuns], (prRuns): number => prRuns.filter((run) => (run.run_attempt ?? 1) > 1).length],
breadcrumbs: [
(_, p) => [p.repoOwner, p.repoName, p.number],
diff --git a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
new file mode 100644
index 000000000000..4923fe01b4ce
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
@@ -0,0 +1,300 @@
+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from 'lib/api'
+import { Dayjs, dayjs } from 'lib/dayjs'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
+
+import { DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import {
+ engineeringAnalyticsMasterFailures,
+ engineeringAnalyticsRepoOverview,
+ engineeringAnalyticsRunFailureLogs,
+} from '../generated/api'
+import type { MasterFailureGroupApi, RepoOverviewApi, RunFailureLogsApi } from '../generated/api.schemas'
+import { ciStatusOf } from '../lib/ci'
+import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
+import { PullRequestRow, STUCK_AFTER_DAYS, engineeringAnalyticsLogic, isStuck } from './engineeringAnalyticsLogic'
+import type { repoOverviewLogicType } from './repoOverviewLogicType'
+
+const projectId = (): string => String(ApiConfig.getCurrentProjectId())
+
+// Pinned to 24h regardless of the shared window — a week of failures is a firehose at monorepo volume.
+const MASTER_FAILURES_WINDOW = '-24h'
+
+const TOP_COST_WORKFLOWS = 5
+
+export interface CostShareRow {
+ workflowName: string | null
+ costUsd: number
+ share: number
+}
+
+// Warehouse timestamps are strings — parse like the curated builders do (repo_overview._BUCKET_SELECT).
+const RUN_STARTED_AT = 'parseDateTimeBestEffort(run_started_at)'
+
+// Refuse to interpolate anything but a plain identifier into SQL.
+const TABLE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/
+
+// Backend granularity ladder (workflow_health._pick_granularity): hour ≤48h, day ≤90d, else week.
+function bucketExpr(from: Dayjs, to: Dayjs): string {
+ const spanHours = to.diff(from, 'hour')
+ if (spanHours <= 48) {
+ return `toStartOfHour(${RUN_STARTED_AT})`
+ }
+ if (spanHours <= 90 * 24) {
+ return `toStartOfDay(${RUN_STARTED_AT})`
+ }
+ return `toStartOfWeek(${RUN_STARTED_AT}, 1)`
+}
+
+function masterHealthSql(
+ metricSelect: string,
+ table: string,
+ branch: string,
+ dateFrom: string | null,
+ dateTo: string | null
+): string | null {
+ const from = dateStringToDayJs(dateFrom ?? SHARED_DEFAULT_DATE_FROM)
+ if (!from) {
+ return null
+ }
+ const to = dateTo ? dateStringToDayJs(dateTo) : null
+ const where = [
+ `status = 'completed'`,
+ `head_branch = '${branch}'`,
+ `${RUN_STARTED_AT} >= toDateTime('${from.format('YYYY-MM-DD HH:mm:ss')}')`,
+ ]
+ if (to) {
+ where.push(`${RUN_STARTED_AT} <= toDateTime('${to.format('YYYY-MM-DD HH:mm:ss')}')`)
+ }
+ return [
+ 'SELECT',
+ ` ${bucketExpr(from, to ?? dayjs())} AS bucket_start,`,
+ ` ${metricSelect}`,
+ `FROM ${table}`,
+ `WHERE ${where.join('\n AND ')}`,
+ 'GROUP BY bucket_start',
+ 'ORDER BY bucket_start',
+ 'LIMIT 400',
+ ].join('\n')
+}
+
+function masterHealthNode(sql: string, display: ChartDisplayType, yColumn: string): DataVisualizationNode {
+ return {
+ kind: NodeKind.DataVisualizationNode,
+ source: { kind: NodeKind.HogQLQuery, query: sql },
+ display,
+ chartSettings: { xAxis: { column: 'bucket_start' }, yAxis: [{ column: yColumn }] },
+ }
+}
+
+export const repoOverviewLogic = kea<repoOverviewLogicType>([
+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'repoOverviewLogic']),
+
+ connect(() => ({
+ values: [
+ engineeringAnalyticsFiltersLogic,
+ ['dateFrom', 'dateTo'],
+ engineeringAnalyticsLogic,
+ [
+ 'sourceId',
+ 'activeSource',
+ 'pullRequests',
+ 'pullRequestsLoading',
+ 'cards',
+ 'workflowHealth',
+ 'workflowHealthLoading',
+ 'notConnected',
+ ],
+ ],
+ })),
+
+ actions({
+ loadLogsForRun: (runId: number) => ({ runId }),
+ }),
+
+ loaders(({ values }) => ({
+ overview: [
+ null as RepoOverviewApi | null,
+ {
+ loadOverview: async (): Promise<RepoOverviewApi> =>
+ await engineeringAnalyticsRepoOverview(projectId(), {
+ date_from: values.dateFrom ?? undefined,
+ date_to: values.dateTo ?? undefined,
+ source_id: values.sourceId ?? undefined,
+ }),
+ },
+ ],
+ masterFailures: [
+ [] as MasterFailureGroupApi[],
+ {
+ loadMasterFailures: async (): Promise<MasterFailureGroupApi[]> =>
+ await engineeringAnalyticsMasterFailures(projectId(), {
+ date_from: MASTER_FAILURES_WINDOW,
+ source_id: values.sourceId ?? undefined,
+ }),
+ },
+ ],
+ // 'unavailable' marks a failed fetch so we don't retry on every expand.
+ failureLogs: [
+ {} as Record<number, RunFailureLogsApi | 'unavailable'>,
+ {
+ loadFailureLogs: async ({
+ runId,
+ }: {
+ runId: number
+ }): Promise<Record<number, RunFailureLogsApi | 'unavailable'>> => {
+ try {
+ const logs = await engineeringAnalyticsRunFailureLogs(projectId(), {
+ run_id: runId,
+ source_id: values.sourceId ?? undefined,
+ })
+ return { ...values.failureLogs, [runId]: logs }
+ } catch {
+ return { ...values.failureLogs, [runId]: 'unavailable' }
+ }
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ // Non-400 failure only; the shared 400 "not connected" state comes from engineeringAnalyticsLogic.
+ overviewFailed: [
+ false,
+ {
+ loadOverview: () => false,
+ loadOverviewSuccess: () => false,
+ loadOverviewFailure: () => true,
+ },
+ ],
+ }),
+
+ selectors({
+ jobsAvailable: [(s) => [s.overview], (overview): boolean => overview?.jobs_available ?? false],
+ defaultBranch: [(s) => [s.overview], (overview): string => overview?.default_branch ?? 'master'],
+ failingWorkflowCount: [
+ (s) => [s.masterFailures],
+ (masterFailures): number => new Set(masterFailures.map((group) => group.workflow_name)).size,
+ ],
+ // The warehouse table behind the master-health embeds, mirroring the backend's per-team
+ // `prefix + github_workflow_runs` resolution (logic/sources.py).
+ runsTableName: [
+ (s) => [s.activeSource],
+ (activeSource): string | null => {
+ if (!activeSource) {
+ return null
+ }
+ const table = `${activeSource.prefix}github_workflow_runs`
+ return TABLE_IDENTIFIER.test(table) ? table : null
+ },
+ ],
+ masterSuccessRateQuery: [
+ (s) => [s.runsTableName, s.defaultBranch, s.dateFrom, s.dateTo],
+ (runsTableName, defaultBranch, dateFrom, dateTo): DataVisualizationNode | null => {
+ if (!runsTableName) {
+ return null
+ }
+ const sql = masterHealthSql(
+ `round(100 * countIf(conclusion = 'success') / count(), 1) AS success_rate`,
+ runsTableName,
+ defaultBranch,
+ dateFrom,
+ dateTo
+ )
+ return sql ? masterHealthNode(sql, ChartDisplayType.ActionsLineGraph, 'success_rate') : null
+ },
+ ],
+ masterFailedRunsQuery: [
+ (s) => [s.runsTableName, s.defaultBranch, s.dateFrom, s.dateTo],
+ (runsTableName, defaultBranch, dateFrom, dateTo): DataVisualizationNode | null => {
+ if (!runsTableName) {
+ return null
+ }
+ const sql = masterHealthSql(
+ `countIf(conclusion != 'success') AS failed_runs`,
+ runsTableName,
+ defaultBranch,
+ dateFrom,
+ dateTo
+ )
+ return sql ? masterHealthNode(sql, ChartDisplayType.ActionsBar, 'failed_runs') : null
+ },
+ ],
+ // Open PRs with failing CI or stuck (open >7d, non-draft, non-bot) — not the full open list.
+ attentionPrs: [
+ (s) => [s.pullRequests],
+ (pullRequests): PullRequestRow[] => {
+ const stuckCutoffMs = dayjs().subtract(STUCK_AFTER_DAYS, 'day').valueOf()
+ return pullRequests
+ .filter(
+ (row) => row.state === 'open' && (ciStatusOf(row) === 'failing' || isStuck(row, stuckCutoffMs))
+ )
+ .sort((a, b) => Number(ciStatusOf(b) === 'failing') - Number(ciStatusOf(a) === 'failing'))
+ },
+ ],
+ draftCount: [
+ (s) => [s.pullRequests],
+ (pullRequests): number => pullRequests.filter((row) => row.state === 'open' && row.isDraft).length,
+ ],
+ costByWorkflow: [
+ (s) => [s.workflowHealth],
+ (workflowHealth): CostShareRow[] => {
+ const costed = workflowHealth.filter((row) => (row.estimatedCostUsd ?? 0) > 0)
+ if (!costed.length) {
+ return []
+ }
+ const total = costed.reduce((sum, row) => sum + (row.estimatedCostUsd ?? 0), 0)
+ const top = [...costed]
+ .sort((a, b) => (b.estimatedCostUsd ?? 0) - (a.estimatedCostUsd ?? 0))
+ .slice(0, TOP_COST_WORKFLOWS)
+ const rows: CostShareRow[] = top.map((row) => ({
+ workflowName: row.workflowName,
+ costUsd: row.estimatedCostUsd ?? 0,
+ share: (row.estimatedCostUsd ?? 0) / total,
+ }))
+ const otherCost = total - rows.reduce((sum, row) => sum + row.costUsd, 0)
+ if (costed.length > TOP_COST_WORKFLOWS && otherCost > 0) {
+ rows.push({ workflowName: null, costUsd: otherCost, share: otherCost / total })
+ }
+ return rows
+ },
+ ],
+ otherCostWorkflowCount: [
+ (s) => [s.workflowHealth],
+ (workflowHealth): number =>
+ Math.max(
+ 0,
+ workflowHealth.filter((row) => (row.estimatedCostUsd ?? 0) > 0).length - TOP_COST_WORKFLOWS
+ ),
+ ],
+ }),
+
+ listeners(({ actions, values }) => ({
+ loadLogsForRun: ({ runId }) => {
+ if (!(runId in values.failureLogs)) {
+ actions.loadFailureLogs({ runId })
+ }
+ },
+ // The failures feed is pinned to -24h, so it only re-reads on source change / refresh.
+ [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
+ actions.loadOverview()
+ },
+ [engineeringAnalyticsLogic.actionTypes.setSourceId]: () => {
+ actions.loadOverview()
+ actions.loadMasterFailures()
+ },
+ [engineeringAnalyticsLogic.actionTypes.refresh]: () => {
+ actions.loadOverview()
+ actions.loadMasterFailures()
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadOverview()
+ actions.loadMasterFailures()
+ }),
+])
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
index e92d10165820..03041d768806 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
@@ -6,8 +6,13 @@ import { urls } from 'scenes/urls'
import { Breadcrumb } from '~/types'
-import { engineeringAnalyticsWorkflowJobs, engineeringAnalyticsWorkflowRun } from '../generated/api'
-import type { WorkflowJobApi, WorkflowRunDetailApi } from '../generated/api.schemas'
+import {
+ engineeringAnalyticsRunFailureLogs,
+ engineeringAnalyticsWorkflowJobs,
+ engineeringAnalyticsWorkflowRun,
+} from '../generated/api'
+import type { RunFailureLogsApi, WorkflowJobApi, WorkflowRunDetailApi } from '../generated/api.schemas'
+import { isDecisiveFailure } from '../lib/lifecycle'
import { RunCostSummary, summarizeRunCost } from '../lib/runHealth'
import type { workflowRunDetailLogicType } from './workflowRunDetailLogicType'
@@ -38,10 +43,8 @@ export const workflowRunDetailLogic = kea<workflowRunDetailLogicType>([
}),
},
],
- // A single run's jobs — the breakdown the PR view shows on expand. null while not loaded (kea
- // reducers can't hold undefined), [] when the source isn't synced. Scoped to the run's actual
- // attempt (loaded first): a rerun's jobs source can lag, and the backend's omitted-attempt fallback
- // would otherwise show an older attempt's jobs/costs.
+ // null = not loaded, [] = source unsynced. Scoped to the run's actual attempt (loaded first) —
+ // the backend's omitted-attempt fallback would otherwise show an older attempt's jobs/costs.
jobs: [
null as WorkflowJobApi[] | null,
{
@@ -53,6 +56,22 @@ export const workflowRunDetailLogic = kea<workflowRunDetailLogicType>([
}),
},
],
+ // Fetched only for a decisively failed run; 'unavailable' = the fetch itself failed.
+ failureLogs: [
+ null as RunFailureLogsApi | 'unavailable' | null,
+ {
+ loadFailureLogs: async (): Promise<RunFailureLogsApi | 'unavailable'> => {
+ try {
+ return await engineeringAnalyticsRunFailureLogs(projectId(), {
+ run_id: props.runId,
+ source_id: props.sourceId ?? undefined,
+ })
+ } catch {
+ return 'unavailable'
+ }
+ },
+ },
+ ],
})),
reducers({
@@ -67,10 +86,8 @@ export const workflowRunDetailLogic = kea<workflowRunDetailLogicType>([
}),
selectors({
- // Exposed so the scene can preserve `?source=` when linking out to the PR detail.
sourceId: [() => [(_, p: WorkflowRunDetailLogicProps) => p.sourceId], (sourceId): string | null => sourceId],
- // The run's own CI cost, summed from the jobs already loaded for the breakdown table — no extra
- // query. null until jobs load or when nothing on the run is billable. Mirrors the PR page's tile.
+ // Summed from the already-loaded jobs — no extra query.
runCost: [(s) => [s.jobs], (jobs): RunCostSummary | null => (jobs ? summarizeRunCost(jobs) : null)],
// A non-numeric path segment yields NaN — the scene shows a clean "not found" instead of a load error.
isValidRunId: [
@@ -95,14 +112,19 @@ export const workflowRunDetailLogic = kea<workflowRunDetailLogicType>([
],
}),
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
// Load jobs only once the run is in, so they can be scoped to the run's real attempt.
- loadRunSuccess: () => actions.loadJobs(),
+ loadRunSuccess: () => {
+ actions.loadJobs()
+ // Failure logs only exist for failed runs — skip the query otherwise.
+ if (isDecisiveFailure(values.run?.conclusion ?? null)) {
+ actions.loadFailureLogs()
+ }
+ },
})),
afterMount(({ actions, props }) => {
- // Skip the load for a non-numeric run id (NaN) — it would just 400; the scene renders "not found".
- // Jobs load on loadRunSuccess (needs the run's attempt first).
+ // A non-numeric run id would just 400; the scene renders "not found" instead.
if (Number.isFinite(props.runId)) {
actions.loadRun()
}
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
index a37e621d9d94..da7ad8ce05e5 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
@@ -8,12 +8,14 @@ import { Breadcrumb } from '~/types'
import type { ActivityRun } from '../components/RunActivityChart'
import {
+ engineeringAnalyticsJobAggregates,
engineeringAnalyticsWorkflowJobs,
engineeringAnalyticsWorkflowRunActivity,
engineeringAnalyticsWorkflowRunnerCosts,
engineeringAnalyticsWorkflowRuns,
} from '../generated/api'
import type {
+ WorkflowJobAggregateApi,
WorkflowJobApi,
WorkflowRunActivityApi,
WorkflowRunDetailApi,
@@ -26,12 +28,10 @@ import type { workflowRunsLogicType } from './workflowRunsLogicType'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
-// Mirrors the backend runs-list cap (`workflow_run_list.py` `_LIMIT`). A full list is likely truncated, so
-// the header labels run rollups "recent" rather than full-window.
+// Mirrors the backend runs-list cap (`workflow_run_list.py` `_LIMIT`).
const RUN_LIST_LIMIT = 200
-/** A workflow run mapped to the shared RunsTable shape: the RunRowBase fields the table needs, plus the
- * lead-column data this page shows (run id, branch, attributed PR). */
+/** RunRowBase fields plus this page's lead-column data (run id, branch, attributed PR). */
export interface WorkflowRunRow {
runId: number | null
runAttempt: number | null
@@ -40,6 +40,7 @@ export interface WorkflowRunRow {
startedAt: string | null
id: number
headBranch: string | null
+ headSha: string
prNumber: number
repoOwner: string
repoName: string
@@ -58,9 +59,8 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
props({} as WorkflowRunsLogicProps),
key((props) => `${props.repoOwner}/${props.repoName}/${props.workflowName}@${props.sourceId ?? ''}`),
- // The shared CI-analytics window and branch scope both the runs list and the runner-cost breakdown —
- // one window and branch, the same the Workflows tab uses, so drilling in from a branch-scoped tab keeps
- // that scope instead of silently widening back to all branches (which reads as "more runs").
+ // Same window and branch scope as the Workflows tab, so drilling in keeps the scope instead of
+ // silently widening back to all branches.
connect(() => ({
values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'appliedBranch']],
})),
@@ -90,9 +90,8 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
}),
},
],
- // Compact per-run points for the activity chart, over the full window at a higher cap than the runs
- // table — so the chart spans multiple days (and its focus-lens brush appears) on busy workflows where
- // the 200-run table would collapse to a sub-day slice.
+ // Activity-chart points at a higher cap than the runs table, so the chart spans the full window
+ // on busy workflows where 200 runs collapse to a sub-day slice.
runActivity: [
{ points: [], truncated: false, limit: 0 } as WorkflowRunActivityApi,
{
@@ -107,7 +106,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
}),
},
],
- // Cost split by runner tier over the window — "where this workflow's spend goes"; [] when jobs aren't synced.
+ // Cost split by runner tier; [] when the job-level source isn't synced.
runnerCosts: [
[] as WorkflowRunnerCostApi[],
{
@@ -122,11 +121,24 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
}),
},
],
+ // Per-job rollups; [] when the job-level source isn't synced.
+ jobAggregates: [
+ [] as WorkflowJobAggregateApi[],
+ {
+ loadJobAggregates: async (): Promise<WorkflowJobAggregateApi[]> =>
+ await engineeringAnalyticsJobAggregates(projectId(), {
+ workflow_name: props.workflowName,
+ date_from: values.dateFrom ?? undefined,
+ date_to: values.dateTo ?? undefined,
+ branch: values.appliedBranch || undefined,
+ source_id: props.sourceId ?? undefined,
+ }),
+ },
+ ],
runJobs: [
{} as Record<string, WorkflowJobApi[]>,
{
- // Lazy: fetched only on first expand. Keyed by run+attempt; reads the post-await
- // values.runJobs so two near-simultaneous first-expands don't clobber each other.
+ // Reads the post-await values.runJobs so near-simultaneous first-expands don't clobber.
loadJobs: async ({
runId,
runAttempt,
@@ -164,8 +176,6 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
}),
selectors({
- // Pass props through as values so the scene reads repo/workflow identity (title, links) without
- // reaching into logic internals, and can preserve `?source=` on outbound links.
sourceId: [() => [(_, p: WorkflowRunsLogicProps) => p.sourceId], (sourceId): string | null => sourceId],
repoOwner: [() => [(_, p: WorkflowRunsLogicProps) => p.repoOwner], (repoOwner): string => repoOwner],
repoName: [() => [(_, p: WorkflowRunsLogicProps) => p.repoName], (repoName): string => repoName],
@@ -173,7 +183,6 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
() => [(_, p: WorkflowRunsLogicProps) => p.workflowName],
(workflowName): string => workflowName,
],
- // Runs mapped to the shared RunsTable row shape, reusing the same runs → jobs table the PR detail uses.
runRows: [
(s) => [s.runs],
(runs: WorkflowRunDetailApi[]): WorkflowRunRow[] =>
@@ -185,13 +194,12 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
startedAt: run.run_started_at,
id: run.id,
headBranch: run.head_branch,
+ headSha: run.head_sha,
prNumber: run.pr_number,
repoOwner: run.repo.owner,
repoName: run.repo.name,
})),
],
- // The activity chart's points, mapped to the shape it plots. Sourced from the higher-capped activity
- // endpoint (not the 200-run table) so the chart covers the full window and its brush shows.
activityRuns: [
(s) => [s.runActivity],
(runActivity: WorkflowRunActivityApi): ActivityRun[] =>
@@ -204,26 +212,57 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
prNumber: point.pr_number,
})),
],
- // The chart's own cap was hit — it covers only the most recent runs, not the full window. Distinct
- // from `runsTruncated` (the table's smaller cap), so the chart labels itself honestly.
+ // The chart's own cap, distinct from `runsTruncated` (the table's smaller cap).
activityTruncated: [
(s) => [s.runActivity],
(runActivity: WorkflowRunActivityApi): boolean => runActivity.truncated,
],
- // Verdict + headline stats for the health strip above the chart.
healthSummary: [(s) => [s.runRows], (runRows): HealthSummary => computeHealthSummary(runRows)],
- // Runs list is capped server-side; when hit, run rollups cover only the most recent runs (cost
- // still comes from the full-window aggregate), so the header labels them as such.
+ // Latest completed master/main run's conclusion; null when the window has none (PR-only workflow).
+ masterConclusion: [
+ (s) => [s.runRows],
+ (runRows): string | null => {
+ const masterRuns = runRows
+ .filter(
+ (run) =>
+ (run.headBranch === 'master' || run.headBranch === 'main') &&
+ run.conclusion != null &&
+ run.startedAt != null
+ )
+ .sort((a, b) => (b.startedAt ?? '').localeCompare(a.startedAt ?? ''))
+ return masterRuns[0]?.conclusion ?? null
+ },
+ ],
+ // Median queue wait across jobs, weighted by how often each job runs. Null until jobs are synced.
+ queueP50Seconds: [
+ (s) => [s.jobAggregates],
+ (jobAggregates): number | null => {
+ const weighted: { value: number; weight: number }[] = jobAggregates
+ .filter((row) => row.queue_p50_seconds != null)
+ .map((row) => ({ value: row.queue_p50_seconds as number, weight: row.job_count }))
+ .sort((a, b) => a.value - b.value)
+ const total = weighted.reduce((sum, entry) => sum + entry.weight, 0)
+ if (!total) {
+ return null
+ }
+ let acc = 0
+ for (const entry of weighted) {
+ acc += entry.weight
+ if (acc >= total / 2) {
+ return entry.value
+ }
+ }
+ return weighted[weighted.length - 1].value
+ },
+ ],
runsTruncated: [(s) => [s.runRows], (runRows): boolean => runRows.length >= RUN_LIST_LIMIT],
- // Billable minutes + estimated cost summed across runner tiers, for the strip's cost rollup.
costSummary: [
(s) => [s.runnerCosts],
(runnerCosts): CostSummary | null => {
if (runnerCosts.length === 0) {
return null
}
- // Free (GitHub-hosted) runners report null cost; gate each field so an all-free workflow
- // shows no cost rather than a misleading $0.00 / 0 min from summing nulls as zero.
+ // Free runners report null — a bare sum would turn "no cost data" into a misleading $0.00.
const hasBillable = runnerCosts.some((cost) => cost.billable_minutes != null)
const hasEstimatedCost = runnerCosts.some((cost) => cost.estimated_cost_usd != null)
return {
@@ -245,12 +284,6 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
path: urls.engineeringAnalytics(),
iconType: 'health',
},
- {
- key: 'EngineeringAnalyticsWorkflowsTab',
- name: 'Workflows',
- path: urls.engineeringAnalyticsWorkflows(),
- iconType: 'health',
- },
{
key: ['EngineeringAnalyticsWorkflowRuns', `${repoOwner}/${repoName}/${workflowName}`],
name: `${repoOwner}/${repoName} · ${workflowName}`,
@@ -262,21 +295,21 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
listeners(({ actions, values }) => ({
setRunExpanded: ({ expanded, runId, runAttempt }) => {
- // Fetch a run+attempt's jobs once, on first expand.
if (expanded && runId != null && !(jobCacheKey(runId, runAttempt) in values.runJobs)) {
actions.loadJobs({ runId, runAttempt })
}
},
- // The shared window scopes all three reads — reload them together when it changes.
[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadRuns()
actions.loadRunActivity()
actions.loadRunnerCosts()
+ actions.loadJobAggregates()
},
[engineeringAnalyticsFiltersLogic.actionTypes.setAppliedBranch]: () => {
actions.loadRuns()
actions.loadRunActivity()
actions.loadRunnerCosts()
+ actions.loadJobAggregates()
},
})),
@@ -284,5 +317,6 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
actions.loadRuns()
actions.loadRunActivity()
actions.loadRunnerCosts()
+ actions.loadJobAggregates()
}),
])
diff --git a/products/engineering_analytics/manifest.tsx b/products/engineering_analytics/manifest.tsx
index 4141a196995f..76f7a82076fd 100644
--- a/products/engineering_analytics/manifest.tsx
+++ b/products/engineering_analytics/manifest.tsx
@@ -41,20 +41,13 @@ export const manifest: ProductManifest = {
description: "A single workflow's recent runs across the connected repo.",
iconType: 'health',
},
- EngineeringAnalyticsAuthor: {
- import: () => import('./frontend/scenes/EngineeringAnalyticsAuthorScene'),
- projectBased: true,
- name: 'Author CI',
- layout: 'app-container',
- description: "One author's pull requests and the CI cost they incurred.",
- iconType: 'health',
- },
},
// Detail paths mirror GitHub 1:1 (owner/repo/pull/:n, owner/repo/actions/runs/:id); cross-repo
// aggregates stay at the product root. Provider lives on the data (RepoRef.provider), so these url
// builders are the single place to branch verbs for a future provider (e.g. GitLab).
routes: {
'/engineering-analytics': ['EngineeringAnalytics', 'engineeringAnalytics'],
+ '/engineering-analytics/pulls': ['EngineeringAnalytics', 'engineeringAnalyticsPullRequestList'],
'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],
'/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],
'/engineering-analytics/:repoOwner/:repoName/pull/:number': [
@@ -69,11 +62,15 @@ export const manifest: ProductManifest = {
'EngineeringAnalyticsWorkflowRuns',
'engineeringAnalyticsWorkflowRuns',
],
- '/engineering-analytics/author/:handle': ['EngineeringAnalyticsAuthor', 'engineeringAnalyticsAuthor'],
},
- redirects: {},
+ redirects: {
+ // The author surface was removed: analytics stay at team/repo level (see README locked decisions).
+ '/engineering-analytics/authors': '/engineering-analytics',
+ '/engineering-analytics/author/:handle': '/engineering-analytics',
+ },
urls: {
engineeringAnalytics: (): string => '/engineering-analytics',
+ engineeringAnalyticsPullRequestList: (): string => '/engineering-analytics/pulls',
engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',
engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',
engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>
@@ -82,8 +79,6 @@ export const manifest: ProductManifest = {
`/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/runs/${runId}`,
engineeringAnalyticsWorkflowRuns: (repoOwner: string, repoName: string, workflowName: string): string =>
`/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/workflows/${encodeURIComponent(workflowName)}`,
- engineeringAnalyticsAuthor: (handle: string): string =>
- `/engineering-analytics/author/${encodeURIComponent(handle)}`,
},
fileSystemTypes: {},
treeItemsNew: [],
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index a4f79e498693..322c14508b4a 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -31,6 +31,12 @@ tools:
pushes' failures are included too. logs_available is false when CI hasn't failed, the logs aged out of the
short Logs retention, or a fork PR has no run association to resolve. Use pr-runs or workflow-jobs for the
run/job metadata behind these logs.
+ engineering-analytics-job-aggregates:
+ operation: engineering_analytics_job_aggregates
+ enabled: false
+ engineering-analytics-master-failures:
+ operation: engineering_analytics_master_failures
+ enabled: false
engineering-analytics-pr-cost:
operation: engineering_analytics_pr_cost
enabled: true
@@ -58,6 +64,12 @@ tools:
engineering-analytics-quarantine-request:
operation: engineering_analytics_quarantine_request
enabled: false
+ engineering-analytics-repo-overview:
+ operation: engineering_analytics_repo_overview
+ enabled: false
+ engineering-analytics-run-failure-logs:
+ operation: engineering_analytics_run_failure_logs
+ enabled: false
engineering-analytics-sources:
operation: engineering_analytics_sources
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 072aa2c2427d..9c81eac4bdd5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11999,6 +11999,8 @@ export namespace Schemas {
failing: number;
/** Latest runs not yet completed (queued or in progress). */
pending: number;
+ /** The workflow names behind `failing`, sorted - names what is failing instead of leaving a bare count. */
+ failing_workflows?: string[];
}
export interface EventsHeatMapColumnAggregationResult {
@@ -29643,6 +29645,23 @@ export namespace Schemas {
recommended_actions: RecommendedAction[];
}
+ export interface MasterFailureGroup {
+ /** Repository the failures occurred in. */
+ repo: RepoRef;
+ /** GitHub Actions workflow name the failing runs belong to. */
+ workflow_name: string;
+ /** De-sharded failing job name (matrix '(G/N)' suffix stripped) — the group's failure signature together with the workflow. '' when the job-level source isn't synced and the group degrades to workflow level. */
+ failed_job: string;
+ /** Distinct failing default-branch runs in this group within the window. */
+ run_count: number;
+ /** When the oldest failing run in the group started. */
+ first_seen: string;
+ /** When the newest failing run in the group started. */
+ last_seen: string;
+ /** Run id of the newest failing run — the drill-down anchor. */
+ latest_run_id: number;
+ }
+
/**
* * `key` - key
* * `value` - value
@@ -47411,6 +47430,61 @@ export namespace Schemas {
layout?: LayoutEnum;
}
+ export interface RepoOverview {
+ /** Workflow runs started in the window, all branches and workflows. */
+ run_count: number;
+ /** Same count over the equal-length window immediately before date_from — the delta baseline. */
+ run_count_prev: number;
+ /**
+ * Fraction of completed runs that succeeded (0-1) in the window. Null if none completed.
+ * @nullable
+ */
+ success_rate: number | null;
+ /**
+ * Success rate over the previous window. Null if none completed.
+ * @nullable
+ */
+ success_rate_prev: number | null;
+ /** Runs in the window that were a 2nd+ attempt (attempt > 1). */
+ rerun_cycles: number;
+ /** Re-run cycles over the previous window. */
+ rerun_cycles_prev: number;
+ /**
+ * Median merged_at - created_at over PRs merged in the window, bots and drafts excluded. Coarse by design: draft and ready-for-review time are fused. Null when nothing merged.
+ * @nullable
+ */
+ median_open_to_merge_seconds: number | null;
+ /**
+ * The same median over the previous window. Null when nothing merged.
+ * @nullable
+ */
+ median_open_to_merge_seconds_prev: number | null;
+ /**
+ * Billable (self-hosted) job minutes in the window; null when the job-level source isn't synced.
+ * @nullable
+ */
+ billable_minutes: number | null;
+ /**
+ * Billable minutes over the previous window; null when the job-level source isn't synced.
+ * @nullable
+ */
+ billable_minutes_prev: number | null;
+ /**
+ * Estimated CI cost in USD (billable minutes x runner-tier rate); null when the job-level source isn't synced.
+ * @nullable
+ */
+ estimated_cost_usd: number | null;
+ /**
+ * Estimated cost over the previous window; null when the job-level source isn't synced.
+ * @nullable
+ */
+ estimated_cost_usd_prev: number | null;
+ /** Whether the job-level source is synced (cost and queue figures exist). */
+ jobs_available: boolean;
+ /** 'master' or 'main', picked by observed run volume in the window. */
+ default_branch: string;
+ }
+
export interface ScanEvidence {
/** Number of files scanned */
filesScanned: number;
@@ -47587,6 +47661,17 @@ export namespace Schemas {
reference: RoleExternalReference | null;
}
+ export interface RunFailureLogs {
+ /** Failed CI jobs of this run with their thinned failure logs, grouped by job. */
+ jobs: CIJobFailureLog[];
+ /** Workflow run id the failure logs are for. */
+ run_id: number;
+ /** False when no failure logs were found — the run didn't fail, or its logs aged out of the short Logs retention. */
+ logs_available: boolean;
+ /** True when the overall line cap across all jobs was hit. */
+ truncated: boolean;
+ }
+
export interface RunInsightsResponse {
/** Results for each insight tile on the dashboard. */
results: DashboardTileResult[];
@@ -53872,6 +53957,13 @@ export namespace Schemas {
* @nullable
*/
estimated_cost_usd?: number | null;
+ /** Runs in the window that were a 2nd+ attempt - retry pressure, a flakiness proxy. */
+ rerun_cycles?: number;
+ /**
+ * Success rate over the equal-length window before date_from - the delta baseline. Null when that window had no completed runs.
+ * @nullable
+ */
+ success_rate_prev?: number | null;
}
export interface WorkflowJob {
@@ -53914,6 +54006,54 @@ export namespace Schemas {
estimated_cost_usd: number | null;
}
+ export interface WorkflowJobAggregate {
+ /** De-sharded job name: the matrix '(G/N)' suffix is stripped and unexpanded '${{ matrix.* }}' templates are collapsed, so shards of one matrix aggregate together. */
+ job_name: string;
+ /** Job instances observed in the window (all shards, all attempts). */
+ job_count: number;
+ /** Distinct raw job names inside the group - the observed matrix width. */
+ shard_count: number;
+ /** Distinct workflow runs the job appeared in. */
+ runs_in: number;
+ /**
+ * runs_in divided by the workflow's total runs in the window; below 1.0 means the job is conditional and skips some runs. Null when the workflow had no runs.
+ * @nullable
+ */
+ run_share: number | null;
+ /**
+ * Median queue wait (created to started) in seconds - where runner-capacity problems hide. Null when nothing started.
+ * @nullable
+ */
+ queue_p50_seconds: number | null;
+ /**
+ * Median duration of completed job instances, in seconds. Null if none completed.
+ * @nullable
+ */
+ p50_seconds: number | null;
+ /**
+ * 95th-percentile duration of completed job instances, in seconds. Null if none completed.
+ * @nullable
+ */
+ p95_seconds: number | null;
+ /**
+ * Decisive failures ('failure', 'timed_out') over completed instances (0-1). Null if none completed.
+ * @nullable
+ */
+ failure_rate: number | null;
+ /** Job instances that ran on a 2nd+ run attempt - retry pressure. */
+ retry_job_count: number;
+ /**
+ * Billable (self-hosted) minutes across the group's instances; null when every instance ran on an unknown tier.
+ * @nullable
+ */
+ billable_minutes: number | null;
+ /**
+ * Estimated cost in USD via the runner-tier rate ladder; null when every instance ran on an unknown tier.
+ * @nullable
+ */
+ estimated_cost_usd: number | null;
+ }
+
export interface WorkflowRunActivityPoint {
/** GitHub Actions run id. */
run_id: number;
@@ -62302,6 +62442,48 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsJobAggregatesParams = {
+ /**
+ * Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
+ */
+ branch?: string;
+ /**
+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
+ */
+ date_from?: string;
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
+ /**
+ * Workflow name to aggregate jobs for.
+ */
+ workflow_name: string;
+ };
+
+ 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.
+ */
+ branch?: string;
+ /**
+ * Window start: relative ('-24h', '-7d') or ISO8601. Defaults to -24h.
+ */
+ date_from?: string;
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
+ };
+
export type EngineeringAnalyticsPrCostParams = {
/**
* Pull request number to estimate cost for.
@@ -62373,6 +62555,32 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsRepoOverviewParams = {
+ /**
+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
+ */
+ date_from?: string;
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
+ };
+
+ export type EngineeringAnalyticsRunFailureLogsParams = {
+ /**
+ * Workflow run id whose failure logs to fetch.
+ */
+ run_id: number;
+ /**
+ * 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 EngineeringAnalyticsWorkflowHealthParams = {
/**
* Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.