CI (SIAX Cloud) / integration (push) Successful in 43s
CI (SIAX Cloud) / security (push) Successful in 21s
CI (SIAX Cloud) / quality (push) Successful in 1m5s
Security Scan (SIAX Cloud) / security (push) Successful in 23s
CI (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m0s
CI (SIAX Cloud) / integration (pull_request) Successful in 42s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 38s
BI-P018 — every field the prompt names, plus the one it names by its absence.
The record carries `compiled_query_hash` and never the statement, and that is
ENFORCED: `assertNoRawSql` runs before any record is emitted and refuses one
whose `error` field looks like SQL. The realistic leak is ClickHouse's own
error text, which echoes the query — the test uses exactly that string. The
recorder writes at EVERY transition, because a recorder that only writes at
the end loses precisely the executions worth investigating. Illegal state
transitions throw rather than overwrite a terminal row.
The one place raw SQL is retained stays BI-P017's analyst statement history,
where a privileged human ran unreviewed SQL and "who ran what" must survive.
Different record, different retention posture, stated in both files.
BI-P019 — "stops" is VERIFIED, not requested. Aborting the client stops US
waiting, not the server; KILL QUERY without SYNC tells you nothing; even SYNC
can return while the query unwinds. So cancelAndVerify aborts, kills, then
POLLS the process list until the query is GONE or the deadline passes — and
if the deadline passes it returns `verified_stopped: false` rather than a
cheerful `true`. The return type is an outcome object, not a boolean, so a
caller cannot mistake "we asked" for "it stopped". An unreachable engine is
read as "still running" (fail closed), so the kill is still attempted at the
moment an operator most needs it to be.
Proven live against ClickHouse 24.8.14.39, with the counterfactual first:
* an identical bomb left alone IS still running after 2s — so "gone after
we cancelled" is not just "the query was short";
* the cancelled query had read 6,559,476,156 rows, and was verified gone
57ms after the request;
* system.query_log records ExceptionWhileProcessing with code 394,
QUERY_WAS_CANCELLED — ClickHouse's verdict, not ours.
BI-P021 — the honest version. A budget checked once before execution bounds
nothing, and the module says so in its first paragraph. ClickHouse's
max_rows_to_read bounds ONE query; it cannot express "this tenant may scan X
per hour", which is what a budget is for. So enforcement polls the engine's
live read_rows/read_bytes counters and CANCELS the running query, through
BI-P019 with verification, when window spend would be exceeded.
Measured live: a 1,000,000-row window cancelled the query at 130,883,409 rows,
92ms in, verified stopped, code 394. THE OVERSHOOT IS DOCUMENTED, in the module
and in the evidence: enforcement is granular to the poll interval, so this is
a bound of the form "within roughly one poll interval of engine throughput",
not a hard cap. Quoting it as a hard cap would be wrong.
Two more things stated rather than implied:
* `enforceInFlight: false` is reported by describeEnforcement() as
"NOT ENFORCED — this budget is advisory", and the constructor REFUSES to
accept enforceInFlight without a process control;
* an unshared window store is reported as non-binding across replicas
("with N replicas a tenant can spend up to N times this budget").
* a query the budget killed is still charged for the work it burned. Not
charging is how a tenant learns the cheapest query is a cancelled one.
Evidence: evidence/bi-p019-p021/cancellation-and-budget.json
268 unit tests, 7 live tests. typecheck + eslint clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
139 lines
5.6 KiB
TypeScript
139 lines
5.6 KiB
TypeScript
/**
|
|
* src/analytics/execution/clickhouse-process-control.ts
|
|
* ======================================================
|
|
* BI-P019/BI-P021 — the ClickHouse implementation of `EngineProcessControl`.
|
|
*
|
|
* Three statements, each chosen for a measured reason:
|
|
*
|
|
* isRunning `SELECT count() FROM system.processes WHERE query_id = …`
|
|
* — the authority on whether the server is still working. Note
|
|
* that `KILL QUERY SYNC` returning is NOT this: a killed query
|
|
* can still appear here briefly while it unwinds, which is
|
|
* exactly why cancellation polls instead of trusting the kill.
|
|
*
|
|
* requestKill `KILL QUERY WHERE query_id = … ASYNC` — ASYNC, not SYNC,
|
|
* because the verification loop is what establishes the stop and
|
|
* a SYNC kill would block this call for up to the query's
|
|
* remaining lifetime while providing no stronger guarantee.
|
|
*
|
|
* progress `read_rows`, `read_bytes` and `elapsed` from the same table —
|
|
* live counters, which is what makes BI-P021's in-flight budget
|
|
* enforcement possible at all.
|
|
*
|
|
* KILL and the system-table reads are ADMINISTRATIVE. They run on the engine's
|
|
* own credential, never on the tenant's restricted user (which has no access
|
|
* to system.processes — measured: ACCESS_DENIED, code 497). The tenant-scoping
|
|
* check therefore happens HERE, on the query id, before any statement is sent.
|
|
*/
|
|
import { SiaxError } from '../../platform/errors';
|
|
import type { EngineProcessControl, QueryProgress } from './cancellation';
|
|
|
|
export interface ClickHouseProcessControlOptions {
|
|
baseUrl: string;
|
|
/** "user:password" for the ADMIN credential. From a secret ref. */
|
|
basicAuth?: string;
|
|
timeoutMs?: number;
|
|
/**
|
|
* Restricts every operation to query ids carrying this prefix, so a caller
|
|
* cannot kill or inspect another tenant's work through this object.
|
|
*/
|
|
queryIdPrefix?: string;
|
|
}
|
|
|
|
export class ClickHouseProcessControl implements EngineProcessControl {
|
|
readonly engine = 'clickhouse';
|
|
private readonly baseUrl: string;
|
|
private readonly authHeader?: string;
|
|
private readonly timeoutMs: number;
|
|
private readonly prefix?: string;
|
|
|
|
constructor(opts: ClickHouseProcessControlOptions) {
|
|
this.baseUrl = opts.baseUrl.replace(/\/+$/, '');
|
|
this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString('base64')}` : undefined;
|
|
this.timeoutMs = opts.timeoutMs ?? 10_000;
|
|
this.prefix = opts.queryIdPrefix;
|
|
}
|
|
|
|
private assertScoped(queryId: string): void {
|
|
if (this.prefix && !queryId.startsWith(this.prefix)) {
|
|
throw new SiaxError('AUTHORIZATION_DENIED', '0pt.analytics', 'query does not belong to this scope');
|
|
}
|
|
if (!/^[A-Za-z0-9_-]{1,128}$/.test(queryId)) {
|
|
// The id reaches ClickHouse as a bound parameter, but a malformed id is
|
|
// a bug worth surfacing rather than a string worth binding.
|
|
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'malformed query id');
|
|
}
|
|
}
|
|
|
|
async isRunning(queryId: string): Promise<boolean> {
|
|
this.assertScoped(queryId);
|
|
const body = await this.send(
|
|
'SELECT count() AS n FROM system.processes WHERE query_id = {qid:String} FORMAT JSON',
|
|
{ param_qid: queryId },
|
|
);
|
|
const n = Number((JSON.parse(body) as { data: Array<{ n: string | number }> }).data[0]?.n ?? 0);
|
|
return n > 0;
|
|
}
|
|
|
|
async requestKill(queryId: string): Promise<boolean> {
|
|
this.assertScoped(queryId);
|
|
await this.send(
|
|
'KILL QUERY WHERE query_id = {qid:String} ASYNC FORMAT JSON',
|
|
{ param_qid: queryId },
|
|
false,
|
|
);
|
|
return true;
|
|
}
|
|
|
|
async progress(queryId: string): Promise<QueryProgress | undefined> {
|
|
this.assertScoped(queryId);
|
|
const body = await this.send(
|
|
'SELECT read_rows, read_bytes, toUInt64(elapsed * 1000) AS elapsed_ms FROM system.processes ' +
|
|
'WHERE query_id = {qid:String} FORMAT JSON',
|
|
{ param_qid: queryId },
|
|
);
|
|
const row = (JSON.parse(body) as { data: Array<Record<string, string | number>> }).data[0];
|
|
if (!row) return undefined;
|
|
return {
|
|
rows_read: Number(row.read_rows ?? 0),
|
|
bytes_read: Number(row.read_bytes ?? 0),
|
|
elapsed_ms: Number(row.elapsed_ms ?? 0),
|
|
};
|
|
}
|
|
|
|
private async send(sql: string, params: Record<string, string>, expectJson = true): Promise<string> {
|
|
const url = new URL(this.baseUrl);
|
|
url.searchParams.set('query', sql);
|
|
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
|
// NOT readonly: KILL mutates server state. The other two would tolerate
|
|
// readonly, but sharing one path keeps the credential story simple.
|
|
url.searchParams.set('max_execution_time', '10');
|
|
const headers: Record<string, string> = {};
|
|
if (this.authHeader) headers.Authorization = this.authHeader;
|
|
let res: Response;
|
|
try {
|
|
res = await fetch(url.toString(), {
|
|
method: 'POST',
|
|
headers,
|
|
body: '',
|
|
signal: AbortSignal.timeout(this.timeoutMs),
|
|
});
|
|
} 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',
|
|
`process-control statement failed (CH code ${code})`,
|
|
);
|
|
}
|
|
if (expectJson && !text.trim()) {
|
|
throw new SiaxError('PERMANENT_FAILURE', 'clickhouse', 'empty response from process-control statement');
|
|
}
|
|
return text;
|
|
}
|
|
}
|