Skip to content

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

fix(eng-analytics): show current ci health (#70509)

Raúl Negrón-Otero30eb43c8025e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 25e19d114583..ce02ede0324b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5631,9 +5631,13 @@ snapshots:
scenes-app-data-warehouse-sql-editor--top-tools-per-server--light:
hash: v1.k794b7964.e6420f44b86930d43085b575192d3c26ac0401919a4af6f8d7bd1c799e964836.pZmiZ4w-9QbQ60TFc6Sx94NT0YmU4EULydWdqDqxDmY
scenes-app-engineering-analytics-repo-overview--repo-overview--dark:
- hash: v1.k794b7964.c6f38d08b3c59294a9443a62fdf1b76fab8f2a026d3c3bb169f8ec86575e2296.xPQhtO1OrkOaRa8V_fKsaZMyJ9CM9iW_HTB3w5wa9r8
+ hash: v1.k794b7964.2f6a03768f7fd744209d68ad0d4ed30f8f13e6457c005caee001711bce72559a.wGhGJXZVT2RMHTY1nYDEsKOe8gs15i8OKJTOiHy6M2A
scenes-app-engineering-analytics-repo-overview--repo-overview--light:
- hash: v1.k794b7964.10713695bfff7d1fe091a19db8a951832946f61cc5711f41edf479cdc443e071.j1YL510Wvt_XUK4isWUN7pSluY0kL7yvzokjkR1P1es
+ hash: v1.k794b7964.fa63ebe5edc3d998537561d334db2ca368d4f68a6eb62ae51d05f005af379311.n3sBaR2EfJiLyoFcIhsp_z4thfRlGElFns_X7qaNQII
+ scenes-app-engineering-analytics-repo-overview--repo-overview-failing--dark:
+ hash: v1.k794b7964.0fe8332bfa26e030a0ff01303d1fcce2c57442e90e979ef0b7aa42530720119a.G2CN2Y5L8tUETotqOpviY8y6o9IAWJHCzYs9xYRc1Mw
+ scenes-app-engineering-analytics-repo-overview--repo-overview-failing--light:
+ hash: v1.k794b7964.4e1ed6c540fca8e95dad14c8d479a3ffc5b8a0eec6083ddddeed1e2ceabfe5b6.UC2p5Di8xVfGABNMYuqx6WqTIf5fC3pr8WsFSlB0J5o
scenes-app-engineering-analytics-test-health--flaky-test-leaderboard--dark:
hash: v1.k794b7964.8e887d3516448ca8544b66f54ec2b15c348c795f5eeb38121d8822614ab6895a.FSJv5vBtsNGzICpMzsq58FRQDj-CMLwqFPl9IVKY4A4
scenes-app-engineering-analytics-test-health--flaky-test-leaderboard--light:
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 4e2a1ef517d7..8e66c6570cbf 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -142,6 +142,7 @@ A PR's current CI status is the head-SHA join between the two (the `ci_rollup` C
- `ci_cards` — open-PR backlog counts (open / repos / stuck >7d / failing CI).
- `pull_requests` — PR list with head-SHA CI rollup; `date_from` recency window. Capped (newest first) and returned as `{items, truncated, limit}` so the page never silently under-counts against `ci_cards`.
- `workflow_health` — per-workflow run count, success rate, p50/p95 duration, last failure over a `date_from`/`date_to` window, optionally scoped to a single git `branch` (`head_branch`) or PR-attributed runs excluding the default branch (`run_scope=pull_request`; master/main, same-repo PRs only). p50/p95 are over successful runs only — there is no knob, because cancelled (superseded) and failed runs end early and would bias any duration percentile low.
+- `current_branch_health` — complete current default-branch verdict over a fixed 24-hour window: the detected branch, settled-workflow count, complete failing-workflow count, and a bounded name preview. This is a separate aggregate because `workflow_health` intentionally caps its per-workflow rows and cannot safely prove the fleet is green.
- `pr_lifecycle` — PR header + ordered CI-run timeline (a genuine assembly; `metric_quality = "partial"` until reviews/deploys land).
- `ci_failure_logs` — the thinned failure log lines for a PR's CI, grouped by job. Resolves the PR to its run_ids via the same `pull_requests` attribution as `pr_runs`, then reads the Logs product (`service.name = github-ci-logs`) joined on `run_id`. Reads from Logs, not the warehouse.
- `flaky_tests` — the flaky-test leaderboard: per-test CI spans from the Traces product (`trace_spans`, emitted by Backend CI's report-test-timings job) grouped by pytest nodeid over a window (default `-7d`, max 30 days), scoped to the selected GitHub source via the emitted `ci.repository`, and ranked by flakiness signal. A test qualifies by passing on retry (`rerun_passed`) at least `min_rerun_passes` times (default 1) OR failing on at least `min_failed_prs` distinct PRs (default 3). Absolute counts only, never rates — sub-threshold passing runs aren't emitted, so denominators are biased. Reads from Traces, not the warehouse.
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index b110fd0b9a8a..292bd131de7d 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -26,6 +26,7 @@ from products.engineering_analytics.backend import logic
from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
CIFailureLogs,
+ CurrentBranchHealth,
FlakyTestList,
GitHubSource,
MasterFailureGroup,
@@ -318,6 +319,15 @@ def get_repo_overview(
)
+def get_current_branch_health(
+ *,
+ team: Team,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> CurrentBranchHealth:
+ return logic.build_current_branch_health(curated=_authorized_source(team, source_id, user_access_control))
+
+
def get_repo_run_activity(
*,
team: Team,
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 5e202b5fcc47..e9ed47d7b8e2 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -831,6 +831,19 @@ class RepoOverview:
open_to_merge_series_granularity: str
+@dataclass(frozen=True)
+class CurrentBranchHealth:
+ """Current default-branch CI verdict over the last 24 hours.
+
+ Counts cover every workflow with a completed run; names are a bounded preview for UI copy.
+ """
+
+ default_branch: str
+ settled_workflows: int
+ failing_workflows: int
+ failing_workflow_names: list[str]
+
+
@dataclass(frozen=True)
class MasterFailureGroup:
"""One group of default-branch failures: a (workflow, de-sharded failing job) signature with
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index 9cda2a3b1144..41dca8074641 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -16,6 +16,7 @@ from posthog.utils import relative_date_parse
from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
CIFailureLogs,
+ CurrentBranchHealth,
FlakyTestList,
GitHubSource,
MasterFailureGroup,
@@ -43,6 +44,7 @@ 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.current_branch_health import query_current_branch_health
from products.engineering_analytics.backend.logic.queries.flaky_tests import query_flaky_tests
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
@@ -332,6 +334,12 @@ def build_repo_overview(
return query_repo_overview(curated=curated, date_from=parsed_from, date_to=parsed_to)
+def build_current_branch_health(*, curated: CuratedGitHubSource) -> CurrentBranchHealth:
+ date_from, date_to = _parse_window(curated.team, None, None, default=_DEFAULT_WORKFLOW_WINDOW)
+ branch = query_default_branch(curated=curated, date_from=date_from, date_to=date_to)
+ return query_current_branch_health(curated=curated, date_from=date_from, branch=branch)
+
+
def build_repo_run_activity(
*,
curated: CuratedGitHubSource,
diff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
index 70b98293b2d6..33b2663916ae 100644
--- a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
@@ -15,6 +15,14 @@ from products.engineering_analytics.backend.facade.contracts import WorkflowHeal
# answers "how long until CI stopped", not "how long does CI take to pass".
DURATION_PERCENTILE_CONDITION = "status = 'completed' AND conclusion = 'success'"
+# The one "failing right now" signal, per workflow: did the latest completed run fail?
+# Ordered by (run_started_at, id) so a same-second tie resolves deterministically to the
+# later-created run. argMaxIf defaults to 0 (false) over zero matching rows, so consumers must
+# pair it with a completed-run count to tell "latest run passed" apart from "no completed run yet".
+LATEST_COMPLETED_RUN_FAILED = (
+ "argMaxIf(conclusion IN ('failure', 'timed_out'), (run_started_at, id), status = 'completed')"
+)
+
def branch_filter_clause(
branch: str | None, placeholders: dict[str, ast.Expr], *, column: str = "r.head_branch"
diff --git a/products/engineering_analytics/backend/logic/queries/current_branch_health.py b/products/engineering_analytics/backend/logic/queries/current_branch_health.py
new file mode 100644
index 000000000000..3838f5c77e02
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/current_branch_health.py
@@ -0,0 +1,52 @@
+"""Current default-branch CI verdict over the fixed recent-health window."""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.facade.contracts import CurrentBranchHealth
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._workflow_filters import LATEST_COMPLETED_RUN_FAILED
+
+_FAILING_NAME_LIMIT = 20
+
+_SELECT = f"""
+ SELECT
+ workflow_name,
+ countIf(status = 'completed') AS completed_count,
+ {LATEST_COMPLETED_RUN_FAILED} AS latest_failed
+ FROM __RUNS_SOURCE__ AS r
+ WHERE run_started_at >= {{date_from}} AND head_branch = {{branch}}
+ GROUP BY workflow_name
+"""
+
+
+def query_current_branch_health(
+ *, curated: CuratedGitHubSource, date_from: datetime, branch: str
+) -> CurrentBranchHealth:
+ response = curated.run(
+ _SELECT.replace("__RUNS_SOURCE__", curated.run_source()),
+ query_type="engineering_analytics.current_branch_health",
+ placeholders={
+ "date_from": ast.Constant(value=date_from),
+ "branch": ast.Constant(value=branch),
+ },
+ )
+
+ settled_workflows = 0
+ failing_workflow_names: list[str] = []
+ for workflow_name, completed_count, latest_failed in response.results or []:
+ # Nothing completed yet: not settled, and LATEST_COMPLETED_RUN_FAILED's 0 default would read as passing.
+ if not completed_count:
+ continue
+ settled_workflows += 1
+ if latest_failed:
+ failing_workflow_names.append(workflow_name)
+
+ failing_workflow_names.sort()
+ return CurrentBranchHealth(
+ default_branch=branch,
+ settled_workflows=settled_workflows,
+ failing_workflows=len(failing_workflow_names),
+ failing_workflow_names=failing_workflow_names[:_FAILING_NAME_LIMIT],
+ )
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.py
index 7e5a847d1894..86b3bd79f6d4 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py
@@ -33,6 +33,7 @@ from products.engineering_analytics.backend.logic.queries._buckets import (
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float
from products.engineering_analytics.backend.logic.queries._workflow_filters import (
DURATION_PERCENTILE_CONDITION,
+ LATEST_COMPLETED_RUN_FAILED,
branch_filter_clause,
date_to_filter_clause,
run_scope_filter_clause,
@@ -54,8 +55,8 @@ _SELECT = f"""
quantileIf(0.95)(duration_seconds, {DURATION_PERCENTILE_CONDITION}) AS p95_seconds,
max(if(conclusion IN ('failure', 'timed_out'), run_started_at, NULL)) AS last_failure_at,
countIf(status = 'completed') AS completed_count,
- argMaxIf(conclusion IN ('failure', 'timed_out'), run_started_at, status = 'completed') AS latest_failed,
- argMaxIf(conclusion, run_started_at, status = 'completed') AS latest_conclusion,
+ {LATEST_COMPLETED_RUN_FAILED} AS latest_failed,
+ argMaxIf(conclusion, (run_started_at, id), 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__ __RUN_SCOPE__
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index 3db04493f96a..3dce2e3bf547 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,
CostPerMergeBucket,
+ CurrentBranchHealth,
FlakyTestItem,
FlakyTestList,
GitHubSource,
@@ -881,6 +882,24 @@ class RepoOverviewSerializer(DataclassSerializer):
}
+class CurrentBranchHealthSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = CurrentBranchHealth
+ extra_kwargs = {
+ "default_branch": {
+ "help_text": "Detected default branch ('master' or 'main') from runs in the same 24-hour window."
+ },
+ "settled_workflows": {"help_text": "Workflows with at least one completed run in the last 24 hours."},
+ "failing_workflows": {
+ "help_text": "Workflows whose latest completed run in the last 24 hours failed or timed out."
+ },
+ "failing_workflow_names": {
+ "help_text": "Alphabetical preview of failing workflow names, capped at 20; use failing_workflows "
+ "for the complete count."
+ },
+ }
+
+
class MasterFailureGroupSerializer(DataclassSerializer):
repo = RepoRefSerializer(help_text="Repository the failures occurred in.")
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index b2bd8deec4e6..e36cd496c1df 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -7,6 +7,7 @@ contract. These same endpoints back both the MCP tools and the UI:
- ``ci_cards`` — backlog headline counts.
- ``pull_requests`` — PR list with head-SHA CI rollup.
- ``workflow_health`` — per-workflow CI health over a window.
+- ``current_branch_health`` — complete current default-branch CI verdict.
- ``pr_lifecycle`` — a single PR's header plus its ordered CI timeline.
- ``quarantine`` — the repo's checked-in flaky-test quarantine file.
"""
@@ -33,6 +34,7 @@ from products.engineering_analytics.backend.facade.contracts import (
from products.engineering_analytics.backend.presentation.serializers import (
CICardSummarySerializer,
CIFailureLogsSerializer,
+ CurrentBranchHealthSerializer,
FlakyTestListSerializer,
GitHubSourceSerializer,
MasterFailureGroupSerializer,
@@ -164,6 +166,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"flaky_tests",
"repo_overview",
"repo_run_activity",
+ "current_branch_health",
"master_failures",
"run_failure_logs",
"job_aggregates",
@@ -868,6 +871,31 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
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_current_branch_health",
+ parameters=[_SOURCE_ID],
+ responses={
+ 200: CurrentBranchHealthSerializer,
+ 400: OpenApiResponse(description="Invalid source_id."),
+ },
+ description=(
+ "Current default-branch CI verdict over the fixed last-24-hours window. Counts every workflow whose "
+ "latest completed run failed or timed out; failing workflow names are a bounded preview. The default "
+ "branch is detected from the same window, independently of analytics date filters."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def current_branch_health(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_current_branch_health(
+ team=self.team,
+ 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(CurrentBranchHealthSerializer(instance=result).data)
+
@extend_schema(
operation_id="engineering_analytics_repo_run_activity",
parameters=[
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index 64130401fc58..2695c35ad303 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -358,6 +358,26 @@ class TestEndpointMapping(BaseTest):
assert result.limit == 2
assert len(result.items) == 2
+ def test_current_branch_health_counts_every_workflow(self) -> None:
+ workflow_rows = [(f"Workflow {index}", 1, 0) for index in range(100)]
+ workflow_rows.extend((f"Low-volume failure {index:02d}", 1, 1) for index in range(21))
+ workflow_rows.append(("Still running", 0, 0))
+
+ def run(sql: str, *, query_type: str, **kwargs) -> SimpleNamespace:
+ if query_type == "engineering_analytics.default_branch":
+ return _resp([(0, 12)])
+ assert query_type == "engineering_analytics.current_branch_health"
+ assert "LIMIT" not in sql.upper()
+ return _resp(workflow_rows)
+
+ with mock.patch(_RUN_QUERY, side_effect=run):
+ health = api.get_current_branch_health(team=self.team)
+
+ assert health.default_branch == "main"
+ assert health.settled_workflows == 121
+ assert health.failing_workflows == 21
+ assert health.failing_workflow_names == [f"Low-volume failure {index:02d}" for index in range(20)]
+
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, rerun_cycles.
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 3da7127e8482..ea9565ddd13f 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -36,6 +36,15 @@ def _cards() -> contracts.CICardSummary:
return contracts.CICardSummary(open_prs=5, repos=2, stuck=1, failing_ci=1)
+def _current_branch_health() -> contracts.CurrentBranchHealth:
+ return contracts.CurrentBranchHealth(
+ default_branch="main",
+ settled_workflows=101,
+ failing_workflows=1,
+ failing_workflow_names=["Low-volume failure"],
+ )
+
+
def _pr_list_item() -> contracts.PullRequestListItem:
return contracts.PullRequestListItem(
number=10,
@@ -202,6 +211,18 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert list_health.call_args.kwargs["branch"] == "main"
assert list_health.call_args.kwargs["run_scope"] == "pull_request"
+ def test_current_branch_health_serializes(self) -> None:
+ with mock.patch(f"{_VIEWS}.get_current_branch_health", return_value=_current_branch_health()):
+ response = self.client.get(self._url("current_branch_health"))
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {
+ "default_branch": "main",
+ "settled_workflows": 101,
+ "failing_workflows": 1,
+ "failing_workflow_names": ["Low-volume failure"],
+ }
+
def test_repo_run_activity_serializes_and_forwards_branch(self) -> None:
result = contracts.WorkflowRunActivity(
points=[
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 84cf902ec675..d9177f2bb45a 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -89,6 +89,17 @@ export interface CIFailureLogsApi {
truncated: boolean
}
+export interface CurrentBranchHealthApi {
+ /** Detected default branch ('master' or 'main') from runs in the same 24-hour window. */
+ default_branch: string
+ /** Workflows with at least one completed run in the last 24 hours. */
+ settled_workflows: number
+ /** Workflows whose latest completed run in the last 24 hours failed or timed out. */
+ failing_workflows: number
+ /** Alphabetical preview of failing workflow names, capped at 20; use failing_workflows for the complete count. */
+ failing_workflow_names: string[]
+}
+
export interface FlakyTestItemApi {
/** Reconstructed pytest nodeid (the CI span name), e.g. 'posthog/api/test/test_event/TestEvents::test_x'. A stable grouping key, not a runnable selector — use `selector` to run or quarantine the test. */
nodeid: string
@@ -960,6 +971,13 @@ export type EngineeringAnalyticsCiFailureLogsParams = {
source_id?: string
}
+export type EngineeringAnalyticsCurrentBranchHealthParams = {
+ /**
+ * 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 EngineeringAnalyticsFlakyTestsParams = {
/**
* Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window may span at most 30 days.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 0cc2361c9510..fbc0bde03133 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -11,9 +11,11 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
CICardSummaryApi,
CIFailureLogsApi,
+ CurrentBranchHealthApi,
EngineeringAnalyticsAuthorWorkflowCostsParams,
EngineeringAnalyticsCiCardsParams,
EngineeringAnalyticsCiFailureLogsParams,
+ EngineeringAnalyticsCurrentBranchHealthParams,
EngineeringAnalyticsFlakyTestsParams,
EngineeringAnalyticsJobAggregatesParams,
EngineeringAnalyticsMasterFailuresParams,
@@ -147,6 +149,39 @@ export const engineeringAnalyticsCiFailureLogs = async (
})
}
+export const getEngineeringAnalyticsCurrentBranchHealthUrl = (
+ projectId: string,
+ params?: EngineeringAnalyticsCurrentBranchHealthParams
+) => {
+ 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/current_branch_health/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/current_branch_health/`
+}
+
+/**
+ * Current default-branch CI verdict over the fixed last-24-hours window. Counts every workflow whose latest completed run failed or timed out; failing workflow names are a bounded preview. The default branch is detected from the same window, independently of analytics date filters.
+ */
+export const engineeringAnalyticsCurrentBranchHealth = async (
+ projectId: string,
+ params?: EngineeringAnalyticsCurrentBranchHealthParams,
+ options?: RequestInit
+): Promise<CurrentBranchHealthApi> => {
+ return apiMutator<CurrentBranchHealthApi>(getEngineeringAnalyticsCurrentBranchHealthUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsFlakyTestsUrl = (
projectId: string,
params?: EngineeringAnalyticsFlakyTestsParams
diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx
index 71a6b5b74868..8fdc7f74a5e2 100644
--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx
+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx
@@ -8,6 +8,7 @@ import { mswDecorator } from '~/mocks/browser'
import type {
GitHubSourceApi,
+ MasterFailureGroupApi,
PullRequestListApi,
RepoOverviewApi,
WorkflowHealthItemApi,
@@ -110,6 +111,20 @@ const WORKFLOW_HEALTH: WorkflowHealthItemApi[] = [
healthItem('Frontend CI', 71.9, [0, 1, 0, 0, 2, 0, 1], 0.95),
]
+// The latest run recovered, but the 24-hour failure feed still includes the earlier failure. The hero
+// must stay green while the triage section preserves that history.
+const RECENT_FAILURES: MasterFailureGroupApi[] = [
+ {
+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },
+ workflow_name: 'Backend CI',
+ failed_job: 'Backend tests',
+ run_count: 1,
+ first_seen: '2026-07-01T12:00:00Z',
+ last_seen: '2026-07-01T12:00:00Z',
+ latest_run_id: 8999,
+ },
+]
+
const PULL_REQUESTS: PullRequestListApi = {
items: [
{
@@ -215,7 +230,13 @@ const meta: Meta = {
get: {
'api/projects/:team_id/engineering_analytics/sources/': SOURCES,
'api/projects/:team_id/engineering_analytics/repo_overview/': OVERVIEW,
- 'api/projects/:team_id/engineering_analytics/master_failures/': [],
+ 'api/projects/:team_id/engineering_analytics/current_branch_health/': {
+ default_branch: 'master',
+ settled_workflows: WORKFLOW_HEALTH.length,
+ failing_workflows: 0,
+ failing_workflow_names: [],
+ },
+ 'api/projects/:team_id/engineering_analytics/master_failures/': RECENT_FAILURES,
'api/projects/:team_id/engineering_analytics/repo_run_activity/': ACTIVITY,
'api/projects/:team_id/engineering_analytics/ci_cards/': {
open_prs: 18,
@@ -237,3 +258,21 @@ export const RepoOverview: Story = {
render: () => <App />,
parameters: { pageUrl: urls.engineeringAnalytics() },
}
+
+// The red verdict: failing workflows drive the danger styling, the names subline, and the jump link.
+export const RepoOverviewFailing: Story = {
+ render: () => <App />,
+ parameters: { pageUrl: urls.engineeringAnalytics() },
+ decorators: [
+ mswDecorator({
+ get: {
+ 'api/projects/:team_id/engineering_analytics/current_branch_health/': {
+ default_branch: 'master',
+ settled_workflows: WORKFLOW_HEALTH.length,
+ failing_workflows: 2,
+ failing_workflow_names: ['Backend CI', 'E2E - Playwright'],
+ },
+ },
+ }),
+ ],
+}
diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
index 9c54fd2ec6fe..06b79622a4d2 100644
--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
@@ -39,23 +39,34 @@ function withSource(url: string, sourceId: string | null): string {
/** The page's thesis: is the pipeline healthy right now? Default-branch verdict plus open-PR backlog
* pressure, both current-state, so it sits above the date filter that scopes everything below. */
function PipelineVerdictHero({
- failingCount,
- failingWorkflows,
+ summary,
loading,
+ failed,
defaultBranch,
backlog,
}: {
- failingCount: number
- failingWorkflows: string[]
+ summary: { settledWorkflows: number; failingNow: number; failingWorkflowNames: string[] }
loading: boolean
+ failed: boolean
defaultBranch: string
backlog: { open: number | null; failingCi: number | null; stuck: number | null }
}): JSX.Element {
- const failing = failingCount > 0
- const dotColor = loading ? 'var(--muted)' : failing ? 'var(--danger)' : 'var(--success)'
- const status = loading ? 'Checking' : failing ? `${failingCount} failing` : 'Passing'
+ const failingCount = summary.failingNow
+ const failing = !loading && !failed && summary.settledWorkflows > 0 && failingCount > 0
+ const unknown = failed || summary.settledWorkflows === 0
+ const dotColor = loading || unknown ? 'var(--muted)' : failing ? 'var(--danger)' : 'var(--success)'
+ const status = loading
+ ? 'Checking'
+ : failed
+ ? 'Unavailable'
+ : summary.settledWorkflows === 0
+ ? 'No completed runs'
+ : failing
+ ? `${failingCount} failing`
+ : 'Passing'
// Only the failing state earns a subline (which workflows broke). "Passing" already says the rest.
- const failingNames = failingWorkflows.slice(0, 3).join(', ') + (failingCount > 3 ? ` +${failingCount - 3}` : '')
+ const failingNames =
+ summary.failingWorkflowNames.slice(0, 3).join(', ') + (failingCount > 3 ? ` +${failingCount - 3}` : '')
return (
<LemonCard
hoverEffect={failing}
@@ -66,7 +77,7 @@ function PipelineVerdictHero({
)}
>
<div className="flex min-w-0 flex-col gap-1.5">
- <Tooltip title="Default-branch workflow runs failing in the last 24 hours.">
+ <Tooltip title="Default-branch workflows whose latest completed run failed in the last 24 hours.">
<span className="w-fit cursor-default font-mono text-xs text-tertiary">{defaultBranch}</span>
</Tooltip>
<span className="flex items-baseline gap-2.5">
@@ -78,7 +89,7 @@ function PipelineVerdictHero({
<span
className={cn(
'text-3xl font-bold leading-none tracking-tight',
- loading ? 'text-tertiary' : failing ? 'text-danger' : 'text-primary'
+ loading || unknown ? 'text-tertiary' : failing ? 'text-danger' : 'text-primary'
)}
>
{status}
@@ -97,13 +108,13 @@ function PipelineVerdictHero({
}
function MasterFailuresSection(): JSX.Element {
- const { masterFailures, masterFailuresLoading, failureLogs, failureLogsLoading, defaultBranch } =
+ const { masterFailures, masterFailuresLoading, failureLogs, failureLogsLoading, currentDefaultBranch } =
useValues(repoOverviewLogic)
const { loadLogsForRun } = useActions(repoOverviewLogic)
const { sourceId } = useValues(engineeringAnalyticsLogic)
return (
- <Section id="now" title={`Failing on ${defaultBranch}`} note="Last 24 hours">
+ <Section id="now" title={`Failing on ${currentDefaultBranch}`} note="Last 24 hours">
<LemonCard hoverEffect={false} className="overflow-hidden p-0">
<LemonTable<MasterFailureGroupApi>
dataSource={masterFailures}
@@ -206,7 +217,7 @@ function MasterFailuresSection(): JSX.Element {
),
},
]}
- emptyState={`Nothing failing on ${defaultBranch} in the last 24 hours.`}
+ emptyState={`Nothing failing on ${currentDefaultBranch} in the last 24 hours.`}
nouns={['failure group', 'failure groups']}
/>
<div className="border-t border-primary px-4 py-2 text-[11px] text-tertiary">
@@ -230,20 +241,27 @@ export function RepoOverviewScene(): JSX.Element {
passRateSeries,
openToMergeSeries,
jobsAvailable,
- defaultBranch,
+ overviewDefaultBranch,
+ currentDefaultBranch,
notConnected,
overviewFailed,
overviewLoading,
- failingWorkflowCount,
- masterFailures,
- masterFailuresLoading,
+ currentHealthSummary,
+ currentBranchHealthFailed,
+ currentBranchHealthLoading,
prPreviewCount,
workflowPreviewCount,
} = useValues(repoOverviewLogic)
const { cards, pullRequestsLoading, workflowHealth, workflowHealthLoading, sourceId, activeSource } =
useValues(engineeringAnalyticsLogic)
- const { loadOverview, loadMasterFailures, loadRepoActivity, showMorePrs, showMoreWorkflows } =
- useActions(repoOverviewLogic)
+ const {
+ loadOverview,
+ loadCurrentBranchHealth,
+ loadMasterFailures,
+ loadRepoActivity,
+ showMorePrs,
+ showMoreWorkflows,
+ } = useActions(repoOverviewLogic)
const { searchParams } = useValues(router)
const { timezone } = useValues(teamLogic)
const chartTheme = useChartTheme()
@@ -256,8 +274,6 @@ export function RepoOverviewScene(): JSX.Element {
// The hub previews each table: a short, sorted slice with "Show more" to grow in place, and "View all"
// to the dedicated full table. Workflows are ranked by cost (or run count) to pick the top few; the
// table then displays them failing-first-then-name. attentionPrs is already ordered failing-first.
- // Distinct workflow names failing on the default branch — the hero's "what's broken" subline.
- const failingWorkflows = Array.from(new Set(masterFailures.map((group) => group.workflow_name)))
const shownPrs = attentionPrs.slice(0, prPreviewCount)
const canShowMorePrs = shownPrs.length < attentionPrs.length && prPreviewCount < HUB_PREVIEW_MAX
// Rank the leaderboard by spend when cost is known (where the money goes), else by run volume.
@@ -279,6 +295,7 @@ export function RepoOverviewScene(): JSX.Element {
<CIAnalyticsLoadError
onRetry={() => {
loadOverview()
+ loadCurrentBranchHealth()
loadMasterFailures()
loadRepoActivity()
}}
@@ -294,10 +311,10 @@ export function RepoOverviewScene(): JSX.Element {
{/* The thesis: is the pipeline healthy right now? Current-state, above the date filter. */}
<PipelineVerdictHero
- failingCount={failingWorkflowCount}
- failingWorkflows={failingWorkflows}
- loading={masterFailuresLoading}
- defaultBranch={defaultBranch}
+ summary={currentHealthSummary}
+ loading={currentBranchHealthLoading}
+ failed={currentBranchHealthFailed}
+ defaultBranch={currentDefaultBranch}
backlog={{
open: cards?.openPrs ?? null,
failingCi: cards?.failingCi ?? null,
@@ -428,7 +445,7 @@ export function RepoOverviewScene(): JSX.Element {
<Section
id="master"
- title={`${defaultBranch === 'main' ? 'Main' : 'Master'} health`}
+ title={`${overviewDefaultBranch === 'main' ? 'Main' : 'Master'} health`}
busy={repoActivityLoading}
>
{/* Hub preview: one bar per default-branch commit, height = CI duration, color = verdict — the
@@ -455,8 +472,8 @@ export function RepoOverviewScene(): JSX.Element {
{repoActivityLoading
? 'Loading…'
: repoActivityFailed
- ? `Couldn't load ${defaultBranch} activity. Refresh to retry.`
- : `Not enough completed runs on ${defaultBranch} in the window to chart yet.`}
+ ? `Couldn't load ${overviewDefaultBranch} activity. Refresh to retry.`
+ : `Not enough completed runs on ${overviewDefaultBranch} in the window to chart yet.`}
</LemonCard>
)}
</Section>
diff --git a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
index 82cf5f912351..3d1a0accc228 100644
--- a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
@@ -6,12 +6,14 @@ import { dayjs } from 'lib/dayjs'
import type { ActivityRun } from '../components/RunActivityChart'
import {
+ engineeringAnalyticsCurrentBranchHealth,
engineeringAnalyticsMasterFailures,
engineeringAnalyticsRepoOverview,
engineeringAnalyticsRepoRunActivity,
engineeringAnalyticsRunFailureLogs,
} from '../generated/api'
import type {
+ CurrentBranchHealthApi,
MasterFailureGroupApi,
RepoOverviewApi,
RunFailureLogsApi,
@@ -36,6 +38,12 @@ export interface CostShareRow {
share: number
}
+export interface CurrentHealthSummary {
+ settledWorkflows: number
+ failingNow: number
+ failingWorkflowNames: string[]
+}
+
export const repoOverviewLogic = kea<repoOverviewLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'repoOverviewLogic']),
@@ -84,6 +92,18 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
}),
},
],
+ currentBranchHealth: [
+ null as CurrentBranchHealthApi | null,
+ {
+ loadCurrentBranchHealth: async (_: void, breakpoint): Promise<CurrentBranchHealthApi> => {
+ const health = await engineeringAnalyticsCurrentBranchHealth(projectId(), {
+ source_id: values.sourceId ?? undefined,
+ })
+ breakpoint()
+ return health
+ },
+ },
+ ],
// One collapsed point per default-branch commit (all its workflows folded together) for the
// master-health scatter — the backend owns the collapse, so the UI just plots the points.
repoActivity: [
@@ -140,6 +160,14 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
loadRepoActivityFailure: () => true,
},
],
+ currentBranchHealthFailed: [
+ false,
+ {
+ loadCurrentBranchHealth: () => false,
+ loadCurrentBranchHealthSuccess: () => false,
+ loadCurrentBranchHealthFailure: () => true,
+ },
+ ],
// How many rows the hub's preview tables show. Start short (HUB_PREVIEW_ROWS), grow by a fixed
// step on "Show more", capped so the hub stays a preview — the full tables live on the dedicated
// pages. No reset on reload: slicing tolerates any list length, and keeping the user's expansion
@@ -156,10 +184,19 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
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,
+ overviewDefaultBranch: [(s) => [s.overview], (overview): string => overview?.default_branch ?? 'master'],
+ currentDefaultBranch: [
+ (s) => [s.currentBranchHealth, s.overviewDefaultBranch],
+ (currentBranchHealth, overviewDefaultBranch): string =>
+ currentBranchHealth?.default_branch ?? overviewDefaultBranch,
+ ],
+ currentHealthSummary: [
+ (s) => [s.currentBranchHealth],
+ (currentBranchHealth): CurrentHealthSummary => ({
+ settledWorkflows: currentBranchHealth?.settled_workflows ?? 0,
+ failingNow: currentBranchHealth?.failing_workflows ?? 0,
+ failingWorkflowNames: currentBranchHealth?.failing_workflow_names ?? [],
+ }),
],
// Backend-collapsed commit points, mapped to the shared chart shape (one dot per default-branch
// commit: start time, wall-clock CI duration, overall verdict).
@@ -331,11 +368,13 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
},
[engineeringAnalyticsLogic.actionTypes.setSourceId]: () => {
actions.loadOverview()
+ actions.loadCurrentBranchHealth()
actions.loadMasterFailures()
actions.loadRepoActivity()
},
[engineeringAnalyticsLogic.actionTypes.refresh]: () => {
actions.loadOverview()
+ actions.loadCurrentBranchHealth()
actions.loadMasterFailures()
actions.loadRepoActivity()
},
@@ -343,6 +382,7 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
afterMount(({ actions }) => {
actions.loadOverview()
+ actions.loadCurrentBranchHealth()
actions.loadMasterFailures()
actions.loadRepoActivity()
}),
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index c5c1f055e464..0f0a0680034c 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -35,6 +35,9 @@ tools:
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.
feature_flag: engineering-analytics
+ engineering-analytics-current-branch-health:
+ operation: engineering_analytics_current_branch_health
+ enabled: false
engineering-analytics-flaky-tests:
operation: engineering_analytics_flaky_tests
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f05fb77a1943..f084ea402e62 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14712,6 +14712,17 @@ export namespace Schemas {
access_secret: string;
}
+ export interface CurrentBranchHealth {
+ /** Detected default branch ('master' or 'main') from runs in the same 24-hour window. */
+ default_branch: string;
+ /** Workflows with at least one completed run in the last 24 hours. */
+ settled_workflows: number;
+ /** Workflows whose latest completed run in the last 24 hours failed or timed out. */
+ failing_workflows: number;
+ /** Alphabetical preview of failing workflow names, capped at 20; use failing_workflows for the complete count. */
+ failing_workflow_names: string[];
+ }
+
export interface CurrentMapping {
/** A utm_source value already mapped to an integration */
raw_utm_source: string;
@@ -68373,6 +68384,13 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsCurrentBranchHealthParams = {
+ /**
+ * 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 EngineeringAnalyticsFlakyTestsParams = {
/**
* Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window may span at most 30 days.