@query-farm/vgi 0.44.0 → 0.46.0

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.
Files changed (73) hide show
  1. package/README.md +8 -1
  2. package/dist/arrow/impl-arrowjs/index.d.ts +1 -1
  3. package/dist/arrow/impl-arrowjs/ipc.d.ts +6 -0
  4. package/dist/arrow/impl-flechette/build.d.ts +2 -2
  5. package/dist/arrow/impl-flechette/canonical.d.ts +2 -2
  6. package/dist/arrow/impl-flechette/index.d.ts +1 -1
  7. package/dist/arrow/impl-flechette/ipc.d.ts +6 -0
  8. package/dist/arrow/impl-flechette/schema.d.ts +19 -5
  9. package/dist/arrow/index.d.ts +1 -1
  10. package/dist/catalog/contents-codec.d.ts +7 -0
  11. package/dist/catalog/contents-digest.d.ts +2 -1
  12. package/dist/catalog/interface.d.ts +3 -0
  13. package/dist/catalog/publication-envelope.d.ts +1 -0
  14. package/dist/catalog/publication.d.ts +142 -0
  15. package/dist/catalog/s3-publication.d.ts +38 -0
  16. package/dist/client/client.d.ts +20 -1
  17. package/dist/client-entry.js +189 -37
  18. package/dist/client-entry.js.map +15 -12
  19. package/dist/codec/asd.d.ts +4 -0
  20. package/dist/functions/continuation.d.ts +69 -0
  21. package/dist/functions/table-in-out.d.ts +51 -7
  22. package/dist/functions/types.d.ts +20 -0
  23. package/dist/generated/vgi-client.d.ts +7 -14
  24. package/dist/generated/vgi-protocol-schemas.d.ts +2 -0
  25. package/dist/generated/vgi-protocol-types.d.ts +26 -3
  26. package/dist/generated/vgi-service.d.ts +3 -3
  27. package/dist/index.core.d.ts +1 -0
  28. package/dist/index.d.ts +4 -0
  29. package/dist/index.js +981 -138
  30. package/dist/index.js.map +31 -25
  31. package/dist/protocol/dispatch.d.ts +1 -1
  32. package/dist/protocol/handlers/catalog/contents.d.ts +4 -4
  33. package/dist/serve-entry.js +643 -81
  34. package/dist/serve-entry.js.map +22 -18
  35. package/dist/util/parent-rows.d.ts +8 -0
  36. package/dist/worker-cf-entry.d.ts +1 -1
  37. package/dist/worker-cf-entry.js +821 -131
  38. package/dist/worker-cf-entry.js.map +29 -24
  39. package/package.json +4 -4
  40. package/src/arrow/impl-arrowjs/index.ts +1 -0
  41. package/src/arrow/impl-arrowjs/ipc.ts +23 -0
  42. package/src/arrow/impl-flechette/build.ts +4 -2
  43. package/src/arrow/impl-flechette/canonical.ts +14 -7
  44. package/src/arrow/impl-flechette/index.ts +1 -0
  45. package/src/arrow/impl-flechette/ipc.ts +19 -0
  46. package/src/arrow/index.ts +1 -1
  47. package/src/catalog/contents-codec.ts +77 -0
  48. package/src/catalog/contents-digest.ts +20 -17
  49. package/src/catalog/interface.ts +3 -0
  50. package/src/catalog/publication-envelope.ts +62 -0
  51. package/src/catalog/publication.ts +290 -0
  52. package/src/catalog/read-only.ts +6 -2
  53. package/src/catalog/s3-publication.ts +81 -0
  54. package/src/client/client.ts +82 -30
  55. package/src/codec/asd.ts +40 -1
  56. package/src/codec/conform.ts +2 -1
  57. package/src/filter-pushdown/collector.ts +17 -1
  58. package/src/functions/continuation.ts +202 -0
  59. package/src/functions/table-in-out.ts +131 -56
  60. package/src/functions/types.ts +20 -0
  61. package/src/generated/vgi-client.ts +8 -16
  62. package/src/generated/vgi-protocol-schemas.ts +14 -6
  63. package/src/generated/vgi-protocol-types.ts +39 -5
  64. package/src/generated/vgi-service.ts +4 -3
  65. package/src/index.core.ts +6 -0
  66. package/src/index.ts +5 -0
  67. package/src/protocol/dispatch.ts +1 -1
  68. package/src/protocol/handlers/catalog/admin.ts +7 -4
  69. package/src/protocol/handlers/catalog/contents.ts +50 -35
  70. package/src/protocol/handlers/function.ts +12 -0
  71. package/src/protocol/state-serializer.ts +7 -1
  72. package/src/util/parent-rows.ts +41 -0
  73. package/src/worker-cf-entry.ts +3 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.44.0",
3
+ "version": "0.46.0",
4
4
  "description": "TypeScript framework for extending DuckDB with user-defined functions via the Vector Gateway Interface (VGI) over Arrow IPC.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Query Farm LLC (https://query.farm)",
@@ -87,16 +87,16 @@
87
87
  },
88
88
  "dependencies": {
89
89
  "@noble/ciphers": "^2.3.0",
90
- "@query-farm/flechette": "^2.4.1"
90
+ "@query-farm/flechette": "^2.7.1"
91
91
  },
92
92
  "peerDependencies": {
93
93
  "@query-farm/apache-arrow": "^21.1.1",
94
- "@query-farm/vgi-rpc": "^0.29.0"
94
+ "@query-farm/vgi-rpc": "^0.29.2"
95
95
  },
96
96
  "devDependencies": {
97
97
  "@duckdb/node-api": "^1.5.5-r.4",
98
98
  "@query-farm/apache-arrow": "^21.1.1",
99
- "@query-farm/vgi-rpc": "^0.29.0",
99
+ "@query-farm/vgi-rpc": "^0.29.2",
100
100
  "@types/bun": "latest",
101
101
  "typescript": "^7.0.2"
102
102
  },
@@ -49,6 +49,7 @@ export {
49
49
  deserializeSchema,
50
50
  serializeBatch,
51
51
  deserializeBatch,
52
+ deserializeBatches, serializeBatches, serializeCollectionRows,
52
53
  } from "./ipc.js";
53
54
 
54
55
  // Column statistics (sparse-union heavy — backend-specific).
@@ -1,3 +1,4 @@
1
+ import { batchFromRows } from "./build.js";
1
2
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
3
  // Arrow IPC stream serialization/deserialization for schemas and batches.
3
4
 
@@ -65,3 +66,25 @@ export function deserializeBatch(bytes: Uint8Array): RecordBatch {
65
66
  }
66
67
  return batches[0];
67
68
  }
69
+
70
+ /** Decode every data batch of a collection stream (including dictionary replacements). */
71
+ export function deserializeBatches(bytes: Uint8Array): VgiBatch[] {
72
+ return [...RecordBatchReader.from(bytes)];
73
+ }
74
+
75
+ /** Write all batches to one IPC stream. */
76
+ export function serializeBatches(batches: VgiBatch[], schema: VgiSchema): Uint8Array {
77
+ const writer = new RecordBatchStreamWriter();
78
+ writer.reset(undefined, schema as Schema);
79
+ for (const batch of batches) (writer as any)._writeRecordBatch(batch as RecordBatch);
80
+ writer.close();
81
+ return writer.toUint8Array(true);
82
+ }
83
+
84
+ /** Build shared dictionaries once and emit bounded slices of the collection. */
85
+ export function serializeCollectionRows(schema: VgiSchema, rows: Record<string, any>[], maxBatchRows: number): Uint8Array {
86
+ const batch = batchFromRows(rows, schema);
87
+ const batches: VgiBatch[] = [];
88
+ for (let offset = 0; offset < batch.numRows; offset += maxBatchRows) batches.push(batch.slice(offset, offset + maxBatchRows));
89
+ return serializeBatches(batches, schema);
90
+ }
@@ -30,13 +30,14 @@ export function columnFromArray(values: any[], type: VgiDataType): VgiColumnData
30
30
  export function batchFromRows(
31
31
  rows: Record<string, any>[],
32
32
  schema: VgiSchema,
33
+ maxBatchRows?: number,
33
34
  ): VgiBatch {
34
35
  if (rows.length === 0) return emptyBatch(schema);
35
36
  const columns: Record<string, any[]> = {};
36
37
  for (const f of schema.fields) {
37
38
  columns[f.name] = rows.map((r) => r[f.name] ?? null);
38
39
  }
39
- return batchFromColumns(columns, schema);
40
+ return batchFromColumns(columns, schema, "rich", maxBatchRows);
40
41
  }
41
42
 
42
43
  /**
@@ -48,6 +49,7 @@ export function batchFromColumns(
48
49
  columns: Record<string, any[]>,
49
50
  schema: VgiSchema,
50
51
  repr: "rich" | "raw" = "rich",
52
+ maxBatchRows?: number,
51
53
  ): VgiBatch {
52
54
  let numRows = 0;
53
55
  for (const f of schema.fields) {
@@ -61,5 +63,5 @@ export function batchFromColumns(
61
63
  const toCanon = repr === "raw" ? codec.rawToCanonical : codec.richToCanonical;
62
64
  canonicalColumns[f.name] = values.map((v) => toCanon.call(codec, v));
63
65
  }
64
- return writeCanonicalBatch(canonicalColumns, schema, numRows);
66
+ return writeCanonicalBatch(canonicalColumns, schema, numRows, maxBatchRows);
65
67
  }
@@ -9,9 +9,10 @@
9
9
  //
10
10
  // flechette's `columnFromArray` already handles the complex cases (List, Map,
11
11
  // Struct, Decimal, Timestamp[ns]) when given the right options, so the WRITE
12
- // side is mostly delegation. The one wrinkle is Date: flechette stores a Date
13
- // column correctly only when fed JS `Date` objects, but our canonical date32 is
14
- // a day-number and date64 is ms-bigint — so we convert canonical -> Date here.
12
+ // side is mostly delegation. Date32 needs epoch milliseconds rather than our
13
+ // canonical day-number. Date64 takes canonical bigint milliseconds directly:
14
+ // Flechette 2.7.1 preserves raw bigint storage, while Date/number inputs are
15
+ // normalized to midnight and would lose an existing time-of-day component.
15
16
  //
16
17
  // On the READ side, flechette's Column/Data `.at()` already decodes every
17
18
  // scalar to its canonical JS value LOSSLESSLY (timestamp/duration/time64 ->
@@ -62,6 +63,7 @@ export function writeCanonicalBatch(
62
63
  columns: Record<string, unknown[]>,
63
64
  schema: VgiSchema,
64
65
  numRows: number,
66
+ maxBatchRows?: number,
65
67
  ): VgiBatch {
66
68
  const childCols: Column<any>[] = [];
67
69
  const fields: any[] = [];
@@ -69,8 +71,8 @@ export function writeCanonicalBatch(
69
71
  const ftype = toFlechetteType(f.type);
70
72
  const values = columns[f.name];
71
73
  const col: Column<any> = values
72
- ? f_columnFromArray(prepareForFlechette(f.type, values), ftype, COLUMN_OPTS)
73
- : f_columnFromArray(new Array(numRows).fill(null), ftype, COLUMN_OPTS);
74
+ ? f_columnFromArray(prepareForFlechette(f.type, values), ftype, { ...COLUMN_OPTS, maxBatchRows })
75
+ : f_columnFromArray(new Array(numRows).fill(null), ftype, { ...COLUMN_OPTS, maxBatchRows });
74
76
  childCols.push(col);
75
77
  const nullable = (f as any).nullable ?? true;
76
78
  const metadata = (f as any).metadata ?? null;
@@ -87,19 +89,23 @@ export function writeCanonicalBatch(
87
89
 
88
90
  /**
89
91
  * Convert canonical values into the shape flechette's columnFromArray needs.
90
- * Date columns: canonical day-number / ms-bigint -> JS Date. Map columns:
92
+ * Date32 columns: canonical day-number -> JS Date; Date64 stays ms-bigint. Map columns:
91
93
  * canonical Array<[k,v]> -> Map. Struct/List recurse. Everything else passes
92
94
  * through.
93
95
  */
94
96
  export function prepareForFlechette(type: VgiDataType, values: unknown[]): unknown[] {
95
97
  const tid = type.typeId;
98
+ if (tid === -1) {
99
+ return prepareForFlechette((type as any).dictionary as VgiDataType, values);
100
+ }
96
101
  if (tid === 8) {
97
102
  const isDay = (type as any).unit === 0;
98
103
  return values.map((v) => {
99
104
  if (v == null) return null;
105
+ if (!isDay) return typeof v === "bigint" ? v : BigInt(v instanceof Date ? v.getTime() : v as number);
100
106
  if (v instanceof Date) return v;
101
107
  const n = typeof v === "bigint" ? Number(v) : (v as number);
102
- return new Date(isDay ? n * MS_PER_DAY : n);
108
+ return new Date(n * MS_PER_DAY);
103
109
  });
104
110
  }
105
111
  if (tid === 11 && (type as any).unit === MONTH_DAY_NANO) {
@@ -173,6 +179,7 @@ export function prepareForFlechette(type: VgiDataType, values: unknown[]): unkno
173
179
 
174
180
  function needsPrepare(type: VgiDataType): boolean {
175
181
  const tid = type.typeId;
182
+ if (tid === -1) return needsPrepare((type as any).dictionary as VgiDataType);
176
183
  if (tid === 8 || tid === 17) return true;
177
184
  if (tid === 11 && (type as any).unit === MONTH_DAY_NANO) return true;
178
185
  if (tid === 13) return ((type as any).children ?? []).some((c: any) => needsPrepare(c.type));
@@ -54,6 +54,7 @@ export {
54
54
  deserializeSchema,
55
55
  serializeBatch,
56
56
  deserializeBatch,
57
+ deserializeBatches, serializeBatches, serializeCollectionRows,
57
58
  } from "./ipc.js";
58
59
 
59
60
  // Column statistics — sparse-union min/max via the codec/canonical path.
@@ -1,3 +1,4 @@
1
+ import { batchFromRows } from "./build.js";
1
2
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
3
  // Arrow IPC stream serialization/deserialization for the flechette backend.
3
4
  //
@@ -10,6 +11,7 @@
10
11
  import {
11
12
  tableFromIPC,
12
13
  tableToIPC,
14
+ tablesToIPC,
13
15
  columnFromArray,
14
16
  field as f_field,
15
17
  Table,
@@ -174,3 +176,20 @@ export function deserializeBatch(input: Uint8Array): VgiBatch {
174
176
  },
175
177
  }) as unknown as VgiBatch;
176
178
  }
179
+
180
+ /** Flechette resolves all record batches and their dictionaries into one logical table. */
181
+ export function deserializeBatches(bytes: Uint8Array): VgiBatch[] {
182
+ return [deserializeBatch(bytes)];
183
+ }
184
+
185
+ /** The input batches must share dictionaries; collection encoding builds them together. */
186
+ export function serializeBatches(batches: VgiBatch[], schema: VgiSchema): Uint8Array {
187
+ if (batches.length === 0) return serializeSchema(schema);
188
+ return tablesToIPC(batches as any[], { format: "stream" }) as Uint8Array;
189
+ }
190
+
191
+ /** Build bounded batches together so their dictionary indices share one value table. */
192
+ export function serializeCollectionRows(schema: VgiSchema, rows: Record<string, any>[], maxBatchRows: number): Uint8Array {
193
+ const table = batchFromRows(rows, schema, maxBatchRows);
194
+ return tableToIPC(table as any, { format: "stream" }) as Uint8Array;
195
+ }
@@ -61,7 +61,7 @@ export {
61
61
  // canonical single-value read (backend-agnostic, lossless)
62
62
  readCanonicalValue,
63
63
  // IPC
64
- serializeSchema, deserializeSchema, serializeBatch, deserializeBatch,
64
+ serializeSchema, deserializeSchema, serializeBatch, deserializeBatch, deserializeBatches, serializeBatches, serializeCollectionRows,
65
65
  // Column statistics
66
66
  buildStatisticsBatch,
67
67
  } from "#arrow-impl";
@@ -0,0 +1,77 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Catalog-wide collection streams, independent of delivery and attachment state.
3
+ import { encodeASDCollection, decodeASDCollection } from "../codec/asd.js";
4
+ import {
5
+ SchemaInfoSchema, TableInfoSchema, ViewInfoSchema, FunctionInfoSchema, MacroInfoSchema, IndexInfoSchema,
6
+ } from "../generated/vgi-protocol-schemas.js";
7
+ import type { CatalogContentsResponse, SchemaInfo, TableInfo, ViewInfo, FunctionInfo, MacroInfo, IndexInfo } from "../generated/vgi-client.js";
8
+ import type { SchemaContentsInfo } from "./interface.js";
9
+
10
+ // Preserve component boundaries even when a schema name contains delimiters.
11
+ const schemaPathKey = (path: readonly string[]) => JSON.stringify(path.map((part) => part.toLowerCase()));
12
+
13
+ export const CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"] as const;
14
+ export type CatalogStreams = Pick<CatalogContentsResponse, typeof CATALOG_STREAM_KINDS[number]>;
15
+
16
+ export function encodeCatalogStreams(inventory: readonly SchemaContentsInfo[]): CatalogStreams {
17
+ const streams = {
18
+ schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
19
+ tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
20
+ views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
21
+ functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
22
+ macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
23
+ indexes: encodeASDCollection(IndexInfoSchema, inventory.flatMap((s) => s.indexes)),
24
+ };
25
+ return streams;
26
+ }
27
+
28
+ /** Preserve raw path components, overloads and every table-function subtype. */
29
+ export function decodeCatalogStreams(response: CatalogContentsResponse, ifNoneMatch?: string | null): SchemaContentsInfo[] {
30
+ if (response.not_modified) {
31
+ if (response.etag == null || (ifNoneMatch !== undefined && response.etag !== ifNoneMatch)
32
+ || CATALOG_STREAM_KINDS.some((kind) => response[kind] != null)) {
33
+ throw new Error("invalid catalog_contents not_modified response");
34
+ }
35
+ return [];
36
+ }
37
+ const infos = decodeASDCollection<SchemaInfo>(SchemaInfoSchema, response.schemas);
38
+ const schemas: SchemaContentsInfo[] = [];
39
+ const index = new Map<string, SchemaContentsInfo>();
40
+ for (const schema of infos) {
41
+ if (!Array.isArray(schema.path) || schema.path.length === 0) throw new Error("catalog schema has an empty path");
42
+ const key = schemaPathKey(schema.path);
43
+ if (index.has(key)) throw new Error("catalog contains duplicate schema paths");
44
+ if (schema.path.length > 1 && !index.has(schemaPathKey(schema.path.slice(0, -1)))) {
45
+ throw new Error("catalog schema is missing its preceding parent");
46
+ }
47
+ const entry: SchemaContentsInfo = { schema, tables: [], views: [], scalar_functions: [], aggregate_functions: [], table_functions: [], scalar_macros: [], table_macros: [], indexes: [] };
48
+ index.set(key, entry);
49
+ schemas.push(entry);
50
+ }
51
+ const owner = (item: { schema_path: string[] }): SchemaContentsInfo => {
52
+ const entry = index.get(schemaPathKey(item.schema_path));
53
+ if (!entry) throw new Error("catalog object references an absent schema");
54
+ return entry;
55
+ };
56
+ for (const item of decodeASDCollection<TableInfo>(TableInfoSchema, response.tables)) owner(item).tables.push(item);
57
+ for (const item of decodeASDCollection<ViewInfo>(ViewInfoSchema, response.views)) owner(item).views.push(item);
58
+ for (const item of decodeASDCollection<FunctionInfo>(FunctionInfoSchema, response.functions)) {
59
+ const entry = owner(item);
60
+ switch (String(item.function_type).toUpperCase()) {
61
+ case "SCALAR": entry.scalar_functions.push(item); break;
62
+ case "AGGREGATE": entry.aggregate_functions.push(item); break;
63
+ case "TABLE": case "TABLE_BUFFERING": entry.table_functions.push(item); break;
64
+ default: throw new Error(`unknown catalog function type ${item.function_type}`);
65
+ }
66
+ }
67
+ for (const item of decodeASDCollection<MacroInfo>(MacroInfoSchema, response.macros)) {
68
+ const entry = owner(item);
69
+ switch (String(item.macro_type).toUpperCase()) {
70
+ case "SCALAR": entry.scalar_macros.push(item); break;
71
+ case "TABLE": entry.table_macros.push(item); break;
72
+ default: throw new Error(`unknown catalog macro type ${item.macro_type}`);
73
+ }
74
+ }
75
+ for (const item of decodeASDCollection<IndexInfo>(IndexInfoSchema, response.indexes)) owner(item).indexes.push(item);
76
+ return schemas;
77
+ }
@@ -9,17 +9,8 @@
9
9
  */
10
10
 
11
11
  import type { SchemaContents } from "../generated/vgi-protocol-types.js";
12
-
13
- const KINDS = [
14
- "tables",
15
- "views",
16
- "scalar_functions",
17
- "aggregate_functions",
18
- "table_functions",
19
- "scalar_macros",
20
- "table_macros",
21
- "indexes",
22
- ] as const;
12
+ import type { CatalogStreams } from "./contents-codec.js";
13
+ import { CATALOG_STREAM_KINDS } from "./contents-codec.js";
23
14
 
24
15
  /**
25
16
  * Hex SHA-256 over a `catalog_contents` snapshot: the `content-hash` etag.
@@ -38,7 +29,7 @@ const KINDS = [
38
29
  * @param schemas The snapshot, in wire order.
39
30
  * @returns The lowercase hex digest.
40
31
  */
41
- export async function catalogContentsDigest(schemas: readonly SchemaContents[]): Promise<string> {
32
+ export async function catalogContentsDigest(streams: CatalogStreams | readonly SchemaContents[], version: number = 0): Promise<string> {
42
33
  const utf8 = new TextEncoder();
43
34
  const parts: Uint8Array[] = [];
44
35
  let total = 0;
@@ -58,11 +49,23 @@ export async function catalogContentsDigest(schemas: readonly SchemaContents[]):
58
49
  for (const v of values) chunk(v);
59
50
  };
60
51
 
61
- count(schemas.length);
62
- for (const entry of schemas) {
63
- chunks(entry.path.map((p) => utf8.encode(p)));
64
- chunk(entry.schema);
65
- for (const kind of KINDS) chunks(entry[kind]);
52
+ if (Array.isArray(streams)) {
53
+ // Compatibility helper for author-side legacy inventories; the wire writer
54
+ // hashes the six streams below.
55
+ count(streams.length);
56
+ for (const entry of streams) {
57
+ chunks(entry.path.map((p: string) => utf8.encode(p)));
58
+ chunk(entry.schema);
59
+ for (const kind of ["tables", "views", "scalar_functions", "aggregate_functions", "table_functions", "scalar_macros", "table_macros", "indexes"] as const) chunks(entry[kind]);
60
+ }
61
+ } else {
62
+ chunk(utf8.encode("vgi.catalog-contents.2.2"));
63
+ count(version);
64
+ for (const kind of CATALOG_STREAM_KINDS) {
65
+ const value = (streams as CatalogStreams)[kind];
66
+ count(value == null ? 0 : 1);
67
+ if (value != null) chunk(value);
68
+ }
66
69
  }
67
70
 
68
71
  const buf = new Uint8Array(total);
@@ -1,3 +1,4 @@
1
+ import type { CatalogSnapshotPolicy } from "./publication.js";
1
2
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
3
  // CatalogInterface abstract class with ~35 methods.
3
4
  // Matching Python's vgi/catalog/catalog_interface.py
@@ -562,6 +563,8 @@ function isPromise<T>(v: Awaitable<T>): v is Promise<T> {
562
563
  }
563
564
 
564
565
  export abstract class CatalogInterface {
566
+ /** Opt-in immutable external delivery for catalog_contents. */
567
+ catalogSnapshotPolicy: CatalogSnapshotPolicy | null = null;
565
568
  /**
566
569
  * Opt-in framework etag for `catalog_contents`. `"content-hash"`: when
567
570
  * `catalogContents` returns no etag of its own, the worker uses the hex
@@ -0,0 +1,62 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Inspect IPC message framing before a backend can merge/drop record batches.
3
+ // The catalog's RPC envelope is exactly Schema + one 1-row RecordBatch. Its
4
+ // single binary field needs no dictionary messages. Inner metadata schemas are
5
+ // checked separately by the ordinary catalog codecs.
6
+ export function validateCatalogPublicationEnvelope(bytes: Uint8Array): void {
7
+ try {
8
+ const stream = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9
+ let position = 0, messages = 0;
10
+ while (position < bytes.length) {
11
+ let length = stream.getInt32(position, true); position += 4;
12
+ if (length === -1) { length = stream.getInt32(position, true); position += 4; }
13
+ if (length === 0) {
14
+ if (position !== bytes.length) throw new Error("trailing data");
15
+ break;
16
+ }
17
+ if (length < 4 || length > bytes.length - position) throw new Error("invalid message length");
18
+ const head = new DataView(bytes.buffer, bytes.byteOffset + position, length);
19
+ const tableField = (table: number, field: number): number | null => {
20
+ const vtable = table - head.getInt32(table, true);
21
+ const vlength = head.getUint16(vtable, true);
22
+ if (vlength < 4 || vlength % 2 || vtable + vlength > length) throw new Error("invalid vtable");
23
+ if (4 + 2 * field >= vlength) return null;
24
+ const offset = head.getUint16(vtable + 4 + 2 * field, true);
25
+ return offset === 0 ? null : table + offset;
26
+ };
27
+ const follow = (pointer: number) => pointer + head.getUint32(pointer, true);
28
+ const root = head.getUint32(0, true);
29
+ const typePosition = tableField(root, 1);
30
+ const type = typePosition == null ? 0 : head.getUint8(typePosition);
31
+ if (type !== (messages === 0 ? 1 : messages === 1 ? 3 : -1)) throw new Error("expected one schema and one record batch");
32
+ if (type === 3) {
33
+ const header = tableField(root, 2);
34
+ if (header == null) throw new Error("missing record header");
35
+ const rows = tableField(follow(header), 0);
36
+ if (rows == null || head.getBigInt64(rows, true) !== 1n) throw new Error("expected one response row");
37
+ }
38
+ const metadata = tableField(root, 4);
39
+ if (metadata != null) {
40
+ const vector = follow(metadata), count = head.getUint32(vector, true);
41
+ if (count > length / 4) throw new Error("invalid metadata vector");
42
+ for (let i = 0; i < count; i++) {
43
+ const keyPointer = tableField(follow(vector + 4 + 4 * i), 0);
44
+ if (keyPointer == null) continue;
45
+ const keyStart = follow(keyPointer), keyLength = head.getUint32(keyStart, true);
46
+ if (keyStart + 4 + keyLength > length) throw new Error("invalid metadata key");
47
+ const key = new TextDecoder().decode(new Uint8Array(head.buffer, head.byteOffset + keyStart + 4, keyLength));
48
+ if (key === "vgi_rpc.location" || key === "vgi_rpc.log_level") throw new Error("pointer/log metadata is not a catalog result");
49
+ }
50
+ }
51
+ const bodyPosition = tableField(root, 3);
52
+ const bodyLength = bodyPosition == null ? 0 : Number(head.getBigInt64(bodyPosition, true));
53
+ position += length;
54
+ if (!Number.isSafeInteger(bodyLength) || bodyLength < 0 || bodyLength > bytes.length - position) throw new Error("invalid body length");
55
+ position += bodyLength;
56
+ messages++;
57
+ }
58
+ if (messages !== 2) throw new Error("missing response batch");
59
+ } catch (error) {
60
+ throw new Error(`invalid published RPC envelope: ${error instanceof Error ? error.message : String(error)}`);
61
+ }
62
+ }