Repository navigation
feat(common-utils): SLO definition schema #3788
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| requireDuration: true, | ||
| }), | ||
| ).toBe('(Duration) <= 250000000'); | ||
| expect(getSloDefaultDuration(traceSource)).toEqual({ | ||
| expression: 'Duration', | ||
| unit: 'ns', | ||
| numeric: true, | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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>; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
latencyrejected; target 0 and 100 rejected;numeric: falseproducingaccurateCastOrNull(...);getSloLatencyEligibleFilterreturning undefined vs the isNotNull filter; andgetSloDefaultDurationwith 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