diff --git a/packages/common-utils/src/core/__tests__/slo.test.ts b/packages/common-utils/src/core/__tests__/slo.test.ts new file mode 100644 index 0000000000..9bb54b6a00 --- /dev/null +++ b/packages/common-utils/src/core/__tests__/slo.test.ts @@ -0,0 +1,78 @@ +import { + buildSloLatencyGoodSql, + getSloDefaultDuration, +} from '@/core/sloLatency'; +import { SloInputSchema } from '@/slo'; +import { SourceKind, TSource } from '@/types'; + +const traceSource = { + id: 'source-1', + kind: SourceKind.Trace, + name: 'Traces', + connection: 'conn-1', + from: { databaseName: 'otel', tableName: 'otel_traces' }, + timestampValueExpression: 'Timestamp', + defaultTableSelectExpression: 'Timestamp, ServiceName', + durationExpression: 'Duration', + durationPrecision: 9, + traceIdExpression: 'TraceId', + spanIdExpression: 'SpanId', + parentSpanIdExpression: 'ParentSpanId', + spanNameExpression: 'SpanName', + spanKindExpression: 'SpanKind', + statusCodeExpression: 'StatusCode', + serviceNameExpression: 'ServiceName', +} as unknown as TSource; + +const availability = { + indicator: { + template: 'availability', + eligible: { + where: "SpanKind = 'Server'", + whereLanguage: 'sql', + filters: [{ type: 'sql', condition: "ServiceName IN ('checkout')" }], + }, + good: "StatusCode != 'Error'", + }, +}; + +describe('SLO schema', () => { + const base = { + name: 'Checkout availability', + source: 'source-1', + target: 99.9, + window: '30d' as const, + }; + + it('requires a good condition unless the template is latency', () => { + expect( + SloInputSchema.safeParse({ + ...base, + indicator: { + template: 'availability', + eligible: { where: '', whereLanguage: 'sql' }, + }, + }).success, + ).toBe(false); + expect(SloInputSchema.safeParse({ ...base, ...availability }).success).toBe( + true, + ); + }); + + it('derives latency thresholds in the source unit', () => { + expect( + buildSloLatencyGoodSql({ + expression: 'Duration', + unit: 'ns', + thresholdMs: 250, + numeric: true, + requireDuration: true, + }), + ).toBe('(Duration) <= 250000000'); + expect(getSloDefaultDuration(traceSource)).toEqual({ + expression: 'Duration', + unit: 'ns', + numeric: true, + }); + }); +}); diff --git a/packages/common-utils/src/core/sloLatency.ts b/packages/common-utils/src/core/sloLatency.ts new file mode 100644 index 0000000000..c87cc810f7 --- /dev/null +++ b/packages/common-utils/src/core/sloLatency.ts @@ -0,0 +1,68 @@ +import type { SloLatency } from '@/slo'; +import { Filter, isTraceSource, TSource } from '@/types'; + +type SloDurationUnit = SloLatency['unit']; + +function unitsPerMs(unit: SloDurationUnit): number { + switch (unit) { + case 'ns': + return 1_000_000; + case 'us': + return 1_000; + case 'ms': + return 1; + case 's': + return 0.001; + } +} + +/** Trace sources store the precision as digits after seconds: 3 is ms, 9 is ns. */ +function unitFromPrecision(precision: number): SloDurationUnit { + if (precision >= 9) return 'ns'; + if (precision >= 6) return 'us'; + if (precision >= 3) return 'ms'; + return 's'; +} + +/** + * The duration as a number. A string attribute (every Map value in the OTel + * schema) is cast, and anything that does not parse becomes NULL. + */ +export function getSloDurationValueExpression(latency: SloLatency): string { + return latency.numeric + ? `(${latency.expression})` + : `accurateCastOrNull(${latency.expression}, 'Float64')`; +} + +export function buildSloLatencyGoodSql(latency: SloLatency): string { + const threshold = Number( + (latency.thresholdMs * unitsPerMs(latency.unit)).toPrecision(12), + ); + return `${getSloDurationValueExpression(latency)} <= ${threshold}`; +} + +/** + * Eligibility guard for a cast duration: events that lack it, such as log + * lines without the attribute, stay out of the SLO rather than burning budget. + */ +export function getSloLatencyEligibleFilter( + latency: SloLatency, +): Filter | undefined { + if (latency.numeric || !latency.requireDuration) return undefined; + return { + type: 'sql', + condition: `isNotNull(${getSloDurationValueExpression(latency)})`, + }; +} + +/** The source's own duration column, when it has one (trace sources). */ +export function getSloDefaultDuration( + source: TSource, +): Pick | undefined { + if (!isTraceSource(source) || !source.durationExpression) return undefined; + return { + expression: source.durationExpression, + unit: unitFromPrecision(source.durationPrecision ?? 3), + numeric: true, + }; +} diff --git a/packages/common-utils/src/slo.ts b/packages/common-utils/src/slo.ts new file mode 100644 index 0000000000..1a5e68ef99 --- /dev/null +++ b/packages/common-utils/src/slo.ts @@ -0,0 +1,99 @@ +import { z } from 'zod/v3'; + +import { FilterSchema } from '@/types'; + +// An SLO follows OpenSLO v1 concepts in one flat document: an occurrence +// based indicator (good over eligible events), a target percentage and a +// rolling window. The eligible events keep the shape of a saved search +// (where clause, language, filters), so Search and the SLO count the same +// rows. + +export const SLO_SCHEMA_VERSION = 1; + +/** Guard rail on definitions per team. */ +export const SLO_MAX_PER_TEAM = 200; + +/** Groups tracked per SLO: the busiest by eligible events. */ +export const SLO_MAX_GROUPS = 100; +/** Window events a group needs before it gets a state of its own. */ +export const SLO_GROUP_MIN_EVENTS = 100; + +export const SloWindowSchema = z.enum(['7d', '30d']); +export type SloWindow = z.infer; + +export const SloTemplateSchema = z.enum(['availability', 'latency']); +export type SloTemplate = z.infer; + +export const SloEligibleSchema = z.object({ + where: z.string().max(10000), + whereLanguage: z.enum(['lucene', 'sql']), + filters: z.array(FilterSchema).max(50).optional(), +}); + +export const SloDurationUnitSchema = z.enum(['ns', 'us', 'ms', 's']); + +export const SloLatencySchema = z.object({ + /** Column or expression holding the duration, e.g. Duration or LogAttributes['latency_ms']. */ + expression: z + .string() + .trim() + .min(1, 'A duration expression is required') + .max(1024), + unit: SloDurationUnitSchema, + thresholdMs: z.number().positive(), + /** The expression is already numeric (a trace duration column); otherwise it is cast. */ + numeric: z.boolean().default(false), + /** Leave out events without a readable duration instead of counting them as bad. */ + requireDuration: z.boolean().default(true), +}); +export type SloLatency = z.infer; + +export const SloIndicatorSchema = z + .object({ + template: SloTemplateSchema, + eligible: SloEligibleSchema, + /** SQL condition for good events; the latency template derives it instead. */ + good: z.string().trim().max(10000).optional(), + latency: SloLatencySchema.optional(), + }) + .superRefine((indicator, ctx) => { + if (indicator.template === 'latency') { + if (indicator.latency == null) { + ctx.addIssue({ + code: 'custom', + path: ['latency'], + message: 'A latency SLO needs a duration, unit and threshold', + }); + } + } else if (!indicator.good) { + ctx.addIssue({ + code: 'custom', + path: ['good'], + message: 'A good-event condition is required', + }); + } + }); +export type SloIndicator = z.infer; + +export const SloInputSchema = z.object({ + version: z.literal(SLO_SCHEMA_VERSION).default(SLO_SCHEMA_VERSION), + name: z.string().trim().min(1, 'Name is required').max(256), + description: z.string().max(4096).optional(), + tags: z.array(z.string().trim().min(1).max(64)).max(32).default([]), + source: z.string().min(1, 'Source is required'), + indicator: SloIndicatorSchema, + /** Percentage of good events, for example 99.9. */ + target: z + .number() + .gt(0, 'Target must be above 0%') + .lt(100, 'Target must be below 100%'), + /** Rolling window the target and the error budget apply to. */ + window: SloWindowSchema, + /** + * One expression whose values each get their own SLI, budget, state and + * alert, for example ServiceName or SpanAttributes['http.route']. + */ + groupBy: z.string().trim().max(512).nullish(), +}); +export type SloInput = z.input; +export type SloDefinition = z.output;