Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions packages/common-utils/src/core/__tests__/slo.test.ts
Original file line number Diff line number Diff line change
@@ -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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — Tests skip the latency template schema, the target bounds, the cast path, the eligibility guard and precisions that aren't multiples of 3

The PR says the tests cover target bounds and the indicator per template, but only the availability case is checked. Add cases for: latency template without latency rejected; target 0 and 100 rejected; numeric: false producing accurateCastOrNull(...); getSloLatencyEligibleFilter returning undefined vs the isNotNull filter; and getSloDefaultDuration with durationPrecision 3/6/7. The p=7 case would have caught the unit bug above.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

requireDuration: true,
}),
).toBe('(Duration) <= 250000000');
expect(getSloDefaultDuration(traceSource)).toEqual({
expression: 'Duration',
unit: 'ns',
numeric: true,
});
});
});
68 changes: 68 additions & 0 deletions packages/common-utils/src/core/sloLatency.ts
Original file line number Diff line number Diff line change
@@ -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<SloLatency, 'expression' | 'unit' | 'numeric'> | undefined {
if (!isTraceSource(source) || !source.durationExpression) return undefined;
return {
expression: source.durationExpression,
unit: unitFromPrecision(source.durationPrecision ?? 3),
numeric: true,
};
}
99 changes: 99 additions & 0 deletions packages/common-utils/src/slo.ts
Original file line number Diff line number Diff line change
@@ -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<typeof SloWindowSchema>;

export const SloTemplateSchema = z.enum(['availability', 'latency']);
export type SloTemplate = z.infer<typeof SloTemplateSchema>;

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<typeof SloLatencySchema>;

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<typeof SloIndicatorSchema>;

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<typeof SloInputSchema>;
export type SloDefinition = z.output<typeof SloInputSchema>;
Loading