@szdatatalk/sqlward 0.3.0 → 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.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export const PROMOTED: true;
2
- export const CONTRACT_VERSION: "0.3.0";
2
+ export const CONTRACT_VERSION: "0.3.2";
3
3
  export const MAX_WASM_INPUT_BYTES: 1048576;
4
+ export const MAX_WASM_DBT_INPUT_BYTES: 8388608;
4
5
 
5
6
  export interface LineageEdge {
6
7
  sourceTable: string;
@@ -32,13 +33,17 @@ export interface WasmVersionInfo {
32
33
  export interface SqlWardWasmInstance {
33
34
  promoted: true;
34
35
  maxInputBytes: number;
36
+ maxDbtInputBytes: number;
35
37
  versionInfo(): WasmVersionInfo;
36
38
  parseColumn(request: Record<string, unknown> | string): Record<string, unknown>;
37
39
  evaluatePolicy(request: Record<string, unknown> | string): Record<string, unknown>;
38
40
  verifyReceipt(request: Record<string, unknown> | string): Record<string, unknown>;
39
41
  verifyWorkflowEvidence(bundle: Record<string, unknown> | string): Record<string, unknown>;
40
42
  bind(request: Record<string, unknown> | string): Record<string, unknown>;
41
- analyzeDbt(request: Record<string, unknown> | string): Record<string, unknown>;
43
+ analyzeDbt(request: Record<string, unknown> | string, options?: { slim?: boolean }): Record<string, unknown>;
44
+ diffDbt(request: Record<string, unknown> | string): Record<string, unknown>;
45
+ impactDbt(request: Record<string, unknown> | string): Record<string, unknown>;
46
+ sealDbt(snapshot: Record<string, unknown> | string): Record<string, unknown>;
42
47
  profileOmop(request: Record<string, unknown> | string): Record<string, unknown>;
43
48
  analyzeMappingImpact(request: Record<string, unknown> | string): Record<string, unknown>;
44
49
  queryRobotImpact(query: Record<string, unknown> | string): Record<string, unknown>;
@@ -64,6 +69,8 @@ export type WasmWorkerOperation =
64
69
  | "verifyWorkflowEvidence"
65
70
  | "bind"
66
71
  | "analyzeDbt"
72
+ | "diffDbt"
73
+ | "impactDbt"
67
74
  | "profileOmop"
68
75
  | "analyzeMappingImpact"
69
76
  | "queryRobotImpact"
@@ -82,3 +89,14 @@ export function runWasmWorker(
82
89
  payload: unknown,
83
90
  options?: WasmWorkerOptions,
84
91
  ): Promise<unknown>;
92
+ export function slimDbtManifest(
93
+ manifest: Record<string, unknown> | string,
94
+ options?: { includeCompiledCode?: boolean; onlyModelIds?: string[] | null },
95
+ ): Record<string, unknown>;
96
+ export function slimDbtCatalog(
97
+ catalog: Record<string, unknown> | string | null | undefined,
98
+ ): Record<string, unknown> | null;
99
+ export function analyzeDbtBatched(
100
+ request: Record<string, unknown>,
101
+ options?: WasmWorkerOptions & { batchSize?: number; maxBatchBytes?: number; useWorker?: boolean },
102
+ ): Promise<Record<string, unknown>>;
package/index.js CHANGED
@@ -1,24 +1,151 @@
1
1
  /**
2
- * Offline Node & WASM runtime SDK (`@szdatatalk/sqlward`, v0.3.0).
2
+ * Offline Node & WASM runtime SDK (`@szdatatalk/sqlward`, v0.3.2).
3
3
  *
4
4
  * Zero Python dependency, zero compiler required at runtime, zero network access.
5
5
  * Executes `sqlward_wasm.wasm` directly in-process or inside a terminable
6
- * `node:worker_threads` Worker with 1 MiB byte bounds for 8-dialect SQL parsing,
7
- * column lineage, graph digest/impact, M6 policy/receipt/workflow verification,
8
- * and pure-Rust domain adapters (bind, dbt, OMOP, robot, interop). Never executes SQL.
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
9
  */
10
10
 
11
+ import { createHash } from "node:crypto";
11
12
  import fs from "node:fs";
12
13
  import path from "node:path";
13
14
  import { fileURLToPath } from "node:url";
14
15
  import { Worker } from "node:worker_threads";
15
16
 
16
17
  export const PROMOTED = true;
17
- export const CONTRACT_VERSION = "0.3.0";
18
+ export const CONTRACT_VERSION = "0.3.2";
18
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
+ }
19
123
 
20
124
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
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
+
22
149
  export function defaultWasmPath() {
23
150
  if (process.env.SQLWARD_WASM_PATH) {
24
151
  return process.env.SQLWARD_WASM_PATH;
@@ -42,6 +169,165 @@ export function defaultWasmPath() {
42
169
  return candidates[0];
43
170
  }
44
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
+
45
331
  export function edgeKey(edge) {
46
332
  return [
47
333
  edge.sourceTable,
@@ -105,16 +391,23 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
105
391
  const wasmLastPtr = ex.sw_wasm_last_ptr || ex.lk_wasm_last_ptr;
106
392
  const wasmLastLen = ex.sw_wasm_last_len || ex.lk_wasm_last_len;
107
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;
108
395
  const wasmGraphDigest = ex.sw_wasm_graph_digest || ex.lk_wasm_graph_digest;
109
396
  const wasmImpactDownstream = ex.sw_wasm_impact_downstream || ex.lk_wasm_impact_downstream;
110
397
  const wasmImpactUpstream = ex.sw_wasm_impact_upstream || ex.lk_wasm_impact_upstream;
111
398
  const encoder = new TextEncoder();
112
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;
113
404
 
114
- function writeUtf8(str) {
405
+ function writeUtf8(str, limitBytes = MAX_WASM_INPUT_BYTES) {
115
406
  const encoded = encoder.encode(str);
116
- if (encoded.byteLength > MAX_WASM_INPUT_BYTES) {
117
- throw new RangeError("WASM_INPUT_TOO_LARGE: payload exceeds 1 MiB limit");
407
+ if (encoded.byteLength > limitBytes) {
408
+ throw new RangeError(
409
+ `WASM_INPUT_TOO_LARGE: payload (${encoded.byteLength} bytes) exceeds ${limitBytes} byte limit`,
410
+ );
118
411
  }
119
412
  if (encoded.byteLength === 0) {
120
413
  return { ptr: 0, len: 0 };
@@ -151,12 +444,12 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
151
444
  );
152
445
  }
153
446
 
154
- function callSingleJson(fn, payload) {
447
+ function callSingleJson(fn, payload, limitBytes = MAX_WASM_INPUT_BYTES) {
155
448
  if (typeof fn !== "function") {
156
- throw new Error("WASM_EXPORT_MISSING: rebuild sqlward_wasm.wasm >= 0.3.0");
449
+ throw new Error("WASM_EXPORT_MISSING: rebuild sqlward_wasm.wasm >= 0.3.1");
157
450
  }
158
451
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
159
- const buf = writeUtf8(json);
452
+ const buf = writeUtf8(json, limitBytes);
160
453
  try {
161
454
  const rc = fn(buf.ptr, buf.len);
162
455
  const text = readLastResult();
@@ -170,6 +463,7 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
170
463
  return {
171
464
  promoted: true,
172
465
  maxInputBytes: Number(wasmMaxInputBytes()),
466
+ maxDbtInputBytes: maxDbtBytes,
173
467
  versionInfo() {
174
468
  if (typeof ex.sw_wasm_version_info !== "function") {
175
469
  return { version: CONTRACT_VERSION, promoted: true, sqlParseInWasm: false };
@@ -185,6 +479,15 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
185
479
  evaluatePolicy(request) {
186
480
  return callSingleJson(ex.sw_wasm_policy_eval, request);
187
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
+ },
188
491
  verifyReceipt(request) {
189
492
  return callSingleJson(ex.sw_wasm_receipt_verify, request);
190
493
  },
@@ -194,8 +497,54 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
194
497
  bind(request) {
195
498
  return callSingleJson(ex.sw_wasm_bind, request);
196
499
  },
197
- analyzeDbt(request) {
198
- return callSingleJson(ex.sw_wasm_dbt_analyze, request);
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);
199
548
  },
200
549
  profileOmop(request) {
201
550
  return callSingleJson(ex.sw_wasm_omop_profile, request);
@@ -209,6 +558,9 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
209
558
  verifyInterop(request) {
210
559
  return callSingleJson(ex.sw_wasm_interop_verify, request);
211
560
  },
561
+ retrieveContext(request) {
562
+ return callSingleJson(ex.sw_wasm_context_retrieve, request);
563
+ },
212
564
  graphDigestFromEdges(edges) {
213
565
  const json = normalizeEdgesPayload(edges);
214
566
  const buf = writeUtf8(json);
@@ -272,10 +624,14 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
272
624
 
273
625
  /**
274
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.
275
628
  */
276
629
  export function runWasmWorker(operation, payload, options = {}) {
277
630
  const { timeoutMs = 5000, signal, wasmPath = defaultWasmPath() } = options;
278
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;
279
635
 
280
636
  return new Promise((resolve, reject) => {
281
637
  if (signal?.aborted) {
@@ -288,13 +644,14 @@ export function runWasmWorker(operation, payload, options = {}) {
288
644
  : typeof payload?.edges === "string"
289
645
  ? payload.edges
290
646
  : JSON.stringify(payload ?? {});
291
- if (Buffer.byteLength(rawJson, "utf8") > MAX_WASM_INPUT_BYTES) {
292
- reject(new RangeError("WASM_INPUT_TOO_LARGE: payload exceeds 1 MiB limit"));
647
+ if (Buffer.byteLength(rawJson, "utf8") > maxBytes) {
648
+ reject(new RangeError(`WASM_INPUT_TOO_LARGE: payload exceeds ${maxBytes} byte limit`));
293
649
  return;
294
650
  }
295
651
 
296
652
  const worker = new Worker(workerScript, {
297
653
  workerData: { operation, payload, wasmPath },
654
+ execArgv: [],
298
655
  });
299
656
  let settled = false;
300
657
  let cancelReason = null;
@@ -339,3 +696,248 @@ export function runWasmWorker(operation, payload, options = {}) {
339
696
  });
340
697
  });
341
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
+ }
package/package.json CHANGED
@@ -1,7 +1,16 @@
1
1
  {
2
2
  "name": "@szdatatalk/sqlward",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/shygoly/sqlward.git",
8
+ "directory": "packages/wasm"
9
+ },
10
+ "homepage": "https://github.com/shygoly/sqlward#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/shygoly/sqlward/issues"
13
+ },
5
14
  "description": "Zero-Python WASM runtime for SqlWard: 8-dialect SQL lineage, M6 security policy, receipts, and dbt/OMOP/Robot/M5 adapters",
6
15
  "type": "module",
7
16
  "main": "index.js",
Binary file
package/wasm-worker.js CHANGED
@@ -29,6 +29,10 @@ async function main() {
29
29
  result = wasm.bind(payload);
30
30
  } else if (operation === "analyzeDbt") {
31
31
  result = wasm.analyzeDbt(payload);
32
+ } else if (operation === "diffDbt") {
33
+ result = wasm.diffDbt(payload);
34
+ } else if (operation === "impactDbt") {
35
+ result = wasm.impactDbt(payload);
32
36
  } else if (operation === "profileOmop") {
33
37
  result = wasm.profileOmop(payload);
34
38
  } else if (operation === "analyzeMappingImpact") {
@@ -37,6 +41,8 @@ async function main() {
37
41
  result = wasm.queryRobotImpact(payload);
38
42
  } else if (operation === "verifyInterop") {
39
43
  result = wasm.verifyInterop(payload);
44
+ } else if (operation === "retrieveContext") {
45
+ result = wasm.retrieveContext(payload);
40
46
  } else {
41
47
  throw new Error(`unsupported WASM worker operation: ${operation}`);
42
48
  }