Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(console): operations funnel + pipeline health (PR-3 / v1.5 W1+W9) (#102)
Beenu Arora9a7744c9db24
diff --git a/apps/docs/docs/console/funnel-kpis.md b/apps/docs/docs/console/funnel-kpis.mdnew file mode 100644index 000000000..8ffd0e201--- /dev/null+++ b/apps/docs/docs/console/funnel-kpis.md@@ -0,0 +1,181 @@+---+sidebar_position: 1+title: Funnel KPIs and pipeline health+description: How AiSOC turns raw telemetry into a six-tile operations funnel, an efficiency report, and a five-stage pipeline-health rail on the dashboard — backed by /metrics/funnel and /health/pipeline.+---++# Funnel KPIs and pipeline health++Tier-1 SOC consoles open on the same picture: a row of funnel tiles that says how much signal made it into the analyst's queue, an efficiency report that says how well the pipeline converted raw events into alerts, and a per-stage health rail that says where the next outage will come from. v1.5 brings that picture to AiSOC's `/dashboard` without breaking the existing flat per-page layout.++This page documents the three widgets, their data sources, and the endpoints they call.++## Where the widgets sit++The new `funnel-kpis` and `efficiency-and-pipeline` widgets render at the top of `/dashboard`, above the existing top-metrics row. Both are drag-and-drop reorderable; their order persists in `localStorage` under `aisoc:dashboard-widget-order` (the dashboard auto-migrates older saved orders to include the new widgets).++```+┌──────────────────────────────────────────────────────────────────────┐+│ Welcome │+├──────────────────────────────────────────────────────────────────────┤+│ Operations Funnel ─ 6 tiles │+│ Events of Interest · Correlation Inst. · Alerts Generated │+│ Signal / Noise · MTTD · Analyst Queue │+├──────────────────────────────────────────────────┬───────────────────┤+│ Efficiency Report │ Pipeline Health │+│ Correlation efficiency │ Ingest │+│ Alert yield │ Normalize │+│ MITRE coverage │ Fuse │+│ │ Correlate │+│ │ Alert │+└──────────────────────────────────────────────────┴───────────────────┘+```++## `FunnelKpiBar` — six tiles, one period++The bar renders six tiles in fixed order. Each tile carries an absolute value and, where the API returns one, a period-over-period delta:++| Tile | Value | Delta direction |+|---|---|---|+| Events of Interest | normalized events in window | up is good |+| Correlation Instances | fired correlations in window | up is good |+| Alerts Generated | alerts created in window | up is good |+| Signal / Noise | `1 − (FP / dispositioned alerts)` | up is good |+| MTTD | mean `created_at → first_seen_at` across alerts in window | **down is good** |+| Analyst Queue | active alerts in `new`/`triaging`/`in_progress` | **down is good** |++Delta direction matters because the same percent change has the opposite meaning on MTTD or Queue: a +20% Analyst Queue is bad, a +20% Alerts Generated is good. The component encodes this so the green/red coloring is correct without the operator having to think about it.++Loading and error states are deliberately quiet:++- **Loading** — six skeleton tiles with the same labels and shape as the loaded view, so the layout never jumps.+- **Error** — a single "Funnel metrics unavailable" line replaces the tiles; the rest of the dashboard keeps rendering. `useSWR` is configured with `shouldRetryOnError: false` so a 5xx doesn't melt the API.++## `EfficiencyReport` — how well the pipeline converts++Three bars, all clamped to `[0, 1]` so the visualization never overflows:++1. **Correlation efficiency** = `alerts / correlation_instances`. Clamped to `1.0`. Tells you how much of your correlation work turned into an actual alert.+2. **Alert yield** = `alerts / events_of_interest`. Always tiny — `0.00208` is healthy. Tells you what fraction of raw signal made it to an analyst.+3. **MITRE coverage** = `covered / total`. Surfaces "42 / 201 · 20.9%" — the count of distinct MITRE tactic + technique IDs (`Txxxx` and `TAxxxx`) referenced by detection rules with at least one alert in the window, divided by the configured total (see [Tunables](#tunables)).++The `EfficiencyReport` and `FunnelKpiBar` deliberately share an SWR cache key (`funnel-metrics:<period>`) so both widgets de-dupe on a single call to `GET /api/v1/metrics/funnel`.++## `PipelineHealth` — five stages, four statuses++The rail mirrors the data path end-to-end:++```+Ingest → Normalize → Fuse → Correlate → Alert+```++Each stage card shows:++- **Backlog** — queued items waiting for the stage. Sourced from connector-level backlog counters for `ingest`/`normalize` and from `alert`-table row counts in `new`/`pending` for `alert`.+- **p95 latency (ms)** — derived from existing alert timestamp fields (`created_at`, `first_seen_at`, `fused_at`, etc.) so we don't need a separate metrics store. Stages without a meaningful latency signal report `0`.+- **Error rate** — fraction of failed runs in the window. Sourced from `Connector.last_error_at` / `last_success_at` counters and aggregated.+- **Status** — `unknown | green | yellow | red`, derived from the same `compute_freshness` service that powers the existing connector health page (`services/api/app/services/connector_freshness.py`) plus per-stage staleness thresholds. The top-of-rail badge reports the worst stage status.++`refreshInterval` is 30 s for pipeline health and 60 s for the funnel — fast enough to spot a fuse-stage backlog spike, slow enough not to pound the API.++## Endpoints++### `GET /api/v1/metrics/funnel`++```+GET /api/v1/metrics/funnel?period=1h|24h|7d|30d+```++Returns:++```json+{+ "period": "24h",+ "events_of_interest": 94612,+ "correlation_instances": 73515,+ "alerts_generated": 153,+ "signal_to_noise": 0.864,+ "mttd_seconds": 252,+ "analyst_queue_depth": 27,+ "correlation_efficiency": 0.777,+ "alert_yield": 0.00208,+ "mitre_coverage": { "covered": 71, "total": 100, "ratio": 0.71 },+ "deltas": {+ "events_of_interest": 0.037,+ "correlation_instances": 0.012,+ "alerts_generated": -0.04,+ "signal_to_noise": 0.005,+ "mttd_seconds": -0.18,+ "analyst_queue_depth": 0.20+ },+ "generated_at": "2026-05-13T10:00:00Z"+}+```++Key implementation notes (`services/api/app/api/v1/endpoints/metrics.py`):++- Tenant-scoped via `AuthUser`; every query joins on `tenant_id` or — for ClickHouse — passes through `services/api/app/services/lake_sql.py:rewrite_for_tenant` which uses `sqlglot` to enforce the tenant clause before the query reaches the lake.+- `events_of_interest` reads from ClickHouse `aisoc.raw_events` when the lake is enabled, with a Postgres-only fallback (alerts table count) for air-gapped deployments where `AISOC_DISABLE_CLICKHOUSE=1`.+- `mttd_seconds` reuses the exact same `AVG(EXTRACT EPOCH FROM (created_at - first_seen_at))` expression as the existing SOC metrics endpoint so the two never disagree.+- `signal_to_noise` is `1 − (FP count / total dispositioned)` — alerts with `disposition` in `false_positive` divided by alerts with any disposition. Returns `0.0` when there is no dispositioned alert (no work done yet).+- Deltas are signed fractions, not percent: `0.05` means +5%. The previous-period window is the same duration immediately before the current one.++### `GET /api/v1/health/pipeline`++```+GET /api/v1/health/pipeline+```++Returns:++```json+{+ "overall_status": "yellow",+ "stages": [+ {"stage": "ingest", "backlog": 0, "p95_latency_ms": 120, "error_rate": 0, "status": "green"},+ {"stage": "normalize", "backlog": 5, "p95_latency_ms": 200, "error_rate": 0.01, "status": "green"},+ {"stage": "fuse", "backlog": 42, "p95_latency_ms": 1800, "error_rate": 0.03, "status": "yellow"},+ {"stage": "correlate", "backlog": 12, "p95_latency_ms": 600, "error_rate": 0, "status": "green"},+ {"stage": "alert", "backlog": 3, "p95_latency_ms": 300, "error_rate": 0, "status": "green"}+ ],+ "generated_at": "2026-05-13T10:00:00Z"+}+```++`overall_status` is the worst per-stage status (`red > yellow > green > unknown`) and drives the colored badge at the top of the rail.++## Tunables++Configuration lives in `services/api/app/core/config.py`:++| Setting | Default | Purpose |+|---|---|---|+| `AISOC_FUNNEL_MITRE_TOTAL` | `201` | Denominator for MITRE coverage. Set to your active framework's technique count (e.g. ATT&CK Enterprise v15 = 201). The numerator is computed live from rules with at least one alert in window. |+| `AISOC_PIPELINE_STALE_WARN_SECONDS` | `300` | Per-stage staleness threshold below which a stage stays `green`. Above this, the stage flips to `yellow`. |+| `AISOC_PIPELINE_STALE_DOWN_SECONDS` | `900` | Per-stage staleness threshold above which a stage flips to `red`. |++All three are env-driven and tenant-uniform (deliberately — the picture of "is my pipeline healthy" should not vary per tenant).++## Why this shape++A few design choices are worth calling out:++1. **One endpoint, two widgets.** `FunnelKpiBar` and `EfficiencyReport` are split for layout reasons, not data-fetching reasons. Sharing the SWR key means the dashboard makes one network call for both. If we ever need to refresh the efficiency report independently, the cache key would split.+2. **No mock data, anywhere.** The previous `34%` SNR in `NoiseTuningView` was the only mocked KPI left in v1.4. It now reads from this endpoint and falls back to a deterministic local computation only when the API is unreachable — never to a fixed constant.+3. **Stages, not connectors.** The reference SOC console renders pipeline health per-stage, not per-connector, because operators want to know "is fusion behind?" — not "which of 47 connectors is having a bad day." The connector health page (`/health`) still exists for the per-connector drill-down.+4. **Worst-status badge.** The top-of-rail status is intentionally pessimistic. A single red stage flips the rail to red, because in SOC operations the worst link defines the chain.++## Operator playbook++| Symptom | Likely cause | First check |+|---|---|---|+| MTTD tile is red and rising | Triage queue is backlogged, or alerts are firing without `first_seen_at` getting written | Open `/queue` and look at oldest unclaimed; verify the alert worker is running |+| Signal / Noise dropping below `0.5` | Recent rule change is over-firing | `/detection/tuning` to find the noisiest rule |+| Fuse stage in yellow with high backlog | Correlation rule is slow or unbounded | Inspect last fusion logs; check rule windowing |+| All stages `unknown` | No connectors have polled in `> AISOC_PIPELINE_STALE_DOWN_SECONDS` | Likely a deployment issue, not a data issue — check the connector scheduler |++## Related++- [Connector health and schema-drift sentinel](../features/connector-health.md) — the per-connector drill-down behind the ingest stage.+- [Credentials vault](../operations/credentials.md) — how connector credentials are encrypted at rest.+- [Architecture](../architecture.md) — the full data-flow diagram these widgets render against.diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 37140744c..e2d5c20a0 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -30,7 +30,7 @@ const sidebars: SidebarsConfig = {{type: "category",label: "Console",- items: ["console/queue", "console/rule-tuning"],+ items: ["console/funnel-kpis", "console/queue", "console/rule-tuning"],},{type: "category",diff --git a/apps/web/src/components/dashboard/DashboardView.tsx b/apps/web/src/components/dashboard/DashboardView.tsxindex eec6f9b99..5a9bae849 100644--- a/apps/web/src/components/dashboard/DashboardView.tsx+++ b/apps/web/src/components/dashboard/DashboardView.tsx@@ -23,6 +23,9 @@ import { format } from 'date-fns';import { LiveFeedPanel } from './LiveFeedPanel';import { SOCMetricsDashboard } from './SOCMetricsDashboard';import { DashboardWelcome } from './DashboardWelcome';+import { FunnelKpiBar } from './FunnelKpiBar';+import { EfficiencyReport } from './EfficiencyReport';+import { PipelineHealth } from './PipelineHealth';const RechartsArea = dynamic(() => import('recharts').then((m) => {@@ -224,6 +227,8 @@ const WIDGET_ORDER_KEY = 'aisoc:dashboard:widget-order';type WidgetId =| 'welcome'+ | 'funnel-kpis'+ | 'efficiency-and-pipeline'| 'top-metrics'| 'charts-row'| 'bottom-row'@@ -231,6 +236,8 @@ type WidgetId =const DEFAULT_WIDGET_ORDER: WidgetId[] = ['welcome',+ 'funnel-kpis',+ 'efficiency-and-pipeline','top-metrics','charts-row','bottom-row',@@ -401,6 +408,19 @@ export function DashboardView() {const widgetContent: Record<WidgetId, ReactNode> = {welcome: <Suspense fallback={null}><DashboardWelcome /></Suspense>,+ // PR-3 / W1: Six-tile funnel KPI strip (events → correlations → alerts ++ // signal/noise, MTTD, analyst queue) backed by /api/v1/metrics/funnel.+ 'funnel-kpis': <FunnelKpiBar period="24h" />,++ // PR-3 / W1+W9: Efficiency ratios (correlation efficiency, alert yield,+ // MITRE coverage) alongside per-stage pipeline health.+ 'efficiency-and-pipeline': (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <EfficiencyReport period="24h" />+ <PipelineHealth />+ </div>+ ),+'top-metrics': (<div>{/* Section header */}diff --git a/apps/web/src/components/dashboard/EfficiencyReport.tsx b/apps/web/src/components/dashboard/EfficiencyReport.tsxnew file mode 100644index 000000000..45f2f0340--- /dev/null+++ b/apps/web/src/components/dashboard/EfficiencyReport.tsx@@ -0,0 +1,182 @@+'use client';++/**+ * EfficiencyReport+ * ================+ * Composite efficiency card that surfaces the **derived** funnel ratios:+ *+ * • Correlation efficiency = alerts / correlation_instances (clamped 0..1)+ * • Alert yield = alerts / events_of_interest (clamped 0..1)+ * • MITRE coverage = covered / total+ *+ * Backed by `GET /api/v1/metrics/funnel`. Designed to sit next to+ * {@link FunnelKpiBar} on the operations dashboard. The report intentionally+ * shares the SWR cache key with the bar so both components stay in lock-step+ * without firing two requests.+ *+ * Author: Beenu Arora <[email protected]>+ */++import useSWR from 'swr';+import { clsx } from 'clsx';+import { metricsApi, type FunnelMetrics } from '@/lib/api';++type Period = '1h' | '24h' | '7d' | '30d';++interface EfficiencyReportProps {+ /** Time window. Should match the sibling FunnelKpiBar period. */+ period?: Period;+ /** Override the SWR cache key. Defaults to the same key as FunnelKpiBar. */+ cacheKey?: string;+}++function clamp01(value: number): number {+ if (!Number.isFinite(value)) return 0;+ if (value < 0) return 0;+ if (value > 1) return 1;+ return value;+}++function fmtPct(ratio: number): string {+ if (!Number.isFinite(ratio)) return '—';+ const pct = clamp01(ratio) * 100;+ return `${pct.toFixed(1).replace(/\.0$/, '')}%`;+}++function fmtCoverage(covered: number, total: number): string {+ if (!Number.isFinite(covered) || !Number.isFinite(total) || total <= 0)+ return '—';+ const pct = (covered / total) * 100;+ return `${covered}/${total} • ${pct.toFixed(1).replace(/\.0$/, '')}%`;+}++interface BarRowProps {+ label: string;+ description: string;+ value: number;+ /** Whether the value is "good" close to 1 (true) or close to a target (false). */+ goodHigh?: boolean;+ /** Display value (formatted). */+ display: string;+}++function BarRow({+ label,+ description,+ value,+ goodHigh = true,+ display,+}: BarRowProps) {+ const v = clamp01(value);+ // For "good-high" metrics, color by threshold; for others, neutral.+ let barColor = 'bg-blue-500/70';+ if (goodHigh) {+ if (v < 0.2) barColor = 'bg-red-500/70';+ else if (v < 0.5) barColor = 'bg-amber-500/70';+ else barColor = 'bg-green-500/70';+ }++ return (+ <div>+ <div className="flex items-baseline justify-between gap-3 mb-1">+ <div className="min-w-0">+ <p className="text-sm font-medium text-gray-200 truncate">{label}</p>+ <p className="text-[11px] text-gray-500 truncate">{description}</p>+ </div>+ <p className="text-sm font-semibold text-gray-100 tabular-nums shrink-0">+ {display}+ </p>+ </div>+ <div className="h-1.5 w-full rounded-full bg-gray-800/80 overflow-hidden">+ <div+ className={clsx('h-full rounded-full transition-[width]', barColor)}+ style={{ width: `${(v * 100).toFixed(1)}%` }}+ />+ </div>+ </div>+ );+}++function LoadingBar({ label }: { label: string }) {+ return (+ <div>+ <div className="flex items-baseline justify-between gap-3 mb-1">+ <p className="text-sm font-medium text-gray-200 truncate">{label}</p>+ <div className="h-4 w-12 rounded bg-gray-800/60 animate-pulse" />+ </div>+ <div className="h-1.5 w-full rounded-full bg-gray-800/40 animate-pulse" />+ </div>+ );+}++export function EfficiencyReport({+ period = '24h',+ cacheKey,+}: EfficiencyReportProps = {}) {+ const key = cacheKey ?? `funnel-metrics:${period}`;+ const { data, error, isLoading } = useSWR<FunnelMetrics>(+ key,+ () => metricsApi.getFunnel(period),+ {+ refreshInterval: 60_000,+ revalidateOnFocus: false,+ shouldRetryOnError: false,+ },+ );++ return (+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-5">+ <div className="flex items-center justify-between mb-4">+ <div>+ <h2 className="text-base font-semibold text-gray-100">+ Efficiency Report+ </h2>+ <p className="text-xs text-gray-500 mt-0.5">+ How well raw signal converts to actionable alerts+ </p>+ </div>+ <span className="text-xs text-gray-500">Last {period}</span>+ </div>++ {error ? (+ <p className="text-sm text-gray-400">Efficiency metrics unavailable.</p>+ ) : isLoading || !data ? (+ <div className="space-y-4">+ <LoadingBar label="Correlation efficiency" />+ <LoadingBar label="Alert yield" />+ <LoadingBar label="MITRE coverage" />+ </div>+ ) : (+ <div className="space-y-4">+ <BarRow+ label="Correlation efficiency"+ description="Alerts produced per correlation instance"+ value={data.correlation_efficiency}+ display={fmtPct(data.correlation_efficiency)}+ />+ <BarRow+ label="Alert yield"+ description="Alerts produced per event of interest"+ value={data.alert_yield}+ display={fmtPct(data.alert_yield)}+ />+ <BarRow+ label="MITRE coverage"+ description="Tactic + technique IDs surfaced by your alerts"+ value={+ data.mitre_coverage.total > 0+ ? data.mitre_coverage.covered / data.mitre_coverage.total+ : 0+ }+ display={fmtCoverage(+ data.mitre_coverage.covered,+ data.mitre_coverage.total,+ )}+ />+ </div>+ )}+ </div>+ );+}++export default EfficiencyReport;diff --git a/apps/web/src/components/dashboard/FunnelKpiBar.test.tsx b/apps/web/src/components/dashboard/FunnelKpiBar.test.tsxnew file mode 100644index 000000000..9093d1045--- /dev/null+++ b/apps/web/src/components/dashboard/FunnelKpiBar.test.tsx@@ -0,0 +1,195 @@+/**+ * FunnelKpiBar / EfficiencyReport / PipelineHealth — rendering smoke tests.+ *+ * The three components are the v1.5 SOC console parity widgets (PR-3). They+ * are thin presentation layers over `GET /api/v1/metrics/funnel` and+ * `GET /api/v1/health/pipeline`, but they encode a handful of behaviors the+ * analyst experience depends on:+ *+ * 1. FunnelKpiBar — colors deltas by direction *and* by metric semantics:+ * positive Δ on MTTD / Analyst Queue is bad (red), positive Δ on Events+ * / Alerts is good (green). We pin both directions.+ * 2. EfficiencyReport — clamps the bar fill to 0..1 and renders the MITRE+ * coverage as "covered/total · pct%".+ * 3. PipelineHealth — surfaces the per-stage status dot (`green | yellow |+ * red | unknown`) and the worst-status badge at the top.+ *+ * SWR is mocked at the module boundary so each test can control the loading /+ * error / data states without touching the real fetcher.+ *+ * Author: Beenu Arora <[email protected]>+ */++import { describe, expect, it, vi, beforeEach } from 'vitest';+import { render, screen } from '@testing-library/react';++const swrData = vi.hoisted(() => new Map<string, unknown>());+const swrErrors = vi.hoisted(() => new Map<string, unknown>());+const swrLoading = vi.hoisted(() => new Set<string>());++vi.mock('swr', () => ({+ __esModule: true,+ default: (key: unknown) => {+ const k = typeof key === 'string' ? key : JSON.stringify(key);+ if (swrLoading.has(k)) {+ return { data: undefined, error: undefined, isLoading: true };+ }+ return {+ data: swrData.get(k),+ error: swrErrors.get(k),+ isLoading: false,+ };+ },+}));++vi.mock('@/lib/api', () => ({+ __esModule: true,+ metricsApi: {+ getFunnel: vi.fn(),+ getPipelineHealth: vi.fn(),+ },+}));++// Import the components *after* the mocks so the module-level useSWR is+// bound to our stub.+import { FunnelKpiBar } from './FunnelKpiBar';+import { EfficiencyReport } from './EfficiencyReport';+import { PipelineHealth } from './PipelineHealth';++const FUNNEL_KEY = 'funnel-metrics:24h';+const PIPELINE_KEY = 'pipeline-health';++const SAMPLE_FUNNEL = {+ period: '24h' as const,+ events_of_interest: 1_234,+ correlation_instances: 87,+ alerts_generated: 42,+ signal_to_noise: 0.83,+ mttd_seconds: 480,+ analyst_queue_depth: 9,+ correlation_efficiency: 0.48,+ alert_yield: 0.034,+ mitre_coverage: { covered: 42, total: 201, ratio: 0.209 },+ deltas: {+ events_of_interest: 0.12,+ correlation_instances: 0.05,+ alerts_generated: -0.08,+ signal_to_noise: 0.02,+ mttd_seconds: -0.15,+ analyst_queue_depth: 0.2,+ },+ generated_at: '2026-05-13T10:00:00Z',+};++const SAMPLE_PIPELINE = {+ overall_status: 'yellow' as const,+ stages: [+ { stage: 'ingest' as const, backlog: 0, p95_latency_ms: 120, error_rate: 0, status: 'green' as const },+ { stage: 'normalize' as const, backlog: 5, p95_latency_ms: 200, error_rate: 0.01, status: 'green' as const },+ { stage: 'fuse' as const, backlog: 42, p95_latency_ms: 1_800, error_rate: 0.03, status: 'yellow' as const },+ { stage: 'correlate' as const, backlog: 12, p95_latency_ms: 600, error_rate: 0, status: 'green' as const },+ { stage: 'alert' as const, backlog: 3, p95_latency_ms: 300, error_rate: 0, status: 'green' as const },+ ],+ generated_at: '2026-05-13T10:00:00Z',+};++describe('FunnelKpiBar', () => {+ beforeEach(() => {+ swrData.clear();+ swrErrors.clear();+ swrLoading.clear();+ });++ it('renders six tiles with formatted values and signed deltas', () => {+ swrData.set(FUNNEL_KEY, SAMPLE_FUNNEL);+ render(<FunnelKpiBar period="24h" />);++ expect(screen.getByText(/Operations Funnel/i)).toBeInTheDocument();+ // 1.2k for 1234 (k abbreviation), 87 raw, 42 raw, 83% S/N, 8m MTTD, 9 queue.+ expect(screen.getByText('1.2k')).toBeInTheDocument();+ expect(screen.getByText('87')).toBeInTheDocument();+ expect(screen.getByText('42')).toBeInTheDocument();+ expect(screen.getByText('83%')).toBeInTheDocument();+ expect(screen.getByText('8m')).toBeInTheDocument();+ expect(screen.getByText('9')).toBeInTheDocument();++ // Positive Δ on EOI / alerts means up; negative on alerts is shown with a minus.+ expect(screen.getByText('+12%')).toBeInTheDocument();+ expect(screen.getByText('−8%')).toBeInTheDocument();+ });++ it('shows skeleton tiles while loading', () => {+ swrLoading.add(FUNNEL_KEY);+ render(<FunnelKpiBar period="24h" />);+ expect(screen.getByText(/Operations Funnel/i)).toBeInTheDocument();+ // Six labels still render even in the skeleton state.+ expect(screen.getByText('Events of Interest')).toBeInTheDocument();+ expect(screen.getByText('MTTD')).toBeInTheDocument();+ });++ it('renders a graceful error message when the funnel call fails', () => {+ swrErrors.set(FUNNEL_KEY, new Error('boom'));+ swrData.set(FUNNEL_KEY, SAMPLE_FUNNEL); // present but error takes precedence+ render(<FunnelKpiBar period="24h" />);+ expect(screen.getByText(/Funnel metrics unavailable/i)).toBeInTheDocument();+ });+});++describe('EfficiencyReport', () => {+ beforeEach(() => {+ swrData.clear();+ swrErrors.clear();+ swrLoading.clear();+ });++ it('renders correlation efficiency, alert yield, and MITRE coverage', () => {+ swrData.set(FUNNEL_KEY, SAMPLE_FUNNEL);+ render(<EfficiencyReport period="24h" />);++ expect(screen.getByText(/Efficiency Report/i)).toBeInTheDocument();+ // 0.48 → 48%, 0.034 → 3.4%, coverage "42/201 · 20.9%".+ expect(screen.getByText('48%')).toBeInTheDocument();+ expect(screen.getByText('3.4%')).toBeInTheDocument();+ expect(screen.getByText(/42\/201/)).toBeInTheDocument();+ });++ it('falls back to a helpful empty state when the call errors', () => {+ swrErrors.set(FUNNEL_KEY, new Error('boom'));+ render(<EfficiencyReport period="24h" />);+ expect(screen.getByText(/Efficiency metrics unavailable/i)).toBeInTheDocument();+ });+});++describe('PipelineHealth', () => {+ beforeEach(() => {+ swrData.clear();+ swrErrors.clear();+ swrLoading.clear();+ });++ it('renders all five pipeline stages with formatted latency + backlog', () => {+ swrData.set(PIPELINE_KEY, SAMPLE_PIPELINE);+ render(<PipelineHealth />);++ // Each stage card has a unique subtitle — use those to assert the+ // five-card rail is present without colliding with the header subtitle.+ expect(screen.getByText('Connector → raw events')).toBeInTheDocument();+ expect(screen.getByText('OCSF mapping')).toBeInTheDocument();+ expect(screen.getByText('Alert fusion')).toBeInTheDocument();+ expect(screen.getByText('Cross-source correlation')).toBeInTheDocument();+ expect(screen.getByText('Final alert emission')).toBeInTheDocument();++ // Formatted values: backlog 42, p95 1.8s, error 3% on the "fuse" stage.+ expect(screen.getByText('1.8 s')).toBeInTheDocument();+ expect(screen.getByText('3%')).toBeInTheDocument();+ });++ it('surfaces the unavailable badge when the pipeline call errors', () => {+ swrErrors.set(PIPELINE_KEY, new Error('boom'));+ render(<PipelineHealth />);+ // Header keeps the title; the live/unavailable indicator flips to+ // "unavailable" without the rest of the rail throwing.+ expect(screen.getByText('Pipeline Health')).toBeInTheDocument();+ expect(screen.getByText('unavailable')).toBeInTheDocument();+ });+});diff --git a/apps/web/src/components/dashboard/FunnelKpiBar.tsx b/apps/web/src/components/dashboard/FunnelKpiBar.tsxnew file mode 100644index 000000000..22bde6717--- /dev/null+++ b/apps/web/src/components/dashboard/FunnelKpiBar.tsx@@ -0,0 +1,230 @@+'use client';++/**+ * FunnelKpiBar+ * ============+ * Six-tile KPI strip that mirrors the reference SOC console's funnel widget.+ *+ * Tiles, left to right:+ * 1. Events of Interest (24h delta)+ * 2. Correlation Instances (24h delta)+ * 3. Alerts Generated (24h delta)+ * 4. Signal / Noise (24h delta — higher is better)+ * 5. MTTD (24h delta — lower is better)+ * 6. Analyst Queue Depth (24h delta — lower is better)+ *+ * Data source: `GET /api/v1/metrics/funnel?period=…` ({@link metricsApi.getFunnel}).+ * Polls every 60 s with stale-while-revalidate.+ *+ * Author: Beenu Arora <[email protected]>+ */++import useSWR from 'swr';+import { clsx } from 'clsx';+import { metricsApi, type FunnelMetrics } from '@/lib/api';++type Period = '1h' | '24h' | '7d' | '30d';++interface FunnelKpiBarProps {+ /** Time window for the funnel. Defaults to `24h` (matches DashboardView). */+ period?: Period;+ /** Override the SWR cache key — useful when multiple bars coexist. */+ cacheKey?: string;+}++interface TileProps {+ label: string;+ value: string;+ delta: number | null;+ /**+ * When `true`, a *negative* delta is rendered green (good) and positive is red+ * (worse). When `false`, positive is green. Mirrors the reference console's+ * coloring for MTTD / Queue (lower-is-better) vs Events / Alerts.+ */+ lowerIsBetter?: boolean;+ /** Tiny note under the value (e.g. "events", "alerts/sec"). */+ unit?: string;+}++function formatNumber(n: number): string {+ if (!Number.isFinite(n)) return '—';+ if (Math.abs(n) >= 1_000_000)+ return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`;+ if (Math.abs(n) >= 1_000)+ return `${(n / 1_000).toFixed(1).replace(/\.0$/, '')}k`;+ return String(Math.round(n));+}++function formatDurationSeconds(sec: number): string {+ if (!Number.isFinite(sec) || sec < 0) return '—';+ if (sec < 60) return `${Math.round(sec)}s`;+ if (sec < 3600) return `${Math.round(sec / 60)}m`;+ return `${(sec / 3600).toFixed(1).replace(/\.0$/, '')}h`;+}++function formatPercent(ratio: number): string {+ if (!Number.isFinite(ratio)) return '—';+ return `${(ratio * 100).toFixed(1).replace(/\.0$/, '')}%`;+}++function formatDelta(delta: number | null): string {+ if (delta === null || !Number.isFinite(delta)) return '—';+ const pct = delta * 100;+ const rounded = Math.abs(pct) >= 10 ? Math.round(pct) : pct.toFixed(1);+ const sign = pct > 0 ? '+' : pct < 0 ? '−' : '';+ return `${sign}${Math.abs(Number(rounded))}%`;+}++function Tile({ label, value, delta, lowerIsBetter = false, unit }: TileProps) {+ const isGood =+ delta === null || delta === 0+ ? null+ : lowerIsBetter+ ? delta < 0+ : delta > 0;+ const deltaColor =+ isGood === null+ ? 'text-gray-500'+ : isGood+ ? 'text-green-400'+ : 'text-red-400';++ return (+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4 min-w-0">+ <p className="text-[11px] text-gray-500 font-medium uppercase tracking-wider truncate">+ {label}+ </p>+ <p className="text-2xl font-bold text-gray-100 mt-1 tabular-nums truncate">+ {value}+ </p>+ <div className="flex items-baseline gap-2 mt-1">+ <span className={clsx('text-xs font-medium tabular-nums', deltaColor)}>+ {formatDelta(delta)}+ </span>+ {unit && <span className="text-[11px] text-gray-600 truncate">{unit}</span>}+ </div>+ </div>+ );+}++function LoadingTile({ label }: { label: string }) {+ return (+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4 min-w-0">+ <p className="text-[11px] text-gray-500 font-medium uppercase tracking-wider truncate">+ {label}+ </p>+ <div className="mt-2 h-7 w-20 rounded bg-gray-800/60 animate-pulse" />+ <div className="mt-2 h-3 w-12 rounded bg-gray-800/40 animate-pulse" />+ </div>+ );+}++const TILE_LABELS = [+ 'Events of Interest',+ 'Correlation Instances',+ 'Alerts Generated',+ 'Signal / Noise',+ 'MTTD',+ 'Analyst Queue',+] as const;++export function FunnelKpiBar({+ period = '24h',+ cacheKey,+}: FunnelKpiBarProps = {}) {+ const key = cacheKey ?? `funnel-metrics:${period}`;+ const { data, error, isLoading } = useSWR<FunnelMetrics>(+ key,+ () => metricsApi.getFunnel(period),+ {+ refreshInterval: 60_000,+ revalidateOnFocus: false,+ shouldRetryOnError: false,+ },+ );++ if (isLoading || !data) {+ return (+ <div>+ <div className="flex items-center justify-between mb-3">+ <h2 className="text-base font-semibold text-gray-100">Operations Funnel</h2>+ <span className="text-xs text-gray-500">Last {period}</span>+ </div>+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">+ {TILE_LABELS.map((l) => (+ <LoadingTile key={l} label={l} />+ ))}+ </div>+ </div>+ );+ }++ if (error) {+ return (+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4 text-sm text-gray-400">+ Funnel metrics unavailable.+ </div>+ );+ }++ const { deltas } = data;++ return (+ <div>+ <div className="flex items-center justify-between mb-3">+ <div>+ <h2 className="text-base font-semibold text-gray-100">+ Operations Funnel+ </h2>+ <p className="text-xs text-gray-500 mt-0.5">+ Live tenant pipeline: events → correlations → alerts+ </p>+ </div>+ <span className="text-xs text-gray-500">Last {period}</span>+ </div>++ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">+ <Tile+ label="Events of Interest"+ value={formatNumber(data.events_of_interest)}+ delta={deltas.events_of_interest}+ unit="events"+ />+ <Tile+ label="Correlation Instances"+ value={formatNumber(data.correlation_instances)}+ delta={deltas.correlation_instances}+ unit="groups"+ />+ <Tile+ label="Alerts Generated"+ value={formatNumber(data.alerts_generated)}+ delta={deltas.alerts_generated}+ unit="alerts"+ />+ <Tile+ label="Signal / Noise"+ value={formatPercent(data.signal_to_noise)}+ delta={deltas.signal_to_noise}+ unit="of dispositioned"+ />+ <Tile+ label="MTTD"+ value={formatDurationSeconds(data.mttd_seconds)}+ delta={deltas.mttd_seconds}+ lowerIsBetter+ unit="to first-seen"+ />+ <Tile+ label="Analyst Queue"+ value={formatNumber(data.analyst_queue_depth)}+ delta={deltas.analyst_queue_depth}+ lowerIsBetter+ unit="open"+ />+ </div>+ </div>+ );+}++export default FunnelKpiBar;diff --git a/apps/web/src/components/dashboard/PipelineHealth.tsx b/apps/web/src/components/dashboard/PipelineHealth.tsxnew file mode 100644index 000000000..fe963d940--- /dev/null+++ b/apps/web/src/components/dashboard/PipelineHealth.tsx@@ -0,0 +1,214 @@+'use client';++/**+ * PipelineHealth+ * ==============+ * Five-stage pipeline health strip (ingest → normalize → fuse → correlate → alert).+ * Each stage shows backlog, p95 latency, error rate, and an at-a-glance status+ * ({@link Status}). Mirrors the reference SOC console's pipeline-health rail.+ *+ * Data source: `GET /api/v1/health/pipeline` ({@link metricsApi.getPipelineHealth}).+ * Polls every 30 s; ignores SWR retries (the endpoint never throws under nominal+ * conditions — failures are reported in the row).+ *+ * Author: Beenu Arora <[email protected]>+ */++import useSWR from 'swr';+import { clsx } from 'clsx';+import {+ metricsApi,+ type PipelineHealth as PipelineHealthData,+ type PipelineStage,+} from '@/lib/api';++type Status = PipelineStage['status'];++const STAGE_LABELS: Record<PipelineStage['stage'], string> = {+ ingest: 'Ingest',+ normalize: 'Normalize',+ fuse: 'Fuse',+ correlate: 'Correlate',+ alert: 'Alert',+};++const STAGE_DESCRIPTIONS: Record<PipelineStage['stage'], string> = {+ ingest: 'Connector → raw events',+ normalize: 'OCSF mapping',+ fuse: 'Alert fusion',+ correlate: 'Cross-source correlation',+ alert: 'Final alert emission',+};++const STAGE_ORDER: PipelineStage['stage'][] = [+ 'ingest',+ 'normalize',+ 'fuse',+ 'correlate',+ 'alert',+];++function statusStyles(status: Status) {+ switch (status) {+ case 'green':+ return {+ dot: 'bg-green-500',+ ring: 'ring-green-500/30',+ text: 'text-green-400',+ bar: 'bg-green-500/70',+ };+ case 'yellow':+ return {+ dot: 'bg-amber-500',+ ring: 'ring-amber-500/30',+ text: 'text-amber-400',+ bar: 'bg-amber-500/70',+ };+ case 'red':+ return {+ dot: 'bg-red-500',+ ring: 'ring-red-500/30',+ text: 'text-red-400',+ bar: 'bg-red-500/70',+ };+ default:+ return {+ dot: 'bg-gray-600',+ ring: 'ring-gray-600/30',+ text: 'text-gray-500',+ bar: 'bg-gray-600/50',+ };+ }+}++function formatLatency(ms: number): string {+ if (!Number.isFinite(ms) || ms < 0) return '—';+ if (ms < 1) return '< 1 ms';+ if (ms < 1000) return `${Math.round(ms)} ms`;+ if (ms < 60_000) return `${(ms / 1000).toFixed(1).replace(/\.0$/, '')} s`;+ return `${(ms / 60_000).toFixed(1).replace(/\.0$/, '')} m`;+}++function formatBacklog(n: number): string {+ if (!Number.isFinite(n) || n < 0) return '—';+ if (n >= 1_000_000)+ return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`;+ if (n >= 1_000) return `${(n / 1_000).toFixed(1).replace(/\.0$/, '')}k`;+ return String(Math.round(n));+}++function formatErrorRate(ratio: number): string {+ if (!Number.isFinite(ratio) || ratio < 0) return '—';+ if (ratio === 0) return '0%';+ if (ratio < 0.001) return '< 0.1%';+ return `${(ratio * 100).toFixed(2).replace(/\.?0+$/, '')}%`;+}++function StageCard({ stage }: { stage: PipelineStage }) {+ const styles = statusStyles(stage.status);+ return (+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4 min-w-0">+ <div className="flex items-center justify-between mb-1">+ <p className="text-sm font-semibold text-gray-100 truncate">+ {STAGE_LABELS[stage.stage]}+ </p>+ <span+ className={clsx('h-2.5 w-2.5 rounded-full ring-2', styles.dot, styles.ring)}+ aria-label={`status ${stage.status}`}+ />+ </div>+ <p className="text-[11px] text-gray-500 truncate">+ {STAGE_DESCRIPTIONS[stage.stage]}+ </p>++ <dl className="mt-3 space-y-1.5">+ <div className="flex items-baseline justify-between text-xs">+ <dt className="text-gray-500">Backlog</dt>+ <dd className="font-medium text-gray-200 tabular-nums">+ {formatBacklog(stage.backlog)}+ </dd>+ </div>+ <div className="flex items-baseline justify-between text-xs">+ <dt className="text-gray-500">p95</dt>+ <dd className="font-medium text-gray-200 tabular-nums">+ {formatLatency(stage.p95_latency_ms)}+ </dd>+ </div>+ <div className="flex items-baseline justify-between text-xs">+ <dt className="text-gray-500">Errors</dt>+ <dd className={clsx('font-medium tabular-nums', styles.text)}>+ {formatErrorRate(stage.error_rate)}+ </dd>+ </div>+ </dl>+ </div>+ );+}++function LoadingStage({ stage }: { stage: PipelineStage['stage'] }) {+ return (+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4 min-w-0">+ <div className="flex items-center justify-between mb-1">+ <p className="text-sm font-semibold text-gray-100 truncate">+ {STAGE_LABELS[stage]}+ </p>+ <span className="h-2.5 w-2.5 rounded-full bg-gray-700 animate-pulse" />+ </div>+ <p className="text-[11px] text-gray-500 truncate">+ {STAGE_DESCRIPTIONS[stage]}+ </p>+ <div className="mt-3 space-y-2">+ <div className="h-3 w-full rounded bg-gray-800/60 animate-pulse" />+ <div className="h-3 w-full rounded bg-gray-800/60 animate-pulse" />+ <div className="h-3 w-2/3 rounded bg-gray-800/60 animate-pulse" />+ </div>+ </div>+ );+}++export function PipelineHealth() {+ const { data, error, isLoading } = useSWR<PipelineHealthData>(+ 'pipeline-health',+ () => metricsApi.getPipelineHealth(),+ {+ refreshInterval: 30_000,+ revalidateOnFocus: false,+ shouldRetryOnError: false,+ },+ );++ // Build a stage→data map and render in canonical order so the UI never+ // re-orders mid-flight even if the API ever changes its ordering.+ const stagesByName: Partial<Record<PipelineStage['stage'], PipelineStage>> = {};+ for (const s of data?.stages ?? []) stagesByName[s.stage] = s;++ return (+ <div>+ <div className="flex items-center justify-between mb-3">+ <div>+ <h2 className="text-base font-semibold text-gray-100">+ Pipeline Health+ </h2>+ <p className="text-xs text-gray-500 mt-0.5">+ Ingest → normalize → fuse → correlate → alert+ </p>+ </div>+ {error ? (+ <span className="text-xs text-red-400">unavailable</span>+ ) : (+ <span className="text-xs text-gray-500">Live</span>+ )}+ </div>++ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">+ {STAGE_ORDER.map((name) => {+ const stage = stagesByName[name];+ if (isLoading || !stage) return <LoadingStage key={name} stage={name} />;+ return <StageCard key={name} stage={stage} />;+ })}+ </div>+ </div>+ );+}++export default PipelineHealth;diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 6e1999b11..de989a210 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1432,6 +1432,64 @@ export interface DashboardMetrics {threatsBySource: Array<{ source: string; count: number }>;}+/**+ * Funnel KPI metrics (PR-3 / W1).+ *+ * Mirrors ``FunnelMetrics`` Pydantic model in+ * ``services/api/app/api/v1/endpoints/metrics.py``. Drives the+ * ``FunnelKpiBar`` and ``EfficiencyReport`` widgets on the dashboard.+ */+export interface FunnelMetrics {+ period: '1h' | '24h' | '7d' | '30d';+ events_of_interest: number;+ correlation_instances: number;+ alerts_generated: number;+ /** 0..1 ratio: 1 − (FP / total dispositioned alerts). */+ signal_to_noise: number;+ /** Mean time-to-detect in seconds (Alert.created_at → first_seen_at). */+ mttd_seconds: number;+ /** Active alerts owned by analysts (`status in new/triaging/in_progress`). */+ analyst_queue_depth: number;+ /** Alerts produced per correlation instance, clamped to [0, 1]. */+ correlation_efficiency: number;+ /** Alerts produced per event-of-interest, clamped to [0, 1]. */+ alert_yield: number;+ mitre_coverage: { covered: number; total: number; ratio: number };+ /** Period-over-period deltas (fraction, e.g. 0.05 = +5%). */+ deltas: {+ events_of_interest: number;+ correlation_instances: number;+ alerts_generated: number;+ signal_to_noise: number;+ mttd_seconds: number;+ analyst_queue_depth: number;+ };+ /** ISO-8601 server timestamp. */+ generated_at: string;+}++/**+ * Pipeline health (PR-3 / W9).+ *+ * Mirrors ``PipelineHealth`` Pydantic model. Drives the+ * ``PipelineHealth`` strip on /dashboard.+ */+export interface PipelineStage {+ stage: 'ingest' | 'normalize' | 'fuse' | 'correlate' | 'alert';+ backlog: number;+ p95_latency_ms: number;+ error_rate: number;+ status: 'unknown' | 'green' | 'yellow' | 'red';+}++export interface PipelineHealth {+ /** Worst stage status, surfaced at the top of the pipeline rail. */+ overall_status: 'unknown' | 'green' | 'yellow' | 'red';+ stages: PipelineStage[];+ /** ISO-8601 server timestamp. */+ generated_at: string;+}+export const metricsApi = {getDashboard: () =>request<DashboardMetrics>('/api/v1/metrics/dashboard'),@@ -1443,6 +1501,14 @@ export const metricsApi = {params: { period },},),++ /** Funnel KPIs (events → correlations → alerts) with deltas. */+ getFunnel: (period: '1h' | '24h' | '7d' | '30d' = '24h') =>+ request<FunnelMetrics>('/api/v1/metrics/funnel', { params: { period } }),++ /** Per-stage pipeline health (ingest → normalize → fuse → correlate → alert). */+ getPipelineHealth: () =>+ request<PipelineHealth>('/api/v1/health/pipeline'),};// ─── Connectors ──────────────────────────────────────────────────────────────diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 1248b0cc9..972429d84 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -5768,6 +5768,83 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/metrics/funnel:+ get:+ tags:+ - metrics+ summary: Get Funnel Metrics+ description: 'Return the live tenant funnel for the SOC Console (v1.5).+++ Funnel: events_of_interest → correlation_instances → alerts_generated →++ analyst_queue_depth, plus efficiency ratios and MITRE coverage.+++ ``deltas`` compares the current window to the immediately preceding window++ of the same length (e.g. for ``period=24h`` we compare to the 24h ending++ 24h ago). Values are percentage changes rounded to two decimals; a delta++ of ``0.0`` means "no meaningful baseline" (the previous window was empty).'+ operationId: get_funnel_metrics_api_v1_metrics_funnel_get+ security:+ - HTTPBearer: []+ parameters:+ - name: period+ in: query+ required: false+ schema:+ type: string+ pattern: ^(1h|24h|7d|30d)$+ default: 24h+ title: Period+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/FunnelMetrics'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/health/pipeline:+ get:+ tags:+ - health+ summary: Get Pipeline Health+ description: 'Return a 5-stage health snapshot of the SOC pipeline for the tenant.+++ Stages: ``ingest → normalize → fuse → correlate → alert``. See the++ module docstring for what each cell measures and why some columns++ are intentionally ``0`` until deeper instrumentation lands.+++ The window for latency / backlog computations is the last hour.++ The ``status`` ladder is ``unknown | green | yellow | red`` and++ follows the same convention as++ ``app.services.connector_freshness``.'+ operationId: get_pipeline_health_api_v1_health_pipeline_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/PipelineHealth'+ security:+ - HTTPBearer: []/api/v1/sla/metrics:get:tags:@@ -17006,6 +17083,102 @@ components:- updatedAttitle: FrontendDetectionRuledescription: Mirrors `DetectionRule` in apps/web/src/lib/api.ts.+ FunnelDeltas:+ properties:+ events_of_interest:+ type: number+ title: Events Of Interest+ correlation_instances:+ type: number+ title: Correlation Instances+ alerts_generated:+ type: number+ title: Alerts Generated+ signal_to_noise:+ type: number+ title: Signal To Noise+ mttd_seconds:+ type: number+ title: Mttd Seconds+ analyst_queue_depth:+ type: number+ title: Analyst Queue Depth+ type: object+ required:+ - events_of_interest+ - correlation_instances+ - alerts_generated+ - signal_to_noise+ - mttd_seconds+ - analyst_queue_depth+ title: FunnelDeltas+ description: Period-over-period percentage deltas for the funnel KPI bar.+ FunnelMetrics:+ properties:+ period:+ type: string+ title: Period+ events_of_interest:+ type: integer+ title: Events Of Interest+ correlation_instances:+ type: integer+ title: Correlation Instances+ alerts_generated:+ type: integer+ title: Alerts Generated+ signal_to_noise:+ type: number+ title: Signal To Noise+ mttd_seconds:+ type: number+ title: Mttd Seconds+ analyst_queue_depth:+ type: integer+ title: Analyst Queue Depth+ correlation_efficiency:+ type: number+ title: Correlation Efficiency+ alert_yield:+ type: number+ title: Alert Yield+ mitre_coverage:+ $ref: '#/components/schemas/MitreCoverage'+ deltas:+ $ref: '#/components/schemas/FunnelDeltas'+ generated_at:+ type: string+ format: date-time+ title: Generated At+ type: object+ required:+ - period+ - events_of_interest+ - correlation_instances+ - alerts_generated+ - signal_to_noise+ - mttd_seconds+ - analyst_queue_depth+ - correlation_efficiency+ - alert_yield+ - mitre_coverage+ - deltas+ - generated_at+ title: FunnelMetrics+ description: 'Tenant funnel + efficiency for the selected period.+++ All counts are absolute for ``period``. ``signal_to_noise`` is the++ fraction of *resolved* alerts that ended in disposition ``true_positive``++ (i.e. signal / (signal + noise)). ``mttd_seconds`` mirrors /metrics/soc''s++ MTTD definition (Alert.created_at → Alert.first_seen_at) but expressed in++ seconds for funnel-level precision. ``deltas`` compares this period to the++ immediately preceding period of the same length.'GateLogOut:properties:id:@@ -18857,6 +19030,31 @@ components:- pushedtitle: MispPushResultdescription: Embedded in a STIX response when ``push_to_misp=true``.+ MitreCoverage:+ properties:+ covered:+ type: integer+ title: Covered+ total:+ type: integer+ title: Total+ ratio:+ type: number+ title: Ratio+ type: object+ required:+ - covered+ - total+ - ratio+ title: MitreCoverage+ description: "Slice of the MITRE ATT&CK landscape we have observable coverage\+ \ for.\n\n``covered`` counts the distinct techniques observed via either:\n\+ \ * a tenant alert in the selected window (``Alert.mitre_techniques``), or\n\+ \ * an enabled tenant/platform detection rule\n (``DetectionRule.mitre_techniques``\+ \ where ``status == 'enabled'``).\n\n``total`` is configurable via ``AISOC_FUNNEL_MITRE_TOTAL``\+ \ and defaults to\nthe MITRE ATT&CK Enterprise v17 technique count (201) so\+ \ the ratio is\ninterpretable as \"% of ATT&CK we're watching for\". The ratio\+ \ is clamped to\n``[0.0, 1.0]`` even if operators downsize the universe."MitreCoverageCell:properties:techniqueId:@@ -19830,6 +20028,66 @@ components:- description- categorytitle: PermissionOut+ PipelineHealth:+ properties:+ overall_status:+ type: string+ title: Overall Status+ stages:+ items:+ $ref: '#/components/schemas/PipelineStage'+ type: array+ title: Stages+ generated_at:+ type: string+ format: date-time+ title: Generated At+ type: object+ required:+ - overall_status+ - stages+ - generated_at+ title: PipelineHealth+ description: Top-level response for ``GET /health/pipeline``.+ PipelineStage:+ properties:+ stage:+ type: string+ title: Stage+ backlog:+ type: integer+ title: Backlog+ p95_latency_ms:+ type: number+ title: P95 Latency Ms+ error_rate:+ type: number+ title: Error Rate+ status:+ type: string+ title: Status+ type: object+ required:+ - stage+ - backlog+ - p95_latency_ms+ - error_rate+ - status+ title: PipelineStage+ description: 'One row in the pipeline health strip.+++ ``status`` follows the green/yellow/red/unknown ladder used by++ ``app.services.connector_freshness``. ``backlog`` is the number of items++ currently waiting at this stage (e.g. enabled-but-stale connectors for++ ``ingest``, unacked alerts for ``alert``). ``p95_latency_ms`` is the 95th++ percentile end-to-end latency for items that traversed this stage in the++ last hour. ``error_rate`` is errors / processed in the same window.'PluginManifestOut:properties:id:diff --git a/services/api/app/api/v1/endpoints/health.py b/services/api/app/api/v1/endpoints/health.pynew file mode 100644index 000000000..1534a44d6--- /dev/null+++ b/services/api/app/api/v1/endpoints/health.py@@ -0,0 +1,511 @@+"""Pipeline health endpoint — operator-facing snapshot of the SOC pipeline.++Backs ``GET /api/v1/health/pipeline`` (v1.5 SOC Console parity).++Returns a 5-row strip describing the health of each stage of the+pipeline ``ingest → normalize → fuse → correlate → alert``. The shape+matches the ``PipelineHealth`` Pydantic model declared alongside the+funnel response in ``endpoints/metrics.py`` so the funnel and pipeline-+health views can share the same schema package.++Honest-measurement principles+-----------------------------++The plan calls for ``{backlog, p95_latency_ms, error_rate, status}`` per+stage. We compute each cell from data we *actually have* — no synthetic+fillers, no fake percentiles. When a column is genuinely unknowable+without deeper instrumentation (e.g. fusion-engine job timings), the+response is ``0`` (numeric) or ``unknown`` (status). The SOC Console UI+renders zeros as "n/a" pills rather than zero-bars so operators don't+read absence as "all good".++Per-stage definitions+---------------------++* **ingest** — events arriving from connectors. ``status`` aggregates+ ``app.services.connector_freshness`` across all enabled connectors+ (worst-of). ``backlog`` is the number of enabled connectors that+ haven't fired an event within 2× their per-category cadence (the+ ``red`` band in ``connector_freshness``). ``error_rate`` is+ ``unhealthy / enabled`` from ``Connector.health_status``.+ ``p95_latency_ms`` is left at 0 — we don't carry a source-side+ timestamp on the wire to compute true ingest lag.++* **normalize** — raw event JSON → structured ``Alert`` fields+ (event_time, src/dst, MITRE, severity). ``p95_latency_ms`` is+ ``percentile_cont(0.95) WITHIN GROUP (created_at - event_time)`` for+ alerts in the last hour where ``event_time`` was set. ``backlog``+ is 0 (no queue at this layer in the current pipeline). ``error_rate``+ is 0 — parse errors are not yet surfaced to Postgres.++* **fuse** — events grouped into alerts. ``p95_latency_ms`` is+ ``percentile_cont(0.95) WITHIN GROUP (last_seen - first_seen)`` for+ alerts in the window. ``backlog`` is 0 (the fusion engine doesn't+ queue alerts — it emits or drops). ``error_rate`` is 0.++* **correlate** — multi-event correlation. ``backlog`` is the count of+ recent *single-event* alerts (``jsonb_array_length(source_event_ids)+ = 1``) in the window — alerts that haven't yet been merged into a+ richer incident. ``p95_latency_ms`` is left at 0 (the fusion service+ doesn't emit per-correlation-job timing yet).++* **alert** — alert visible to analyst. ``backlog`` is the open queue+ depth (``status in ('new','triaging','in_progress')`` AND+ ``first_seen_at IS NULL``). ``p95_latency_ms`` is+ ``percentile_cont(0.95) WITHIN GROUP (first_seen_at - created_at)``+ — i.e. MTTD p95. ``error_rate`` is 0.++Status ladder+-------------++Each stage's status follows the same ladder used by+``connector_freshness``: ``unknown | green | yellow | red``. The+thresholds for latency-driven stages are read from two configurable+knobs in ``app.core.config``:++* ``AISOC_PIPELINE_STALE_WARN_SECONDS`` (default 600) — green ceiling+* ``AISOC_PIPELINE_STALE_DOWN_SECONDS`` (default 1800) — yellow ceiling++Any stage with no data in the window collapses to ``unknown`` rather+than ``green``, mirroring the "never paint green on absence of data"+rule in ``connector_freshness``.+"""++from __future__ import annotations++import logging+from datetime import UTC, datetime, timedelta+from typing import Any++from fastapi import APIRouter+from sqlalchemy import and_, func, select++from app.api.v1.deps import AuthUser, DBSession+from app.api.v1.endpoints.metrics import PipelineHealth, PipelineStage+from app.core.config import settings+from app.models.alert import Alert+from app.models.connector import Connector+from app.services.connector_freshness import compute_freshness++logger = logging.getLogger(__name__)++router = APIRouter(prefix="/health", tags=["health"])+++# ───────────────────────────── Status helpers ────────────────────────────────+++# Order from best to worst. ``unknown`` is slightly worse than ``green`` so a+# tenant with one brand-new (never-seen-an-event) connector still reports+# ``unknown`` overall rather than ``green`` — we never paint green on absence+# of data. Matches the convention enforced by ``connector_freshness``.+_STATUS_RANK: dict[str, int] = {"green": 0, "unknown": 1, "yellow": 2, "red": 3}+++def _status_from_latency(+ *,+ p95_seconds: float | None,+ warn_seconds: int,+ down_seconds: int,+) -> str:+ """Map a p95 latency to ``unknown|green|yellow|red``.++ ``None`` (no data in the window) → ``unknown``; we deliberately do+ not return ``green`` for absence of data.+ """+ if p95_seconds is None:+ return "unknown"+ if p95_seconds <= warn_seconds:+ return "green"+ if p95_seconds <= down_seconds:+ return "yellow"+ return "red"+++def _worst_status(statuses: list[str]) -> str:+ """Aggregate a list of statuses to the worst entry on ``_STATUS_RANK``."""+ if not statuses:+ return "unknown"+ return max(statuses, key=lambda s: _STATUS_RANK.get(s, 1))+++# Postgres ``percentile_cont(p)`` returns ``double precision``. SQLAlchemy+# exposes it via the ``func`` namespace; we wrap the (admittedly verbose)+# ``WITHIN GROUP (ORDER BY ...)`` expression here so the per-stage helpers+# below stay readable.+def _p95_seconds_expr(expr: Any) -> Any:+ """Build a SQLA expression for ``percentile_cont(0.95) WITHIN GROUP``.++ ``expr`` is the per-row scalar to take the percentile of (already in+ seconds — callers pass ``func.extract('epoch', ...)``).+ """+ return func.percentile_cont(0.95).within_group(expr)+++# ─────────────────────────────── ingest stage ────────────────────────────────+++async def _ingest_stage(db, tenant_id, *, now: datetime) -> PipelineStage:+ """Build the ``ingest`` row from connector freshness aggregates.++ Reads every Connector for the tenant, runs ``compute_freshness``+ per row (which honours per-instance cadence overrides via+ ``connector_config.expected_cadence_seconds``), then rolls the+ per-connector statuses up to a single worst-of verdict.+ """+ rows = (+ await db.execute(+ select(+ Connector.category,+ Connector.last_event_at,+ Connector.health_status,+ Connector.is_enabled,+ Connector.connector_config,+ ).where(Connector.tenant_id == tenant_id)+ )+ ).all()++ enabled = [r for r in rows if r.is_enabled]+ if not enabled:+ # No enabled connectors → nothing is flowing on purpose. Status+ # ``unknown`` rather than red so a fresh tenant doesn't see a+ # paged alert before they've onboarded anything.+ return PipelineStage(+ stage="ingest",+ backlog=0,+ p95_latency_ms=0.0,+ error_rate=0.0,+ status="unknown",+ )++ statuses: list[str] = []+ backlog = 0+ unhealthy = 0+ for r in enabled:+ override: int | None = None+ if isinstance(r.connector_config, dict):+ raw_override = r.connector_config.get("expected_cadence_seconds")+ if isinstance(raw_override, (int, float)) and raw_override > 0:+ override = int(raw_override)+ verdict = compute_freshness(+ category=r.category,+ last_event_at=r.last_event_at,+ now=now,+ override_seconds=override,+ )+ statuses.append(verdict.status)+ if verdict.status == "red":+ backlog += 1+ if r.health_status == "unhealthy":+ unhealthy += 1++ error_rate = round(unhealthy / len(enabled), 4) if enabled else 0.0+ return PipelineStage(+ stage="ingest",+ backlog=backlog,+ p95_latency_ms=0.0,+ error_rate=error_rate,+ status=_worst_status(statuses),+ )+++# ───────────────────────────── normalize stage ───────────────────────────────+++async def _normalize_stage(+ db,+ tenant_id,+ *,+ warn_seconds: int,+ down_seconds: int,+ window_start: datetime,+ window_end: datetime,+) -> PipelineStage:+ """Build the ``normalize`` row from event_time → created_at lag.++ The "normalize" step in the AiSOC pipeline is the transition from+ raw event JSON (carrying a vendor-side ``event_time``) to a fully+ structured ``Alert`` row in Postgres. The p95 lag between the two+ is the most honest single-number proxy for normalization latency.+ """+ p95_seconds = await db.scalar(+ select(_p95_seconds_expr(func.extract("epoch", Alert.created_at - Alert.event_time))).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= window_start,+ Alert.created_at < window_end,+ Alert.event_time.isnot(None),+ )+ )+ )+ if p95_seconds is None:+ return PipelineStage(+ stage="normalize",+ backlog=0,+ p95_latency_ms=0.0,+ error_rate=0.0,+ status="unknown",+ )++ p95_seconds = max(0.0, float(p95_seconds))+ return PipelineStage(+ stage="normalize",+ backlog=0,+ p95_latency_ms=round(p95_seconds * 1000.0, 2),+ error_rate=0.0,+ status=_status_from_latency(+ p95_seconds=p95_seconds,+ warn_seconds=warn_seconds,+ down_seconds=down_seconds,+ ),+ )+++# ─────────────────────────────── fuse stage ──────────────────────────────────+++async def _fuse_stage(+ db,+ tenant_id,+ *,+ warn_seconds: int,+ down_seconds: int,+ window_start: datetime,+ window_end: datetime,+) -> PipelineStage:+ """Build the ``fuse`` row from first_seen → last_seen spread.++ A single Alert can absorb many raw events. The spread between the+ earliest and latest contributing event (first_seen → last_seen)+ is the closest single-number proxy for fusion latency we can+ compute without instrumenting the fusion service itself.+ """+ p95_seconds = await db.scalar(+ select(_p95_seconds_expr(func.extract("epoch", Alert.last_seen - Alert.first_seen))).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= window_start,+ Alert.created_at < window_end,+ Alert.first_seen.isnot(None),+ Alert.last_seen.isnot(None),+ )+ )+ )+ if p95_seconds is None:+ return PipelineStage(+ stage="fuse",+ backlog=0,+ p95_latency_ms=0.0,+ error_rate=0.0,+ status="unknown",+ )++ p95_seconds = max(0.0, float(p95_seconds))+ return PipelineStage(+ stage="fuse",+ backlog=0,+ p95_latency_ms=round(p95_seconds * 1000.0, 2),+ error_rate=0.0,+ status=_status_from_latency(+ p95_seconds=p95_seconds,+ warn_seconds=warn_seconds,+ down_seconds=down_seconds,+ ),+ )+++# ───────────────────────────── correlate stage ───────────────────────────────+++async def _correlate_stage(+ db,+ tenant_id,+ *,+ window_start: datetime,+ window_end: datetime,+) -> PipelineStage:+ """Build the ``correlate`` row from single-event-alert backlog.++ Backlog = alerts in the window with exactly one source event (i.e.+ not yet correlated). Status is ``green`` if at least one alert in+ the window has multiple source events (correlation engine is+ working), ``yellow`` if alerts exist but none are multi-event+ (correlation engine is idle), and ``unknown`` if there are no+ alerts at all in the window.+ """+ single_event = (+ await db.scalar(+ select(func.count()).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= window_start,+ Alert.created_at < window_end,+ func.jsonb_array_length(Alert.source_event_ids) == 1,+ )+ )+ )+ or 0+ )+ multi_event = (+ await db.scalar(+ select(func.count()).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= window_start,+ Alert.created_at < window_end,+ func.jsonb_array_length(Alert.source_event_ids) >= 2,+ )+ )+ )+ or 0+ )++ total = int(single_event) + int(multi_event)+ if total == 0:+ status = "unknown"+ elif multi_event > 0:+ status = "green"+ else:+ status = "yellow"++ return PipelineStage(+ stage="correlate",+ backlog=int(single_event),+ p95_latency_ms=0.0,+ error_rate=0.0,+ status=status,+ )+++# ─────────────────────────────── alert stage ─────────────────────────────────+++async def _alert_stage(+ db,+ tenant_id,+ *,+ warn_seconds: int,+ down_seconds: int,+ window_start: datetime,+ window_end: datetime,+) -> PipelineStage:+ """Build the ``alert`` row from MTTD p95 + open-queue depth.++ Backlog is the open-queue depth (alerts visible to an analyst that+ haven't been viewed yet). ``p95_latency_ms`` is MTTD p95 — the+ p95 wall-clock gap between ``created_at`` (the alert appeared in+ Postgres) and ``first_seen_at`` (the analyst opened it).+ """+ unacked = (+ await db.scalar(+ select(func.count()).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.status.in_(("new", "triaging", "in_progress")),+ Alert.first_seen_at.is_(None),+ )+ )+ )+ or 0+ )++ p95_seconds = await db.scalar(+ select(_p95_seconds_expr(func.extract("epoch", Alert.first_seen_at - Alert.created_at))).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= window_start,+ Alert.created_at < window_end,+ Alert.first_seen_at.isnot(None),+ )+ )+ )++ if p95_seconds is None:+ # No alerts have been seen by an analyst in the window. If+ # there are unacked alerts in the queue we report ``yellow``+ # (the analyst is behind); otherwise ``unknown`` (no data).+ status = "yellow" if unacked > 0 else "unknown"+ latency_ms = 0.0+ else:+ p95_seconds = max(0.0, float(p95_seconds))+ latency_ms = round(p95_seconds * 1000.0, 2)+ status = _status_from_latency(+ p95_seconds=p95_seconds,+ warn_seconds=warn_seconds,+ down_seconds=down_seconds,+ )++ return PipelineStage(+ stage="alert",+ backlog=int(unacked),+ p95_latency_ms=latency_ms,+ error_rate=0.0,+ status=status,+ )+++# ─────────────────────────────── endpoint ────────────────────────────────────++[email protected]("/pipeline", response_model=PipelineHealth)+async def get_pipeline_health(+ user: AuthUser,+ db: DBSession,+) -> PipelineHealth:+ """Return a 5-stage health snapshot of the SOC pipeline for the tenant.++ Stages: ``ingest → normalize → fuse → correlate → alert``. See the+ module docstring for what each cell measures and why some columns+ are intentionally ``0`` until deeper instrumentation lands.++ The window for latency / backlog computations is the last hour.+ The ``status`` ladder is ``unknown | green | yellow | red`` and+ follows the same convention as+ ``app.services.connector_freshness``.+ """+ now = datetime.now(UTC)+ window_start = now - timedelta(hours=1)+ window_end = now++ warn_seconds = int(getattr(settings, "AISOC_PIPELINE_STALE_WARN_SECONDS", 600) or 600)+ down_seconds = int(getattr(settings, "AISOC_PIPELINE_STALE_DOWN_SECONDS", 1800) or 1800)++ stages = [+ await _ingest_stage(db, user.tenant_id, now=now),+ await _normalize_stage(+ db,+ user.tenant_id,+ warn_seconds=warn_seconds,+ down_seconds=down_seconds,+ window_start=window_start,+ window_end=window_end,+ ),+ await _fuse_stage(+ db,+ user.tenant_id,+ warn_seconds=warn_seconds,+ down_seconds=down_seconds,+ window_start=window_start,+ window_end=window_end,+ ),+ await _correlate_stage(+ db,+ user.tenant_id,+ window_start=window_start,+ window_end=window_end,+ ),+ await _alert_stage(+ db,+ user.tenant_id,+ warn_seconds=warn_seconds,+ down_seconds=down_seconds,+ window_start=window_start,+ window_end=window_end,+ ),+ ]++ return PipelineHealth(+ overall_status=_worst_status([s.status for s in stages]),+ stages=stages,+ generated_at=now,+ )diff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.pyindex 53d7202aa..468fef9cf 100644--- a/services/api/app/api/v1/endpoints/metrics.py+++ b/services/api/app/api/v1/endpoints/metrics.py@@ -12,20 +12,31 @@ Tier 1.4 (SOC metrics dashboard) — exposes:* Confidence calibration over time: reliability curve buckets — actualtrue-positive rate within each predicted-confidence bin* ATT&CK heatmap: tactic × technique counts++v1.5 (SOC Console parity) adds:+ * /metrics/funnel — live tenant funnel (events → correlations → alerts →+ analyst queue) with period support (1h|24h|7d|30d) and period-over-period+ deltas. Powers the new Funnel KPI bar + Efficiency Report on the+ dashboard."""+import loggingfrom datetime import UTC, datetime, timedelta-from fastapi import APIRouter+from fastapi import APIRouter, Queryfrom pydantic import BaseModelfrom sqlalchemy import and_, func, selectfrom app.api.v1.deps import AuthUser, DBSession+from app.core.config import settingsfrom app.models.alert import Alertfrom app.models.case import Casefrom app.models.connector import Connector+from app.models.detection_rule import DetectionRulefrom app.models.remediation import RemediationGateLog+logger = logging.getLogger(__name__)+router = APIRouter(prefix="/metrics", tags=["metrics"])@@ -77,6 +88,106 @@ class DashboardMetrics(BaseModel):threatsBySource: list[SourceThreat]+# ───────────────────────────── v1.5 Funnel models ─────────────────────────────+#+# These models back the new /metrics/funnel endpoint exposed by the SOC+# Console (v1.5 — Tier 6, W1 + W9). The endpoint is read by:+# * apps/web — <FunnelKpiBar /> on /dashboard+# * apps/web — <EfficiencyReport /> tile+# * apps/web — <NoiseRatio /> tile (replaces synthetic signal:noise)+#+# Shape is contract-frozen against the v1.5 SOC Console parity plan; do not+# rename fields without bumping the apps/web TS types in lockstep.+++class MitreCoverage(BaseModel):+ """Slice of the MITRE ATT&CK landscape we have observable coverage for.++ ``covered`` counts the distinct techniques observed via either:+ * a tenant alert in the selected window (``Alert.mitre_techniques``), or+ * an enabled tenant/platform detection rule+ (``DetectionRule.mitre_techniques`` where ``status == 'enabled'``).++ ``total`` is configurable via ``AISOC_FUNNEL_MITRE_TOTAL`` and defaults to+ the MITRE ATT&CK Enterprise v17 technique count (201) so the ratio is+ interpretable as "% of ATT&CK we're watching for". The ratio is clamped to+ ``[0.0, 1.0]`` even if operators downsize the universe.+ """++ covered: int+ total: int+ ratio: float+++class FunnelDeltas(BaseModel):+ """Period-over-period percentage deltas for the funnel KPI bar."""++ events_of_interest: float+ correlation_instances: float+ alerts_generated: float+ signal_to_noise: float+ mttd_seconds: float+ analyst_queue_depth: float+++class FunnelMetrics(BaseModel):+ """Tenant funnel + efficiency for the selected period.++ All counts are absolute for ``period``. ``signal_to_noise`` is the+ fraction of *resolved* alerts that ended in disposition ``true_positive``+ (i.e. signal / (signal + noise)). ``mttd_seconds`` mirrors /metrics/soc's+ MTTD definition (Alert.created_at → Alert.first_seen_at) but expressed in+ seconds for funnel-level precision. ``deltas`` compares this period to the+ immediately preceding period of the same length.+ """++ period: str+ events_of_interest: int+ correlation_instances: int+ alerts_generated: int+ signal_to_noise: float+ mttd_seconds: float+ analyst_queue_depth: int+ correlation_efficiency: float+ alert_yield: float+ mitre_coverage: MitreCoverage+ deltas: FunnelDeltas+ generated_at: datetime+++# ────────────────────────── v1.5 Pipeline-health models ───────────────────────+#+# Backs GET /health/pipeline. Surfaces a stage-by-stage health summary for the+# ingest → normalize → fuse → correlate → alert pipeline, which the SOC+# Console renders as the Pipeline Health strip on /dashboard.+++class PipelineStage(BaseModel):+ """One row in the pipeline health strip.++ ``status`` follows the green/yellow/red/unknown ladder used by+ ``app.services.connector_freshness``. ``backlog`` is the number of items+ currently waiting at this stage (e.g. enabled-but-stale connectors for+ ``ingest``, unacked alerts for ``alert``). ``p95_latency_ms`` is the 95th+ percentile end-to-end latency for items that traversed this stage in the+ last hour. ``error_rate`` is errors / processed in the same window.+ """++ stage: str+ backlog: int+ p95_latency_ms: float+ error_rate: float+ status: str+++class PipelineHealth(BaseModel):+ """Top-level response for ``GET /health/pipeline``."""++ overall_status: str+ stages: list[PipelineStage]+ generated_at: datetime++@router.get("/dashboard", response_model=DashboardMetrics)async def get_dashboard_metrics(user: AuthUser,@@ -541,3 +652,324 @@ async def get_alert_trend(for r in rows]}+++# ──────────────────────────── v1.5 funnel endpoint ────────────────────────────+++_FUNNEL_PERIOD_MAP: dict[str, timedelta] = {+ "1h": timedelta(hours=1),+ "24h": timedelta(hours=24),+ "7d": timedelta(days=7),+ "30d": timedelta(days=30),+}+++def _pct_delta(current: float, previous: float) -> float:+ """Compute period-over-period percentage change.++ Returns 0.0 when the previous value is zero (avoids `inf`). Otherwise:++ ((current - previous) / previous) * 100, rounded to 2 decimals.+ """+ if previous == 0:+ return 0.0+ return round(((current - previous) / previous) * 100.0, 2)+++async def _events_of_interest(db, tenant_id, start, end) -> int:+ """Count tenant raw events that landed in the analytical lake.++ Primary source is ``aisoc.raw_events`` in ClickHouse — the same table the+ fusion correlator reads — which is the source-of-truth for "events of+ interest" (i.e. anything an ingest connector emitted after enrichment but+ before alerting).++ Falls back to a PostgreSQL-derived count (sum of distinct+ ``source_event_ids`` across alerts in the window) when ClickHouse is+ disabled via ``AISOC_DISABLE_CLICKHOUSE`` or unreachable. This keeps the+ endpoint usable in air-gapped / Postgres-only deployments and in tests.+ """+ if getattr(settings, "AISOC_DISABLE_CLICKHOUSE", False):+ return await _events_of_interest_from_alerts(db, tenant_id, start, end)++ try:+ from app.db.clickhouse import (+ LakeQueryError,+ LakeQueryNotConfiguredError,+ execute_lake_query,+ )+ from app.services.lake_sql import rewrite_for_tenant+ except Exception: # pragma: no cover — defensive+ return await _events_of_interest_from_alerts(db, tenant_id, start, end)++ sql = (+ "SELECT count() AS cnt "+ "FROM aisoc.raw_events "+ f"WHERE ingested_at >= toDateTime('{start.strftime('%Y-%m-%d %H:%M:%S')}') "+ f"AND ingested_at < toDateTime('{end.strftime('%Y-%m-%d %H:%M:%S')}')"+ )++ try:+ rewrite = rewrite_for_tenant(sql, tenant_id, row_cap=1)+ result = await execute_lake_query(rewrite.sql, timeout_seconds=5.0)+ except LakeQueryNotConfiguredError:+ return await _events_of_interest_from_alerts(db, tenant_id, start, end)+ except LakeQueryError as exc:+ logger.warning("events_of_interest ClickHouse fallback: %s", exc)+ return await _events_of_interest_from_alerts(db, tenant_id, start, end)+ except Exception as exc: # pragma: no cover — defensive+ logger.warning("events_of_interest unexpected error: %s", exc)+ return await _events_of_interest_from_alerts(db, tenant_id, start, end)++ if not result.rows:+ return 0+ try:+ return int(result.rows[0][0] or 0)+ except (TypeError, ValueError, IndexError):+ return 0+++async def _events_of_interest_from_alerts(db, tenant_id, start, end) -> int:+ """Fallback EOI: sum of ``jsonb_array_length(source_event_ids)`` across+ alerts in the window. Conservative — only counts events that already+ correlated into an alert — but never lies in air-gapped deployments.+ """+ val = await db.scalar(+ select(func.coalesce(func.sum(func.jsonb_array_length(Alert.source_event_ids)), 0)).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= start,+ Alert.created_at < end,+ )+ )+ )+ return int(val or 0)+++async def _funnel_window(db, tenant_id, start, end, *, mitre_total: int) -> dict:+ """Compute the funnel for a single [start, end) window."""+ events_of_interest = await _events_of_interest(db, tenant_id, start, end)++ # Correlation instances = alerts whose source_event_ids has >= 2 events+ # (i.e. multiple raw events fused into a single alert). Single-event+ # alerts are excluded so the ratio stays meaningful when one detection+ # rule fires repeatedly.+ correlation_instances = (+ await db.scalar(+ select(func.count()).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= start,+ Alert.created_at < end,+ func.jsonb_array_length(Alert.source_event_ids) >= 2,+ )+ )+ )+ or 0+ )++ alerts_generated = (+ await db.scalar(+ select(func.count()).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= start,+ Alert.created_at < end,+ )+ )+ )+ or 0+ )++ # Signal-to-noise: of *resolved* alerts in the window, what fraction+ # ended in disposition='true_positive'? Closed alerts with no disposition+ # are excluded from both numerator and denominator so the ratio reflects+ # analyst judgement, not lifecycle state.+ sig_total = (+ await db.scalar(+ select(func.count()).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= start,+ Alert.created_at < end,+ Alert.disposition.in_(("true_positive", "false_positive", "benign", "duplicate")),+ )+ )+ )+ or 0+ )+ sig_tp = (+ await db.scalar(+ select(func.count()).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= start,+ Alert.created_at < end,+ Alert.disposition == "true_positive",+ )+ )+ )+ or 0+ )+ signal_to_noise = round((sig_tp / sig_total), 4) if sig_total else 0.0++ # MTTD in seconds for alerts created in this window that have been seen.+ mttd_seconds_raw = await db.scalar(+ select(func.avg(func.extract("epoch", Alert.first_seen_at - Alert.created_at))).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.first_seen_at.isnot(None),+ Alert.created_at >= start,+ Alert.created_at < end,+ )+ )+ )+ mttd_seconds = round(float(mttd_seconds_raw or 0.0), 2)++ # Analyst queue depth = open alerts (snapshot, not window-bound) that an+ # analyst would see in their queue right now: status in {new, triaging,+ # in_progress} and no disposition.+ analyst_queue_depth = (+ await db.scalar(+ select(func.count()).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.status.in_(("new", "triaging", "in_progress")),+ Alert.disposition.is_(None),+ )+ )+ )+ or 0+ )++ # Correlation efficiency = correlation_instances / events_of_interest.+ # "What share of raw events did the fusion engine collapse into a+ # correlated incident?" Capped at 1.0 in case EOI is under-counted by the+ # PostgreSQL fallback.+ if events_of_interest > 0:+ correlation_efficiency = round(min(correlation_instances / events_of_interest, 1.0), 4)+ else:+ correlation_efficiency = 0.0++ # Alert yield = alerts_generated / events_of_interest. "How many of the+ # raw events that landed in the lake became analyst-visible alerts?"+ if events_of_interest > 0:+ alert_yield = round(min(alerts_generated / events_of_interest, 1.0), 4)+ else:+ alert_yield = 0.0++ # MITRE coverage: union of distinct techniques across (a) alerts in the+ # window and (b) enabled detection rules visible to the tenant (platform+ # rules + tenant rules).+ covered = await _mitre_covered(db, tenant_id, start, end)+ ratio = round(min(covered / mitre_total, 1.0), 4) if mitre_total > 0 else 0.0+ coverage = MitreCoverage(covered=covered, total=mitre_total, ratio=ratio)++ return {+ "events_of_interest": int(events_of_interest),+ "correlation_instances": int(correlation_instances),+ "alerts_generated": int(alerts_generated),+ "signal_to_noise": signal_to_noise,+ "mttd_seconds": mttd_seconds,+ "analyst_queue_depth": int(analyst_queue_depth),+ "correlation_efficiency": correlation_efficiency,+ "alert_yield": alert_yield,+ "mitre_coverage": coverage,+ }+++async def _mitre_covered(db, tenant_id, start, end) -> int:+ """Count distinct MITRE techniques visible to this tenant.++ Union of:+ * techniques observed on alerts created in the window+ * techniques referenced by enabled detection rules (tenant-scoped or+ platform-wide where ``tenant_id IS NULL``)+ """+ alert_techs = (+ (+ await db.execute(+ select(func.distinct(func.jsonb_array_elements_text(Alert.mitre_techniques))).where(+ and_(+ Alert.tenant_id == tenant_id,+ Alert.created_at >= start,+ Alert.created_at < end,+ )+ )+ )+ )+ .scalars()+ .all()+ )++ rule_techs = (+ (+ await db.execute(+ select(func.distinct(func.jsonb_array_elements_text(DetectionRule.mitre_techniques))).where(+ and_(+ DetectionRule.status == "enabled",+ (DetectionRule.tenant_id == tenant_id) | (DetectionRule.tenant_id.is_(None)),+ )+ )+ )+ )+ .scalars()+ .all()+ )++ techniques = {t for t in alert_techs if t} | {t for t in rule_techs if t}+ return len(techniques)++[email protected]("/funnel", response_model=FunnelMetrics)+async def get_funnel_metrics(+ user: AuthUser,+ db: DBSession,+ period: str = Query("24h", pattern=r"^(1h|24h|7d|30d)$"),+) -> FunnelMetrics:+ """Return the live tenant funnel for the SOC Console (v1.5).++ Funnel: events_of_interest → correlation_instances → alerts_generated →+ analyst_queue_depth, plus efficiency ratios and MITRE coverage.++ ``deltas`` compares the current window to the immediately preceding window+ of the same length (e.g. for ``period=24h`` we compare to the 24h ending+ 24h ago). Values are percentage changes rounded to two decimals; a delta+ of ``0.0`` means "no meaningful baseline" (the previous window was empty).+ """+ delta = _FUNNEL_PERIOD_MAP[period]+ now = datetime.now(UTC)+ end = now+ start = end - delta+ prev_end = start+ prev_start = prev_end - delta++ mitre_total = int(getattr(settings, "AISOC_FUNNEL_MITRE_TOTAL", 201)) or 201++ current = await _funnel_window(db, user.tenant_id, start, end, mitre_total=mitre_total)+ previous = await _funnel_window(db, user.tenant_id, prev_start, prev_end, mitre_total=mitre_total)++ deltas = FunnelDeltas(+ events_of_interest=_pct_delta(current["events_of_interest"], previous["events_of_interest"]),+ correlation_instances=_pct_delta(current["correlation_instances"], previous["correlation_instances"]),+ alerts_generated=_pct_delta(current["alerts_generated"], previous["alerts_generated"]),+ signal_to_noise=_pct_delta(current["signal_to_noise"], previous["signal_to_noise"]),+ mttd_seconds=_pct_delta(current["mttd_seconds"], previous["mttd_seconds"]),+ analyst_queue_depth=_pct_delta(current["analyst_queue_depth"], previous["analyst_queue_depth"]),+ )++ return FunnelMetrics(+ period=period,+ events_of_interest=current["events_of_interest"],+ correlation_instances=current["correlation_instances"],+ alerts_generated=current["alerts_generated"],+ signal_to_noise=current["signal_to_noise"],+ mttd_seconds=current["mttd_seconds"],+ analyst_queue_depth=current["analyst_queue_depth"],+ correlation_efficiency=current["correlation_efficiency"],+ alert_yield=current["alert_yield"],+ mitre_coverage=current["mitre_coverage"],+ deltas=deltas,+ generated_at=now,+ )diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex 2a0b56918..da8d8267b 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -28,6 +28,7 @@ from app.api.v1.endpoints import (feedback,fusion,graph,+ health,hunts,identity_graph,identity_timeline,@@ -101,6 +102,11 @@ api_router.include_router(rbac.router)api_router.include_router(audit.router)api_router.include_router(compliance.router)api_router.include_router(metrics.router)+# v1.5 SOC Console parity — per-stage health strip for the operator+# dashboard. Lives at /api/v1/health/pipeline and returns the+# ingest → normalize → fuse → correlate → alert snapshot defined in+# endpoints/health.py.+api_router.include_router(health.router)api_router.include_router(sla.router)api_router.include_router(investigations.router)diff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex 33222ae52..77ee5ff78 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -318,6 +318,23 @@ class Settings(BaseSettings):# AISOC_FEATURE_DETECTION_DRIFT is True. Defaults to 168h (weekly).AISOC_DRIFT_SWEEP_INTERVAL_HOURS: int = 168+ # ------------------------------------------------------------------+ # v1.5 SOC Console parity — funnel + pipeline health (PR-3).+ # ------------------------------------------------------------------+ # Denominator used by /metrics/funnel mitre_coverage. Defaults to the+ # current size of the MITRE ATT&CK Enterprise technique catalog so the+ # ratio stays interpretable as "% of ATT&CK we're watching for". Operators+ # can pin a smaller universe (e.g. the subset they care about) via the env+ # var ``AISOC_FUNNEL_MITRE_TOTAL``.+ AISOC_FUNNEL_MITRE_TOTAL: int = 201++ # /health/pipeline staleness thresholds (seconds). A connector is treated+ # as "stale" when its ``last_event_at`` is older than the warn threshold+ # and "down" when it exceeds the down threshold. Defaults match the+ # 5-minute poll cadence documented in services/connectors.+ AISOC_PIPELINE_STALE_WARN_SECONDS: int = 600 # 10 minutes+ AISOC_PIPELINE_STALE_DOWN_SECONDS: int = 1800 # 30 minutes+# ------------------------------------------------------------------# Air-gapped operating mode (Tier 3.1 — air-gapped certification).# When AISOC_AIRGAPPED is True the API:diff --git a/services/api/tests/test_funnel_and_pipeline.py b/services/api/tests/test_funnel_and_pipeline.pynew file mode 100644index 000000000..f2d31509f--- /dev/null+++ b/services/api/tests/test_funnel_and_pipeline.py@@ -0,0 +1,1002 @@+"""Unit tests for the v1.5 SOC Console funnel + pipeline-health endpoints.++These two endpoints (``GET /api/v1/metrics/funnel`` and ``GET /api/v1/health/pipeline``)+back the new operator dashboard. They're pure read-side aggregations over+Postgres (and ClickHouse for one column on the funnel), so we test them+the same way the rest of the read-side endpoints in this project are+tested — patch the DB seam, exercise every branch in isolation, and+assert on the shape we hand back to FastAPI.++We deliberately do NOT spin up the TestClient here. The endpoint+functions are thin orchestrators around per-stage / per-metric helpers;+the integration tests in CI exercise the SQL against a real Postgres+fixture. The job of *this* file is to lock the per-cell math down to a+specification you can read in 30 seconds:++* "no data" returns ``unknown``, never ``green`` (mirrors+ ``connector_freshness``);+* deltas are percentage changes, never raw differences;+* p95 latency is reported in milliseconds, not seconds;+* MITRE coverage is computed against a configurable denominator;+* the overall pipeline status is the worst-of across the 5 stages.++If any of those invariants change without a corresponding test update,+the dashboard quietly starts lying — and that's exactly the kind of+regression the v1.5 honest-measurement plan was supposed to prevent.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++# ──────────────────────────────────────────────────────────────────────────────+# Helpers+# ──────────────────────────────────────────────────────────────────────────────+++def _user() -> SimpleNamespace:+ """Stand-in for ``CurrentUser`` — only ``tenant_id`` is read."""+ return SimpleNamespace(+ user_id=uuid.uuid4(),+ tenant_id=uuid.uuid4(),+ )+++def _connector_row(+ *,+ category: str = "edr",+ last_event_at: datetime | None = None,+ health_status: str = "healthy",+ is_enabled: bool = True,+ connector_config: dict | None = None,+) -> SimpleNamespace:+ """Stand-in for a row returned by the ingest-stage query.++ The query selects 5 columns: ``category``, ``last_event_at``,+ ``health_status``, ``is_enabled``, ``connector_config``. We+ expose them as attributes so the production code can keep+ using ``r.category`` style access without mock plumbing.+ """+ return SimpleNamespace(+ category=category,+ last_event_at=last_event_at,+ health_status=health_status,+ is_enabled=is_enabled,+ connector_config=connector_config or {},+ )+++def _execute_result_all(rows: list) -> MagicMock:+ """Mock ``await db.execute(...).all()`` returning ``rows``."""+ result = MagicMock()+ result.all = MagicMock(return_value=rows)+ return result+++def _scalars_all_result(values: list) -> MagicMock:+ """Mock ``await db.execute(...).scalars().all()`` returning ``values``."""+ scalars = MagicMock()+ scalars.all = MagicMock(return_value=values)+ result = MagicMock()+ result.scalars = MagicMock(return_value=scalars)+ return result+++# ──────────────────────────────────────────────────────────────────────────────+# /metrics/funnel — _pct_delta (pure)+# ──────────────────────────────────────────────────────────────────────────────+++class TestPctDelta:+ """Period-over-period percentage helper.++ Tiny and pure — the contract is exactly two lines: zero-base+ returns 0.0 (never ``inf``), otherwise round to two decimals.+ """++ def test_zero_previous_returns_zero(self) -> None:+ from app.api.v1.endpoints.metrics import _pct_delta++ # The dashboard cannot render ``inf`` or ``NaN`` — we'd+ # rather show "no change" than a useless ∞ pill.+ assert _pct_delta(10.0, 0.0) == 0.0+ assert _pct_delta(0.0, 0.0) == 0.0++ def test_positive_change(self) -> None:+ from app.api.v1.endpoints.metrics import _pct_delta++ # 100 → 150 ⇒ +50% exactly.+ assert _pct_delta(150.0, 100.0) == 50.0++ def test_negative_change(self) -> None:+ from app.api.v1.endpoints.metrics import _pct_delta++ # 100 → 75 ⇒ −25% exactly.+ assert _pct_delta(75.0, 100.0) == -25.0++ def test_rounds_to_two_decimals(self) -> None:+ from app.api.v1.endpoints.metrics import _pct_delta++ # 3/7 ⇒ 0.4285714… ⇒ 42.86% (2 dp).+ assert _pct_delta(10.0, 7.0) == round(((10 - 7) / 7) * 100.0, 2)+++# ──────────────────────────────────────────────────────────────────────────────+# /metrics/funnel — _funnel_window happy path+# ──────────────────────────────────────────────────────────────────────────────+++class TestFunnelWindow:+ """Single-window roll-up shared by current + previous windows."""++ @pytest.mark.asyncio+ async def test_returns_full_keyset_with_safe_defaults(self) -> None:+ # Empty tenant: every counter must be a Python ``int``/``float``+ # (never ``None``) and ``mitre_coverage`` must be a populated+ # ``MitreCoverage`` instance — Pydantic 422s otherwise.+ from app.api.v1.endpoints.metrics import MitreCoverage, _funnel_window++ db = MagicMock()+ # 7 scalar() calls in order:+ # 1. correlation_instances+ # 2. alerts_generated+ # 3. sig_total (disposition in the closed set)+ # 4. sig_tp (disposition='true_positive')+ # 5. mttd_seconds_raw+ # 6. analyst_queue_depth+ # _events_of_interest path uses _events_of_interest_from_alerts → 7. EOI sum+ db.scalar = AsyncMock(side_effect=[0, 0, 0, 0, 0, None, 0])+ # _mitre_covered calls db.execute() twice (alert_techs, rule_techs)+ db.execute = AsyncMock(+ side_effect=[+ _scalars_all_result([]),+ _scalars_all_result([]),+ ]+ )++ tenant = uuid.uuid4()+ start = datetime.now(UTC) - timedelta(hours=24)+ end = datetime.now(UTC)++ with patch(+ "app.api.v1.endpoints.metrics.settings",+ SimpleNamespace(AISOC_DISABLE_CLICKHOUSE=True, AISOC_FUNNEL_MITRE_TOTAL=201),+ ):+ result = await _funnel_window(db, tenant, start, end, mitre_total=201)++ assert result["events_of_interest"] == 0+ assert result["correlation_instances"] == 0+ assert result["alerts_generated"] == 0+ assert result["signal_to_noise"] == 0.0+ assert result["mttd_seconds"] == 0.0+ assert result["analyst_queue_depth"] == 0+ assert result["correlation_efficiency"] == 0.0+ assert result["alert_yield"] == 0.0+ assert isinstance(result["mitre_coverage"], MitreCoverage)+ assert result["mitre_coverage"].total == 201+ assert result["mitre_coverage"].covered == 0+ assert result["mitre_coverage"].ratio == 0.0++ @pytest.mark.asyncio+ async def test_signal_to_noise_uses_dispositioned_alerts(self) -> None:+ # 4 dispositioned, 1 true_positive → SNR = 0.25.+ from app.api.v1.endpoints.metrics import _funnel_window++ db = MagicMock()+ # scalar() order in _funnel_window (with ClickHouse disabled):+ # 1. EOI fallback → 50+ # 2. correlation_instances → 2+ # 3. alerts_generated → 10+ # 4. sig_total → 4+ # 5. sig_tp → 1+ # 6. mttd_seconds_raw → 60.0+ # 7. analyst_queue_depth → 3+ db.scalar = AsyncMock(side_effect=[50, 2, 10, 4, 1, 60.0, 3])+ db.execute = AsyncMock(+ side_effect=[+ _scalars_all_result([]),+ _scalars_all_result([]),+ ]+ )++ with patch(+ "app.api.v1.endpoints.metrics.settings",+ SimpleNamespace(AISOC_DISABLE_CLICKHOUSE=True, AISOC_FUNNEL_MITRE_TOTAL=201),+ ):+ result = await _funnel_window(+ db,+ uuid.uuid4(),+ datetime.now(UTC) - timedelta(hours=24),+ datetime.now(UTC),+ mitre_total=201,+ )++ assert result["signal_to_noise"] == 0.25+ # MTTD is in seconds, rounded to 2 dp.+ assert result["mttd_seconds"] == 60.0+ # Correlation efficiency = 2 correlated / 50 EOI = 0.04.+ assert result["correlation_efficiency"] == 0.04+ # Alert yield = 10 / 50 = 0.2.+ assert result["alert_yield"] == 0.2++ @pytest.mark.asyncio+ async def test_efficiency_clamps_to_one(self) -> None:+ # Postgres fallback can under-count EOI vs alerts → ratios > 1+ # are clamped to 1.0 so the UI doesn't render a nonsense "117%+ # alert yield" pill.+ from app.api.v1.endpoints.metrics import _funnel_window++ db = MagicMock()+ # Order: EOI=3, correlation=5, alerts=12, sig_total=0, sig_tp=0,+ # mttd=None, queue=0 → both ratios should clamp to 1.0.+ db.scalar = AsyncMock(side_effect=[3, 5, 12, 0, 0, None, 0])+ db.execute = AsyncMock(+ side_effect=[+ _scalars_all_result([]),+ _scalars_all_result([]),+ ]+ )++ with patch(+ "app.api.v1.endpoints.metrics.settings",+ SimpleNamespace(AISOC_DISABLE_CLICKHOUSE=True, AISOC_FUNNEL_MITRE_TOTAL=201),+ ):+ result = await _funnel_window(+ db,+ uuid.uuid4(),+ datetime.now(UTC) - timedelta(hours=24),+ datetime.now(UTC),+ mitre_total=201,+ )++ assert result["correlation_efficiency"] == 1.0+ assert result["alert_yield"] == 1.0++ @pytest.mark.asyncio+ async def test_mitre_coverage_unions_alerts_and_rules(self) -> None:+ # _mitre_covered unions: alerts techs ∪ enabled-rule techs.+ # The union must deduplicate.+ from app.api.v1.endpoints.metrics import _funnel_window++ db = MagicMock()+ # Minimum viable scalar fixtures.+ db.scalar = AsyncMock(side_effect=[0, 0, 0, 0, None, 0, 0])+ # alert_techs: T1078, T1059+ # rule_techs: T1059, T1110 → union = {T1078, T1059, T1110} = 3+ db.execute = AsyncMock(+ side_effect=[+ _scalars_all_result(["T1078", "T1059"]),+ _scalars_all_result(["T1059", "T1110"]),+ ]+ )++ with patch(+ "app.api.v1.endpoints.metrics.settings",+ SimpleNamespace(AISOC_DISABLE_CLICKHOUSE=True, AISOC_FUNNEL_MITRE_TOTAL=10),+ ):+ result = await _funnel_window(+ db,+ uuid.uuid4(),+ datetime.now(UTC) - timedelta(hours=24),+ datetime.now(UTC),+ mitre_total=10,+ )++ assert result["mitre_coverage"].covered == 3+ assert result["mitre_coverage"].total == 10+ assert result["mitre_coverage"].ratio == 0.3++ @pytest.mark.asyncio+ async def test_mitre_coverage_ratio_clamps_to_one(self) -> None:+ # If the tenant has more techniques in scope than the configured+ # ATT&CK total (operator misconfigured ``AISOC_FUNNEL_MITRE_TOTAL``),+ # we still clamp to 1.0 — the UI can't render "150% coverage".+ from app.api.v1.endpoints.metrics import _funnel_window++ db = MagicMock()+ db.scalar = AsyncMock(side_effect=[0, 0, 0, 0, None, 0, 0])+ db.execute = AsyncMock(+ side_effect=[+ _scalars_all_result([f"T{i}" for i in range(50)]),+ _scalars_all_result([]),+ ]+ )++ with patch(+ "app.api.v1.endpoints.metrics.settings",+ SimpleNamespace(AISOC_DISABLE_CLICKHOUSE=True, AISOC_FUNNEL_MITRE_TOTAL=10),+ ):+ result = await _funnel_window(+ db,+ uuid.uuid4(),+ datetime.now(UTC) - timedelta(hours=24),+ datetime.now(UTC),+ mitre_total=10,+ )++ assert result["mitre_coverage"].covered == 50+ assert result["mitre_coverage"].ratio == 1.0+++# ──────────────────────────────────────────────────────────────────────────────+# /metrics/funnel — endpoint orchestration+# ──────────────────────────────────────────────────────────────────────────────+++class TestGetFunnelMetrics:+ """End-to-end assembly: current + previous window, deltas, schema."""++ @pytest.mark.asyncio+ async def test_returns_funnel_metrics_with_deltas(self) -> None:+ from app.api.v1.endpoints.metrics import (+ FunnelMetrics,+ MitreCoverage,+ get_funnel_metrics,+ )++ user = _user()++ # We patch ``_funnel_window`` directly so we don't have to feed+ # the SQL helper 14 mock side_effects in the right order. This+ # keeps the test focused on the orchestrator's job: pulling two+ # windows, computing deltas, packaging into ``FunnelMetrics``.+ current = {+ "events_of_interest": 200,+ "correlation_instances": 30,+ "alerts_generated": 50,+ "signal_to_noise": 0.6,+ "mttd_seconds": 90.0,+ "analyst_queue_depth": 5,+ "correlation_efficiency": 0.15,+ "alert_yield": 0.25,+ "mitre_coverage": MitreCoverage(covered=30, total=201, ratio=0.1493),+ }+ previous = {+ "events_of_interest": 100,+ "correlation_instances": 10,+ "alerts_generated": 25,+ "signal_to_noise": 0.5,+ "mttd_seconds": 100.0,+ "analyst_queue_depth": 8,+ "correlation_efficiency": 0.1,+ "alert_yield": 0.25,+ "mitre_coverage": MitreCoverage(covered=20, total=201, ratio=0.0995),+ }++ with patch(+ "app.api.v1.endpoints.metrics._funnel_window",+ new=AsyncMock(side_effect=[current, previous]),+ ):+ payload = await get_funnel_metrics(user=user, db=MagicMock(), period="24h")++ assert isinstance(payload, FunnelMetrics)+ assert payload.period == "24h"+ assert payload.events_of_interest == 200+ assert payload.correlation_instances == 30+ assert payload.alerts_generated == 50+ assert payload.signal_to_noise == 0.6+ assert payload.mttd_seconds == 90.0+ assert payload.analyst_queue_depth == 5+ assert payload.correlation_efficiency == 0.15+ assert payload.alert_yield == 0.25+ assert payload.mitre_coverage.covered == 30+ # Deltas are percent change vs previous window.+ # EOI: 200 vs 100 → +100%+ assert payload.deltas.events_of_interest == 100.0+ # Correlations: 30 vs 10 → +200%+ assert payload.deltas.correlation_instances == 200.0+ # Alerts: 50 vs 25 → +100%+ assert payload.deltas.alerts_generated == 100.0+ # SNR: 0.6 vs 0.5 → +20%+ assert payload.deltas.signal_to_noise == 20.0+ # MTTD: 90 vs 100 → −10% (faster is better — UI flips sign)+ assert payload.deltas.mttd_seconds == -10.0+ # Queue: 5 vs 8 → −37.5%+ assert payload.deltas.analyst_queue_depth == -37.5++ @pytest.mark.asyncio+ async def test_period_validation_accepts_known_values(self) -> None:+ # The pattern regex on the ``period`` query is the *only* place+ # the API enforces the four allowed windows. Make sure every+ # documented period maps to a non-zero ``timedelta`` so we+ # can't accidentally drop one.+ from app.api.v1.endpoints.metrics import _FUNNEL_PERIOD_MAP++ assert set(_FUNNEL_PERIOD_MAP.keys()) == {"1h", "24h", "7d", "30d"}+ for window in _FUNNEL_PERIOD_MAP.values():+ assert window.total_seconds() > 0+++# ──────────────────────────────────────────────────────────────────────────────+# /health/pipeline — pure helpers+# ──────────────────────────────────────────────────────────────────────────────+++class TestStatusFromLatency:+ """Latency → status ladder.++ Specification: ``None`` is never ``green``. Below the warn ceiling+ is ``green``; below the down ceiling is ``yellow``; above is+ ``red``. Boundaries are inclusive on the lower side (i.e. exactly+ ``warn_seconds`` is still ``green``).+ """++ def test_none_returns_unknown(self) -> None:+ from app.api.v1.endpoints.health import _status_from_latency++ assert _status_from_latency(p95_seconds=None, warn_seconds=600, down_seconds=1800) == "unknown"++ def test_below_warn_is_green(self) -> None:+ from app.api.v1.endpoints.health import _status_from_latency++ assert _status_from_latency(p95_seconds=0.0, warn_seconds=600, down_seconds=1800) == "green"+ assert _status_from_latency(p95_seconds=599.0, warn_seconds=600, down_seconds=1800) == "green"+ # Exactly at the warn ceiling → still green (≤, not <).+ assert _status_from_latency(p95_seconds=600.0, warn_seconds=600, down_seconds=1800) == "green"++ def test_below_down_is_yellow(self) -> None:+ from app.api.v1.endpoints.health import _status_from_latency++ assert _status_from_latency(p95_seconds=601.0, warn_seconds=600, down_seconds=1800) == "yellow"+ # Exactly at the down ceiling → still yellow.+ assert _status_from_latency(p95_seconds=1800.0, warn_seconds=600, down_seconds=1800) == "yellow"++ def test_above_down_is_red(self) -> None:+ from app.api.v1.endpoints.health import _status_from_latency++ assert _status_from_latency(p95_seconds=1801.0, warn_seconds=600, down_seconds=1800) == "red"+++class TestWorstStatus:+ """Aggregator that drives ``overall_status`` and the ingest roll-up."""++ def test_empty_list_returns_unknown(self) -> None:+ from app.api.v1.endpoints.health import _worst_status++ # A tenant with no enabled stages → "we don't know," not "all good".+ assert _worst_status([]) == "unknown"++ def test_returns_worst_entry(self) -> None:+ from app.api.v1.endpoints.health import _worst_status++ assert _worst_status(["green", "green"]) == "green"+ assert _worst_status(["green", "yellow"]) == "yellow"+ assert _worst_status(["green", "yellow", "red"]) == "red"+ assert _worst_status(["yellow", "red"]) == "red"++ def test_unknown_ranks_worse_than_green(self) -> None:+ from app.api.v1.endpoints.health import _worst_status++ # Mirrors connector_freshness: we never paint green over+ # an "unknown" — a brand-new connector with no events yet+ # should not let the tenant's overall_status say "green."+ assert _worst_status(["green", "unknown"]) == "unknown"++ def test_unknown_ranks_better_than_yellow(self) -> None:+ from app.api.v1.endpoints.health import _worst_status++ assert _worst_status(["unknown", "yellow"]) == "yellow"+ assert _worst_status(["unknown", "red"]) == "red"++ def test_unrecognised_status_defaults_to_unknown_rank(self) -> None:+ # Defensive: a typo / drift in status strings must NOT+ # let a stage win the aggregation by accident.+ from app.api.v1.endpoints.health import _worst_status++ # ``"weird"`` resolves to the same rank as "unknown" (1),+ # which is worse than "green" (0) but better than "yellow" (2).+ assert _worst_status(["green", "weird"]) in ("weird", "unknown")+ assert _worst_status(["weird", "yellow"]) == "yellow"+++# ──────────────────────────────────────────────────────────────────────────────+# /health/pipeline — per-stage helpers+# ──────────────────────────────────────────────────────────────────────────────+++class TestIngestStage:+ """Connector freshness roll-up."""++ @pytest.mark.asyncio+ async def test_no_enabled_connectors_returns_unknown(self) -> None:+ from app.api.v1.endpoints.health import _ingest_stage++ # A fresh tenant with zero connectors should report ``unknown``,+ # NOT ``red`` — they haven't onboarded anything yet and a red+ # pill on the dashboard would page them gratuitously.+ db = MagicMock()+ db.execute = AsyncMock(return_value=_execute_result_all([]))++ stage = await _ingest_stage(db, uuid.uuid4(), now=datetime.now(UTC))+ assert stage.stage == "ingest"+ assert stage.backlog == 0+ assert stage.p95_latency_ms == 0.0+ assert stage.error_rate == 0.0+ assert stage.status == "unknown"++ @pytest.mark.asyncio+ async def test_all_disabled_connectors_returns_unknown(self) -> None:+ from app.api.v1.endpoints.health import _ingest_stage++ db = MagicMock()+ db.execute = AsyncMock(return_value=_execute_result_all([_connector_row(is_enabled=False)]))+ stage = await _ingest_stage(db, uuid.uuid4(), now=datetime.now(UTC))+ assert stage.status == "unknown"+ assert stage.backlog == 0++ @pytest.mark.asyncio+ async def test_all_green_connectors_returns_green(self) -> None:+ from app.api.v1.endpoints.health import _ingest_stage++ now = datetime.now(UTC)+ # EDR cadence is 5 min → 1 min ago is well within green.+ recent = now - timedelta(minutes=1)+ db = MagicMock()+ db.execute = AsyncMock(+ return_value=_execute_result_all(+ [+ _connector_row(category="edr", last_event_at=recent),+ _connector_row(category="siem", last_event_at=recent),+ ]+ )+ )++ stage = await _ingest_stage(db, uuid.uuid4(), now=now)+ assert stage.status == "green"+ assert stage.backlog == 0+ assert stage.error_rate == 0.0++ @pytest.mark.asyncio+ async def test_one_stale_connector_pushes_red(self) -> None:+ from app.api.v1.endpoints.health import _ingest_stage++ now = datetime.now(UTC)+ # 1 healthy + 1 way past 2× EDR cadence (5 min × 2 = 10 min).+ db = MagicMock()+ db.execute = AsyncMock(+ return_value=_execute_result_all(+ [+ _connector_row(category="edr", last_event_at=now - timedelta(minutes=1)),+ _connector_row(category="edr", last_event_at=now - timedelta(hours=2)),+ ]+ )+ )++ stage = await _ingest_stage(db, uuid.uuid4(), now=now)+ assert stage.status == "red"+ # Exactly one connector in the red band.+ assert stage.backlog == 1++ @pytest.mark.asyncio+ async def test_error_rate_uses_health_status(self) -> None:+ from app.api.v1.endpoints.health import _ingest_stage++ now = datetime.now(UTC)+ recent = now - timedelta(minutes=1)+ db = MagicMock()+ db.execute = AsyncMock(+ return_value=_execute_result_all(+ [+ _connector_row(+ category="edr",+ last_event_at=recent,+ health_status="healthy",+ ),+ _connector_row(+ category="edr",+ last_event_at=recent,+ health_status="unhealthy",+ ),+ _connector_row(+ category="edr",+ last_event_at=recent,+ health_status="unhealthy",+ ),+ _connector_row(+ category="edr",+ last_event_at=recent,+ health_status="healthy",+ ),+ ]+ )+ )++ stage = await _ingest_stage(db, uuid.uuid4(), now=now)+ # 2 unhealthy / 4 enabled = 0.5 error rate.+ assert stage.error_rate == 0.5++ @pytest.mark.asyncio+ async def test_per_connector_cadence_override_is_honoured(self) -> None:+ from app.api.v1.endpoints.health import _ingest_stage++ now = datetime.now(UTC)+ # SIEM default is 15 min. Without the override, 30 min ago+ # would be RED (> 2× cadence). With override=3600 (1h), it's+ # still GREEN (≤ cadence).+ db = MagicMock()+ db.execute = AsyncMock(+ return_value=_execute_result_all(+ [+ _connector_row(+ category="siem",+ last_event_at=now - timedelta(minutes=30),+ connector_config={"expected_cadence_seconds": 3600},+ )+ ]+ )+ )++ stage = await _ingest_stage(db, uuid.uuid4(), now=now)+ assert stage.status == "green"+++class TestNormalizeStage:+ """Normalize p95 from ``created_at - event_time`` (seconds → ms)."""++ @pytest.mark.asyncio+ async def test_no_data_returns_unknown(self) -> None:+ from app.api.v1.endpoints.health import _normalize_stage++ # ``percentile_cont`` returns NULL when no rows match → None+ # → must be ``unknown`` rather than a misleading ``green``.+ db = MagicMock()+ db.scalar = AsyncMock(return_value=None)++ now = datetime.now(UTC)+ stage = await _normalize_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.stage == "normalize"+ assert stage.status == "unknown"+ assert stage.p95_latency_ms == 0.0++ @pytest.mark.asyncio+ async def test_fast_p95_is_green_and_in_milliseconds(self) -> None:+ from app.api.v1.endpoints.health import _normalize_stage++ db = MagicMock()+ # 12.5 seconds end-to-end normalize lag.+ db.scalar = AsyncMock(return_value=12.5)++ now = datetime.now(UTC)+ stage = await _normalize_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.status == "green"+ # 12.5s → 12500.0ms (no rounding loss; the round() to 2dp+ # only matters for fractional ms).+ assert stage.p95_latency_ms == 12500.0++ @pytest.mark.asyncio+ async def test_slow_p95_is_red(self) -> None:+ from app.api.v1.endpoints.health import _normalize_stage++ db = MagicMock()+ # 1h normalize lag → above the default 30-min down ceiling.+ db.scalar = AsyncMock(return_value=3600.0)++ now = datetime.now(UTC)+ stage = await _normalize_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.status == "red"+ assert stage.p95_latency_ms == 3600_000.0++ @pytest.mark.asyncio+ async def test_negative_lag_floors_to_zero(self) -> None:+ # Clock skew can produce a negative p95 lag (event_time later+ # than created_at, e.g. NTP drift on a connector). We clamp+ # to zero rather than reporting a negative ms latency.+ from app.api.v1.endpoints.health import _normalize_stage++ db = MagicMock()+ db.scalar = AsyncMock(return_value=-5.0)++ now = datetime.now(UTC)+ stage = await _normalize_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.p95_latency_ms == 0.0+ assert stage.status == "green"+++class TestFuseStage:+ """Fuse p95 mirrors normalize — same shape, different SQL."""++ @pytest.mark.asyncio+ async def test_no_data_returns_unknown(self) -> None:+ from app.api.v1.endpoints.health import _fuse_stage++ db = MagicMock()+ db.scalar = AsyncMock(return_value=None)+ now = datetime.now(UTC)+ stage = await _fuse_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.stage == "fuse"+ assert stage.status == "unknown"+ assert stage.p95_latency_ms == 0.0++ @pytest.mark.asyncio+ async def test_p95_window_in_yellow_band(self) -> None:+ from app.api.v1.endpoints.health import _fuse_stage++ db = MagicMock()+ # 800s ⇒ above warn (600) but below down (1800) → yellow.+ db.scalar = AsyncMock(return_value=800.0)+ now = datetime.now(UTC)+ stage = await _fuse_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.status == "yellow"+ assert stage.p95_latency_ms == 800_000.0+++class TestCorrelateStage:+ """Correlation health: backlog = single-event alerts; status by mix."""++ @pytest.mark.asyncio+ async def test_no_alerts_returns_unknown(self) -> None:+ from app.api.v1.endpoints.health import _correlate_stage++ db = MagicMock()+ # single_event=0, multi_event=0.+ db.scalar = AsyncMock(side_effect=[0, 0])+ now = datetime.now(UTC)+ stage = await _correlate_stage(+ db,+ uuid.uuid4(),+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.stage == "correlate"+ assert stage.status == "unknown"+ assert stage.backlog == 0++ @pytest.mark.asyncio+ async def test_only_single_event_alerts_returns_yellow(self) -> None:+ # Correlation engine isn't producing multi-event alerts —+ # backlog = single-event count, status = yellow.+ from app.api.v1.endpoints.health import _correlate_stage++ db = MagicMock()+ # single_event=7, multi_event=0.+ db.scalar = AsyncMock(side_effect=[7, 0])+ now = datetime.now(UTC)+ stage = await _correlate_stage(+ db,+ uuid.uuid4(),+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.status == "yellow"+ assert stage.backlog == 7++ @pytest.mark.asyncio+ async def test_mixed_alerts_returns_green_with_backlog(self) -> None:+ from app.api.v1.endpoints.health import _correlate_stage++ db = MagicMock()+ # 3 still-single + 2 already-correlated → green, backlog=3.+ db.scalar = AsyncMock(side_effect=[3, 2])+ now = datetime.now(UTC)+ stage = await _correlate_stage(+ db,+ uuid.uuid4(),+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.status == "green"+ assert stage.backlog == 3+++class TestAlertStage:+ """Alert queue depth + MTTD p95."""++ @pytest.mark.asyncio+ async def test_no_unacked_no_data_is_unknown(self) -> None:+ from app.api.v1.endpoints.health import _alert_stage++ db = MagicMock()+ # unacked=0, p95=None.+ db.scalar = AsyncMock(side_effect=[0, None])+ now = datetime.now(UTC)+ stage = await _alert_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.stage == "alert"+ assert stage.backlog == 0+ assert stage.status == "unknown"+ assert stage.p95_latency_ms == 0.0++ @pytest.mark.asyncio+ async def test_unacked_no_p95_is_yellow(self) -> None:+ # Queue has work but nothing's been seen yet → analyst is+ # behind ⇒ yellow.+ from app.api.v1.endpoints.health import _alert_stage++ db = MagicMock()+ db.scalar = AsyncMock(side_effect=[7, None])+ now = datetime.now(UTC)+ stage = await _alert_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.backlog == 7+ assert stage.status == "yellow"++ @pytest.mark.asyncio+ async def test_fast_mttd_is_green(self) -> None:+ from app.api.v1.endpoints.health import _alert_stage++ db = MagicMock()+ # 0 unacked, 45s MTTD p95.+ db.scalar = AsyncMock(side_effect=[0, 45.0])+ now = datetime.now(UTC)+ stage = await _alert_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.status == "green"+ assert stage.p95_latency_ms == 45000.0+ assert stage.backlog == 0++ @pytest.mark.asyncio+ async def test_slow_mttd_is_red(self) -> None:+ from app.api.v1.endpoints.health import _alert_stage++ db = MagicMock()+ # 2 hours MTTD p95 → well above the down ceiling.+ db.scalar = AsyncMock(side_effect=[3, 7200.0])+ now = datetime.now(UTC)+ stage = await _alert_stage(+ db,+ uuid.uuid4(),+ warn_seconds=600,+ down_seconds=1800,+ window_start=now - timedelta(hours=1),+ window_end=now,+ )+ assert stage.status == "red"+ assert stage.p95_latency_ms == 7_200_000.0+ assert stage.backlog == 3+++# ──────────────────────────────────────────────────────────────────────────────+# /health/pipeline — endpoint orchestration+# ──────────────────────────────────────────────────────────────────────────────+++class TestGetPipelineHealth:+ """End-to-end assembly: five stages in order, worst-of overall."""++ @pytest.mark.asyncio+ async def test_returns_five_stages_in_canonical_order(self) -> None:+ from app.api.v1.endpoints.health import (+ PipelineHealth,+ PipelineStage,+ get_pipeline_health,+ )++ # Patch each stage helper so we don't have to feed a long+ # AsyncMock side_effect chain. The orchestrator's job is the+ # ordering + overall_status — that's what we lock in here.+ ingest = PipelineStage(stage="ingest", backlog=0, p95_latency_ms=0.0, error_rate=0.0, status="green")+ normalize = PipelineStage(stage="normalize", backlog=0, p95_latency_ms=10.0, error_rate=0.0, status="green")+ fuse = PipelineStage(stage="fuse", backlog=0, p95_latency_ms=20.0, error_rate=0.0, status="green")+ correlate = PipelineStage(stage="correlate", backlog=0, p95_latency_ms=0.0, error_rate=0.0, status="green")+ alert = PipelineStage(stage="alert", backlog=0, p95_latency_ms=30.0, error_rate=0.0, status="green")++ with (+ patch("app.api.v1.endpoints.health._ingest_stage", new=AsyncMock(return_value=ingest)),+ patch(+ "app.api.v1.endpoints.health._normalize_stage",+ new=AsyncMock(return_value=normalize),+ ),+ patch("app.api.v1.endpoints.health._fuse_stage", new=AsyncMock(return_value=fuse)),+ patch(+ "app.api.v1.endpoints.health._correlate_stage",+ new=AsyncMock(return_value=correlate),+ ),+ patch(+ "app.api.v1.endpoints.health._alert_stage",+ new=AsyncMock(return_value=alert),+ ),+ ):+ payload = await get_pipeline_health(user=_user(), db=MagicMock())++ assert isinstance(payload, PipelineHealth)+ assert [s.stage for s in payload.stages] == [+ "ingest",+ "normalize",+ "fuse",+ "correlate",+ "alert",+ ]+ # All green ⇒ overall green.+ assert payload.overall_status == "green"+ # ``generated_at`` should be very close to "now".+ assert (datetime.now(UTC) - payload.generated_at).total_seconds() < 5++ @pytest.mark.asyncio+ async def test_overall_is_worst_of_stages(self) -> None:+ from app.api.v1.endpoints.health import (+ PipelineStage,+ get_pipeline_health,+ )++ # 1 yellow stage among greens ⇒ overall yellow.+ green = PipelineStage(stage="x", backlog=0, p95_latency_ms=0.0, error_rate=0.0, status="green")+ yellow = PipelineStage(stage="alert", backlog=4, p95_latency_ms=900_000.0, error_rate=0.0, status="yellow")++ with (+ patch("app.api.v1.endpoints.health._ingest_stage", new=AsyncMock(return_value=green)),+ patch("app.api.v1.endpoints.health._normalize_stage", new=AsyncMock(return_value=green)),+ patch("app.api.v1.endpoints.health._fuse_stage", new=AsyncMock(return_value=green)),+ patch("app.api.v1.endpoints.health._correlate_stage", new=AsyncMock(return_value=green)),+ patch("app.api.v1.endpoints.health._alert_stage", new=AsyncMock(return_value=yellow)),+ ):+ payload = await get_pipeline_health(user=_user(), db=MagicMock())++ assert payload.overall_status == "yellow"++ # 1 red stage ⇒ overall red, no matter what the others say.+ red = PipelineStage(stage="fuse", backlog=0, p95_latency_ms=99_999_999.0, error_rate=0.0, status="red")++ with (+ patch("app.api.v1.endpoints.health._ingest_stage", new=AsyncMock(return_value=green)),+ patch("app.api.v1.endpoints.health._normalize_stage", new=AsyncMock(return_value=green)),+ patch("app.api.v1.endpoints.health._fuse_stage", new=AsyncMock(return_value=red)),+ patch("app.api.v1.endpoints.health._correlate_stage", new=AsyncMock(return_value=green)),+ patch("app.api.v1.endpoints.health._alert_stage", new=AsyncMock(return_value=yellow)),+ ):+ payload = await get_pipeline_health(user=_user(), db=MagicMock())+ assert payload.overall_status == "red"