/** * src/analytics/quality/clickhouse-quality-runner.ts * =================================================== * BI-P025 — the ClickHouse `QualityQueryRunner`. * * One statement per rule, and it counts BOTH numbers in a single pass: * * SELECT countIf() AS violations, count() AS evaluated * FROM . WHERE tenant_id = {tenant:String} AND dataset_id = … * * `evaluated` is not decoration. It is what makes an EMPTY dataset * distinguishable from a CLEAN one — the false green * `NativeQualityProvider` refuses. Counting only violations would make the two * cases identical at this layer, and no amount of care upstream could recover * the difference. * * The BI-P011 forced tenant predicate applies here exactly as it does to a * metric query: `tenant_id = {tenant:String}` is condition[0], the value is * bound, and a quality run therefore cannot read another tenant's rows even * though it runs on an administrative credential. * * `unique` gets its own statement shape, because a duplicate is a property of * a GROUP, not of a row, and pretending otherwise would make the rule count * the wrong thing. */ import { SiaxError } from '../../platform/errors'; import { assertSafeIdentifier, FORCED_TENANT_PREDICATE } from '../engine/query-compiler'; import type { QualityQueryRunner } from './quality-provider'; export interface ClickHouseQualityRunnerOptions { baseUrl: string; basicAuth?: string; database: string; /** dataset_id -> physical table. An unlisted dataset is refused, not guessed. */ tables: Record; timeoutMs?: number; /** Ceiling for a quality scan; a check must not become the expensive query. */ maxRowsToRead?: number; } /** Marker the provider emits for the `unique` rule. */ const UNIQUE_MARKER = /^__unique__\(([A-Za-z_][A-Za-z0-9_]{0,62})\)$/; export class ClickHouseQualityRunner implements QualityQueryRunner { readonly engine = 'clickhouse'; constructor(private readonly opts: ClickHouseQualityRunnerOptions) { assertSafeIdentifier(opts.database, 'database'); for (const table of Object.values(opts.tables)) assertSafeIdentifier(table, 'table'); } async count(args: { tenant_id: string; dataset_id: string; violationExpression: string; params: Record; }): Promise<{ violations: number; evaluated: number }> { if (!args.tenant_id?.trim()) { throw new SiaxError( 'UNAUTHENTICATED', '0pt.analytics.quality', 'a quality run requires a verified tenant', ); } const table = this.opts.tables[args.dataset_id]; if (!table) { throw new SiaxError( 'NOT_FOUND', '0pt.analytics.quality', `dataset "${args.dataset_id}" has no physical table registered for quality runs`, ); } const params: Record = { ...args.params, param_tenant: args.tenant_id, param_dataset: args.dataset_id, }; const where = `${FORCED_TENANT_PREDICATE} AND dataset_id = {dataset:String}`; const unique = UNIQUE_MARKER.exec(args.violationExpression.trim()); const sql = unique ? // A duplicate is a property of a GROUP. Count the rows that belong to a // key appearing more than once, and the total rows, in one pass. `SELECT sum(multiIf(c > 1, c, 0)) AS violations, sum(c) AS evaluated FROM ` + `(SELECT ${assertSafeIdentifier(unique[1], 'field')} AS k, count() AS c ` + `FROM ${this.opts.database}.${table} WHERE ${where} GROUP BY k) FORMAT JSON` : `SELECT countIf(${args.violationExpression}) AS violations, count() AS evaluated ` + `FROM ${this.opts.database}.${table} WHERE ${where} FORMAT JSON`; const url = new URL(this.opts.baseUrl.replace(/\/+$/, '')); url.searchParams.set('query', sql); for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v); url.searchParams.set('max_rows_to_read', String(this.opts.maxRowsToRead ?? 5_000_000_000)); url.searchParams.set('read_overflow_mode', 'throw'); url.searchParams.set('max_execution_time', '60'); url.searchParams.set('timeout_overflow_mode', 'throw'); const headers: Record = {}; if (this.opts.basicAuth) { headers.Authorization = `Basic ${Buffer.from(this.opts.basicAuth).toString('base64')}`; } let res: Response; try { res = await fetch(url.toString(), { method: 'POST', headers, body: '', signal: AbortSignal.timeout(this.opts.timeoutMs ?? 60_000), }); } catch (cause) { throw new SiaxError('DEPENDENCY_UNAVAILABLE', 'clickhouse', 'clickhouse unreachable', { cause }); } const text = await res.text(); if (!res.ok) { const code = /Code:\s*(\d+)/.exec(text)?.[1] ?? String(res.status); throw new SiaxError('PERMANENT_FAILURE', 'clickhouse', `quality query failed (CH code ${code})`); } const row = ( JSON.parse(text) as { data: Array<{ violations: string | number; evaluated: string | number }> } ).data[0]; if (!row) { throw new SiaxError('PERMANENT_FAILURE', 'clickhouse', 'quality query returned no counts'); } return { violations: Number(row.violations ?? 0), evaluated: Number(row.evaluated ?? 0) }; } }