@query-farm/vgi 0.45.0 → 0.47.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 (102) hide show
  1. package/README.md +19 -6
  2. package/dist/arrow/impl-arrowjs/index.d.ts +1 -1
  3. package/dist/arrow/impl-arrowjs/iterate.d.ts +2 -0
  4. package/dist/arrow/impl-flechette/canonical.d.ts +1 -1
  5. package/dist/arrow/impl-flechette/index.d.ts +1 -1
  6. package/dist/arrow/impl-flechette/iterate.d.ts +2 -0
  7. package/dist/arrow/impl-flechette/schema.d.ts +19 -5
  8. package/dist/arrow/index.d.ts +1 -1
  9. package/dist/catalog/column-expressions.d.ts +8 -0
  10. package/dist/catalog/column-metadata.d.ts +11 -0
  11. package/dist/catalog/composite.d.ts +2 -1
  12. package/dist/catalog/descriptors.d.ts +21 -29
  13. package/dist/catalog/interface.d.ts +15 -20
  14. package/dist/catalog/macro-overloads.d.ts +4 -0
  15. package/dist/catalog/read-only.d.ts +1 -1
  16. package/dist/catalog/unconstrained-columns.d.ts +2 -0
  17. package/dist/client/client.d.ts +38 -14
  18. package/dist/client-entry.js +806 -115
  19. package/dist/client-entry.js.map +18 -14
  20. package/dist/functions/continuation.d.ts +69 -0
  21. package/dist/functions/projection.d.ts +18 -0
  22. package/dist/functions/table-in-out.d.ts +51 -7
  23. package/dist/functions/table.d.ts +6 -1
  24. package/dist/functions/types.d.ts +21 -0
  25. package/dist/generated/vgi-client.d.ts +178 -36
  26. package/dist/generated/vgi-protocol-schemas.d.ts +51 -1
  27. package/dist/generated/vgi-protocol-types.d.ts +317 -3
  28. package/dist/generated/vgi-service.d.ts +266 -29
  29. package/dist/index.core.d.ts +3 -1
  30. package/dist/index.js +1747 -320
  31. package/dist/index.js.map +45 -37
  32. package/dist/protocol/dispatch.d.ts +9 -9
  33. package/dist/protocol/handlers/aggregate.d.ts +1 -1
  34. package/dist/protocol/handlers/catalog/index.d.ts +1 -1
  35. package/dist/protocol/handlers/catalog/metadata.d.ts +1 -0
  36. package/dist/protocol/handlers/function.d.ts +1 -1
  37. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  38. package/dist/protocol/handlers/unimplemented.d.ts +1 -1
  39. package/dist/protocol/serializers/bind.d.ts +5 -1
  40. package/dist/protocol/types.d.ts +5 -0
  41. package/dist/rpc-server.d.ts +6 -6
  42. package/dist/serve-entry.js +1607 -436
  43. package/dist/serve-entry.js.map +33 -27
  44. package/dist/util/arrow/index.d.ts +1 -1
  45. package/dist/util/parent-rows.d.ts +8 -0
  46. package/dist/worker-cf-entry.d.ts +1 -1
  47. package/dist/worker-cf-entry.js +1901 -526
  48. package/dist/worker-cf-entry.js.map +45 -37
  49. package/dist/worker.d.ts +1 -1
  50. package/package.json +8 -7
  51. package/src/arrow/impl-arrowjs/index.ts +1 -1
  52. package/src/arrow/impl-arrowjs/iterate.ts +9 -1
  53. package/src/arrow/impl-arrowjs/project.ts +1 -1
  54. package/src/arrow/impl-flechette/canonical.ts +7 -5
  55. package/src/arrow/impl-flechette/index.ts +1 -1
  56. package/src/arrow/impl-flechette/ipc.ts +12 -0
  57. package/src/arrow/impl-flechette/iterate.ts +5 -0
  58. package/src/arrow/impl-flechette/project.ts +6 -8
  59. package/src/arrow/index.ts +1 -1
  60. package/src/catalog/column-expressions.ts +224 -0
  61. package/src/catalog/column-metadata.ts +151 -0
  62. package/src/catalog/composite.ts +5 -1
  63. package/src/catalog/contents-codec.ts +6 -1
  64. package/src/catalog/descriptors.ts +21 -29
  65. package/src/catalog/interface.ts +70 -55
  66. package/src/catalog/macro-overloads.ts +44 -0
  67. package/src/catalog/read-only.ts +69 -71
  68. package/src/catalog/unconstrained-columns.ts +23 -0
  69. package/src/client/client.ts +180 -69
  70. package/src/codec/asd.ts +3 -1
  71. package/src/filter-pushdown/collector.ts +17 -1
  72. package/src/functions/continuation.ts +202 -0
  73. package/src/functions/projection.ts +207 -0
  74. package/src/functions/table-in-out.ts +131 -56
  75. package/src/functions/table.ts +10 -0
  76. package/src/functions/types.ts +21 -0
  77. package/src/generated/vgi-client.ts +200 -37
  78. package/src/generated/vgi-protocol-schemas.ts +456 -41
  79. package/src/generated/vgi-protocol-types.ts +879 -5
  80. package/src/generated/vgi-service.ts +514 -42
  81. package/src/http/client-bundle.ts +1 -1
  82. package/src/http/fetch.ts +1 -1
  83. package/src/index.core.ts +10 -0
  84. package/src/protocol/dispatch.ts +9 -9
  85. package/src/protocol/handlers/aggregate.ts +1 -1
  86. package/src/protocol/handlers/catalog/admin.ts +10 -5
  87. package/src/protocol/handlers/catalog/index.ts +2 -2
  88. package/src/protocol/handlers/catalog/macro.ts +6 -5
  89. package/src/protocol/handlers/catalog/metadata.ts +16 -0
  90. package/src/protocol/handlers/catalog/table.ts +72 -26
  91. package/src/protocol/handlers/catalog/view.ts +24 -3
  92. package/src/protocol/handlers/function.ts +79 -1
  93. package/src/protocol/handlers/table-buffering.ts +1 -1
  94. package/src/protocol/handlers/unimplemented.ts +6 -6
  95. package/src/protocol/serializers/bind.ts +17 -1
  96. package/src/protocol/state-serializer.ts +7 -1
  97. package/src/protocol/types.ts +6 -0
  98. package/src/rpc-server.ts +9 -9
  99. package/src/util/arrow/index.ts +1 -1
  100. package/src/util/parent-rows.ts +41 -0
  101. package/src/worker-cf-entry.ts +3 -0
  102. package/src/worker.ts +1 -1
package/dist/worker.d.ts CHANGED
@@ -29,7 +29,7 @@ export declare class Worker {
29
29
  run(argv?: readonly string[]): void;
30
30
  private _serve;
31
31
  /**
32
- * Build the vgi-rpc server for one transport: `vgi.v2`, the worker's
32
+ * Build the vgi-rpc server for one transport: `vgi.v3`, the worker's
33
33
  * `hostedProtocols()` and reflection everywhere; identity on HTTP only. The
34
34
  * one construction path every transport uses (see `rpc-server.ts`).
35
35
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.45.0",
3
+ "version": "0.47.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)",
@@ -29,7 +29,7 @@
29
29
  "node": ">=22.15"
30
30
  },
31
31
  "type": "module",
32
- "//sideEffects": "Entry modules are listed so the bundler cannot tree-shake them away. Under a bare `sideEffects: false`, an entry consisting only of re-exports builds to a dangling export list with no imports and no definitions — invalid ESM that throws on first import. Modules not listed stay side-effect-free, so consumers still tree-shake normally.",
32
+ "//sideEffects": "Entry modules are listed so the bundler cannot tree-shake them away. Under a bare `sideEffects: false`, an entry consisting only of re-exports builds to a dangling export list with no imports and no definitions \u2014 invalid ESM that throws on first import. Modules not listed stay side-effect-free, so consumers still tree-shake normally.",
33
33
  "sideEffects": [
34
34
  "./src/index.ts",
35
35
  "./src/client-entry.ts",
@@ -75,7 +75,7 @@
75
75
  "!src/**/*.test.ts",
76
76
  "!src/**/*.spec.ts"
77
77
  ],
78
- "//imports": "`browser` maps to arrow-js DELIBERATELY, not flechette. Measured on the client surface (VgiClient + Arguments + batch helpers), a minified browser bundle is 84 KB gzip via arrow-js vs 116 KB via flechette — arrow-js tree-shakes to the subset the client touches, while flechette links as a unit. Flechette still wins for `worker-cf`, which exercises far more of the Arrow API and cannot take a peer dep. Keep `browser` AFTER `workerd`/`worker`: conditions match in key order, so a workerd build (which sets both) must hit flechette first.",
78
+ "//imports": "`browser` maps to arrow-js DELIBERATELY, not flechette. Measured on the client surface (VgiClient + Arguments + batch helpers), a minified browser bundle is 84 KB gzip via arrow-js vs 116 KB via flechette \u2014 arrow-js tree-shakes to the subset the client touches, while flechette links as a unit. Flechette still wins for `worker-cf`, which exercises far more of the Arrow API and cannot take a peer dep. Keep `browser` AFTER `workerd`/`worker`: conditions match in key order, so a workerd build (which sets both) must hit flechette first.",
79
79
  "imports": {
80
80
  "#arrow-impl": {
81
81
  "flechette": "./src/arrow/impl-flechette/index.ts",
@@ -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.1"
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.1",
99
+ "@query-farm/vgi-rpc": "^0.29.2",
100
100
  "@types/bun": "latest",
101
101
  "typescript": "^7.0.2"
102
102
  },
@@ -108,6 +108,7 @@
108
108
  "build:js": "bun build ./src/index.ts --outdir dist --target node --format esm --sourcemap=external --external @query-farm/apache-arrow --external @query-farm/vgi-rpc && bun build ./src/client-entry.ts --outdir dist --target browser --format esm --sourcemap=external --external @query-farm/apache-arrow --external @query-farm/vgi-rpc && bun build ./src/worker-cf-entry.ts --outdir dist --target node --format esm --sourcemap=external --external @query-farm/apache-arrow --external @query-farm/vgi-rpc && bun build ./src/serve-entry.ts --outdir dist --target bun --format esm --sourcemap=external --external @query-farm/apache-arrow --external @query-farm/vgi-rpc",
109
109
  "postinstall": "node scripts/postinstall.cjs",
110
110
  "build:browser-test": "bun build examples/browser/main.ts --outdir examples/browser/dist --target browser --format esm --sourcemap=external",
111
- "test": "bun test"
111
+ "test": "bun test",
112
+ "build:landing-client": "bun build ./scripts/landing-client-entry.ts --outfile dist/vgi-client.js --target browser --format esm --minify"
112
113
  }
113
114
  }
@@ -36,7 +36,7 @@ export {
36
36
  batchToScalarDict,
37
37
  batchToSecretDict,
38
38
  safeNumber,
39
- decodeDictValue,
39
+ decodeDictValue, decodeMapValue,
40
40
  } from "./iterate.js";
41
41
  export { filterBatch } from "./filter.js";
42
42
  export { projectSchema, projectBatch } from "./project.js";
@@ -1,7 +1,7 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Read data out of Arrow batches as plain JS values.
3
3
 
4
- import { RecordBatch } from "@query-farm/apache-arrow";
4
+ import { makeVector, RecordBatch } from "@query-farm/apache-arrow";
5
5
  import type { VgiBatch, VgiDataType } from "../types.js";
6
6
  import { codecFor } from "../codec/registry.js";
7
7
  import { readCanonicalValue } from "./canonical.js";
@@ -178,3 +178,11 @@ export function safeNumber(value: any): number {
178
178
  }
179
179
  return value as number;
180
180
  }
181
+
182
+ /** Decode a map parameter carried as opaque Arrow Data by the RPC reader. */
183
+ export function decodeMapValue(value: any, index = 0): any {
184
+ if (value?.type?.typeId === 17 && value.valueOffsets && value.children) {
185
+ return readCanonicalValue(value.type, makeVector(value), index);
186
+ }
187
+ return value;
188
+ }
@@ -41,7 +41,7 @@ export function projectSchema(
41
41
  if (!projectionIds) return a;
42
42
  const validIds = validateProjectionIds("projectSchema", projectionIds, a.fields.length);
43
43
  if (validIds.length === 0) return a;
44
- return new Schema(validIds.map((i) => a.fields[i]));
44
+ return new Schema(validIds.map((i) => a.fields[i]), a.metadata);
45
45
  }
46
46
 
47
47
  /**
@@ -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 ->
@@ -88,7 +89,7 @@ export function writeCanonicalBatch(
88
89
 
89
90
  /**
90
91
  * Convert canonical values into the shape flechette's columnFromArray needs.
91
- * 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:
92
93
  * canonical Array<[k,v]> -> Map. Struct/List recurse. Everything else passes
93
94
  * through.
94
95
  */
@@ -101,9 +102,10 @@ export function prepareForFlechette(type: VgiDataType, values: unknown[]): unkno
101
102
  const isDay = (type as any).unit === 0;
102
103
  return values.map((v) => {
103
104
  if (v == null) return null;
105
+ if (!isDay) return typeof v === "bigint" ? v : BigInt(v instanceof Date ? v.getTime() : v as number);
104
106
  if (v instanceof Date) return v;
105
107
  const n = typeof v === "bigint" ? Number(v) : (v as number);
106
- return new Date(isDay ? n * MS_PER_DAY : n);
108
+ return new Date(n * MS_PER_DAY);
107
109
  });
108
110
  }
109
111
  if (tid === 11 && (type as any).unit === MONTH_DAY_NANO) {
@@ -41,7 +41,7 @@ export {
41
41
  batchToScalarDict,
42
42
  batchToSecretDict,
43
43
  safeNumber,
44
- decodeDictValue,
44
+ decodeDictValue, decodeMapValue,
45
45
  } from "./iterate.js";
46
46
  export { filterBatch } from "./filter.js";
47
47
  export { projectSchema, projectBatch } from "./project.js";
@@ -16,6 +16,11 @@ import {
16
16
  field as f_field,
17
17
  Table,
18
18
  } from "@query-farm/flechette";
19
+ // Flechette 2.4's public table writer derives batch lengths from columns.
20
+ // Its assembled-IPC writer supports the explicit length needed when there
21
+ // are no columns. Keep this narrow package-internal use covered by both readers.
22
+ // @ts-expect-error The JavaScript subpath has no adjacent TypeScript declaration.
23
+ import { encodeIPC } from "@query-farm/flechette/src/encode/encode-ipc.js";
19
24
 
20
25
  import type { VgiSchema, VgiBatch } from "../types.js";
21
26
  import { readFirstRecordBatchMeta } from "./message-meta.js";
@@ -137,6 +142,13 @@ export function serializeBatch(batch: VgiBatch): Uint8Array {
137
142
  // the missing empty batch and attaches the map when there is one. Tables
138
143
  // that already have batches and no metadata are unaffected.
139
144
  const md: Map<string, string> | undefined = t._vgiRecordMetadata ?? t.metadata;
145
+ if (batch.schema.fields.length === 0 && batch.numRows > 0) {
146
+ if (!Number.isSafeInteger(batch.numRows)) throw new RangeError("Invalid zero-column batch row count");
147
+ return encodeIPC({
148
+ schema: { version: 5, endianness: 0, fields: [], metadata: batch.schema.metadata ?? null },
149
+ records: [{ length: batch.numRows, nodes: [], regions: [], variadic: [], buffers: [], byteLength: 0, metadata: md }],
150
+ }, { format: "stream" }).finish() as Uint8Array;
151
+ }
140
152
  const batchMetadata = [md && md.size > 0 ? md : undefined];
141
153
  return tableToIPC(t, { format: "stream", batchMetadata } as any) as Uint8Array;
142
154
  }
@@ -142,3 +142,8 @@ export function safeNumber(value: any): number {
142
142
  }
143
143
  return value as number;
144
144
  }
145
+
146
+ /** Flechette already extracts map parameters as ordinary values. */
147
+ export function decodeMapValue(value: any, _index = 0): any {
148
+ return value;
149
+ }
@@ -1,7 +1,7 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Schema/batch projection by column index for the flechette backend.
3
3
 
4
- import { tableFromColumns } from "@query-farm/flechette";
4
+ import { Table } from "@query-farm/flechette";
5
5
  import type { VgiSchema, VgiBatch } from "../types.js";
6
6
 
7
7
  function validateProjectionIds(
@@ -54,11 +54,9 @@ export function projectBatch(
54
54
  );
55
55
  if (valid.length === 0) return batch;
56
56
 
57
- // Rebuild a Table with only the kept columns, in the requested order.
58
- const cols: Record<string, any> = {};
59
- for (const i of valid) {
60
- const f = t.schema.fields[i];
61
- cols[f.name] = t.getChild(f.name);
62
- }
63
- return tableFromColumns(cols) as unknown as VgiBatch;
57
+ // Keep the original fields and schema metadata; rebuilding inferred fields
58
+ // would discard logical type annotations and declared nullability.
59
+ const projectedSchema = { ...t.schema, fields: valid.map((i) => t.schema.fields[i]) };
60
+ const columns = valid.map((i) => t.getChild(t.schema.fields[i].name));
61
+ return new Table(projectedSchema, columns) as unknown as VgiBatch;
64
62
  }
@@ -52,7 +52,7 @@ export {
52
52
  backend,
53
53
  // batch utilities
54
54
  emptyBatch, batchFromRows, batchFromColumns, columnFromArray,
55
- iterRows, batchToScalarDict, batchToSecretDict, safeNumber, decodeDictValue,
55
+ iterRows, batchToScalarDict, batchToSecretDict, safeNumber, decodeDictValue, decodeMapValue,
56
56
  filterBatch, projectSchema, projectBatch,
57
57
  // per-record-batch metadata attachment
58
58
  withBatchMetadata,
@@ -0,0 +1,224 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ import {
3
+ deserializeBatch,
4
+ deserializeSchema,
5
+ type VgiSchema,
6
+ } from "../arrow/index.js";
7
+ import { SqlExpressionSchema } from "../generated/vgi-protocol-schemas.js";
8
+ import {
9
+ decodeSqlExpression,
10
+ encodeSqlExpression,
11
+ } from "../generated/vgi-protocol-types.js";
12
+ import type { SqlExpression } from "../generated/vgi-client.js";
13
+
14
+ export const GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
15
+ export const GENERATION_KEY = "vgi.column.generation.v1";
16
+ const PROFILE = "vgi.expression.duckdb.scalar.v1";
17
+ const MAX_BYTES = 8 * 1024 * 1024;
18
+ const base64 = (bytes: Uint8Array): string =>
19
+ btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
20
+ function text(value: unknown, maximum: number): asserts value is string {
21
+ if (
22
+ typeof value !== "string" ||
23
+ !value ||
24
+ value.includes("\0") ||
25
+ new TextEncoder().encode(value).length > maximum
26
+ )
27
+ throw new Error("invalid generated expression text");
28
+ for (let i = 0; i < value.length; i++) {
29
+ const c = value.charCodeAt(i);
30
+ if (c >= 0xd800 && c <= 0xdbff) {
31
+ const d = value.charCodeAt(++i);
32
+ if (!(d >= 0xdc00 && d <= 0xdfff))
33
+ throw new Error("invalid generated expression Unicode");
34
+ } else if (c >= 0xdc00 && c <= 0xdfff)
35
+ throw new Error("invalid generated expression Unicode");
36
+ }
37
+ }
38
+ function expression(value: SqlExpression, owner: string[]): void {
39
+ text(value.sql, 1024 * 1024);
40
+ if (!value.sql.trim() || value.profile !== PROFILE)
41
+ throw new Error("unsupported generated expression profile or empty SQL");
42
+ if (
43
+ !Array.isArray(value.schema_path) ||
44
+ value.schema_path.length > 32
45
+ )
46
+ throw new Error("invalid generated expression owner");
47
+ value.schema_path.forEach((part) => text(part, 4096));
48
+ if (JSON.stringify(value.schema_path) !== JSON.stringify(owner))
49
+ throw new Error("generated expression owner differs from table schema");
50
+ const context = value.evaluation_context;
51
+ if (!context)
52
+ throw new Error(
53
+ "generated expression requires explicit evaluation context",
54
+ );
55
+ text(context.timezone, 256);
56
+ text(context.collation, 256);
57
+ if (
58
+ !["asc", "desc"].includes(context.default_order) ||
59
+ ![
60
+ "nulls_first",
61
+ "nulls_last",
62
+ "nulls_first_on_asc_last_on_desc",
63
+ "nulls_last_on_asc_first_on_desc",
64
+ ].includes(context.default_null_order) ||
65
+ typeof context.preserve_insertion_order !== "boolean"
66
+ )
67
+ throw new Error("invalid generated expression evaluation context");
68
+ }
69
+ // Check the complete stream before facade readers select its first batch.
70
+ function envelope(bytes: Uint8Array): Uint8Array[] {
71
+ if (!bytes.length || bytes.length > MAX_BYTES)
72
+ throw new Error("invalid generated expression size");
73
+ const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
74
+ const kinds: number[] = [];
75
+ const textBuffers: Uint8Array[] = [];
76
+ let offset = 0;
77
+ while (offset < bytes.length) {
78
+ const prefix = data.getInt32(offset, true) === -1 ? 8 : 4;
79
+ const length = data.getInt32(offset + prefix - 4, true);
80
+ offset += prefix;
81
+ if (!length) {
82
+ if (offset !== bytes.length || kinds.join(",") !== "1,3")
83
+ throw new Error(
84
+ "SqlExpression requires exactly one complete IPC batch",
85
+ );
86
+ return textBuffers;
87
+ }
88
+ if (length < 0 || offset + length > bytes.length)
89
+ throw new Error("invalid expression IPC length");
90
+ const p = offset + data.getUint32(offset, true),
91
+ v = p - data.getInt32(p, true);
92
+ const slot = (id: number) =>
93
+ 4 + id * 2 < data.getUint16(v, true)
94
+ ? data.getUint16(v + 4 + id * 2, true)
95
+ : 0;
96
+ const kind = slot(1),
97
+ body = slot(3);
98
+ if (!kind) throw new Error("invalid expression IPC message");
99
+ kinds.push(data.getUint8(p + kind));
100
+ const bodyLength = body ? Number(data.getBigInt64(p + body, true)) : 0;
101
+ if (bodyLength < 0 || bodyLength > bytes.length - offset - length)
102
+ throw new Error("invalid expression IPC body");
103
+ if (data.getUint8(p + kind) === 3) {
104
+ const headerSlot = slot(2);
105
+ const record = p + headerSlot + data.getUint32(p + headerSlot, true);
106
+ const table = record - data.getInt32(record, true);
107
+ const recordSlot = (id: number) =>
108
+ 4 + id * 2 < data.getUint16(table, true)
109
+ ? data.getUint16(table + 4 + id * 2, true)
110
+ : 0;
111
+ if (recordSlot(3))
112
+ throw new Error("compressed expression IPC is unsupported");
113
+ const bufferSlot = recordSlot(2);
114
+ const buffers =
115
+ record + bufferSlot + data.getUint32(record + bufferSlot, true);
116
+ if (data.getUint32(buffers, true) !== 26)
117
+ throw new Error("invalid SqlExpression buffer layout");
118
+ // SqlExpression's seven Utf8 value buffers, including path and context.
119
+ for (const index of [2, 5, 10, 14, 17, 20, 23]) {
120
+ const buffer = buffers + 4 + index * 16;
121
+ const start = Number(data.getBigInt64(buffer, true));
122
+ const size = Number(data.getBigInt64(buffer + 8, true));
123
+ if (start < 0 || size < 0 || start + size > bodyLength)
124
+ throw new Error("invalid expression string buffer");
125
+ textBuffers.push(
126
+ bytes.subarray(
127
+ offset + length + start,
128
+ offset + length + start + size,
129
+ ),
130
+ );
131
+ }
132
+ }
133
+ offset += length + bodyLength;
134
+ }
135
+ throw new Error("expression IPC lacks end marker");
136
+ }
137
+ function shape(schema: VgiSchema): string {
138
+ const field = (f: any): unknown => [
139
+ f.name,
140
+ f.nullable,
141
+ String(f.type),
142
+ (f.type.children ?? []).map(field),
143
+ ];
144
+ return JSON.stringify(schema.fields.map(field));
145
+ }
146
+ export function validateEncoded(encoded: string, owner: string[]): void {
147
+ if (!encoded.length || encoded.length > 4 * Math.ceil(MAX_BYTES / 3))
148
+ throw new Error("invalid generated expression size");
149
+ const bytes = Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
150
+ if (base64(bytes) !== encoded)
151
+ throw new Error("generated expression requires canonical base64");
152
+ const textBuffers = envelope(bytes);
153
+ const batch = deserializeBatch(bytes);
154
+ if (batch.numRows !== 1 || shape(batch.schema) !== shape(SqlExpressionSchema))
155
+ throw new Error("invalid SqlExpression record schema");
156
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
157
+ textBuffers.forEach((buffer) => utf8.decode(buffer));
158
+ expression(decodeSqlExpression(bytes), owner);
159
+ }
160
+ export function generatedExpressionMetadata(
161
+ sql: string,
162
+ owner: string[],
163
+ ): string {
164
+ const value: SqlExpression = {
165
+ sql,
166
+ profile: PROFILE,
167
+ schema_path: [...owner],
168
+ evaluation_context: {
169
+ timezone: "UTC",
170
+ collation: "binary",
171
+ default_order: "asc",
172
+ default_null_order: "nulls_last",
173
+ preserve_insertion_order: true,
174
+ },
175
+ };
176
+ expression(value, owner);
177
+ return base64(encodeSqlExpression(value));
178
+ }
179
+ /** Validate canonical VIRTUAL metadata without evaluating or rewriting SQL. */
180
+ export function validateColumnExpressions(
181
+ schema: VgiSchema,
182
+ owner: string[],
183
+ allowGenerated = true,
184
+ ): void {
185
+ const type = (t: any): void => {
186
+ for (const f of t?.children ?? t?.fields ?? []) field(f);
187
+ if (t?.dictionary) type(t.dictionary);
188
+ };
189
+ const field = (f: any): void => {
190
+ const metadata: Map<string, string> = f.metadata ?? new Map();
191
+ for (const key of metadata.keys()) {
192
+ if (
193
+ (key.startsWith("vgi.column.generated.") &&
194
+ key !== GENERATED_EXPRESSION_KEY) ||
195
+ (key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
196
+ )
197
+ throw new Error("unknown generated metadata version");
198
+ }
199
+ if (metadata.has("generated_expression"))
200
+ throw new Error(
201
+ "legacy generated expression requires explicit canonical translation",
202
+ );
203
+ if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
204
+ throw new Error("generated expression and category must occur together");
205
+ if (metadata.has(GENERATED_EXPRESSION_KEY)) {
206
+ if (metadata.get(GENERATION_KEY) !== "virtual")
207
+ throw new Error("only VIRTUAL generated columns are supported");
208
+ if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
209
+ throw new Error("generated column cannot have a default");
210
+ validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY)!, owner);
211
+ if (!allowGenerated)
212
+ throw new Error("generated columns unsupported by this catalog");
213
+ }
214
+ type(f.type);
215
+ };
216
+ schema.fields.forEach(field);
217
+ }
218
+ export function validateColumnExpressionsIpc(
219
+ bytes: Uint8Array,
220
+ owner: string[],
221
+ allowGenerated = true,
222
+ ): void {
223
+ validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
224
+ }
@@ -0,0 +1,151 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ import { validateColumnExpressionsIpc } from "./column-expressions.js";
3
+ import type { VgiSchema } from "../arrow/index.js";
4
+ import { encodeTableInfo, type TableInfo } from "../generated/vgi-client.js";
5
+
6
+ function scalarText(value: string): void {
7
+ for (let i = 0; i < value.length; i++) {
8
+ const c = value.charCodeAt(i);
9
+ if (c >= 0xd800 && c <= 0xdbff) {
10
+ const d = value.charCodeAt(++i);
11
+ if (!(d >= 0xdc00 && d <= 0xdfff))
12
+ throw new Error("column metadata contains an unpaired surrogate");
13
+ } else if (c >= 0xdc00 && c <= 0xdfff)
14
+ throw new Error("column metadata contains an unpaired surrogate");
15
+ }
16
+ }
17
+ function tags(value: string): void {
18
+ let i = 0;
19
+ const ws = () => {
20
+ while (i < value.length && /[ \t\r\n]/.test(value[i])) i++;
21
+ };
22
+ const str = (): string => {
23
+ ws();
24
+ const start = i;
25
+ if (value[i++] !== '"')
26
+ throw new Error("column tags require string keys and values");
27
+ while (i < value.length) {
28
+ const c = value[i++];
29
+ if (c === "\\") {
30
+ i++;
31
+ continue;
32
+ }
33
+ if (c === '"') {
34
+ const result = JSON.parse(value.slice(start, i));
35
+ scalarText(result);
36
+ return result;
37
+ }
38
+ }
39
+ throw new Error("unterminated column tag string");
40
+ };
41
+ ws();
42
+ if (value[i++] !== "{") throw new Error("column tags must be a JSON object");
43
+ ws();
44
+ const seen = new Set<string>();
45
+ if (value[i] !== "}")
46
+ for (;;) {
47
+ const key = str();
48
+ if (seen.has(key)) throw new Error("duplicate column tag key");
49
+ seen.add(key);
50
+ ws();
51
+ if (value[i++] !== ":") throw new Error("invalid column tags JSON");
52
+ str();
53
+ ws();
54
+ if (value[i] !== ",") break;
55
+ i++;
56
+ }
57
+ if (value[i++] !== "}") throw new Error("invalid column tags JSON");
58
+ ws();
59
+ if (i !== value.length) throw new Error("trailing column tags JSON");
60
+ }
61
+ function entry(key: string, value: string): void {
62
+ if (key === "comment" || key === "tags") {
63
+ scalarText(value);
64
+ if (key === "tags") tags(value);
65
+ }
66
+ }
67
+
68
+ /** Validate reserved metadata without replacing the original schema or values. */
69
+ export function validateColumnMetadata(schema: VgiSchema): void {
70
+ const type = (t: any): void => {
71
+ for (const f of t?.children ?? t?.fields ?? []) field(f);
72
+ if (t?.dictionary) type(t.dictionary);
73
+ };
74
+ const field = (f: any): void => {
75
+ for (const [k, v] of f.metadata ?? []) entry(k, v);
76
+ type(f.type);
77
+ };
78
+ for (const f of schema.fields) field(f);
79
+ }
80
+
81
+ /** Inspect raw schema-message metadata before Arrow can replace malformed UTF-8.
82
+ * FlatBuffer slots come from Arrow's Message, Schema, Field and KeyValue tables.
83
+ * Only reserved field values are interpreted; all original IPC bytes stay intact.
84
+ */
85
+ export function validateColumnMetadataIpc(bytes: Uint8Array): void {
86
+ const input = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
87
+ const prefix = input.getInt32(0, true) === -1 ? 8 : 4;
88
+ const size = input.getInt32(prefix - 4, true);
89
+ if (size <= 0 || prefix + size > bytes.length)
90
+ throw new Error("invalid column schema IPC");
91
+ const raw = bytes.subarray(prefix, prefix + size);
92
+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
93
+ const u32 = (p: number) => view.getUint32(p, true),
94
+ i32 = (p: number) => view.getInt32(p, true),
95
+ u16 = (p: number) => view.getUint16(p, true);
96
+ const slot = (p: number, id: number): number => {
97
+ const v = p - i32(p),
98
+ o = 4 + id * 2;
99
+ return o < u16(v) ? u16(v + o) : 0;
100
+ };
101
+ const ref = (p: number, id: number): number => {
102
+ const o = slot(p, id);
103
+ return o ? p + o + u32(p + o) : 0;
104
+ };
105
+ const vector = (p: number, id: number, fn: (p: number) => void): void => {
106
+ const v = ref(p, id);
107
+ if (!v) return;
108
+ const n = u32(v);
109
+ if (n > (raw.length - v - 4) / 4)
110
+ throw new Error("invalid column metadata vector");
111
+ for (let j = 0; j < n; j++) {
112
+ const q = v + 4 + j * 4;
113
+ fn(q + u32(q));
114
+ }
115
+ };
116
+ const text = (p: number, id: number): string => {
117
+ const v = ref(p, id);
118
+ if (!v) return "";
119
+ const n = u32(v);
120
+ if (v + 4 + n > raw.length)
121
+ throw new Error("invalid column metadata string");
122
+ return new TextDecoder("utf-8", { fatal: true }).decode(
123
+ raw.subarray(v + 4, v + 4 + n),
124
+ );
125
+ };
126
+ const field = (p: number, depth: number): void => {
127
+ if (depth > 64) throw new Error("column metadata nesting too deep");
128
+ const seen = new Set<string>();
129
+ vector(p, 6, (m) => {
130
+ const k = text(m, 0);
131
+ if (seen.has(k)) throw new Error("duplicate column metadata key");
132
+ seen.add(k);
133
+ if (k === "comment" || k === "tags") entry(k, text(m, 1));
134
+ });
135
+ vector(p, 5, (c) => field(c, depth + 1));
136
+ };
137
+ const message = u32(0),
138
+ kind = slot(message, 1);
139
+ if (!kind || view.getUint8(message + kind) !== 1)
140
+ throw new Error("expected column schema message");
141
+ const schema = ref(message, 2);
142
+ if (!schema) throw new Error("missing column schema");
143
+ vector(schema, 1, (f) => field(f, 0));
144
+ }
145
+ export function validateTableInfoColumns(info: TableInfo): void {
146
+ if (info.columns.length) { validateColumnMetadataIpc(info.columns); validateColumnExpressionsIpc(info.columns, info.schema_path); }
147
+ }
148
+ export function encodeValidatedTableInfo(info: TableInfo): Uint8Array {
149
+ validateTableInfoColumns(info);
150
+ return encodeTableInfo(info);
151
+ }
@@ -96,11 +96,12 @@ export class CompositeCatalogInterface extends CatalogInterface {
96
96
  options?: Record<string, unknown>,
97
97
  dataVersionSpec?: string | null,
98
98
  implementationVersion?: string | null,
99
+ clientCapabilities?: Uint8Array | null,
99
100
  ): Promise<CatalogAttachResult> {
100
101
  for (let i = 0; i < this._backends.length; i++) {
101
102
  const b = this._backends[i];
102
103
  if (b.catalogs().includes(name)) {
103
- const result = await b.attach(name, options, dataVersionSpec, implementationVersion);
104
+ const result = await b.attach(name, options, dataVersionSpec, implementationVersion, clientCapabilities);
104
105
  // Stamp the route-byte so other workers in the pool can decode the
105
106
  // backend without needing in-memory state. Mutate in place so the
106
107
  // wire returns the rewritten id.
@@ -235,6 +236,9 @@ export class CompositeCatalogInterface extends CatalogInterface {
235
236
  override async viewCommentSet(...args: Parameters<CatalogInterface["viewCommentSet"]>): Promise<void> {
236
237
  await (this._route(args[0]).viewCommentSet as (...a: typeof args) => unknown)(...args);
237
238
  }
239
+ override async viewColumnCommentSet(...args: Parameters<CatalogInterface["viewColumnCommentSet"]>): Promise<void> {
240
+ await (this._route(args[0]).viewColumnCommentSet as (...a: typeof args) => unknown)(...args);
241
+ }
238
242
  override async macroCreate(...args: Parameters<CatalogInterface["macroCreate"]>): Promise<void> {
239
243
  await (this._route(args[0]).macroCreate as (...a: typeof args) => unknown)(...args);
240
244
  }
@@ -1,5 +1,6 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Catalog-wide collection streams, independent of delivery and attachment state.
3
+ import { validateTableInfoColumns } from "./column-metadata.js";
3
4
  import { encodeASDCollection, decodeASDCollection } from "../codec/asd.js";
4
5
  import {
5
6
  SchemaInfoSchema, TableInfoSchema, ViewInfoSchema, FunctionInfoSchema, MacroInfoSchema, IndexInfoSchema,
@@ -14,6 +15,7 @@ export const CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions",
14
15
  export type CatalogStreams = Pick<CatalogContentsResponse, typeof CATALOG_STREAM_KINDS[number]>;
15
16
 
16
17
  export function encodeCatalogStreams(inventory: readonly SchemaContentsInfo[]): CatalogStreams {
18
+ for (const schema of inventory) for (const table of schema.tables) validateTableInfoColumns(table);
17
19
  const streams = {
18
20
  schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
19
21
  tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
@@ -53,7 +55,10 @@ export function decodeCatalogStreams(response: CatalogContentsResponse, ifNoneMa
53
55
  if (!entry) throw new Error("catalog object references an absent schema");
54
56
  return entry;
55
57
  };
56
- for (const item of decodeASDCollection<TableInfo>(TableInfoSchema, response.tables)) owner(item).tables.push(item);
58
+ for (const item of decodeASDCollection<TableInfo>(TableInfoSchema, response.tables)) {
59
+ validateTableInfoColumns(item);
60
+ owner(item).tables.push(item);
61
+ }
57
62
  for (const item of decodeASDCollection<ViewInfo>(ViewInfoSchema, response.views)) owner(item).views.push(item);
58
63
  for (const item of decodeASDCollection<FunctionInfo>(FunctionInfoSchema, response.functions)) {
59
64
  const entry = owner(item);