CI (SIAX Cloud) / integration (push) Successful in 43s
CI (SIAX Cloud) / security (push) Successful in 23s
CI (SIAX Cloud) / quality (push) Successful in 57s
Security Scan (SIAX Cloud) / security (push) Successful in 21s
CI (SIAX Cloud) / security (pull_request) Successful in 23s
CI (SIAX Cloud) / integration (pull_request) Successful in 40s
CI (SIAX Cloud) / quality (pull_request) Successful in 55s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 25s
Both prompts are about a FALSE GREEN, so both are tested by constructing the false green and requiring a failure. BI-P025. Three provider kinds, and the interface makes the difference visible instead of implying parity: `providerKind` is "executing" or "ingesting". The native provider runs checks; the dbt and Great Expectations adapters INGEST results produced elsewhere (n0d#38 owns dbt execution against BI-P022, and GE is Python — nothing here runs it). Calling all three "providers" while only one executes is how "we have Great Expectations coverage" ends up in a status report. THE FALSE GREEN, proven against a live ClickHouse 24.8.14.39: a `not_null` check over an EMPTY table returns violations=0, evaluated=0. The raw counts are asserted first — the engine really does say zero-over-zero — and then the provider is required to call it a FAILURE, not a pass. Every rule compiles to a VIOLATION expression rather than a "rows that are fine" count, so the distinction cannot be lost at the runner layer. Same treatment for the ingesting providers: a MISSING dbt result is a failure, and dbt's `error`, `warn` and `skipped` are each asserted not to be passes. `skipped` in particular is the exact shape of l0re's 28 silently-skipped Postgres tests. The gate: zero verdicts QUARANTINES. "No rules ran" and "everything passed" produce the same green in most implementations, which is how a quality gate stops gating without anyone noticing — api0's `trivy --exit-code 0` in another costume. A later passing run does not auto-release either; release takes a principal and a reason, or a flapping rule would quarantine and un-quarantine a dataset between two reads of the same dashboard. BI-P025's DoD is the READ side: a quarantined projection is REFUSED, not annotated. An annotation on a dashboard nobody reads is not a quarantine. Live counts, all exact, from evidence/bi-p025/native-quality-live.json: not_null 5/118, range 3, distribution 4, unique 11. The unique figure is 11 rather than the 6 the first version of the test asserted — the five empty-string customers are duplicates of each other, so not_null and unique overlap on the same defect. The engine was right and the fixture arithmetic was wrong; the breakdown is written into the test rather than the number quietly adjusted. Tenant isolation re-proven on this path specifically, because a quality run uses an ADMINISTRATIVE credential: with 618 rows in the base table, t_alpha evaluates 118 and t_beta 500, and t_beta's blocking failure quarantines t_beta alone. Without the forced predicate one tenant's dirty rows would quarantine another tenant's projection. BI-P026. Five states, and the DoD's operative word is "silently". So the gate sits at the boundary every result crosses: a result with NO freshness envelope is unreleasable — not defaulted to FRESH, not defaulted to UNKNOWN — because "we forgot to attach it" and "the data is current" are indistinguishable to a reader, and any default makes forgetting the silent path. A non-current state without an explicit acknowledgement is refused, so a consumer that ignores the envelope cannot render stale numbers as current. FAILED outranks age: a pipeline that just failed may still hold recently-timestamped data from the previous run, and reporting that as FRESH is how a broken pipeline stays invisible for a day. UNKNOWN is never collapsed into FRESH. 54 unit tests, 11 live tests. typecheck + eslint clean. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
128 lines
5.2 KiB
TypeScript
128 lines
5.2 KiB
TypeScript
/**
|
|
* 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(<violation expression>) AS violations, count() AS evaluated
|
|
* FROM <db>.<table> 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<string, string>;
|
|
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<string, string>;
|
|
}): 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<string, string> = {
|
|
...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<string, string> = {};
|
|
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) };
|
|
}
|
|
}
|