From 0913099ae4e1e82cde1e5e57ff9f48b61668fdf1 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:40:59 +0000 Subject: [PATCH] feat(common-utils): SLO counts query Adds the one query every SLO number comes from (buildSloCountsChartConfig): eligible and good counts over a range, per bucket, for one group, or by group (the 100 groups with the most events, plus one to tell when there are more, and a distinct group count). It is built with buildSearchChartConfig, the builder Search uses, so a drill-down with the same where clause and filters sees the same events. Bad is eligible minus good, so an event whose good condition is NULL counts as bad. The burn rules read 5-minute buckets over the last 6 hours, ending on a 5-minute boundary. Also adds the bad-events search for drill-downs, the parsers for the query rows, describeFilter (moved here so the API and the app share it) and an "slo" query attribution surface. Co-Authored-By: Claude Opus 5.5 --- .../src/clickhouse/attribution.ts | 1 + .../__tests__/__snapshots__/slo.test.ts.snap | 5 + .../src/core/__tests__/slo.test.ts | 315 ++++++++++- packages/common-utils/src/core/slo.ts | 524 ++++++++++++++++++ packages/common-utils/src/filters.ts | 6 + 5 files changed, 850 insertions(+), 1 deletion(-) create mode 100644 packages/common-utils/src/core/__tests__/__snapshots__/slo.test.ts.snap create mode 100644 packages/common-utils/src/core/slo.ts diff --git a/packages/common-utils/src/clickhouse/attribution.ts b/packages/common-utils/src/clickhouse/attribution.ts index e6ca78a11..7839a4567 100644 --- a/packages/common-utils/src/clickhouse/attribution.ts +++ b/packages/common-utils/src/clickhouse/attribution.ts @@ -33,6 +33,7 @@ export const QUERY_SURFACES = [ 'search', 'service-dashboard', 'session-replay', + 'slo', 'unknown', ] as const; diff --git a/packages/common-utils/src/core/__tests__/__snapshots__/slo.test.ts.snap b/packages/common-utils/src/core/__tests__/__snapshots__/slo.test.ts.snap new file mode 100644 index 000000000..0f27c5cae --- /dev/null +++ b/packages/common-utils/src/core/__tests__/__snapshots__/slo.test.ts.snap @@ -0,0 +1,5 @@ +// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing + +exports[`SLO query generator casts an attribute duration and leaves out events without one 1`] = `"SELECT count() AS "slo_eligible",countIf(accurateCastOrNull(LogAttributes['latency_ms'], 'Float64') <= 300) AS "slo_good",toStartOfInterval(toDateTime(Timestamp), INTERVAL 1 hour) AS \`__hdx_time_bucket\` FROM otel.otel_traces WHERE (Timestamp >= fromUnixTimestamp64Milli(1793491200000) AND Timestamp < fromUnixTimestamp64Milli(1794096000000)) AND (((ServiceName ILIKE '%checkout%'))) AND ((isNotNull(accurateCastOrNull(LogAttributes['latency_ms'], 'Float64')))) GROUP BY toStartOfInterval(toDateTime(Timestamp), INTERVAL 1 hour) AS \`__hdx_time_bucket\` ORDER BY toStartOfInterval(toDateTime(Timestamp), INTERVAL 1 hour) AS \`__hdx_time_bucket\`"`; + +exports[`SLO query generator counts eligible and good events over the range 1`] = `"SELECT count() AS "slo_eligible",countIf(StatusCode != 'Error') AS "slo_good" FROM otel.otel_traces WHERE (Timestamp >= fromUnixTimestamp64Milli(1793491200000) AND Timestamp < fromUnixTimestamp64Milli(1794096000000)) AND (SpanKind = 'Server') AND ((ServiceName IN ('checkout')))"`; diff --git a/packages/common-utils/src/core/__tests__/slo.test.ts b/packages/common-utils/src/core/__tests__/slo.test.ts index 2b35939d0..a797bdea9 100644 --- a/packages/common-utils/src/core/__tests__/slo.test.ts +++ b/packages/common-utils/src/core/__tests__/slo.test.ts @@ -1,3 +1,21 @@ +import { parameterizedQueryToSql } from '@/clickhouse'; +import { Metadata } from '@/core/metadata'; +import { renderChartConfig } from '@/core/renderChartConfig'; +import { + buildSloBadEventsSearch, + buildSloBurnChartConfig, + buildSloCountsChartConfig, + getSloBurnCounts, + getSloGroupKey, + getSloGroupValue, + parseSloCountsRow, + parseSloGroupCountRow, + parseSloGroupHistoryRows, + parseSloGroupRows, + parseSloHistoryRows, + SloQueryDefinition, + sumSloBuckets, +} from '@/core/slo'; import { buildSloLatencyGoodSql, getSloDefaultDuration, @@ -28,7 +46,7 @@ const traceSource = { serviceNameExpression: 'ServiceName', } as unknown as TSource; -const availability = { +const availability: SloQueryDefinition = { indicator: { template: 'availability', eligible: { @@ -40,6 +58,301 @@ const availability = { }, }; +const logLatency: SloQueryDefinition = { + indicator: { + template: 'latency', + eligible: { where: 'ServiceName:checkout', whereLanguage: 'lucene' }, + latency: { + expression: "LogAttributes['latency_ms']", + unit: 'ms', + thresholdMs: 300, + numeric: false, + requireDuration: true, + }, + }, +}; + +const dateRange: [Date, Date] = [ + new Date('2026-11-01T00:00:00Z'), + new Date('2026-11-08T00:00:00Z'), +]; + +describe('SLO query generator', () => { + const metadata = { + getColumns: jest.fn().mockResolvedValue([]), + getMaterializedColumnsLookupTable: jest.fn().mockResolvedValue(null), + getColumn: jest.fn().mockResolvedValue(undefined), + getTableMetadata: jest.fn().mockResolvedValue({ primary_key: 'Timestamp' }), + getSkipIndices: jest.fn().mockResolvedValue([]), + getSetting: jest.fn().mockResolvedValue(undefined), + isClickHouseCloud: jest.fn().mockResolvedValue(false), + } as unknown as Metadata; + + const render = async (config: Parameters[0]) => + parameterizedQueryToSql( + await renderChartConfig(config, metadata, undefined), + ); + + it('counts eligible and good events over the range', async () => { + const sql = await render( + buildSloCountsChartConfig({ + slo: availability, + source: traceSource, + dateRange, + }), + ); + expect(sql).toContain('count() AS "slo_eligible"'); + expect(sql).toContain('countIf(StatusCode != \'Error\') AS "slo_good"'); + expect(sql).toContain("(SpanKind = 'Server')"); + expect(sql).toContain("(ServiceName IN ('checkout'))"); + expect(sql).toMatchSnapshot(); + }); + + it('counts the burn windows in 5-minute buckets ending on a boundary', async () => { + const config = buildSloBurnChartConfig({ + slo: availability, + source: traceSource, + now: new Date('2026-11-07T23:58:30Z'), + }); + expect(config.dateRange).toEqual([ + new Date('2026-11-07T17:55:00Z'), + new Date('2026-11-07T23:55:00Z'), + ]); + expect(config.granularity).toBe('5 minute'); + // No timestamp in a count's condition: the buckets carry the time. + const sql = await render(config); + expect(sql).not.toContain('countIf(Timestamp'); + expect(sql).toContain('countIf(StatusCode != \'Error\') AS "slo_good"'); + expect(sql).toContain('INTERVAL 5 minute'); + }); + + it('counts the busiest groups, one more than are tracked', async () => { + const sql = await render( + buildSloCountsChartConfig({ + slo: { ...availability, groupBy: 'ServiceName' }, + source: traceSource, + dateRange, + scope: { byGroup: true }, + }), + ); + expect(sql).toContain('toString(ServiceName) AS "slo_group"'); + expect(sql).toMatch(/ORDER BY slo_eligible DESC\s+LIMIT 101/); + }); + + it('counts the burn buckets of the tracked groups only', async () => { + const sql = await render( + buildSloBurnChartConfig({ + slo: { ...availability, groupBy: 'ServiceName' }, + source: traceSource, + now: new Date('2026-11-07T23:58:30Z'), + scope: { byGroup: true, groups: ['checkout', "o'clock"] }, + }), + ); + expect(sql).toContain( + "(toString(ServiceName) IN ('checkout', 'o''clock'))", + ); + expect(sql).toContain('INTERVAL 5 minute'); + expect(sql).toContain('toString(ServiceName) AS "slo_group"'); + expect(sql).not.toContain('LIMIT'); + }); + + it('scopes a query to one group', async () => { + const sql = await render( + buildSloCountsChartConfig({ + slo: { ...availability, groupBy: 'ServiceName' }, + source: traceSource, + dateRange, + scope: { group: 'checkout' }, + }), + ); + expect(sql).toContain("(toString(ServiceName) = 'checkout')"); + expect(sql).not.toContain('slo_group'); + }); + + it('ignores group scopes on an SLO without a group-by', async () => { + const config = buildSloCountsChartConfig({ + slo: availability, + source: traceSource, + dateRange, + scope: { byGroup: true }, + }); + expect(config.groupBy).toBeUndefined(); + expect(config.limit).toBeUndefined(); + }); + + it('casts an attribute duration and leaves out events without one', async () => { + const sql = await render( + buildSloCountsChartConfig({ + slo: logLatency, + source: traceSource, + dateRange, + granularity: '1 hour', + }), + ); + expect(sql).toContain( + "countIf(accurateCastOrNull(LogAttributes['latency_ms'], 'Float64') <= 300)", + ); + expect(sql).toContain( + "isNotNull(accurateCastOrNull(LogAttributes['latency_ms'], 'Float64'))", + ); + expect(sql).toMatchSnapshot(); + }); +}); + +describe('SLO query results', () => { + it('parses 64-bit counts sent as strings', () => { + expect(parseSloCountsRow([{ slo_eligible: '12', slo_good: '10' }])).toEqual( + { eligible: 12, good: 10 }, + ); + }); + + it('reads history buckets in time order', () => { + expect( + parseSloHistoryRows([ + { + __hdx_time_bucket: '2026-11-01T01:00:00Z', + slo_eligible: '5', + slo_good: '4', + }, + { + __hdx_time_bucket: '2026-11-01T00:00:00Z', + slo_eligible: '3', + slo_good: '3', + }, + { slo_eligible: '1', slo_good: '1' }, + ]), + ).toEqual([ + { ts: Date.parse('2026-11-01T00:00:00Z'), eligible: 3, good: 3 }, + { ts: Date.parse('2026-11-01T01:00:00Z'), eligible: 5, good: 4 }, + ]); + }); + + it('sums the long and short burn windows from the buckets', () => { + const end = new Date('2026-11-08T00:00:00Z'); + const bucket = ( + minutesBeforeEnd: number, + eligible: number, + good: number, + ) => ({ + ts: end.getTime() - minutesBeforeEnd * 60_000, + eligible, + good, + }); + const buckets = [ + bucket(360, 100, 100), // first bucket of 6h, outside 1h + bucket(60, 10, 9), // first bucket of the last hour + bucket(30, 10, 8), + bucket(5, 10, 5), // last bucket + ]; + expect(sumSloBuckets(buckets)).toEqual({ eligible: 130, good: 122 }); + expect( + getSloBurnCounts( + buckets, + [ + { window: '1h', shortWindow: '5m' }, + { window: '6h', shortWindow: '30m' }, + ], + end, + ), + ).toEqual([ + { eligible: 30, good: 22, shortEligible: 10, shortGood: 5 }, + { eligible: 130, good: 122, shortEligible: 20, shortGood: 13 }, + ]); + }); +}); + +describe('SLO group results', () => { + it('reads counts per group in the query order', () => { + expect( + parseSloGroupRows([ + { slo_group: 'checkout', slo_eligible: '30', slo_good: '29' }, + { slo_group: 42, slo_eligible: '10', slo_good: '10' }, + ]), + ).toEqual([ + { value: 'checkout', eligible: 30, good: 29 }, + { value: '42', eligible: 10, good: 10 }, + ]); + }); + + it('splits bucketed rows by group', () => { + const byGroup = parseSloGroupHistoryRows([ + { + slo_group: 'cart', + __hdx_time_bucket: '2026-11-01T00:05:00Z', + slo_eligible: '2', + slo_good: '2', + }, + { + slo_group: 'checkout', + __hdx_time_bucket: '2026-11-01T00:00:00Z', + slo_eligible: '5', + slo_good: '4', + }, + { + slo_group: 'cart', + __hdx_time_bucket: '2026-11-01T00:00:00Z', + slo_eligible: '3', + slo_good: '3', + }, + ]); + expect([...byGroup.keys()]).toEqual(['cart', 'checkout']); + expect(byGroup.get('cart')?.map(b => b.eligible)).toEqual([3, 2]); + }); + + it('reads the distinct group count', () => { + expect(parseSloGroupCountRow([{ slo_group_count: '250' }])).toBe(250); + }); + + it("keys an alert's group state by expression and value", () => { + const key = getSloGroupKey("ResourceAttributes['k8s.ns']", 'a:b'); + expect(key).toBe("ResourceAttributes['k8s.ns']:a:b"); + const slo = { groupBy: "ResourceAttributes['k8s.ns']" }; + expect(getSloGroupValue(slo, key)).toBe('a:b'); + expect(getSloGroupValue(slo, getSloGroupKey(slo.groupBy, ''))).toBe(''); + // Not one of this SLO's groups: ungrouped, or grouped by another one. + expect(getSloGroupValue(slo, '')).toBeUndefined(); + expect(getSloGroupValue(slo, 'SpanName:GET')).toBeUndefined(); + expect(getSloGroupValue({ groupBy: null }, key)).toBeUndefined(); + }); +}); + +describe('SLO bad events drill-down', () => { + it('adds the bad condition to the eligible filters', () => { + expect(buildSloBadEventsSearch(availability)).toEqual({ + where: "SpanKind = 'Server'", + whereLanguage: 'sql', + filters: [ + { type: 'sql', condition: "ServiceName IN ('checkout')" }, + { type: 'sql', condition: "NOT ifNull((StatusCode != 'Error'), 0)" }, + ], + }); + }); + + it('scopes the drill-down to one group', () => { + expect( + buildSloBadEventsSearch( + { ...availability, groupBy: 'ServiceName' }, + undefined, + 'checkout', + ).filters, + ).toEqual([ + { type: 'sql', condition: "ServiceName IN ('checkout')" }, + { type: 'sql', condition: "toString(ServiceName) = 'checkout'" }, + { type: 'sql', condition: "NOT ifNull((StatusCode != 'Error'), 0)" }, + ]); + }); + + it('sorts latency SLOs slowest first and shows a cast duration', () => { + const search = buildSloBadEventsSearch(logLatency, 'Timestamp, Body'); + expect(search.orderBy).toBe( + "accurateCastOrNull(LogAttributes['latency_ms'], 'Float64') DESC", + ); + expect(search.select).toBe( + "Timestamp, Body, accurateCastOrNull(LogAttributes['latency_ms'], 'Float64') AS duration_ms", + ); + }); +}); + describe('SLO schema', () => { const base = { name: 'Checkout availability', diff --git a/packages/common-utils/src/core/slo.ts b/packages/common-utils/src/core/slo.ts new file mode 100644 index 000000000..2908e1e93 --- /dev/null +++ b/packages/common-utils/src/core/slo.ts @@ -0,0 +1,524 @@ +import { z } from 'zod/v3'; + +import { FIXED_TIME_BUCKET_EXPR_ALIAS } from '@/core/renderChartConfig'; +import { buildSearchChartConfig } from '@/core/searchChartConfig'; +import { + buildSloLatencyGoodSql, + getSloDurationValueExpression, + getSloLatencyEligibleFilter, +} from '@/core/sloLatency'; +import { escapeSqlString } from '@/core/utils'; +import { + getSloBurnThreshold, + getSloBurnWindowMs, + getSloWindowMs, + SLO_BURN_CONDITIONS, + SLO_MAX_GROUPS, + SloBurnCondition, + SloBurnWindow, + SloDefinition, + SloHistoryBucket, + SloIndicator, + SloWindow, +} from '@/slo'; +import { + BuilderChartConfigWithDateRange, + DerivedColumn, + DisplayType, + Filter, + isTraceSource, + SQLInterval, + TSource, +} from '@/types'; + +/** The parts of an SLO a query needs. */ +export type SloQueryDefinition = Pick & { + groupBy?: string | null; +}; + +const SLO_GROUP_ALIAS = 'slo_group'; + +/** Group values are compared as text, whatever the expression's type. */ +function getSloGroupExpression(groupBy: string): string { + return `toString(${groupBy})`; +} + +/** Scopes a query or a drill-down to one group of a grouped SLO. */ +export function getSloGroupFilter(groupBy: string, value: string): Filter { + return { + type: 'sql', + condition: `${getSloGroupExpression(groupBy)} = '${escapeSqlString( + value, + )}'`, + }; +} + +/** Limits a query to the groups an SLO tracks; no groups matches nothing. */ +function getSloGroupsFilter(groupBy: string, values: string[]): Filter { + if (values.length === 0) return { type: 'sql', condition: '0' }; + const list = values.map(value => `'${escapeSqlString(value)}'`).join(', '); + return { + type: 'sql', + condition: `${getSloGroupExpression(groupBy)} IN (${list})`, + }; +} + +/** The SLO's group-by expression, or undefined when it has none. */ +export function getSloGroupBy( + slo: Pick, +): string | undefined { + return slo.groupBy?.trim() || undefined; +} + +/** + * The key a grouped SLO's alert keeps a group's state under, in the + * `expression:value` form of threshold alert groups. + */ +export function getSloGroupKey(groupBy: string, value: string): string { + return `${groupBy}:${value}`; +} + +/** + * The group value in an alert group key, or undefined when the key is not + * one of the SLO's groups (it was ungrouped, or grouped by something else). + */ +export function getSloGroupValue( + slo: Pick, + key: string | null | undefined, +): string | undefined { + const groupBy = getSloGroupBy(slo); + if (groupBy == null || !key) return undefined; + const prefix = getSloGroupKey(groupBy, ''); + return key.startsWith(prefix) ? key.slice(prefix.length) : undefined; +} + +/** SQL for good events: written by the user, or derived for latency. */ +export function getSloGoodSql(indicator: SloIndicator): string { + return indicator.template === 'latency' && indicator.latency + ? buildSloLatencyGoodSql(indicator.latency) + : (indicator.good ?? ''); +} + +export type SloBurnRule = (SloBurnCondition & { threshold: number })[]; + +/** + * The burn rule behind the "burning" state, the burn-rate chart and the + * alert, with each condition's threshold for the SLO's window. The 1h + * condition comes first. + */ +export function getSloBurnRule(window: SloWindow): SloBurnRule { + return SLO_BURN_CONDITIONS.map(condition => ({ + ...condition, + threshold: getSloBurnThreshold(condition, window), + })); +} + +export function getSloWindowRange(window: SloWindow, now: Date): [Date, Date] { + return [new Date(now.getTime() - getSloWindowMs(window)), now]; +} + +export function getSloBurnRange( + window: SloBurnWindow, + now: Date, +): [Date, Date] { + return [new Date(now.getTime() - getSloBurnWindowMs(window)), now]; +} + +const SLO_BURN_BUCKET: SQLInterval = '5 minute'; +const SLO_BURN_BUCKET_MS = 5 * 60 * 1000; + +/** + * Range of the burn query: the longest burn window (6h), ending on a + * 5-minute boundary, so every burn window is a whole number of buckets. + */ +export function getSloBurnQueryRange(now: Date): [Date, Date] { + const end = + Math.floor(now.getTime() / SLO_BURN_BUCKET_MS) * SLO_BURN_BUCKET_MS; + return getSloBurnRange('6h', new Date(end)); +} + +/** Buckets for history charts: at most 336 (7d) or 720 (30d) points. */ +export function getSloHistoryGranularity(window: SloWindow): SQLInterval { + return window === '7d' ? '30 minute' : '1 hour'; +} + +/** + * Rows the SLO counts as bad. ClickHouse's countIf treats a NULL condition as + * false, so an event whose good condition is NULL is not good; the ifNull + * keeps that event in the bad set instead of dropping it. + */ +export function getSloBadFilter(goodSql: string): Filter { + return { type: 'sql', condition: `NOT ifNull((${goodSql}), 0)` }; +} + +/** + * The user's filters plus, for a latency SLO on a cast duration, the guard + * that leaves out events without one. Every query takes its filters here. + */ +export function getSloEligibleFilters(indicator: SloIndicator): Filter[] { + const filters: Filter[] = [...(indicator.eligible.filters ?? [])]; + if (indicator.template === 'latency' && indicator.latency) { + const guard = getSloLatencyEligibleFilter(indicator.latency); + if (guard) filters.push(guard); + } + return filters; +} + +function countIf(alias: string, condition: string): DerivedColumn { + return { + aggFn: 'count', + aggCondition: condition, + aggConditionLanguage: 'sql', + valueExpression: '', + alias, + }; +} + +/** + * How a query treats a grouped SLO's groups. Without a scope it counts all + * of the SLO's events together. + */ +export type SloGroupScope = + /** One group's events. */ + | { group: string } + /** + * Per group: the SLO_MAX_GROUPS busiest plus one, which tells the caller + * there are more, or the given groups. + */ + | { byGroup: true; groups?: string[] }; + +/** + * The one query behind every SLO number: eligible and good counts over the + * range, or per bucket with `granularity`, for the whole SLO or by group. + * Rows come from buildSearchChartConfig, as in Search, so a drill-down with + * the same where clause and filters sees the same events. + */ +export function buildSloCountsChartConfig({ + slo, + source, + dateRange, + granularity, + scope, +}: { + slo: SloQueryDefinition; + source: TSource; + dateRange: [Date, Date]; + granularity?: SQLInterval; + scope?: SloGroupScope; +}): BuilderChartConfigWithDateRange { + const groupBy = getSloGroupBy(slo); + const filters = getSloEligibleFilters(slo.indicator); + const byGroup = groupBy != null && scope != null && 'byGroup' in scope; + if (groupBy != null && scope != null) { + if ('group' in scope) filters.push(getSloGroupFilter(groupBy, scope.group)); + else if (scope.groups) { + filters.push(getSloGroupsFilter(groupBy, scope.groups)); + } + } + const config = buildSearchChartConfig(source, { + where: slo.indicator.eligible.where, + whereLanguage: slo.indicator.eligible.whereLanguage, + filters, + select: [ + countIf('slo_eligible', ''), + countIf('slo_good', getSloGoodSql(slo.indicator)), + ], + groupBy: + groupBy != null && byGroup + ? [ + { + valueExpression: getSloGroupExpression(groupBy), + alias: SLO_GROUP_ALIAS, + }, + ] + : undefined, + // The busiest groups first, with one row more than are tracked. + orderBy: + byGroup && granularity == null + ? [{ ordering: 'DESC', valueExpression: 'slo_eligible' }] + : undefined, + displayType: granularity != null ? DisplayType.Line : DisplayType.Table, + dateRange, + dateRangeStartInclusive: true, + dateRangeEndInclusive: false, + granularity, + }); + return { + ...config, + dateRange, + ...(byGroup && granularity == null + ? { limit: { limit: SLO_MAX_GROUPS + 1 } } + : {}), + }; +} + +/** + * Eligible and good counts per 5-minute bucket over the burn query's range. + * Each burn window is summed from these buckets (getSloBurnCounts), so the + * query is a plain bucketed count that a materialized view can serve. + */ +export function buildSloBurnChartConfig({ + slo, + source, + now, + scope, +}: { + slo: SloQueryDefinition; + source: TSource; + now: Date; + scope?: SloGroupScope; +}): BuilderChartConfigWithDateRange { + return buildSloCountsChartConfig({ + slo, + source, + dateRange: getSloBurnQueryRange(now), + granularity: SLO_BURN_BUCKET, + scope, + }); +} + +/** Distinct groups among the SLO's eligible events in the range. */ +export function buildSloGroupCountChartConfig({ + slo, + source, + dateRange, +}: { + slo: SloQueryDefinition & { groupBy: string }; + source: TSource; + dateRange: [Date, Date]; +}): BuilderChartConfigWithDateRange { + const config = buildSearchChartConfig(source, { + where: slo.indicator.eligible.where, + whereLanguage: slo.indicator.eligible.whereLanguage, + filters: getSloEligibleFilters(slo.indicator), + select: [ + { + aggFn: 'count_distinct', + aggCondition: '', + aggConditionLanguage: 'sql', + valueExpression: getSloGroupExpression(slo.groupBy), + alias: 'slo_group_count', + }, + ], + displayType: DisplayType.Table, + dateRange, + dateRangeStartInclusive: true, + dateRangeEndInclusive: false, + }); + return { ...config, dateRange }; +} + +/** Every row of the source in the range, before the eligibility filter. */ +export function buildSloSourceTotalChartConfig({ + source, + dateRange, +}: { + source: TSource; + dateRange: [Date, Date]; +}): BuilderChartConfigWithDateRange { + const config = buildSearchChartConfig(source, { + where: '', + whereLanguage: 'sql', + select: [countIf('slo_total', '')], + displayType: DisplayType.Table, + dateRange, + dateRangeStartInclusive: true, + dateRangeEndInclusive: false, + }); + return { ...config, dateRange }; +} + +// 64-bit counts arrive as strings (output_format_json_quote_64bit_integers). +const count = z.coerce.number().catch(0); + +const countsRowSchema = z.object({ + slo_eligible: count, + slo_good: count, +}); + +/** Eligible and good events over a range. */ +export type SloCounts = { eligible: number; good: number }; + +export function parseSloCountsRow(rows: Record[]): SloCounts { + const row = countsRowSchema.parse(rows[0] ?? {}); + return { eligible: row.slo_eligible, good: row.slo_good }; +} + +/** Counts in the long and short windows of one burn condition. */ +export type SloBurnCounts = SloCounts & { + shortEligible: number; + shortGood: number; +}; + +export function parseSloTotalRow(rows: Record[]): number { + return z.object({ slo_total: count }).parse(rows[0] ?? {}).slo_total; +} + +const historyRowSchema = z + .object({ + slo_eligible: count, + slo_good: count, + [FIXED_TIME_BUCKET_EXPR_ALIAS]: z.string(), + }) + .transform( + ({ [FIXED_TIME_BUCKET_EXPR_ALIAS]: bucket, slo_eligible, slo_good }) => ({ + ts: new Date(bucket).getTime(), + eligible: slo_eligible, + good: slo_good, + }), + ); + +export function parseSloHistoryRows( + rows: Record[], +): SloHistoryBucket[] { + return rows + .map(row => historyRowSchema.safeParse(row)) + .flatMap(result => (result.success ? [result.data] : [])) + .filter(bucket => Number.isFinite(bucket.ts)) + .sort((a, b) => a.ts - b.ts); +} + +// `slo_group` is SLO_GROUP_ALIAS, the group's column in a query by group. +const groupValueSchema = z.object({ slo_group: z.coerce.string() }); +const groupRowSchema = groupValueSchema.extend({ + slo_eligible: count, + slo_good: count, +}); + +/** Counts per group, in the query's order (busiest first). */ +export function parseSloGroupRows( + rows: Record[], +): (SloCounts & { value: string })[] { + return rows.flatMap(row => { + const parsed = groupRowSchema.safeParse(row); + return parsed.success + ? [ + { + value: parsed.data.slo_group, + eligible: parsed.data.slo_eligible, + good: parsed.data.slo_good, + }, + ] + : []; + }); +} + +/** Buckets per group, from a bucketed query by group. */ +export function parseSloGroupHistoryRows( + rows: Record[], +): Map { + const byGroup = new Map[]>(); + for (const row of rows) { + const parsed = groupValueSchema.safeParse(row); + if (!parsed.success) continue; + const value = parsed.data.slo_group; + const groupRows = byGroup.get(value); + if (groupRows) groupRows.push(row); + else byGroup.set(value, [row]); + } + return new Map( + [...byGroup].map(([value, groupRows]) => [ + value, + parseSloHistoryRows(groupRows), + ]), + ); +} + +/** The distinct group count from buildSloGroupCountChartConfig's row. */ +export function parseSloGroupCountRow(rows: Record[]): number { + return z.object({ slo_group_count: count }).parse(rows[0] ?? {}) + .slo_group_count; +} + +/** Eligible and good events over all buckets, which is the whole range. */ +export function sumSloBuckets(buckets: SloHistoryBucket[]): SloCounts { + return buckets.reduce( + (sum, bucket) => ({ + eligible: sum.eligible + bucket.eligible, + good: sum.good + bucket.good, + }), + { eligible: 0, good: 0 }, + ); +} + +/** + * Counts for the long and short window of each condition, from the burn + * query's buckets; every window ends where the query's range ends. + */ +export function getSloBurnCounts( + buckets: SloHistoryBucket[], + conditions: Pick[], + end: Date, +): SloBurnCounts[] { + const sumSince = (window: SloBurnWindow) => { + const start = end.getTime() - getSloBurnWindowMs(window); + return sumSloBuckets( + buckets.filter(b => b.ts >= start && b.ts < end.getTime()), + ); + }; + return conditions.map(condition => { + const short = sumSince(condition.shortWindow); + return { + ...sumSince(condition.window), + shortEligible: short.eligible, + shortGood: short.good, + }; + }); +} + +/** + * Search state for an SLO's bad events, from the same filters every SLO query + * uses plus the bad condition. Latency SLOs sort slowest first, and a + * duration read from an attribute is added next to the default columns. + */ +export function buildSloBadEventsSearch( + slo: SloQueryDefinition, + defaultSelect?: string, + /** Scopes the drill-down to one group of a grouped SLO. */ + group?: string, +): { + where: string; + whereLanguage: 'lucene' | 'sql'; + filters: Filter[]; + orderBy?: string; + select?: string; +} { + const { eligible, template, latency } = slo.indicator; + const groupBy = getSloGroupBy(slo); + const latencyValue = + template === 'latency' && latency + ? getSloDurationValueExpression(latency) + : undefined; + return { + where: eligible.where, + whereLanguage: eligible.whereLanguage, + filters: [ + ...getSloEligibleFilters(slo.indicator), + ...(groupBy != null && group != null + ? [getSloGroupFilter(groupBy, group)] + : []), + getSloBadFilter(getSloGoodSql(slo.indicator)), + ], + ...(latencyValue != null ? { orderBy: `${latencyValue} DESC` } : {}), + ...(latencyValue != null && latency && !latency.numeric && defaultSelect + ? { + select: `${defaultSelect}, ${latencyValue} AS duration_${latency.unit}`, + } + : {}), + }; +} + +/** Default good condition for the availability template. */ +export function buildSloAvailabilityCondition( + source: TSource, +): string | undefined { + if (isTraceSource(source)) { + return source.statusCodeExpression + ? `${source.statusCodeExpression} != 'Error'` + : undefined; + } + if ('severityTextExpression' in source && source.severityTextExpression) { + return `lower(${source.severityTextExpression}) NOT IN ('error', 'fatal', 'critical')`; + } + return undefined; +} diff --git a/packages/common-utils/src/filters.ts b/packages/common-utils/src/filters.ts index fcb4dfe97..16bd2edcb 100644 --- a/packages/common-utils/src/filters.ts +++ b/packages/common-utils/src/filters.ts @@ -613,6 +613,12 @@ function countTopLevelAnd(condition: string): number { return count; } +/** A filter as the condition a person would write, for display. */ +export const describeFilter = (filter: Filter): string => + filter.type === 'sql_ast' + ? `${filter.left} ${filter.operator} ${filter.right}` + : filter.condition; + /** * Whether a filter renders *fully* as a single facet in the search sidebar. *