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): serve workflow tiles from the window (#95099)

Raúl Negrón-Otero755364fe9845
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 58d39f28085e..1682c9cb731f 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -396,6 +396,7 @@ def list_workflow_health(
date_to: str | None = None,
branch: str | None = None,
run_scope: str | None = None,
+ workflow_name: str | None = None,
source_id: str | None = None,
repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
@@ -406,6 +407,7 @@ def list_workflow_health(
date_to=date_to,
branch=branch,
run_scope=run_scope,
+ workflow_name=workflow_name,
)
diff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
index 01700aa4e003..f2829664c07b 100644
--- a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py
@@ -156,6 +156,16 @@ def branch_filter_clause(
return f"AND {column} = {{branch}}"
+def workflow_name_filter_clause(
+ workflow_name: str | None, placeholders: dict[str, ast.Expr], *, column: str = "r.workflow_name"
+) -> str:
+ """The name binds unmodified so it matches the other workflow endpoints."""
+ if not (workflow_name or "").strip():
+ return ""
+ placeholders["workflow_name"] = ast.Constant(value=workflow_name)
+ return f"AND {column} = {{workflow_name}}"
+
+
def date_to_filter_clause(
date_to: datetime | None, placeholders: dict[str, ast.Expr], *, column: str = "r.run_started_at"
) -> str:
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.py
index e06f215680c7..0195e4bfadd8 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py
@@ -53,6 +53,7 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impo
run_started_floor_constant,
success_rate_expr,
window_pair_predicates,
+ workflow_name_filter_clause,
)
from products.engineering_analytics.backend.logic.queries.pr_cost import query_workflow_window_costs
@@ -81,7 +82,7 @@ _SELECT = f"""
countIf(run_attempt > 1) AS rerun_cycles,
countIf(is_merge_queue) AS merge_queue_run_count
FROM __RUNS_SOURCE__ AS r
- WHERE run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__ __RUN_SCOPE__
+ WHERE run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__ __RUN_SCOPE__ __WORKFLOW__
GROUP BY repo_owner, repo_name, workflow_name
ORDER BY run_count DESC
LIMIT {_LIMIT}
@@ -98,7 +99,7 @@ _PREV_SELECT = f"""
workflow_name,
{success_rate_expr()} AS success_rate
FROM __RUNS_SOURCE__ AS r
- WHERE run_started_at >= {{prev_from}} AND run_started_at < {{date_from}} __BRANCH__ __RUN_SCOPE__
+ WHERE run_started_at >= {{prev_from}} AND run_started_at < {{date_from}} __BRANCH__ __RUN_SCOPE__ __WORKFLOW__
GROUP BY repo_owner, repo_name, workflow_name
LIMIT {UNPAGED_SCAN_LIMIT}
"""
@@ -132,7 +133,7 @@ _BUCKET_SELECT = f"""
countIf({SUCCESSFUL_RUN_CONDITION}) AS successes,
countIf(status = 'completed' AND conclusion IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})) AS failures
FROM __RUNS_SOURCE__ AS r
- WHERE run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__ __RUN_SCOPE__
+ WHERE run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__ __RUN_SCOPE__ __WORKFLOW__
GROUP BY repo_owner, repo_name, workflow_name, bucket_start
LIMIT {_BUCKET_LIMIT}
"""
@@ -288,6 +289,7 @@ def query_workflow_health(
date_to: datetime | None,
branch: str | None,
run_scope: WorkflowHealthRunScope,
+ workflow_name: str | None = None,
workload: Workload = Workload.DEFAULT,
) -> list[WorkflowHealthItem]:
granularity = pick_granularity(date_from, date_to)
@@ -298,6 +300,7 @@ def query_workflow_health(
date_to_clause = date_to_filter_clause(date_to, placeholders)
branch_clause = branch_filter_clause(branch, placeholders)
run_scope_clause = run_scope_filter_clause(run_scope)
+ workflow_clause = workflow_name_filter_clause(workflow_name, placeholders)
runs_source = curated.run_source(started_floor=True)
@@ -307,6 +310,7 @@ def query_workflow_health(
.replace("__DATE_TO__", date_to_clause)
.replace("__BRANCH__", branch_clause)
.replace("__RUN_SCOPE__", run_scope_clause)
+ .replace("__WORKFLOW__", workflow_clause)
.replace("__BUCKET_FN__", bucket_expr(granularity))
)
diff --git a/products/engineering_analytics/backend/logic/workflows.py b/products/engineering_analytics/backend/logic/workflows.py
index 46a1cc14f271..8ba505b358e5 100644
--- a/products/engineering_analytics/backend/logic/workflows.py
+++ b/products/engineering_analytics/backend/logic/workflows.py
@@ -140,6 +140,7 @@ def build_workflow_health(
date_to: str | None = None,
branch: str | None = None,
run_scope: str | None = None,
+ workflow_name: str | None = None,
) -> list[WorkflowHealthItem]:
parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WORKFLOW_WINDOW)
return query_workflow_health(
@@ -148,6 +149,7 @@ def build_workflow_health(
date_to=parsed_to,
branch=branch,
run_scope=_parse_run_scope(run_scope),
+ workflow_name=workflow_name,
)
diff --git a/products/engineering_analytics/backend/presentation/views/_base.py b/products/engineering_analytics/backend/presentation/views/_base.py
index 30106bee9eb6..ce1a512d0708 100644
--- a/products/engineering_analytics/backend/presentation/views/_base.py
+++ b/products/engineering_analytics/backend/presentation/views/_base.py
@@ -71,6 +71,15 @@ _RUN_SCOPE = OpenApiParameter(
"attribution (a GitHub limitation), so they appear only under 'all'. Any other value is a 400.",
)
+_WORKFLOW_NAME = OpenApiParameter(
+ name="workflow_name",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional exact workflow name to scope results to, e.g. 'Backend CI'. Omit to rank every "
+ "workflow. Pass it when you want one workflow's figures over the whole window rather than the top slice.",
+)
+
_SOURCE_ID = OpenApiParameter(
name="source_id",
type=OpenApiTypes.UUID,
diff --git a/products/engineering_analytics/backend/presentation/views/workflows.py b/products/engineering_analytics/backend/presentation/views/workflows.py
index 69095f79a9df..095cbaca4ce8 100644
--- a/products/engineering_analytics/backend/presentation/views/workflows.py
+++ b/products/engineering_analytics/backend/presentation/views/workflows.py
@@ -28,6 +28,7 @@ from products.engineering_analytics.backend.presentation.views._base import (
_RUN_SCOPE,
_SOURCE_ID,
_WORKFLOW_DATE_FROM,
+ _WORKFLOW_NAME,
EngineeringAnalyticsViewSetBase,
_bad_request,
_bool_param,
@@ -54,7 +55,7 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):
@extend_schema(
operation_id="engineering_analytics_workflow_health",
- parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _RUN_SCOPE, _SOURCE_ID, _REPO],
+ parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _RUN_SCOPE, _WORKFLOW_NAME, _SOURCE_ID, _REPO],
responses={
200: WorkflowHealthItemSerializer(many=True),
400: OpenApiResponse(
@@ -67,7 +68,8 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):
"by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive "
"failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over "
"successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. "
- "Optionally scope to a single git branch via `branch`, or to one run group via `run_scope` "
+ "Optionally scope to a single git branch via `branch`, to one workflow via `workflow_name`, "
+ "or to one run group via `run_scope` "
"(default_branch, pull_request, merge_queue). Use this for 'is CI getting slower' "
"and 'which workflow is the long pole'; compare two windows to get a trend."
),
@@ -81,6 +83,7 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):
date_to=request.query_params.get("date_to") or None,
branch=request.query_params.get("branch") or None,
run_scope=request.query_params.get("run_scope") or None,
+ workflow_name=request.query_params.get("workflow_name") or None,
source_id=request.query_params.get("source_id") or None,
repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
diff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.py
index ece9e3ee303a..819c2127bf7e 100644
--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py
+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py
@@ -627,6 +627,11 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
assert ci.last_failure_at is not None
assert ci.billable_minutes is None # no jobs source seeded → no cost figure
+ assert len(items) > 1
+ scoped = api.list_workflow_health(team=self.team, date_from="-30d", workflow_name="CI")
+ assert [item.workflow_name for item in scoped] == ["CI"]
+ assert scoped[0].run_count == ci.run_count
+
def test_workflow_health_prev_window_survives_raw_scan_floor(self) -> None:
# The prev-window query's raw-string scan floor must come from prev_from, not date_from.
# A run in [prev_from, date_from) sits below the date_from floor; if that floor leaked into
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 87f9d6e24cd0..ce8f1c72637c 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -2485,6 +2485,10 @@ export type EngineeringAnalyticsWorkflowHealthParams = {
* 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
+ /**
+ * Optional exact workflow name to scope results to, e.g. 'Backend CI'. Omit to rank every workflow. Pass it when you want one workflow's figures over the whole window rather than the top slice.
+ */
+ workflow_name?: string
}
export type EngineeringAnalyticsWorkflowHealthRunScope =
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 91bf9808ec52..cb052076636c 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -959,7 +959,7 @@ export const getEngineeringAnalyticsWorkflowHealthUrl = (
}
/**
- * Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, or to one run group via `run_scope` (default_branch, pull_request, merge_queue). Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.
+ * Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, to one workflow via `workflow_name`, or to one run group via `run_scope` (default_branch, pull_request, merge_queue). Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.
*/
export const engineeringAnalyticsWorkflowHealth = async (
projectId: string,
diff --git a/products/engineering_analytics/frontend/lib/runHealth.test.ts b/products/engineering_analytics/frontend/lib/runHealth.test.ts
index 913396610d7c..00c0ebc7db5f 100644
--- a/products/engineering_analytics/frontend/lib/runHealth.test.ts
+++ b/products/engineering_analytics/frontend/lib/runHealth.test.ts
@@ -52,7 +52,6 @@ describe('runHealth', () => {
{ conclusion: 'neutral', durationSeconds: 600, startedAt: at(13) },
{ conclusion: 'future_outcome', durationSeconds: 600, startedAt: at(14) },
])
- expect(summary.completedRuns).toBe(6)
expect(summary.conclusiveRuns).toBe(1)
expect(summary.passedRuns).toBe(1)
expect(summary.passRate).toBe(1)
@@ -77,8 +76,6 @@ describe('runHealth', () => {
{ conclusion: 'failure', durationSeconds: 240, startedAt: at(10), runAttempt: 2 },
{ conclusion: null, durationSeconds: null, startedAt: at(11), runAttempt: 1 },
])
- expect(summary.completedRuns).toBe(2)
- expect(summary.running).toBe(1)
expect(summary.passRate).toBe(0.5)
expect(summary.failures).toBe(1)
expect(summary.reruns).toBe(1)
@@ -111,7 +108,6 @@ describe('runHealth', () => {
expect(summary.medianSeconds).toBe(600)
expect(summary.p95Seconds).toBe(900)
expect(summary.totalRuns).toBe(5)
- expect(summary.completedRuns).toBe(5)
expect(summary.passRate).toBe(1)
})
diff --git a/products/engineering_analytics/frontend/lib/runHealth.ts b/products/engineering_analytics/frontend/lib/runHealth.ts
index 6e37ec7cf05e..687b4603ae2e 100644
--- a/products/engineering_analytics/frontend/lib/runHealth.ts
+++ b/products/engineering_analytics/frontend/lib/runHealth.ts
@@ -1,3 +1,4 @@
+import type { WorkflowHealthItemApi } from '../generated/api.schemas'
import { isDecisiveFailure, isPassingConclusion } from './lifecycle'
/** Minimal run shape; WorkflowRunRow and PrRunRow both satisfy it. */
@@ -29,22 +30,19 @@ export interface CostableJob {
export type WorkflowState = 'healthy' | 'degraded' | 'failing' | 'unknown'
+/** Every field must be answerable from both the server's window figures and a page of runs. */
export interface HealthSummary {
state: WorkflowState
totalRuns: number
- completedRuns: number
conclusiveRuns: number
passedRuns: number
failures: number
- running: number
/** Runs that were a 2nd+ attempt. */
reruns: number
/** Passes divided by conclusive runs (null when no run reached a verdict). */
passRate: number | null
medianSeconds: number | null
p95Seconds: number | null
- lastFailureAt: string | null
- latestConclusion: string | null
}
// At or above this decisive-failure rate a workflow whose latest run still passed reads as "degraded".
@@ -117,6 +115,35 @@ export function percentileSorted(sortedAsc: number[], q: number): number | null
return sortedAsc[Math.min(sortedAsc.length - 1, Math.max(0, Math.ceil(q * sortedAsc.length) - 1))]
}
+/** Shared by both summaries so a page of runs and the server's figures never disagree on the verdict. */
+function workflowState(latestRunFailed: boolean | null, conclusiveRuns: number, failures: number): WorkflowState {
+ if (latestRunFailed == null) {
+ return 'unknown'
+ }
+ if (latestRunFailed) {
+ return 'failing'
+ }
+ if (conclusiveRuns > 0 && failures / conclusiveRuns >= DEGRADED_FAILURE_RATE) {
+ return 'degraded'
+ }
+ return 'healthy'
+}
+
+export function workflowHealthSummary(item: WorkflowHealthItemApi): HealthSummary {
+ const failures = item.conclusive_run_count - item.successful_run_count
+ return {
+ state: workflowState(item.latest_run_failed, item.conclusive_run_count, failures),
+ totalRuns: item.run_count,
+ conclusiveRuns: item.conclusive_run_count,
+ passedRuns: item.successful_run_count,
+ failures,
+ reruns: item.rerun_cycles ?? 0,
+ passRate: item.success_rate,
+ medianSeconds: item.p50_seconds,
+ p95Seconds: item.p95_seconds,
+ }
+}
+
/**
* Verdict + headline stats for one workflow's runs. Durations use successful runs. Rates use
* conclusive runs, so an unsettled or non-verdict run is never counted as a failure.
@@ -124,7 +151,6 @@ export function percentileSorted(sortedAsc: number[], q: number): number | null
export function computeHealthSummary(runs: HealthRun[]): HealthSummary {
const completed = runs.filter((run) => run.conclusion !== null)
const successful = completed.filter((run) => run.conclusion === 'success')
- const running = runs.length - completed.length
const passed = successful.length
const failures = completed.filter((run) => isDecisiveFailure(run.conclusion)).length
const conclusiveRuns = passed + failures
@@ -141,41 +167,19 @@ export function computeHealthSummary(runs: HealthRun[]): HealthSummary {
.filter((d): d is number => d != null)
const durations = (realDurations.length > 0 ? realDurations : allDurations).sort((a, b) => a - b)
- const byStartDesc = [...completed].sort((a, b) => (b.startedAt ?? '').localeCompare(a.startedAt ?? ''))
- const latestConclusion = byStartDesc[0]?.conclusion ?? null
- const lastFailureAt =
- completed
- .filter((run) => isDecisiveFailure(run.conclusion))
- .map((run) => run.startedAt)
- .filter((at): at is string => !!at)
- .sort()
- .at(-1) ?? null
-
- let state: WorkflowState
- if (completed.length === 0) {
- state = 'unknown'
- } else if (isDecisiveFailure(latestConclusion)) {
- state = 'failing'
- } else if (conclusiveRuns > 0 && failures / conclusiveRuns >= DEGRADED_FAILURE_RATE) {
- state = 'degraded'
- } else {
- state = 'healthy'
- }
+ const latest = [...completed].sort((a, b) => (b.startedAt ?? '').localeCompare(a.startedAt ?? ''))[0]
+ const latestRunFailed = latest ? isDecisiveFailure(latest.conclusion) : null
return {
- state,
+ state: workflowState(latestRunFailed, conclusiveRuns, failures),
totalRuns: runs.length,
- completedRuns: completed.length,
conclusiveRuns,
passedRuns: passed,
failures,
- running,
reruns,
passRate,
medianSeconds: percentileSorted(durations, 0.5),
p95Seconds: percentileSorted(durations, 0.95),
- lastFailureAt,
- latestConclusion,
}
}
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
index f6f083136feb..2c166cd2bdd4 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { IconExternal, IconGear } from '@posthog/icons'
-import { LemonButton, LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
@@ -100,6 +100,8 @@ export function WorkflowRunsScene(): JSX.Element {
repoName,
workflowName,
healthSummary,
+ workflowHealthLoading,
+ workflowHealthFailed,
costSummary,
runsTruncated,
activityRuns,
@@ -321,6 +323,12 @@ export function WorkflowRunsScene(): JSX.Element {
right={verdictPill}
/>
{/* Same window + run scope as the repo hub, so numbers match after drilling in. */}
+ {workflowHealthFailed && (
+ <LemonBanner type="warning">
+ These figures could not load, so they cover only the runs in the table below rather than the whole
+ window. Refresh to try again.
+ </LemonBanner>
+ )}
<ScopePanel busy={panelBusy} controls={<WorkflowScopeControls />}>
<div className="flex flex-wrap gap-2.5">
<MetricTile
@@ -329,7 +337,7 @@ export function WorkflowRunsScene(): JSX.Element {
healthSummary.conclusiveRuns
)} runs with a pass-or-fail result passed.`}
value={percent(healthSummary.passRate)}
- loading={runsLoading}
+ loading={workflowHealthLoading}
/>
<MetricTile
label="Runs"
@@ -339,12 +347,12 @@ export function WorkflowRunsScene(): JSX.Element {
: undefined
}
value={compactCount(healthSummary.totalRuns)}
- sub={runsTruncated ? `stats cover the most recent ${runRows.length}` : undefined}
- loading={runsLoading}
+ sub={runsTruncated ? `table shows the most recent ${runRows.length}` : undefined}
+ loading={workflowHealthLoading}
/>
<MetricTile
label="Duration p50"
- tooltip="Wall-clock, over successful runs."
+ tooltip="Median wall-clock duration over successful runs, excluding runs that settled in under 10 seconds without doing work."
value={
healthSummary.medianSeconds != null
? humanFriendlyDuration(healthSummary.medianSeconds)
@@ -355,7 +363,7 @@ export function WorkflowRunsScene(): JSX.Element {
? `→ ${humanFriendlyDuration(healthSummary.p95Seconds)} p95`
: undefined
}
- loading={runsLoading}
+ loading={workflowHealthLoading}
/>
<MetricTile
label="Queue time p50"
@@ -368,7 +376,7 @@ export function WorkflowRunsScene(): JSX.Element {
tooltip={
costSummary?.estimatedCostUsd != null
? `${compactMinutes(costSummary.billableMinutes)} billable · ${compactUsd(
- healthSummary.totalRuns > 0
+ !workflowHealthFailed && healthSummary.totalRuns > 0
? costSummary.estimatedCostUsd / healthSummary.totalRuns
: null
)} per run.`
@@ -376,7 +384,7 @@ export function WorkflowRunsScene(): JSX.Element {
}
value={costSummary?.estimatedCostUsd != null ? compactUsd(costSummary.estimatedCostUsd) : '—'}
sub={costSummary?.estimatedCostUsd != null ? undefined : 'Job-level source not synced'}
- loading={runnerCostsLoading}
+ loading={runnerCostsLoading || workflowHealthLoading}
/>
</div>
<Section id="health" title="Health" busy={healthBusy}>
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts
index 2939ed8881c7..b6eb460ee86e 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts
@@ -6,6 +6,7 @@ import { initKeaTests } from '~/test/init'
import {
engineeringAnalyticsJobAggregates,
+ engineeringAnalyticsWorkflowHealth,
engineeringAnalyticsWorkflowJobs,
engineeringAnalyticsWorkflowRunActivity,
engineeringAnalyticsWorkflowRunnerCosts,
@@ -16,6 +17,7 @@ import { workflowRunsLogic } from './workflowRunsLogic'
jest.mock('../generated/api', () => ({
engineeringAnalyticsJobAggregates: jest.fn(),
+ engineeringAnalyticsWorkflowHealth: jest.fn(),
engineeringAnalyticsWorkflowJobs: jest.fn(),
engineeringAnalyticsWorkflowRunActivity: jest.fn(),
engineeringAnalyticsWorkflowRunnerCosts: jest.fn(),
@@ -33,6 +35,9 @@ const mockJobs = engineeringAnalyticsWorkflowJobs as jest.MockedFunction<typeof
const mockJobAggregates = engineeringAnalyticsJobAggregates as jest.MockedFunction<
typeof engineeringAnalyticsJobAggregates
>
+const mockWorkflowHealth = engineeringAnalyticsWorkflowHealth as jest.MockedFunction<
+ typeof engineeringAnalyticsWorkflowHealth
+>
describe('workflowRunsLogic', () => {
let logic: ReturnType<typeof workflowRunsLogic.build>
@@ -46,6 +51,7 @@ describe('workflowRunsLogic', () => {
mockRunnerCosts.mockResolvedValue([])
mockJobs.mockResolvedValue([])
mockJobAggregates.mockResolvedValue([])
+ mockWorkflowHealth.mockResolvedValue([])
})
let unmountFilters: (() => void) | undefined
@@ -63,12 +69,13 @@ describe('workflowRunsLogic', () => {
unmountFilters = filters.mount()
await expectLogic(logic).toDispatchActions([
'loadRunsSuccess',
+ 'loadWorkflowHealthSuccess',
'loadRunActivitySuccess',
'loadRunnerCostsSuccess',
'loadJobAggregatesSuccess',
])
- const windowedReads = [mockRuns, mockRunActivity, mockRunnerCosts, mockJobAggregates]
+ const windowedReads = [mockRuns, mockWorkflowHealth, mockRunActivity, mockRunnerCosts, mockJobAggregates]
for (const read of windowedReads) {
expect(read).toHaveBeenLastCalledWith(
'1',
@@ -78,15 +85,17 @@ describe('workflowRunsLogic', () => {
expect(read.mock.lastCall?.[1]).not.toHaveProperty('run_scope')
}
- // Picking a group on the shared filters logic reloads all four reads scoped to it, so the detail
+ // Picking a group on the shared filters logic reloads all five reads scoped to it, so the detail
// page's numbers and its chart match the list it was opened from.
filters.actions.setRunScope('merge_queue')
await expectLogic(logic).toDispatchActions([
'loadRuns',
+ 'loadWorkflowHealth',
'loadRunActivity',
'loadRunnerCosts',
'loadJobAggregates',
'loadRunsSuccess',
+ 'loadWorkflowHealthSuccess',
'loadRunActivitySuccess',
'loadRunnerCostsSuccess',
'loadJobAggregatesSuccess',
@@ -95,4 +104,44 @@ describe('workflowRunsLogic', () => {
expect(read).toHaveBeenLastCalledWith('1', expect.objectContaining({ run_scope: 'merge_queue' }))
}
})
+
+ it('reads the tiles from the window-wide figures, not the capped run table', async () => {
+ mockWorkflowHealth.mockResolvedValue([
+ {
+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },
+ workflow_name: 'CI',
+ run_count: 4000,
+ successful_run_count: 3800,
+ conclusive_run_count: 3900,
+ success_rate: 0.974,
+ p50_seconds: 120,
+ p95_seconds: 600,
+ last_failure_at: null,
+ latest_run_failed: false,
+ latest_run_conclusion: 'success',
+ latest_run_id: 1,
+ latest_run_attempt: 1,
+ granularity: 'day',
+ buckets: [],
+ },
+ ])
+ logic = workflowRunsLogic({ repoOwner: 'PostHog', repoName: 'posthog', workflowName: 'CI', sourceId: null })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
+
+ expect(logic.values.healthSummary.totalRuns).toBe(4000)
+ expect(logic.values.healthSummary.passRate).toBe(0.974)
+ expect(logic.values.healthSummary.state).toBe('healthy')
+
+ // A failed reload must not keep showing the previous window's 4000 runs under the fallback banner.
+ mockWorkflowHealth.mockRejectedValue(new Error('network down'))
+ const filters = engineeringAnalyticsFiltersLogic()
+ unmountFilters = filters.mount()
+ filters.actions.setDateRange('-7d', null)
+ await expectLogic(logic).toDispatchActions(['loadWorkflowHealthFailure'])
+
+ expect(logic.values.workflowHealthFailed).toBe(true)
+ expect(logic.values.healthSummary.totalRuns).toBe(0)
+ expect(logic.values.healthSummary.state).toBe('unknown')
+ })
})
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
index 0bbf6f225fc6..f917662fa275 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
@@ -11,11 +11,13 @@ import { runPrNumber } from '../components/runTables'
import {
engineeringAnalyticsJobAggregates,
engineeringAnalyticsWorkflowJobs,
+ engineeringAnalyticsWorkflowHealth,
engineeringAnalyticsWorkflowRunActivity,
engineeringAnalyticsWorkflowRunnerCosts,
engineeringAnalyticsWorkflowRuns,
} from '../generated/api'
import type {
+ WorkflowHealthItemApi,
WorkflowJobAggregateApi,
WorkflowJobApi,
WorkflowRunActivityApi,
@@ -23,7 +25,7 @@ import type {
WorkflowRunnerCostApi,
} from '../generated/api.schemas'
import { jobCacheKey } from '../lib/jobs'
-import { type CostSummary, type HealthSummary, computeHealthSummary } from '../lib/runHealth'
+import { type CostSummary, type HealthSummary, computeHealthSummary, workflowHealthSummary } from '../lib/runHealth'
import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import type { RunScopeParams } from './engineeringAnalyticsFiltersLogic'
@@ -85,6 +87,9 @@ export interface workflowRunsLogicValues {
runsLoading: boolean
runsTruncated: boolean
sourceId: string | null
+ workflowHealth: WorkflowHealthItemApi | null
+ workflowHealthFailed: boolean
+ workflowHealthLoading: boolean
workflowName: string
}
@@ -174,6 +179,21 @@ export interface workflowRunsLogicActions {
runs: WorkflowRunDetailApi[]
payload?: any
}
+ loadWorkflowHealth: () => any
+ loadWorkflowHealthFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadWorkflowHealthSuccess: (
+ workflowHealth: WorkflowHealthItemApi | null,
+ payload?: any
+ ) => {
+ workflowHealth: WorkflowHealthItemApi | null
+ payload?: any
+ }
setRunExpanded: (
rowKey: string,
expanded: boolean,
@@ -198,7 +218,7 @@ export interface workflowRunsLogicMeta {
runRows: (runs: WorkflowRunDetailApi[]) => WorkflowRunRow[]
activityRuns: (runActivity: WorkflowRunActivityApi) => ActivityRun[]
activityTruncated: (runActivity: WorkflowRunActivityApi) => boolean
- healthSummary: (runRows: WorkflowRunRow[]) => HealthSummary
+ healthSummary: (workflowHealth: WorkflowHealthItemApi | null, runRows: WorkflowRunRow[]) => HealthSummary
masterConclusion: (runRows: WorkflowRunRow[]) => string | null
queueP50Seconds: (jobAggregates: WorkflowJobAggregateApi[]) => number | null
runsTruncated: (runRows: WorkflowRunRow[]) => boolean
@@ -266,6 +286,23 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
}),
},
],
+ // The run table is capped at RUN_LIST_LIMIT, so the tiles read the window-wide figures from here.
+ workflowHealth: [
+ null as WorkflowHealthItemApi | null,
+ {
+ loadWorkflowHealth: async (): Promise<WorkflowHealthItemApi | null> => {
+ const items = await engineeringAnalyticsWorkflowHealth(projectId(), {
+ workflow_name: props.workflowName,
+ repo: `${props.repoOwner}/${props.repoName}`,
+ date_from: values.dateFrom ?? undefined,
+ date_to: values.dateTo ?? undefined,
+ ...values.runScopeParams,
+ source_id: props.sourceId ?? undefined,
+ })
+ return items[0] ?? null
+ },
+ },
+ ],
// Cost split by runner tier; [] when the job-level source isn't synced.
runnerCosts: [
[] as WorkflowRunnerCostApi[],
@@ -328,6 +365,18 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
loadRunsFailure: () => true,
},
],
+ // kea-loaders keeps the last value on failure, which would show the previous window's figures.
+ workflowHealth: {
+ loadWorkflowHealthFailure: () => null,
+ },
+ workflowHealthFailed: [
+ false,
+ {
+ loadWorkflowHealth: () => false,
+ loadWorkflowHealthSuccess: () => false,
+ loadWorkflowHealthFailure: () => true,
+ },
+ ],
expandedRunKeys: [
[] as string[],
{
@@ -384,8 +433,9 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
(runActivity: WorkflowRunActivityApi): boolean => runActivity.truncated,
],
healthSummary: [
- (s) => [s.runRows],
- (runRows: WorkflowRunRow[]): HealthSummary => computeHealthSummary(runRows),
+ (s) => [s.workflowHealth, s.runRows],
+ (workflowHealth: WorkflowHealthItemApi | null, runRows: WorkflowRunRow[]): HealthSummary =>
+ workflowHealth ? workflowHealthSummary(workflowHealth) : computeHealthSummary(runRows),
],
// Latest completed master/main run's conclusion; null when the window has none (PR-only workflow).
masterConclusion: [
@@ -476,12 +526,14 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
},
[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadRuns()
+ actions.loadWorkflowHealth()
actions.loadRunActivity()
actions.loadRunnerCosts()
actions.loadJobAggregates()
},
[engineeringAnalyticsFiltersLogic.actionTypes.setRunScope]: () => {
actions.loadRuns()
+ actions.loadWorkflowHealth()
actions.loadRunActivity()
actions.loadRunnerCosts()
actions.loadJobAggregates()
@@ -490,6 +542,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
afterMount(({ actions }) => {
actions.loadRuns()
+ actions.loadWorkflowHealth()
actions.loadRunActivity()
actions.loadRunnerCosts()
actions.loadJobAggregates()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8511cad64aa1..a25cf23a7d86 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -99248,6 +99248,10 @@ export namespace Schemas {
* 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;
+ /**
+ * Optional exact workflow name to scope results to, e.g. 'Backend CI'. Omit to rank every workflow. Pass it when you want one workflow's figures over the whole window rather than the top slice.
+ */
+ workflow_name?: string;
};
export type EngineeringAnalyticsWorkflowHealthRunScope = typeof EngineeringAnalyticsWorkflowHealthRunScope[keyof typeof EngineeringAnalyticsWorkflowHealthRunScope];
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index d709fb0597f1..7e203917e5f4 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -248,7 +248,7 @@ export const EngineeringAnalyticsTeamCiHealthQueryParams = () => zod.object({
})
/**
- * Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, or to one run group via `run_scope` (default_branch, pull_request, merge_queue). Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.
+ * Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. Success rate covers runs that succeeded or ended in a decisive failure. Skipped, cancelled, neutral, and action-required runs are excluded. p50/p95 are over successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, to one workflow via `workflow_name`, or to one run group via `run_scope` (default_branch, pull_request, merge_queue). Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.
*/
export const EngineeringAnalyticsWorkflowHealthParams = () => zod.object({
project_id: zod
@@ -285,6 +285,12 @@ export const EngineeringAnalyticsWorkflowHealthQueryParams = () => zod.object({
.describe(
'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
),
+ workflow_name: zod
+ .string()
+ .optional()
+ .describe(
+ "Optional exact workflow name to scope results to, e.g. 'Backend CI'. Omit to rank every workflow. Pass it when you want one workflow's figures over the whole window rather than the top slice."
+ ),
})
/**
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index 6701d8e4ebd7..5caa95c2841c 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -328,6 +328,7 @@ const workflowHealth = (): ToolBase<
repo: params.repo,
run_scope: params.run_scope,
source_id: params.source_id,
+ workflow_name: params.workflow_name,
},
})
return await withPostHogUrl(context, result, '/engineering-analytics/workflows')