/** * src/analytics/slo/bi-slo.ts * ============================ * BI-P103 — BI SLO. DoD: "measured baselines exist". * * An SLO you cannot measure from real telemetry is a wish, so every objective * here declares WHERE its number comes from, and the evaluator refuses to * produce a number it does not have. Three ways that refusal shows up, each of * which is a lie the usual implementation tells: * * insufficient_data nothing (or too little) was observed in the window. * An availability objective evaluated over zero events * is NOT 100% attainment — it is silence. This is the * single most common false green in SLO reporting, and * it is the same shape BI-P025 found in a quality * check over an empty table. * not_measurable_here the objective is real but these events cannot * measure it. Dashboard data FRESHNESS is a property * of the dataset (BI-P026 / BI-P105 watermarks), not * of a usage event, and REPORT DELIVERY is N0TIFY's * fact — aud0's seven types carry no delivery event. * Saying so beats fabricating a proxy. * low_confidence a p95 or p99 computed from a handful of samples. The * number is reported WITH its sample size and marked, * because a p99 over 12 requests is the 12th-slowest * request wearing a percentile's clothes. * * The measurement path is aud0's seven BI usage event types (BI-P076, merged * in aud0#34), produced by src/analytics/slo/usage-events.ts. There is * deliberately no second telemetry path: two measurement systems disagree, and * the disagreement is discovered during an incident. */ import type { Aud0BiEvent } from './usage-events'; export const BI_WORKLOAD_CLASSES = ['interactive_dashboard', 'exploration', 'report'] as const; export type BiWorkloadClass = (typeof BI_WORKLOAD_CLASSES)[number]; export const SLO_OBJECTIVE_KINDS = [ 'availability', 'latency_p95_first', 'latency_p95_cached', 'latency_p95', 'latency_p99', 'error_rate', 'freshness', 'max_result_rows', 'timeout', 'completion_sla', 'delivery_sla', ] as const; export type SloObjectiveKind = (typeof SLO_OBJECTIVE_KINDS)[number]; /** Where the number comes from. `none` is an admission, not a placeholder. */ export const MEASUREMENT_SOURCES = [ 'aud0_bi_usage_events', 'analytics_freshness_watermark', 'n0tify_delivery_receipt', 'engine_configuration', ] as const; export type MeasurementSource = (typeof MEASUREMENT_SOURCES)[number]; export interface SloObjective { objective_id: string; workload: BiWorkloadClass; kind: SloObjectiveKind; /** Target value; unit is fixed by kind (ms, ratio, rows, seconds). */ target: number; unit: 'ms' | 'ratio' | 'rows' | 'seconds'; /** Higher-is-better (availability) vs lower-is-better (latency). */ direction: 'at_least' | 'at_most'; measured_from: MeasurementSource; /** Fewer samples than this and the verdict carries low_confidence. */ min_samples: number; rationale: string; } /** * The catalogue, field-for-field with what BI-P103 lists per workload class. * Targets are STARTING POINTS chosen to be honest about what has been * measured: they are the thresholds the evaluator compares against, and * evidence/bi-p103/baseline.json records the first baselines rather than * pretending the targets were derived from a year of production traffic. * * Those baselines are produced by * tests/integration/bi-p103-slo-baseline.integration.test.ts, which runs 460 * real queries against a live ClickHouse and feeds them through this * evaluator. Read the file's own caveats before quoting a number from it: the * cached path measured there is the in-process reference cache rather than * Valkey, every latency is the engine round trip with no HTTP or * authorization layer around it, and there is no concurrency. Seven of the * eleven objectives produced a number; the other four say why they could not, * and `fully_measured` is false. */ export const BI_SLO_CATALOGUE: readonly SloObjective[] = [ // ── interactive dashboard ──────────────────────────────────────────────── { objective_id: 'dash.availability', workload: 'interactive_dashboard', kind: 'availability', target: 0.995, unit: 'ratio', direction: 'at_least', measured_from: 'aud0_bi_usage_events', min_samples: 100, rationale: 'completed / (completed + failed) for dashboard-surface queries.', }, { objective_id: 'dash.p95_first_query', workload: 'interactive_dashboard', kind: 'latency_p95_first', target: 3000, unit: 'ms', direction: 'at_most', measured_from: 'aud0_bi_usage_events', min_samples: 50, rationale: 'cache_hit=false: what a user waits for when they open the dashboard cold.', }, { objective_id: 'dash.p95_cached', workload: 'interactive_dashboard', kind: 'latency_p95_cached', target: 400, unit: 'ms', direction: 'at_most', measured_from: 'aud0_bi_usage_events', min_samples: 50, rationale: 'cache_hit=true: BI-P020 cache hits, measured separately so a high hit rate cannot hide a slow cold path.', }, { objective_id: 'dash.error_rate', workload: 'interactive_dashboard', kind: 'error_rate', target: 0.005, unit: 'ratio', direction: 'at_most', measured_from: 'aud0_bi_usage_events', min_samples: 100, rationale: 'failed / terminal. Cancellations count as failures here: the user did not get an answer.', }, { objective_id: 'dash.freshness', workload: 'interactive_dashboard', kind: 'freshness', target: 900, unit: 'seconds', direction: 'at_most', measured_from: 'analytics_freshness_watermark', min_samples: 1, rationale: 'Data age is a property of the DATASET (BI-P026 freshness, BI-P105 watermark), not of a usage ' + 'event. Usage events cannot measure it and this evaluator does not pretend to.', }, // ── exploration ────────────────────────────────────────────────────────── { objective_id: 'explore.p95', workload: 'exploration', kind: 'latency_p95', target: 10_000, unit: 'ms', direction: 'at_most', measured_from: 'aud0_bi_usage_events', min_samples: 50, rationale: 'explore-surface queries; an analyst tolerates more than a dashboard viewer.', }, { objective_id: 'explore.p99', workload: 'exploration', kind: 'latency_p99', target: 60_000, unit: 'ms', direction: 'at_most', measured_from: 'aud0_bi_usage_events', min_samples: 200, rationale: 'p99 needs a genuinely large sample; below min_samples it is reported as low confidence.', }, { objective_id: 'explore.max_result', workload: 'exploration', kind: 'max_result_rows', target: 1_000_000, unit: 'rows', direction: 'at_most', measured_from: 'aud0_bi_usage_events', min_samples: 1, rationale: 'BI-P012 truncates at the engine ceiling; this watches what actually came back.', }, { objective_id: 'explore.timeout', workload: 'exploration', kind: 'timeout', target: 300, unit: 'seconds', direction: 'at_most', measured_from: 'engine_configuration', min_samples: 1, rationale: 'The configured ceiling (BI-P012 settings profile), not an observation.', }, // ── reports ────────────────────────────────────────────────────────────── { objective_id: 'report.completion_sla', workload: 'report', kind: 'completion_sla', target: 900_000, unit: 'ms', direction: 'at_most', measured_from: 'aud0_bi_usage_events', min_samples: 20, rationale: 'aud0.report_generated duration_ms: submitted to produced.', }, { objective_id: 'report.delivery_sla', workload: 'report', kind: 'delivery_sla', target: 300_000, unit: 'ms', direction: 'at_most', measured_from: 'n0tify_delivery_receipt', min_samples: 20, rationale: "Produced is not delivered. aud0 has no delivery event; the receipt is N0TIFY's, so this " + 'objective is declared and reported unmeasured rather than proxied by completion.', }, ]; export const SLO_STATUSES = ['met', 'breached', 'insufficient_data', 'not_measurable_here'] as const; export type SloStatus = (typeof SLO_STATUSES)[number]; export interface SloResult { objective_id: string; workload: BiWorkloadClass; kind: SloObjectiveKind; status: SloStatus; target: number; unit: SloObjective['unit']; /** The measured value, or undefined when nothing could be measured. */ observed?: number; sample_size: number; /** True when a percentile was computed from fewer samples than min_samples. */ low_confidence?: boolean; detail: string; } export interface SloReport { window_from: string; window_to: string; results: SloResult[]; /** Queries that started and never reached a terminal event in the window. */ unresolved_queries: number; /** True only when EVERY objective produced a real number. */ fully_measured: boolean; } interface QueryFact { query_id: string; surface?: string; started_at: number; outcome?: 'completed' | 'failed'; duration_ms?: number; row_count?: number; cache_hit?: boolean; } function num(v: unknown): number | undefined { return typeof v === 'number' && Number.isFinite(v) ? v : undefined; } function str(v: unknown): string | undefined { return typeof v === 'string' ? v : undefined; } /** * Nearest-rank percentile. No interpolation: with small samples an * interpolated p99 invents a value that no request ever experienced. */ export function percentile(sorted: number[], q: number): number | undefined { if (sorted.length === 0) return undefined; const rank = Math.ceil(q * sorted.length); return sorted[Math.min(sorted.length - 1, Math.max(0, rank - 1))]; } /** Fold the seven event types into per-query facts. */ function foldQueries(events: Aud0BiEvent[]): Map { const facts = new Map(); for (const e of events) { const qid = str(e.payload.query_id); if (!qid) continue; const at = Date.parse(e.occurred_at); const existing = facts.get(qid) ?? { query_id: qid, started_at: Number.isNaN(at) ? 0 : at }; if (e.payload.surface !== undefined) existing.surface = str(e.payload.surface); if (e.event_type === 'aud0.analytics_query_started' && !Number.isNaN(at)) existing.started_at = at; if (e.event_type === 'aud0.analytics_query_completed') { existing.outcome = 'completed'; existing.duration_ms = num(e.payload.duration_ms); existing.row_count = num(e.payload.row_count); existing.cache_hit = e.payload.cache_hit === true; } if (e.event_type === 'aud0.analytics_query_failed') { existing.outcome = 'failed'; existing.duration_ms = num(e.payload.duration_ms); } facts.set(qid, existing); } return facts; } function result( o: SloObjective, status: SloStatus, sample_size: number, detail: string, observed?: number, low_confidence?: boolean, ): SloResult { const r: SloResult = { objective_id: o.objective_id, workload: o.workload, kind: o.kind, status, target: o.target, unit: o.unit, sample_size, detail, }; if (observed !== undefined) r.observed = observed; if (low_confidence) r.low_confidence = true; return r; } function compare(o: SloObjective, observed: number): SloStatus { return o.direction === 'at_least' ? observed >= o.target ? 'met' : 'breached' : observed <= o.target ? 'met' : 'breached'; } /** * Evaluate the catalogue over a window of AUD0 BI usage events. * * Events are DATA: they arrive from aud0's read model, they were written by * other services, and nothing in them is treated as an instruction or as a * schema. Unknown event types and unknown payload keys are ignored, never * spread. */ export function evaluateBiSlos(args: { events: Aud0BiEvent[]; from: Date; to: Date; objectives?: readonly SloObjective[]; }): SloReport { const objectives = args.objectives ?? BI_SLO_CATALOGUE; const fromMs = args.from.getTime(); const toMs = args.to.getTime(); const inWindow = args.events.filter((e) => { const t = Date.parse(e.occurred_at); return !Number.isNaN(t) && t >= fromMs && t <= toMs; }); const queries = [...foldQueries(inWindow).values()]; const dashboardQueries = queries.filter((q) => q.surface === 'dashboard'); const exploreQueries = queries.filter((q) => q.surface === 'explore'); const terminal = (qs: QueryFact[]) => qs.filter((q) => q.outcome !== undefined); const durations = (qs: QueryFact[]) => qs .map((q) => q.duration_ms) .filter((d): d is number => d !== undefined) .sort((a, b) => a - b); const reportDurations = inWindow .filter((e) => e.event_type === 'aud0.report_generated') .map((e) => num(e.payload.duration_ms)) .filter((d): d is number => d !== undefined) .sort((a, b) => a - b); const results = objectives.map((o) => { if (o.measured_from !== 'aud0_bi_usage_events') { return result( o, 'not_measurable_here', 0, `measured from ${o.measured_from}; BI usage events cannot answer it — ${o.rationale}`, ); } switch (o.kind) { case 'availability': case 'error_rate': { const t = terminal(dashboardQueries); if (t.length === 0) { return result(o, 'insufficient_data', 0, 'no terminal dashboard query events in the window'); } const failed = t.filter((q) => q.outcome === 'failed').length; const observed = o.kind === 'availability' ? (t.length - failed) / t.length : failed / t.length; const status = compare(o, observed); return result( o, t.length < o.min_samples ? 'insufficient_data' : status, t.length, t.length < o.min_samples ? `${t.length} terminal queries is below the ${o.min_samples} this objective requires; ` + `the ratio ${observed.toFixed(4)} is reported but not judged` : `${failed} failed of ${t.length} terminal queries`, observed, t.length < o.min_samples, ); } case 'latency_p95_first': case 'latency_p95_cached': { const wanted = o.kind === 'latency_p95_cached'; const sample = durations(dashboardQueries.filter((q) => (q.cache_hit === true) === wanted)); const p95 = percentile(sample, 0.95); if (p95 === undefined) { return result( o, 'insufficient_data', 0, `no ${wanted ? 'cached' : 'uncached'} dashboard durations`, ); } const low = sample.length < o.min_samples; return result( o, low ? 'insufficient_data' : compare(o, p95), sample.length, low ? `p95 over ${sample.length} samples (needs ${o.min_samples}) — reported, not judged` : `p95 over ${sample.length} samples`, p95, low, ); } case 'latency_p95': case 'latency_p99': { const sample = durations(exploreQueries); const q = o.kind === 'latency_p99' ? 0.99 : 0.95; const value = percentile(sample, q); if (value === undefined) return result(o, 'insufficient_data', 0, 'no exploration durations'); const low = sample.length < o.min_samples; return result( o, low ? 'insufficient_data' : compare(o, value), sample.length, low ? `p${q * 100} over ${sample.length} samples (needs ${o.min_samples}); with this few samples ` + `it is the ${Math.ceil((1 - q) * sample.length) || 1}-slowest request, not a percentile` : `p${q * 100} over ${sample.length} samples`, value, low, ); } case 'max_result_rows': { const rows = exploreQueries .map((q) => q.row_count) .filter((r): r is number => r !== undefined) .sort((a, b) => b - a); if (rows.length === 0) return result(o, 'insufficient_data', 0, 'no exploration row counts'); return result(o, compare(o, rows[0]), rows.length, `largest result seen in the window`, rows[0]); } case 'completion_sla': { const p95 = percentile(reportDurations, 0.95); if (p95 === undefined) return result(o, 'insufficient_data', 0, 'no report_generated events'); const low = reportDurations.length < o.min_samples; return result( o, low ? 'insufficient_data' : compare(o, p95), reportDurations.length, low ? `p95 over ${reportDurations.length} reports (needs ${o.min_samples})` : 'p95 report duration', p95, low, ); } default: return result(o, 'not_measurable_here', 0, `no evaluator for kind "${o.kind}"`); } }); const unresolved = queries.filter((q) => q.outcome === undefined).length; return { window_from: args.from.toISOString(), window_to: args.to.toISOString(), results, unresolved_queries: unresolved, fully_measured: results.every((r) => r.status === 'met' || r.status === 'breached'), }; } /** * One line an operator can read: how many objectives are actually being * measured. "9 of 11 met" is meaningless if the other two were never * measured, so the summary counts them separately and never rolls them in. */ export function summariseSloReport(report: SloReport): { met: number; breached: number; insufficient_data: number; not_measurable_here: number; measured_fraction: number; } { const count = (s: SloStatus) => report.results.filter((r) => r.status === s).length; const measured = count('met') + count('breached'); return { met: count('met'), breached: count('breached'), insufficient_data: count('insufficient_data'), not_measurable_here: count('not_measurable_here'), measured_fraction: report.results.length === 0 ? 0 : measured / report.results.length, }; }