-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalytics-verifier.ts
More file actions
221 lines (216 loc) · 7.7 KB
/
Copy pathanalytics-verifier.ts
File metadata and controls
221 lines (216 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { type AnalyticsBundle } from "./bundle-contract.ts";
import {
EXECUTION_LIMITS,
resolvedExecutionSchema,
} from "./execution-contract.ts";
import { createQueryRuntime } from "./query-runtime/index.mjs";
import { parseAnalyticsQuery } from "./sql-policy.ts";
const REVISION = "0".repeat(64);
const NOW = 1_728_000_000_000;
export interface AnalyticsBundleVerification {
bundleId: string;
queryCount: number;
visualizationCount: number;
}
/** Same isolated parser/bootstrap/binding path as ordinary execution. */
export async function verifyAnalyticsBundle(
bundle: AnalyticsBundle,
): Promise<AnalyticsBundleVerification> {
const fixture = await createVerifierFixture();
let runtime: Awaited<ReturnType<typeof createQueryRuntime>> | undefined;
let failed = false;
try {
runtime = await createQueryRuntime({ trustedSource: fixture.handoff });
const queryColumns = new Map<string, Set<string>>();
for (const query of bundle.queries) {
const policy = parseAnalyticsQuery(query.sql);
const parameters = policy.parameters.map((name) => ({
name,
logicalType: "integer" as const,
value: 14,
}));
const admitted = await runtime.admitQuery({
sql: query.sql,
parameters,
cacheability: "stable",
});
if (admitted.kind !== "admitted") {
throw new Error(
`Query ${query.id} failed isolated admission: ${admitted.error.message}`,
);
}
const resolved = resolvedExecutionSchema.parse({
version: 2,
executionId: `analytics-exec_verifier_${bundle.id}_${query.id}`,
snapshot: fixture.snapshot,
bundleId: bundle.id,
bundleRevision: REVISION,
query: {
id: query.id,
revision: REVISION,
title: query.title,
sql: query.sql,
maxRows: query.maxRows,
...admitted.admission,
resultContractRevision: REVISION,
parameters,
},
});
const outcome = await runtime.worker.execute({
resolved,
source: fixture.handoff,
}, new AbortController().signal);
if (outcome.kind === "error") {
throw new Error(
`Query ${query.id} failed DuckDB verification: ${outcome.error.message}`,
);
}
queryColumns.set(
query.id,
new Set(outcome.result.result.columns.map((column) => column.name)),
);
}
for (const visualization of bundle.visualizations) {
const columns = queryColumns.get(visualization.queryId);
if (columns == null) {
throw new Error(
`Visualization ${visualization.id} references an unverified query.`,
);
}
const fields = visualization.kind === "metric"
? [visualization.value]
: visualization.kind === "table"
? visualization.columns.map((column) => column.field)
: [visualization.x, visualization.y];
for (const field of fields) {
if (!columns.has(field)) {
throw new Error(
`Visualization ${visualization.id} references missing query column ${field}.`,
);
}
}
}
return {
bundleId: bundle.id,
queryCount: bundle.queries.length,
visualizationCount: bundle.visualizations.length,
};
} catch (cause) {
failed = true;
throw cause;
} finally {
let cleanupFailure: unknown;
try {
await runtime?.close();
} catch (cause) {
cleanupFailure = cause;
}
try {
await fixture.cleanup();
} catch (cause) {
cleanupFailure ??= cause;
}
if (!failed && cleanupFailure !== undefined) throw cleanupFailure;
}
}
async function createVerifierFixture() {
const directory = await mkdtemp(join(tmpdir(), "analytics-verifier-"));
const path = join(directory, "verification.sqlite");
try {
const sqlite = await import("node:sqlite");
const db = new sqlite.DatabaseSync(path);
try {
db.exec(
`CREATE TABLE analytics_index_state (singleton INTEGER PRIMARY KEY, generation_id INTEGER NOT NULL, fact_projection_version INTEGER NOT NULL, loaded_threads INTEGER NOT NULL, fact_count INTEGER NOT NULL, truncated_threads INTEGER NOT NULL, degraded INTEGER NOT NULL, snapshot_updated_at INTEGER); INSERT INTO analytics_index_state VALUES (1, 1, 1, 1, 1, 0, 0, ${NOW}); CREATE TABLE tool_execution_facts_v1 (source_event_id TEXT PRIMARY KEY, thread_id TEXT, turn_id TEXT, sequence INTEGER, project_id TEXT, provider_id TEXT, created_at_ms INTEGER, turn_started_at_ms INTEGER, turn_completed_at_ms INTEGER, capability_kind TEXT, capability_key TEXT, status TEXT, duration_ms INTEGER, failed INTEGER, error_class TEXT, error_signature TEXT, command_binary TEXT, command_argument_1 TEXT, command_argument_2 TEXT, command_uses_help INTEGER, command_shape TEXT, command_shell_wrapped INTEGER, command_attribution_eligible INTEGER);`,
);
db.prepare(
`INSERT INTO tool_execution_facts_v1 VALUES ('verification', 'verification', 'verification', 1, 'verification', 'verification', ?, ?, ?, 'command', 'native:command_execution', 'completed', 0, 0, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 0)`,
).run(NOW - 1_000, NOW - 2_000, NOW - 500);
} finally {
db.close();
}
const sourceScope = {
scopeKey: "analytics-scope_verifier_fixture",
projection: "tool_execution_fact_v1" as const,
storage: "plugin-owned-sqlite" as const,
};
const range = { startInclusiveMs: NOW - 86_400_000, endExclusiveMs: NOW };
const coverage = {
coverageRevision: 1,
retention: {
startInclusiveMs: range.startInclusiveMs,
earliestVerifiedRetainedInclusiveMs: range.startInclusiveMs,
endExclusiveMs: NOW,
policyDays: EXECUTION_LIMITS.retainedProjectionDays,
},
observed: {
earliestFactMs: NOW - 1_000,
latestFactMs: NOW - 1_000,
asOfMs: NOW,
projectionGeneration: 1,
projectionRevision: REVISION,
},
population: {
candidateThreads: 1,
selectedThreads: 1,
loadedThreads: 1,
retainedFacts: 1,
cappedThreads: 0,
listPages: 1,
eventPages: 1,
eventBytes: 1,
safeFailureCount: 0,
lastSafeFailureAtMs: null,
candidateThreadLimit: 1,
threadPageLimit: 1,
eventPageLimit: 1,
maxEventsPerThread: 1,
maxEventBytes: 1,
},
mode: "complete-retained-projection" as const,
incompleteReasons: [],
backfill: {
state: "complete" as const,
direction: "newest-to-oldest" as const,
completeRange: range,
resumable: true,
},
reconciliation: {
observedAsOfMs: NOW,
lastFullReconciliationAtMs: NOW,
deletionConfirmation: "confirmed" as const,
sourceSemantics: "eventually-reconciled-observed-as-of" as const,
},
degraded: false,
};
const snapshot = {
version: 2 as const,
snapshotId: "analytics-snapshot_verifier_fixture",
sourceScope,
frozenRange: range,
capturedAtMs: NOW,
coverage,
};
const handoff = {
kind: "node-sqlite-readonly" as const,
sourceScope,
snapshotId: snapshot.snapshotId,
sourceGeneration: 1,
factProjectionVersion: 1,
readonlyDatabasePath: path,
maxChunkBytes: EXECUTION_LIMITS.maxTransferChunkBytes,
maxRowsPerChunk: EXECUTION_LIMITS.maxTransferRowsPerChunk,
};
return {
snapshot,
handoff,
cleanup: () => rm(directory, { recursive: true, force: true }),
};
} catch (cause) {
await rm(directory, { recursive: true, force: true });
throw cause;
}
}