@szdatatalk/sqlward 0.0.0-stage → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,943 @@
1
+ /**
2
+ * Offline Node & WASM runtime SDK (`@szdatatalk/sqlward`, v0.3.2).
3
+ *
4
+ * Zero Python dependency, zero compiler required at runtime, zero network access.
5
+ * Executes `sqlward_wasm.wasm` directly in-process or inside a terminable
6
+ * `node:worker_threads` Worker with 1 MiB byte bounds for single-SQL calls and
7
+ * 8 MiB + lossless manifest slimming + automatic model batching for dbt projects.
8
+ * Never executes SQL.
9
+ */
10
+
11
+ import { createHash } from "node:crypto";
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { Worker } from "node:worker_threads";
16
+
17
+ export const PROMOTED = true;
18
+ export const CONTRACT_VERSION = "0.3.2";
19
+ export const MAX_WASM_INPUT_BYTES = 1_048_576;
20
+ export const MAX_WASM_DBT_INPUT_BYTES = 8 * 1_048_576;
21
+
22
+ const KNOWN_MANIFEST_KEYS = new Set([
23
+ "metadata",
24
+ "nodes",
25
+ "sources",
26
+ "macros",
27
+ "docs",
28
+ "exposures",
29
+ "metrics",
30
+ "groups",
31
+ "selectors",
32
+ "disabled",
33
+ "parent_map",
34
+ "child_map",
35
+ "group_map",
36
+ "saved_queries",
37
+ "semantic_models",
38
+ "unit_tests",
39
+ ]);
40
+ const KNOWN_CATALOG_KEYS = new Set(["metadata", "nodes", "sources", "errors"]);
41
+ const sealWasmCache = new Map();
42
+
43
+ function getCachedSealWasm(wasmPath) {
44
+ if (!sealWasmCache.has(wasmPath)) {
45
+ const p = instantiateWasm(wasmPath).catch((err) => {
46
+ sealWasmCache.delete(wasmPath);
47
+ throw err;
48
+ });
49
+ sealWasmCache.set(wasmPath, p);
50
+ }
51
+ return sealWasmCache.get(wasmPath);
52
+ }
53
+
54
+ function computeArtifactOverride(rawInput, parsedObj, knownKeys) {
55
+ let bytes;
56
+ if (typeof rawInput === "string") {
57
+ bytes = Buffer.from(rawInput, "utf8");
58
+ } else {
59
+ bytes = Buffer.from(JSON.stringify(sortJsonKeys(parsedObj)), "utf8");
60
+ }
61
+ let ignored = 0;
62
+ for (const k of Object.keys(parsedObj)) {
63
+ if (!knownKeys.has(k)) ignored += 1;
64
+ }
65
+ return {
66
+ sha256: createHash("sha256").update(bytes).digest("hex"),
67
+ size_bytes: bytes.byteLength,
68
+ ignored_additive_fields: ignored,
69
+ };
70
+ }
71
+
72
+ function collectCompiledSqlSha256(parsedManifest) {
73
+ const out = new Map();
74
+ for (const group of DBT_MANIFEST_GROUPS) {
75
+ const grp = parsedManifest[group];
76
+ if (!grp || typeof grp !== "object" || Array.isArray(grp)) continue;
77
+ for (const [uid, entry] of Object.entries(grp)) {
78
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
79
+ const c1 = typeof entry.compiled_code === "string" ? entry.compiled_code.trim() : "";
80
+ const c2 = typeof entry.compiled_sql === "string" ? entry.compiled_sql.trim() : "";
81
+ const sql = c1 || c2;
82
+ if (sql) {
83
+ out.set(uid, createHash("sha256").update(sql, "utf8").digest("hex"));
84
+ }
85
+ }
86
+ }
87
+ return out;
88
+ }
89
+
90
+ function cmpOptStr(a, b) {
91
+ const aNull = a === null || a === undefined;
92
+ const bNull = b === null || b === undefined;
93
+ if (aNull && bNull) return 0;
94
+ if (aNull) return -1;
95
+ if (bNull) return 1;
96
+ return a < b ? -1 : a > b ? 1 : 0;
97
+ }
98
+
99
+ function cmpInferredEdge(a, b) {
100
+ return (
101
+ cmpOptStr(a.namespace, b.namespace) ||
102
+ cmpOptStr(a.from_node, b.from_node) ||
103
+ cmpOptStr(a.from_relation, b.from_relation) ||
104
+ cmpOptStr(a.from_column, b.from_column) ||
105
+ cmpOptStr(a.to_node, b.to_node) ||
106
+ cmpOptStr(a.to_relation, b.to_relation) ||
107
+ cmpOptStr(a.to_column, b.to_column) ||
108
+ cmpOptStr(a.relation, b.relation) ||
109
+ cmpOptStr(a.detail, b.detail) ||
110
+ cmpOptStr(a.reason, b.reason) ||
111
+ (a.masking_applied === b.masking_applied ? 0 : a.masking_applied ? 1 : -1)
112
+ );
113
+ }
114
+
115
+ function cmpDiagnostic(a, b) {
116
+ return (
117
+ cmpOptStr(a.code, b.code) ||
118
+ cmpOptStr(a.severity, b.severity) ||
119
+ cmpOptStr(a.message, b.message) ||
120
+ cmpOptStr(a.scope_id, b.scope_id)
121
+ );
122
+ }
123
+
124
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
125
+
126
+ const DBT_MANIFEST_GROUPS = [
127
+ "nodes",
128
+ "sources",
129
+ "exposures",
130
+ "metrics",
131
+ "seeds",
132
+ "snapshots",
133
+ "semantic_models",
134
+ "saved_queries",
135
+ "unit_tests",
136
+ ];
137
+
138
+ const DBT_METADATA_KEYS = [
139
+ "dbt_schema_version",
140
+ "dbt_version",
141
+ "adapter_type",
142
+ "project_id",
143
+ "project_name",
144
+ "target_name",
145
+ "invocation_id",
146
+ "generated_at",
147
+ ];
148
+
149
+ export function defaultWasmPath() {
150
+ if (process.env.SQLWARD_WASM_PATH) {
151
+ return process.env.SQLWARD_WASM_PATH;
152
+ }
153
+ if (process.env.LINEAGEKIT_WASM_PATH) {
154
+ return process.env.LINEAGEKIT_WASM_PATH;
155
+ }
156
+ const candidates = [
157
+ path.resolve(__dirname, "wasm/sqlward_wasm.wasm"),
158
+ path.resolve(__dirname, "sqlward_wasm.wasm"),
159
+ path.resolve(__dirname, "../../evidence/phase2/artifacts/wasm/sqlward_wasm.wasm"),
160
+ path.resolve(__dirname, "../../native/target/wasm32-unknown-unknown/release/sqlward_wasm.wasm"),
161
+ path.resolve(__dirname, "../../native/target/wasm32-unknown-unknown/debug/sqlward_wasm.wasm"),
162
+ path.resolve(__dirname, "../../evidence/phase2/artifacts/wasm/lineagekit_wasm.wasm"),
163
+ path.resolve(__dirname, "../../native/target/wasm32-unknown-unknown/release/lineagekit_wasm.wasm"),
164
+ path.resolve(__dirname, "../../native/target/wasm32-unknown-unknown/debug/lineagekit_wasm.wasm"),
165
+ ];
166
+ for (const p of candidates) {
167
+ if (fs.existsSync(p)) return p;
168
+ }
169
+ return candidates[0];
170
+ }
171
+
172
+ function parseJsonObjectInput(value, fieldName) {
173
+ if (value && typeof value === "object" && !Array.isArray(value)) {
174
+ return value;
175
+ }
176
+ if (typeof value === "string") {
177
+ const trimmed = value.trim();
178
+ if (!trimmed) {
179
+ throw new TypeError(`INVALID_ARTIFACT_JSON: ${fieldName} string is empty`);
180
+ }
181
+ let parsed;
182
+ try {
183
+ parsed = JSON.parse(trimmed);
184
+ } catch (err) {
185
+ throw new TypeError(`INVALID_ARTIFACT_JSON: ${fieldName} is not valid JSON (${err.message})`);
186
+ }
187
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
188
+ throw new TypeError(`INVALID_ARTIFACT_JSON: ${fieldName} must decode to a JSON object`);
189
+ }
190
+ return parsed;
191
+ }
192
+ throw new TypeError(
193
+ `INVALID_ARTIFACT_JSON: ${fieldName} must be a JSON object or JSON object string`,
194
+ );
195
+ }
196
+
197
+ /**
198
+ * Losslessly slim a dbt `manifest.json` (object or JSON string) by stripping
199
+ * non-lineage bloat (raw_code, descriptions, docs, macros, meta, patch_path, etc.)
200
+ * while preserving 100% of lineage, DAG, ephemeral CTE, and provenance fields.
201
+ */
202
+ export function slimDbtManifest(manifestInput, options = {}) {
203
+ const { includeCompiledCode = true, onlyModelIds = null } = options;
204
+ const src = parseJsonObjectInput(manifestInput, "manifest");
205
+ const out = {};
206
+
207
+ if (src.metadata && typeof src.metadata === "object" && !Array.isArray(src.metadata)) {
208
+ const meta = {};
209
+ for (const k of DBT_METADATA_KEYS) {
210
+ if (src.metadata[k] !== undefined && src.metadata[k] !== null) {
211
+ meta[k] = src.metadata[k];
212
+ }
213
+ }
214
+ out.metadata = meta;
215
+ }
216
+
217
+ if (src.parent_map && typeof src.parent_map === "object" && !Array.isArray(src.parent_map)) {
218
+ out.parent_map = src.parent_map;
219
+ }
220
+
221
+ const modelFilter = onlyModelIds ? new Set(onlyModelIds) : null;
222
+
223
+ for (const group of DBT_MANIFEST_GROUPS) {
224
+ const grp = src[group];
225
+ if (!grp || typeof grp !== "object" || Array.isArray(grp)) continue;
226
+ const slimGroup = {};
227
+ for (const [uid, entry] of Object.entries(grp)) {
228
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
229
+ const slim = {};
230
+ for (const k of [
231
+ "unique_id",
232
+ "resource_type",
233
+ "name",
234
+ "alias",
235
+ "identifier",
236
+ "database",
237
+ "schema",
238
+ "version",
239
+ "latest_version",
240
+ "original_file_path",
241
+ ]) {
242
+ if (entry[k] !== undefined && entry[k] !== null) slim[k] = entry[k];
243
+ }
244
+ if (entry.quoting && typeof entry.quoting === "object") {
245
+ slim.quoting = {
246
+ database: Boolean(entry.quoting.database),
247
+ schema: Boolean(entry.quoting.schema),
248
+ identifier: Boolean(entry.quoting.identifier),
249
+ };
250
+ }
251
+ if (entry.config && typeof entry.config === "object" && entry.config.materialized) {
252
+ slim.config = { materialized: entry.config.materialized };
253
+ }
254
+ if (entry.depends_on && Array.isArray(entry.depends_on.nodes)) {
255
+ slim.depends_on = { nodes: entry.depends_on.nodes };
256
+ }
257
+ if (includeCompiledCode && (!modelFilter || modelFilter.has(uid))) {
258
+ const sql = entry.compiled_code ?? entry.compiled_sql;
259
+ if (typeof sql === "string" && sql.trim().length > 0) {
260
+ slim.compiled_code = sql;
261
+ }
262
+ }
263
+ slimGroup[uid] = slim;
264
+ }
265
+ out[group] = slimGroup;
266
+ }
267
+
268
+ return out;
269
+ }
270
+
271
+ /**
272
+ * Losslessly slim a dbt `catalog.json` (object or JSON string) to only
273
+ * relation metadata and column names required for schema grounding.
274
+ */
275
+ export function slimDbtCatalog(catalogInput) {
276
+ if (catalogInput === undefined || catalogInput === null) return null;
277
+ const src = parseJsonObjectInput(catalogInput, "catalog");
278
+ const out = {};
279
+ if (src.metadata && typeof src.metadata === "object" && !Array.isArray(src.metadata)) {
280
+ const meta = {};
281
+ for (const k of DBT_METADATA_KEYS) {
282
+ if (src.metadata[k] !== undefined && src.metadata[k] !== null) {
283
+ meta[k] = src.metadata[k];
284
+ }
285
+ }
286
+ out.metadata = meta;
287
+ }
288
+ for (const group of ["nodes", "sources"]) {
289
+ const grp = src[group];
290
+ if (!grp || typeof grp !== "object" || Array.isArray(grp)) continue;
291
+ const slimGroup = {};
292
+ for (const [uid, entry] of Object.entries(grp)) {
293
+ if (!entry || typeof entry !== "object") continue;
294
+ const m = entry.metadata && typeof entry.metadata === "object" ? entry.metadata : {};
295
+ const cols = {};
296
+ if (entry.columns && typeof entry.columns === "object") {
297
+ for (const colName of Object.keys(entry.columns)) {
298
+ cols[colName] = {};
299
+ }
300
+ }
301
+ slimGroup[uid] = {
302
+ metadata: {
303
+ database: m.database ?? null,
304
+ schema: m.schema ?? null,
305
+ name: m.name ?? null,
306
+ },
307
+ columns: cols,
308
+ };
309
+ }
310
+ out[group] = slimGroup;
311
+ }
312
+ return out;
313
+ }
314
+
315
+ function sortJsonKeys(v) {
316
+ if (Array.isArray(v)) return v.map(sortJsonKeys);
317
+ if (v && typeof v === "object") {
318
+ const out = {};
319
+ for (const k of Object.keys(v).sort()) {
320
+ out[k] = sortJsonKeys(v[k]);
321
+ }
322
+ return out;
323
+ }
324
+ return v;
325
+ }
326
+
327
+ function canonicalSha256Hex(v) {
328
+ return createHash("sha256").update(JSON.stringify(sortJsonKeys(v))).digest("hex");
329
+ }
330
+
331
+ export function edgeKey(edge) {
332
+ return [
333
+ edge.sourceTable,
334
+ edge.sourceColumn,
335
+ edge.targetTable,
336
+ edge.targetColumn,
337
+ edge.dependencyType,
338
+ edge.relation,
339
+ edge.maskingApplied === true ? "true" : "false",
340
+ ].join("|");
341
+ }
342
+
343
+ export function compareEdges(actual, expectedDirect, expectedIndirect) {
344
+ const expected = new Set([
345
+ ...expectedDirect.map((e) =>
346
+ edgeKey({ ...e, dependencyType: "Direct", maskingApplied: !!e.maskingApplied }),
347
+ ),
348
+ ...expectedIndirect.map((e) =>
349
+ edgeKey({ ...e, dependencyType: "Indirect", maskingApplied: !!e.maskingApplied }),
350
+ ),
351
+ ]);
352
+ const actualKeys = new Set(actual.map(edgeKey));
353
+ const missing = [...expected].filter((k) => !actualKeys.has(k)).sort();
354
+ const unexpected = [...actualKeys].filter((k) => !expected.has(k)).sort();
355
+ return {
356
+ matchCount: [...expected].filter((k) => actualKeys.has(k)).length,
357
+ missingInActual: missing,
358
+ unexpectedInActual: unexpected,
359
+ isMatch: missing.length === 0 && unexpected.length === 0,
360
+ };
361
+ }
362
+
363
+ function makeStubImports() {
364
+ const noop = () => 0;
365
+ const nsProxy = new Proxy(
366
+ {},
367
+ {
368
+ get: () => noop,
369
+ },
370
+ );
371
+ return new Proxy(
372
+ {},
373
+ {
374
+ get: () => nsProxy,
375
+ },
376
+ );
377
+ }
378
+
379
+ /**
380
+ * Instantiate `sqlward_wasm.wasm` from bytes or file path with zero external glue.
381
+ */
382
+ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
383
+ const bytes =
384
+ wasmSource instanceof Uint8Array || wasmSource instanceof ArrayBuffer
385
+ ? wasmSource
386
+ : fs.readFileSync(wasmSource);
387
+ const { instance } = await WebAssembly.instantiate(bytes, makeStubImports());
388
+ const ex = instance.exports;
389
+ const wasmAlloc = ex.sw_wasm_alloc || ex.lk_wasm_alloc;
390
+ const wasmDealloc = ex.sw_wasm_dealloc || ex.lk_wasm_dealloc;
391
+ const wasmLastPtr = ex.sw_wasm_last_ptr || ex.lk_wasm_last_ptr;
392
+ const wasmLastLen = ex.sw_wasm_last_len || ex.lk_wasm_last_len;
393
+ const wasmMaxInputBytes = ex.sw_wasm_max_input_bytes || ex.lk_wasm_max_input_bytes;
394
+ const wasmMaxDbtInputBytes = ex.sw_wasm_max_dbt_input_bytes;
395
+ const wasmGraphDigest = ex.sw_wasm_graph_digest || ex.lk_wasm_graph_digest;
396
+ const wasmImpactDownstream = ex.sw_wasm_impact_downstream || ex.lk_wasm_impact_downstream;
397
+ const wasmImpactUpstream = ex.sw_wasm_impact_upstream || ex.lk_wasm_impact_upstream;
398
+ const encoder = new TextEncoder();
399
+ const decoder = new TextDecoder("utf-8", { fatal: true });
400
+ const maxDbtBytes =
401
+ typeof wasmMaxDbtInputBytes === "function"
402
+ ? Number(wasmMaxDbtInputBytes())
403
+ : MAX_WASM_DBT_INPUT_BYTES;
404
+
405
+ function writeUtf8(str, limitBytes = MAX_WASM_INPUT_BYTES) {
406
+ const encoded = encoder.encode(str);
407
+ if (encoded.byteLength > limitBytes) {
408
+ throw new RangeError(
409
+ `WASM_INPUT_TOO_LARGE: payload (${encoded.byteLength} bytes) exceeds ${limitBytes} byte limit`,
410
+ );
411
+ }
412
+ if (encoded.byteLength === 0) {
413
+ return { ptr: 0, len: 0 };
414
+ }
415
+ const ptr = wasmAlloc(encoded.byteLength);
416
+ if (!ptr) {
417
+ throw new RangeError("WASM_ALLOC_FAILED: allocation refused by linear-memory cap");
418
+ }
419
+ new Uint8Array(ex.memory.buffer, ptr, encoded.byteLength).set(encoded);
420
+ return { ptr, len: encoded.byteLength };
421
+ }
422
+
423
+ function freeBuf({ ptr, len }) {
424
+ if (ptr && len > 0) {
425
+ wasmDealloc(ptr, len);
426
+ }
427
+ }
428
+
429
+ function readLastResult() {
430
+ const ptr = wasmLastPtr();
431
+ const len = wasmLastLen();
432
+ return decoder.decode(new Uint8Array(ex.memory.buffer, ptr, len));
433
+ }
434
+
435
+ function normalizeEdgesPayload(edges) {
436
+ if (typeof edges === "string") return edges;
437
+ if (!Array.isArray(edges)) return JSON.stringify(edges);
438
+ return JSON.stringify(
439
+ edges.map((e) => ({
440
+ ...e,
441
+ dependencyType:
442
+ typeof e?.dependencyType === "string" ? e.dependencyType.toUpperCase() : e?.dependencyType,
443
+ })),
444
+ );
445
+ }
446
+
447
+ function callSingleJson(fn, payload, limitBytes = MAX_WASM_INPUT_BYTES) {
448
+ if (typeof fn !== "function") {
449
+ throw new Error("WASM_EXPORT_MISSING: rebuild sqlward_wasm.wasm >= 0.3.1");
450
+ }
451
+ const json = typeof payload === "string" ? payload : JSON.stringify(payload);
452
+ const buf = writeUtf8(json, limitBytes);
453
+ try {
454
+ const rc = fn(buf.ptr, buf.len);
455
+ const text = readLastResult();
456
+ if (rc !== 0) throw new Error(text);
457
+ return JSON.parse(text);
458
+ } finally {
459
+ freeBuf(buf);
460
+ }
461
+ }
462
+
463
+ return {
464
+ promoted: true,
465
+ maxInputBytes: Number(wasmMaxInputBytes()),
466
+ maxDbtInputBytes: maxDbtBytes,
467
+ versionInfo() {
468
+ if (typeof ex.sw_wasm_version_info !== "function") {
469
+ return { version: CONTRACT_VERSION, promoted: true, sqlParseInWasm: false };
470
+ }
471
+ const rc = ex.sw_wasm_version_info();
472
+ const text = readLastResult();
473
+ if (rc !== 0) throw new Error(text);
474
+ return JSON.parse(text);
475
+ },
476
+ parseColumn(request) {
477
+ return callSingleJson(ex.sw_wasm_parse_column, request);
478
+ },
479
+ evaluatePolicy(request) {
480
+ return callSingleJson(ex.sw_wasm_policy_eval, request);
481
+ },
482
+ preparePolicySnapshot(request) {
483
+ return callSingleJson(ex.sw_wasm_prepare_policy, request);
484
+ },
485
+ evaluatePolicyPrepared(request) {
486
+ return callSingleJson(ex.sw_wasm_policy_eval_prepared, request);
487
+ },
488
+ evictPolicySnapshot(request) {
489
+ return callSingleJson(ex.sw_wasm_evict_policy, request);
490
+ },
491
+ verifyReceipt(request) {
492
+ return callSingleJson(ex.sw_wasm_receipt_verify, request);
493
+ },
494
+ verifyWorkflowEvidence(bundle) {
495
+ return callSingleJson(ex.sw_wasm_workflow_verify, bundle);
496
+ },
497
+ bind(request) {
498
+ return callSingleJson(ex.sw_wasm_bind, request);
499
+ },
500
+ analyzeDbt(request, options = {}) {
501
+ const { slim = true } = options;
502
+ let payload = request;
503
+ if (slim && request && typeof request === "object" && !Array.isArray(request)) {
504
+ const prepared = { ...request };
505
+ const existingOverrides = prepared.artifact_overrides ?? prepared.artifactOverrides;
506
+ const overrides =
507
+ existingOverrides && typeof existingOverrides === "object"
508
+ ? { ...existingOverrides }
509
+ : {};
510
+ if (prepared.manifest !== undefined) {
511
+ const parsedManifest = parseJsonObjectInput(prepared.manifest, "manifest");
512
+ if (!overrides.manifest) {
513
+ overrides.manifest = computeArtifactOverride(
514
+ prepared.manifest,
515
+ parsedManifest,
516
+ KNOWN_MANIFEST_KEYS,
517
+ );
518
+ }
519
+ prepared.manifest = slimDbtManifest(parsedManifest);
520
+ }
521
+ if (prepared.catalog !== undefined && prepared.catalog !== null) {
522
+ const parsedCatalog = parseJsonObjectInput(prepared.catalog, "catalog");
523
+ if (!overrides.catalog) {
524
+ overrides.catalog = computeArtifactOverride(
525
+ prepared.catalog,
526
+ parsedCatalog,
527
+ KNOWN_CATALOG_KEYS,
528
+ );
529
+ }
530
+ prepared.catalog = slimDbtCatalog(parsedCatalog);
531
+ }
532
+ if (Object.keys(overrides).length > 0) {
533
+ delete prepared.artifactOverrides;
534
+ prepared.artifact_overrides = overrides;
535
+ }
536
+ payload = prepared;
537
+ }
538
+ return callSingleJson(ex.sw_wasm_dbt_analyze, payload, maxDbtBytes);
539
+ },
540
+ diffDbt(request) {
541
+ return callSingleJson(ex.sw_wasm_dbt_diff, request, maxDbtBytes);
542
+ },
543
+ impactDbt(request) {
544
+ return callSingleJson(ex.sw_wasm_dbt_impact, request, maxDbtBytes);
545
+ },
546
+ sealDbt(snapshot) {
547
+ return callSingleJson(ex.sw_wasm_dbt_seal, snapshot, maxDbtBytes);
548
+ },
549
+ profileOmop(request) {
550
+ return callSingleJson(ex.sw_wasm_omop_profile, request);
551
+ },
552
+ analyzeMappingImpact(request) {
553
+ return callSingleJson(ex.sw_wasm_mapping_impact, request);
554
+ },
555
+ queryRobotImpact(query) {
556
+ return callSingleJson(ex.sw_wasm_robot_impact, query);
557
+ },
558
+ verifyInterop(request) {
559
+ return callSingleJson(ex.sw_wasm_interop_verify, request);
560
+ },
561
+ retrieveContext(request) {
562
+ return callSingleJson(ex.sw_wasm_context_retrieve, request);
563
+ },
564
+ graphDigestFromEdges(edges) {
565
+ const json = normalizeEdgesPayload(edges);
566
+ const buf = writeUtf8(json);
567
+ try {
568
+ const rc = wasmGraphDigest(buf.ptr, buf.len);
569
+ const text = readLastResult();
570
+ if (rc !== 0) throw new Error(text);
571
+ return text;
572
+ } finally {
573
+ freeBuf(buf);
574
+ }
575
+ },
576
+ impactDownstream(edges, originTable, originColumn) {
577
+ const json = normalizeEdgesPayload(edges);
578
+ const bEdges = writeUtf8(json);
579
+ const bTbl = writeUtf8(originTable);
580
+ const bCol = writeUtf8(originColumn);
581
+ try {
582
+ const rc = wasmImpactDownstream(
583
+ bEdges.ptr,
584
+ bEdges.len,
585
+ bTbl.ptr,
586
+ bTbl.len,
587
+ bCol.ptr,
588
+ bCol.len,
589
+ );
590
+ const text = readLastResult();
591
+ if (rc !== 0) throw new Error(text);
592
+ return JSON.parse(text);
593
+ } finally {
594
+ freeBuf(bEdges);
595
+ freeBuf(bTbl);
596
+ freeBuf(bCol);
597
+ }
598
+ },
599
+ impactUpstream(edges, originTable, originColumn) {
600
+ const json = normalizeEdgesPayload(edges);
601
+ const bEdges = writeUtf8(json);
602
+ const bTbl = writeUtf8(originTable);
603
+ const bCol = writeUtf8(originColumn);
604
+ try {
605
+ const rc = wasmImpactUpstream(
606
+ bEdges.ptr,
607
+ bEdges.len,
608
+ bTbl.ptr,
609
+ bTbl.len,
610
+ bCol.ptr,
611
+ bCol.len,
612
+ );
613
+ const text = readLastResult();
614
+ if (rc !== 0) throw new Error(text);
615
+ return JSON.parse(text);
616
+ } finally {
617
+ freeBuf(bEdges);
618
+ freeBuf(bTbl);
619
+ freeBuf(bCol);
620
+ }
621
+ },
622
+ };
623
+ }
624
+
625
+ /**
626
+ * Execute WASM analysis inside a terminable worker thread (`AbortSignal` + `timeoutMs`).
627
+ * Worker exits after each call so WASM linear memory is fully reclaimed by the OS.
628
+ */
629
+ export function runWasmWorker(operation, payload, options = {}) {
630
+ const { timeoutMs = 5000, signal, wasmPath = defaultWasmPath() } = options;
631
+ const workerScript = path.join(__dirname, "wasm-worker.js");
632
+ const isDbtOp =
633
+ operation === "analyzeDbt" || operation === "diffDbt" || operation === "impactDbt";
634
+ const maxBytes = isDbtOp ? MAX_WASM_DBT_INPUT_BYTES : MAX_WASM_INPUT_BYTES;
635
+
636
+ return new Promise((resolve, reject) => {
637
+ if (signal?.aborted) {
638
+ reject(new Error("WASM_CANCELLED"));
639
+ return;
640
+ }
641
+ const rawJson =
642
+ typeof payload === "string"
643
+ ? payload
644
+ : typeof payload?.edges === "string"
645
+ ? payload.edges
646
+ : JSON.stringify(payload ?? {});
647
+ if (Buffer.byteLength(rawJson, "utf8") > maxBytes) {
648
+ reject(new RangeError(`WASM_INPUT_TOO_LARGE: payload exceeds ${maxBytes} byte limit`));
649
+ return;
650
+ }
651
+
652
+ const worker = new Worker(workerScript, {
653
+ workerData: { operation, payload, wasmPath },
654
+ execArgv: [],
655
+ });
656
+ let settled = false;
657
+ let cancelReason = null;
658
+
659
+ const finish = (err, val) => {
660
+ if (settled) return;
661
+ settled = true;
662
+ clearTimeout(timer);
663
+ if (signal) signal.removeEventListener("abort", onAbort);
664
+ if (err) reject(err);
665
+ else resolve(val);
666
+ };
667
+
668
+ const onAbort = () => {
669
+ cancelReason = "WASM_CANCELLED";
670
+ worker.terminate().finally(() => finish(new Error("WASM_CANCELLED")));
671
+ };
672
+ if (signal) signal.addEventListener("abort", onAbort, { once: true });
673
+
674
+ const timer = setTimeout(() => {
675
+ cancelReason = "WASM_TIMEOUT";
676
+ worker.terminate().finally(() => finish(new Error("WASM_TIMEOUT")));
677
+ }, timeoutMs);
678
+
679
+ worker.once("message", (msg) => {
680
+ if (cancelReason) {
681
+ finish(new Error(cancelReason));
682
+ return;
683
+ }
684
+ if (msg?.ok) finish(null, msg.result);
685
+ else finish(new Error(msg?.error || "WASM_WORKER_ERROR"));
686
+ });
687
+ worker.once("error", (err) => {
688
+ if (cancelReason) finish(new Error(cancelReason));
689
+ else finish(err);
690
+ });
691
+ worker.once("exit", (code) => {
692
+ if (!settled) {
693
+ if (cancelReason) finish(new Error(cancelReason));
694
+ else if (code !== 0) finish(new Error(`WASM_WORKER_EXIT_${code}`));
695
+ }
696
+ });
697
+ });
698
+ }
699
+
700
+ /**
701
+ * Analyze an arbitrarily large dbt project in pure WASM via lossless manifest slimming
702
+ * plus automatic chunked SQL inference (optional per-batch Worker isolation so WASM
703
+ * linear memory never accumulates across batches).
704
+ */
705
+ export async function analyzeDbtBatched(request, options = {}) {
706
+ const {
707
+ wasmPath = defaultWasmPath(),
708
+ batchSize = 50,
709
+ maxBatchBytes = 4 * 1_048_576,
710
+ useWorker = true,
711
+ timeoutMs = 30_000,
712
+ signal,
713
+ } = options;
714
+
715
+ if (!request || typeof request !== "object" || Array.isArray(request)) {
716
+ throw new TypeError("INVALID_REQUEST: analyzeDbtBatched requires a request object");
717
+ }
718
+ const parsedManifest = parseJsonObjectInput(request.manifest, "manifest");
719
+ const parsedCatalog =
720
+ request.catalog !== undefined && request.catalog !== null
721
+ ? parseJsonObjectInput(request.catalog, "catalog")
722
+ : null;
723
+ const slimmedFull = slimDbtManifest(parsedManifest, { includeCompiledCode: true });
724
+ const slimmedCatalog = parsedCatalog !== null ? slimDbtCatalog(parsedCatalog) : null;
725
+
726
+ const existingOverrides = request.artifact_overrides ?? request.artifactOverrides;
727
+ const artifactOverrides = {
728
+ ...(existingOverrides && typeof existingOverrides === "object" ? existingOverrides : {}),
729
+ };
730
+ if (!artifactOverrides.manifest) {
731
+ artifactOverrides.manifest = computeArtifactOverride(
732
+ request.manifest,
733
+ parsedManifest,
734
+ KNOWN_MANIFEST_KEYS,
735
+ );
736
+ }
737
+ if (parsedCatalog !== null && !artifactOverrides.catalog) {
738
+ artifactOverrides.catalog = computeArtifactOverride(
739
+ request.catalog,
740
+ parsedCatalog,
741
+ KNOWN_CATALOG_KEYS,
742
+ );
743
+ }
744
+
745
+ const analyzeSql = request.analyze_sql ?? request.analyzeSql ?? true;
746
+ const sqlModelIds = [];
747
+ if (analyzeSql && slimmedFull.nodes && typeof slimmedFull.nodes === "object") {
748
+ for (const [uid, entry] of Object.entries(slimmedFull.nodes)) {
749
+ const rtype = entry.resource_type || "model";
750
+ const isEph = entry.config?.materialized === "ephemeral";
751
+ const sql = entry.compiled_code || entry.compiled_sql;
752
+ if (rtype === "model" && !isEph && typeof sql === "string" && sql.trim().length > 0) {
753
+ sqlModelIds.push(uid);
754
+ }
755
+ }
756
+ }
757
+ sqlModelIds.sort();
758
+
759
+ const {
760
+ manifest: _m,
761
+ catalog: _c,
762
+ analyzeSql: _as1,
763
+ analyze_sql: _as2,
764
+ runResults: reqRunResultsCamel,
765
+ run_results: reqRunResultsSnake,
766
+ modelIds: _mi1,
767
+ model_ids: _mi2,
768
+ artifactOverrides: _ao1,
769
+ artifact_overrides: _ao2,
770
+ ...restReq
771
+ } = request;
772
+ const runResultsVal = reqRunResultsSnake ?? reqRunResultsCamel ?? null;
773
+
774
+ const baseReq = {
775
+ ...restReq,
776
+ manifest: slimmedFull,
777
+ ...(slimmedCatalog !== null ? { catalog: slimmedCatalog } : {}),
778
+ ...(runResultsVal !== null ? { run_results: runResultsVal } : {}),
779
+ artifact_overrides: artifactOverrides,
780
+ analyze_sql: analyzeSql,
781
+ };
782
+
783
+ const singleBytes = Buffer.byteLength(JSON.stringify(baseReq), "utf8");
784
+ const execOne = async (payload) => {
785
+ if (useWorker) {
786
+ return runWasmWorker("analyzeDbt", payload, { wasmPath, timeoutMs, signal });
787
+ }
788
+ const wasm = await instantiateWasm(wasmPath);
789
+ return wasm.analyzeDbt(payload, { slim: false });
790
+ };
791
+
792
+ if (!analyzeSql || (sqlModelIds.length <= batchSize && singleBytes <= maxBatchBytes)) {
793
+ return execOne(baseReq);
794
+ }
795
+
796
+ // Pass 1: DAG skeleton without compiled_code (fast, tiny linear memory footprint),
797
+ // anchored to the original raw artifact provenance overrides.
798
+ const skeletonManifest = slimDbtManifest(parsedManifest, { includeCompiledCode: false });
799
+ const skeleton = await execOne({
800
+ ...restReq,
801
+ manifest: skeletonManifest,
802
+ ...(slimmedCatalog !== null ? { catalog: slimmedCatalog } : {}),
803
+ ...(runResultsVal !== null ? { run_results: runResultsVal } : {}),
804
+ artifact_overrides: artifactOverrides,
805
+ analyze_sql: false,
806
+ });
807
+
808
+ // Preserve compiled_sql_sha256 for ALL nodes (including ephemeral models, snapshots, tests)
809
+ const compiledSqlShaByUid = collectCompiledSqlSha256(parsedManifest);
810
+
811
+ // Pass 2: Partition SQL models into bounded batches (both count & byte capped)
812
+ const batches = [];
813
+ let current = [];
814
+ let currentSqlBytes = 0;
815
+ const skeletonBytes = Buffer.byteLength(JSON.stringify(skeletonManifest), "utf8");
816
+ const catalogBytes = slimmedCatalog
817
+ ? Buffer.byteLength(JSON.stringify(slimmedCatalog), "utf8")
818
+ : 0;
819
+ const fixedOverhead = skeletonBytes + catalogBytes + 16_384;
820
+ const sqlBudgetPerBatch = Math.max(256 * 1024, maxBatchBytes - fixedOverhead);
821
+
822
+ for (const uid of sqlModelIds) {
823
+ const sqlLen = Buffer.byteLength(slimmedFull.nodes[uid].compiled_code || "", "utf8");
824
+ if (
825
+ current.length > 0 &&
826
+ (current.length >= batchSize || currentSqlBytes + sqlLen > sqlBudgetPerBatch)
827
+ ) {
828
+ batches.push(current);
829
+ current = [];
830
+ currentSqlBytes = 0;
831
+ }
832
+ current.push(uid);
833
+ currentSqlBytes += sqlLen;
834
+ }
835
+ if (current.length > 0) batches.push(current);
836
+
837
+ const inferredMap = new Map();
838
+ const diagMap = new Map();
839
+ const scopeMap = new Map();
840
+ const nodePatchMap = new Map();
841
+
842
+ for (const d of skeleton.diagnostics || []) {
843
+ diagMap.set(`${d.code}|${d.severity}|${d.scope_id ?? ""}|${d.message}`, d);
844
+ }
845
+
846
+ for (const batchIds of batches) {
847
+ const batchManifest = slimDbtManifest(parsedManifest, {
848
+ includeCompiledCode: true,
849
+ onlyModelIds: batchIds,
850
+ });
851
+ const part = await execOne({
852
+ ...restReq,
853
+ manifest: batchManifest,
854
+ ...(slimmedCatalog !== null ? { catalog: slimmedCatalog } : {}),
855
+ run_results: null,
856
+ sources: null,
857
+ analyze_sql: true,
858
+ model_ids: batchIds,
859
+ });
860
+
861
+ for (const e of part.edges?.inferred || []) {
862
+ const k = JSON.stringify([
863
+ e.from_node,
864
+ e.from_relation,
865
+ e.from_column,
866
+ e.to_node,
867
+ e.to_relation,
868
+ e.to_column,
869
+ e.relation,
870
+ e.detail,
871
+ e.reason,
872
+ e.masking_applied,
873
+ ]);
874
+ inferredMap.set(k, e);
875
+ }
876
+ for (const d of part.diagnostics || []) {
877
+ diagMap.set(`${d.code}|${d.severity}|${d.scope_id ?? ""}|${d.message}`, d);
878
+ }
879
+ for (const s of part.completeness?.scopes || []) {
880
+ scopeMap.set(s.scope_id, s);
881
+ }
882
+ for (const n of part.nodes || []) {
883
+ if (batchIds.includes(n.unique_id)) {
884
+ nodePatchMap.set(n.unique_id, {
885
+ compiled_sql_sha256: n.compiled_sql_sha256,
886
+ ephemeral_resolution: n.ephemeral_resolution,
887
+ });
888
+ }
889
+ }
890
+ }
891
+
892
+ // Merge deterministically back into skeleton
893
+ const mergedNodes = (skeleton.nodes || []).map((n) => {
894
+ const patch = nodePatchMap.get(n.unique_id);
895
+ const fullSha = compiledSqlShaByUid.get(n.unique_id) ?? null;
896
+ if (patch) {
897
+ return {
898
+ ...n,
899
+ ...patch,
900
+ compiled_sql_sha256: patch.compiled_sql_sha256 ?? fullSha,
901
+ };
902
+ }
903
+ return fullSha !== null ? { ...n, compiled_sql_sha256: fullSha } : n;
904
+ });
905
+ const mergedInferred = [...inferredMap.values()].sort(cmpInferredEdge);
906
+ const mergedDiagnostics = [...diagMap.values()].sort(cmpDiagnostic);
907
+ const mergedScopes = [...scopeMap.values()].sort((a, b) =>
908
+ a.scope_id < b.scope_id ? -1 : a.scope_id > b.scope_id ? 1 : 0,
909
+ );
910
+
911
+ const hasErrors = mergedDiagnostics.some((d) => d.severity === "ERROR");
912
+ const hasInconclusive =
913
+ mergedScopes.some((s) => s.level === "inconclusive") ||
914
+ mergedDiagnostics.some((d) => d.severity === "INCONCLUSIVE");
915
+ const catalogPresent = Boolean(skeleton.completeness?.catalog_present);
916
+ const capabilityGaps = catalogPresent ? [] : ["CATALOG_ABSENT"];
917
+
918
+ const mergedEdges = {
919
+ declared: skeleton.edges?.declared || [],
920
+ inferred: mergedInferred,
921
+ };
922
+ const mergedCompleteness = {
923
+ ...skeleton.completeness,
924
+ overall: hasInconclusive ? "inconclusive" : catalogPresent ? "complete" : "partial",
925
+ requires_caller_acceptance: hasInconclusive || !catalogPresent,
926
+ capability_gaps: capabilityGaps,
927
+ scopes: mergedScopes,
928
+ };
929
+ const mergedSnapshot = {
930
+ ...skeleton,
931
+ status: hasErrors ? "ERROR" : hasInconclusive ? "INCONCLUSIVE" : "OK",
932
+ nodes: mergedNodes,
933
+ edges: mergedEdges,
934
+ completeness: mergedCompleteness,
935
+ diagnostics: mergedDiagnostics,
936
+ protected_decision_allowed: !hasErrors && !hasInconclusive && catalogPresent,
937
+ };
938
+
939
+ // Seal in-process with Rust WASM (2–5 ms, zero Worker spawn overhead) so canonical sorting,
940
+ // float serialization, snapshot_id, and evidence_id match single-shot byte-for-byte.
941
+ const sealWasm = await getCachedSealWasm(wasmPath);
942
+ return sealWasm.sealDbt(mergedSnapshot);
943
+ }