@query-farm/vgi 0.47.0 → 0.47.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.47.0",
3
+ "version": "0.47.1",
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)",
@@ -0,0 +1,207 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Canonical constraint records for catalogs that state their own facts.
3
+
4
+ import { encodeASD, decodeASD } from "../codec/asd.js";
5
+ import { isStruct, type VgiDataType, type VgiField } from "../arrow/index.js";
6
+ import {
7
+ CatalogObjectRefSchema,
8
+ ClientCapabilitiesSchema,
9
+ ConstraintDefinitionSchema,
10
+ ConstraintInfoSchema,
11
+ ForeignKeyDefinitionSchema,
12
+ SqlExpressionSchema,
13
+ } from "../generated/vgi-protocol-schemas.js";
14
+ import { decodeCatalogCapabilities, type CatalogCapabilities } from "../generated/vgi-protocol-types.js";
15
+
16
+ /** Read profile: the catalog serves canonical ConstraintInfo records. */
17
+ export const CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
18
+ /** Read profile: CHECK constraints carry DuckDB scalar SQL expressions. */
19
+ export const ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
20
+
21
+ export type ConstraintKind = "NOT_NULL" | "PRIMARY_KEY" | "UNIQUE" | "CHECK" | "FOREIGN_KEY";
22
+ /** Whether the authority enforces the constraint on every write path. */
23
+ export type ConstraintEnforcement = "ENFORCED" | "METADATA_ONLY";
24
+ /** Coverage of existing rows; only ALL_ROWS justifies engine facts. */
25
+ export type ConstraintValidation = "ALL_ROWS" | "FUTURE_WRITES" | "UNVALIDATED";
26
+
27
+ export interface ConstraintRecordSpec {
28
+ /** Schema path of the owning table. */
29
+ schemaPath: readonly string[];
30
+ /** Owning table name. */
31
+ table: string;
32
+ /** Stable provider-owned identity, unique within the table. Never derived by the SDK. */
33
+ id: string;
34
+ kind: ConstraintKind;
35
+ /** Raw component paths, e.g. `[["id"]]` or `[["bbox", "xmin"]]`; empty for CHECK. */
36
+ columns: readonly (readonly string[])[];
37
+ /**
38
+ * The provider's attestation. The DuckDB extension reads only
39
+ * ENFORCED + ALL_ROWS records, so state that only when every row the table
40
+ * can ever return satisfies the constraint.
41
+ */
42
+ enforcement: ConstraintEnforcement;
43
+ validation: ConstraintValidation;
44
+ /** Optional SQL label (CONSTRAINT <name>). */
45
+ declaredName?: string;
46
+ /** CHECK only: a DuckDB scalar expression over the table's columns. */
47
+ checkSql?: string;
48
+ /** FOREIGN_KEY only: the referenced key and its constraint identity. */
49
+ references?: {
50
+ schemaPath: readonly string[];
51
+ table: string;
52
+ columns: readonly (readonly string[])[];
53
+ /** `id` of the referenced table's PRIMARY_KEY or UNIQUE record. */
54
+ constraintId: string;
55
+ };
56
+ }
57
+
58
+ function objectRef(kind: "table" | "constraint", schemaPath: readonly string[], name: string, ownerTable: string | null): Uint8Array {
59
+ return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
60
+ }
61
+
62
+ /** Encode one canonical `ConstraintInfo` record for `TableDescriptor.constraints`. */
63
+ export function constraintRecord(spec: ConstraintRecordSpec): Uint8Array {
64
+ if (!spec.id || spec.id.includes("\0")) throw new Error("constraint id must be nonempty without NUL");
65
+ if ((spec.kind === "CHECK") !== (spec.checkSql !== undefined))
66
+ throw new Error("checkSql is required for CHECK and only CHECK");
67
+ if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
68
+ throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
69
+ if (spec.kind === "NOT_NULL" && spec.columns.length !== 1) throw new Error("NOT_NULL requires exactly one column path");
70
+ if ((spec.kind === "FOREIGN_KEY") !== (spec.references !== undefined))
71
+ throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
72
+ if (spec.references && spec.references.columns.length !== spec.columns.length)
73
+ throw new Error("foreign key local and referenced arity must match");
74
+ const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
75
+ sql: spec.checkSql,
76
+ profile: ROW_SCALAR_EXPRESSION,
77
+ schema_path: spec.schemaPath,
78
+ evaluation_context: {
79
+ timezone: "UTC", collation: "binary", default_order: "asc",
80
+ default_null_order: "nulls_last", preserve_insertion_order: true,
81
+ },
82
+ });
83
+ const ref = spec.references;
84
+ const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
85
+ referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
86
+ referenced_column_paths: ref.columns,
87
+ match: "SIMPLE", on_update: "NO_ACTION", on_delete: "NO_ACTION",
88
+ });
89
+ return encodeASD(ConstraintInfoSchema, {
90
+ ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
91
+ definition: encodeASD(ConstraintDefinitionSchema, {
92
+ kind: spec.kind,
93
+ column_paths: spec.columns,
94
+ declared_name: spec.declaredName ?? null,
95
+ check_expression: check,
96
+ foreign_key: foreign,
97
+ }),
98
+ enforcement: spec.enforcement,
99
+ validation: spec.validation,
100
+ referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table),
101
+ });
102
+ }
103
+
104
+ /**
105
+ * The client-offered profiles from `available`, in canonical (sorted) order.
106
+ * A scalar-expression read is selected only alongside constraint records.
107
+ */
108
+ export function selectReadProfiles(available: readonly string[], clientCapabilities: Uint8Array | null | undefined): string[] {
109
+ if (clientCapabilities == null || available.length === 0) return [];
110
+ const client = decodeASD<{ catalog?: Uint8Array | null }>(ClientCapabilitiesSchema, clientCapabilities);
111
+ const offered: CatalogCapabilities["read"] = client.catalog == null ? [] : decodeCatalogCapabilities(client.catalog).read;
112
+ const selected = available.filter((p) => offered.includes(p));
113
+ if (!selected.includes(CONSTRAINT_RECORDS_READ)) return selected.filter((p) => p !== ROW_SCALAR_EXPRESSION).sort();
114
+ return selected.sort();
115
+ }
116
+
117
+ /** A decoded `ConstraintInfo` record, in `constraintRecord()`'s vocabulary. */
118
+ export interface ConstraintRecordView {
119
+ schemaPath: string[];
120
+ table: string;
121
+ id: string;
122
+ kind: ConstraintKind;
123
+ columns: string[][];
124
+ enforcement: ConstraintEnforcement;
125
+ validation: ConstraintValidation;
126
+ declaredName: string | null;
127
+ checkSql: string | null;
128
+ references: { schemaPath: string[]; table: string; columns: string[][]; constraintId: string | null } | null;
129
+ }
130
+
131
+ type RefRow = { kind: string; schema_path: string[]; name: string; owner_table: string | null };
132
+
133
+ /** Decode a `TableInfo.constraints` entry (the inverse of `constraintRecord`). */
134
+ export function readConstraintRecord(bytes: Uint8Array): ConstraintRecordView {
135
+ const info = decodeASD<any>(ConstraintInfoSchema, bytes);
136
+ const ref = decodeASD<RefRow>(CatalogObjectRefSchema, info.ref);
137
+ const def = decodeASD<any>(ConstraintDefinitionSchema, info.definition);
138
+ const fk = def.foreign_key == null ? null : decodeASD<any>(ForeignKeyDefinitionSchema, def.foreign_key);
139
+ const target = fk == null ? null : decodeASD<RefRow>(CatalogObjectRefSchema, fk.referenced_table);
140
+ const targetKey = info.referenced_constraint == null ? null : decodeASD<RefRow>(CatalogObjectRefSchema, info.referenced_constraint);
141
+ return {
142
+ schemaPath: [...ref.schema_path],
143
+ table: ref.owner_table ?? "",
144
+ id: ref.name,
145
+ kind: def.kind,
146
+ columns: [...def.column_paths].map((p: Iterable<string>) => [...p]),
147
+ enforcement: info.enforcement,
148
+ validation: info.validation,
149
+ declaredName: def.declared_name ?? null,
150
+ checkSql: def.check_expression == null ? null : decodeASD<any>(SqlExpressionSchema, def.check_expression).sql,
151
+ references: fk == null || target == null ? null : {
152
+ schemaPath: [...target.schema_path],
153
+ table: target.name,
154
+ columns: [...fk.referenced_column_paths].map((p: Iterable<string>) => [...p]),
155
+ constraintId: targetKey?.name ?? null,
156
+ },
157
+ };
158
+ }
159
+
160
+ function ordinaryStructChildren(field: VgiField): readonly VgiField[] | null {
161
+ if (!isStruct(field.type)) return null;
162
+ for (const key of field.metadata.keys())
163
+ if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) return null;
164
+ return (field.type as VgiDataType & { children: readonly VgiField[] }).children;
165
+ }
166
+
167
+ /**
168
+ * Check a table's records the way the DuckDB extension does at ATTACH: every
169
+ * record is ENFORCED + ALL_ROWS, and Arrow nullability agrees with the
170
+ * NOT_NULL/PRIMARY_KEY records (a field, descending through ordinary STRUCTs,
171
+ * is non-nullable exactly when a record names its path).
172
+ */
173
+ export function validateConstraintNullability(
174
+ table: string,
175
+ fields: readonly VgiField[],
176
+ constraints: readonly Uint8Array[],
177
+ ): void {
178
+ const required = new Set<string>();
179
+ for (const bytes of constraints) {
180
+ const record = readConstraintRecord(bytes);
181
+ // DuckDB reads only facts that hold for every row; anything else fails ATTACH.
182
+ if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
183
+ throw new Error(
184
+ `Table '${table}': constraint '${record.id}' is ${record.enforcement}/${record.validation}; ` +
185
+ "DuckDB accepts only ENFORCED + ALL_ROWS records"
186
+ );
187
+ if (record.kind === "NOT_NULL" || record.kind === "PRIMARY_KEY")
188
+ for (const path of record.columns) required.add(JSON.stringify(path));
189
+ }
190
+ const walk = (children: readonly VgiField[], prefix: string[]) => {
191
+ for (const field of children) {
192
+ const path = [...prefix, field.name];
193
+ const key = JSON.stringify(path);
194
+ if (field.nullable === required.has(key)) {
195
+ throw new Error(
196
+ field.nullable
197
+ ? `Table '${table}': column ${path.join(".")} is in a NOT_NULL/PRIMARY_KEY record but its Arrow field is nullable`
198
+ : `Table '${table}': column ${path.join(".")} is non-nullable in Arrow but no NOT_NULL/PRIMARY_KEY record names it; ` +
199
+ "declare one with constraintRecord() or make the field nullable"
200
+ );
201
+ }
202
+ const nested = ordinaryStructChildren(field);
203
+ if (nested) walk(nested, path);
204
+ }
205
+ };
206
+ walk(fields, []);
207
+ }
@@ -37,6 +37,8 @@ import { conformColumns } from "../codec/conform.js";
37
37
  import { VgiError } from "../errors.js";
38
38
  import { encodeFunctionInfoOnce, freezeCatalogItem } from "./item-encoding.js";
39
39
  import { macroOverloads } from "./macro-overloads.js";
40
+ import { CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, selectReadProfiles, validateConstraintNullability } from "./constraints.js";
41
+ import { encodeCatalogCapabilities } from "../generated/vgi-protocol-types.js";
40
42
 
41
43
  /**
42
44
  * The fixed attach id ReadOnlyCatalogInterface writes into its items (same
@@ -212,6 +214,10 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
212
214
  encodeAttachCatalogInfo(c)
213
215
  );
214
216
 
217
+ // Constraint records are readable only under a negotiated profile.
218
+ const available = this.catalogReadProfiles();
219
+ const read = selectReadProfiles(available, clientCapabilities);
220
+
215
221
  // Auto-derive supportsTimeTravel from table descriptors
216
222
  const hasTimeTravel = this._descriptor.schemas.some(
217
223
  (s) => s.tables?.some((t) => t.supportsTimeTravel) ?? false
@@ -243,9 +249,27 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
243
249
  // Static, version-frozen catalog: the whole thing can be served in one
244
250
  // catalog_contents call (as vgi-python's ReadOnlyCatalogInterface does).
245
251
  supports_catalog_contents: this.supportsCatalogContents,
252
+ catalog_capabilities: available.length
253
+ ? encodeCatalogCapabilities({ read: [...available].sort(), ddl: [], write: [], transaction: [] })
254
+ : null,
255
+ selected_capabilities: available.length
256
+ ? encodeCatalogCapabilities({ read, ddl: [], write: [], transaction: [] })
257
+ : null,
246
258
  });
247
259
  }
248
260
 
261
+ /**
262
+ * Read profiles this catalog implements. Defaults to constraint records
263
+ * (with scalar CHECK expressions) when any descriptor table carries
264
+ * `constraints`; override when tables are served outside the descriptor.
265
+ */
266
+ catalogReadProfiles(): string[] {
267
+ const hasConstraints = this._descriptor.schemas.some(
268
+ (s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false
269
+ );
270
+ return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
271
+ }
272
+
249
273
  detach(attachOpaqueData: AttachOpaqueData): void {
250
274
  // Remove attachment
251
275
  for (const [name, id] of this._attachments) {
@@ -373,11 +397,16 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
373
397
  }
374
398
 
375
399
  validateColumnMetadata(colSchema);
400
+ // The extension rejects the table at ATTACH when these disagree.
401
+ validateConstraintNullability(t.name, colSchema.fields, t.constraints ?? []);
376
402
  validateColumnExpressions(colSchema, path);
377
403
  const columns = serializeSchema(colSchema);
378
404
 
379
405
  if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
380
- throw new Error("legacy constraint metadata requires explicit canonical records");
406
+ throw new Error(
407
+ `Table '${t.name}': notNull/unique/primaryKey/check/foreignKey are not sent under vgi.v3; ` +
408
+ "declare canonical records with constraintRecord() in `constraints` instead"
409
+ );
381
410
  }
382
411
 
383
412
  // Validate exact raw paths against the full table schema.
package/src/index.core.ts CHANGED
@@ -86,6 +86,7 @@ export type { VgiFunction, FunctionMeta, StreamHandlers, FunctionExample, Handle
86
86
  export { CatalogInterface, type CatalogAttachResult, type CatalogAttachResultInit, buildCatalogAttachResult, type SchemaContentsInfo, type CatalogContentsResult, type SchemaInfo, encodeSchemaInfo, decodeSchemaInfo, type TableInfo, encodeTableInfo, decodeTableInfo, type ViewInfo, encodeViewInfo, decodeViewInfo, type CatalogInfo, encodeCatalogInfo, decodeCatalogInfo, type FunctionInfo, encodeFunctionInfo, decodeFunctionInfo, type FunctionInfoOptions, type MacroInfo, encodeMacroInfo, decodeMacroInfo, type MacroType, type CopyFromFormatInfo, encodeCopyFromFormatInfo, type AttachOpaqueData, type TransactionOpaqueData, buildScanBranchesResult, encodeFormatOptions, type ScanBranchInput } from "./catalog/interface.js";
87
87
  export type { CatalogDescriptor, SchemaDescriptor, TableDescriptor, ViewDescriptor, MacroDescriptor, SettingDescriptor, SecretTypeDescriptor, ForeignKeyDef, DefaultValue } from "./catalog/descriptors.js";
88
88
  export { ReadOnlyCatalogInterface, READ_ONLY_ITEM_ATTACH_ID } from "./catalog/read-only.js";
89
+ export { constraintRecord, readConstraintRecord, validateConstraintNullability, selectReadProfiles, CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, type ConstraintRecordSpec, type ConstraintRecordView, type ConstraintKind, type ConstraintEnforcement, type ConstraintValidation } from "./catalog/constraints.js";
89
90
  export { CompositeCatalogInterface } from "./catalog/composite.js";
90
91
  export { FunctionRegistry } from "./functions/registry.js";
91
92
 
@@ -13,7 +13,8 @@ import {
13
13
  encodeViewInfo,
14
14
  encodeCatalogInfo,
15
15
  } from "../../../generated/vgi-client.js";
16
- import { buildCatalogAttachResult } from "../../../generated/vgi-protocol-types.js";
16
+ import { buildCatalogAttachResult, decodeCatalogCapabilities, encodeCatalogCapabilities } from "../../../generated/vgi-protocol-types.js";
17
+ import { selectReadProfiles } from "../../../catalog/constraints.js";
17
18
  import { serveCatalogContents } from "./contents.js";
18
19
  import { encodeFunctionInfoOnce } from "../../../catalog/item-encoding.js";
19
20
  import { encodeCopyFromFormatInfo } from "../../../catalog/interface.js";
@@ -94,13 +95,28 @@ export function catalogAdminHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
94
95
  innerParams.implementation_version = restored.implementationVersion;
95
96
  optionsDict = restored.options;
96
97
  }
98
+ const clientCapabilities =
99
+ innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities);
97
100
  const result = await cat.attach(
98
101
  innerParams.name,
99
102
  optionsDict,
100
103
  innerParams.data_version_spec ?? null,
101
104
  innerParams.implementation_version ?? null,
102
- innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities),
105
+ clientCapabilities,
103
106
  );
107
+ // Select the client-offered read profiles here, from the request itself
108
+ // (as vgi-python's worker does), so a catalog whose attach() override
109
+ // drops the clientCapabilities argument still negotiates what it serves.
110
+ if (result.catalog_capabilities != null) {
111
+ const available = decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities));
112
+ const chosen = result.selected_capabilities == null
113
+ ? { read: [], ddl: [], write: [], transaction: [] }
114
+ : decodeCatalogCapabilities(toUint8Array(result.selected_capabilities));
115
+ result.selected_capabilities = encodeCatalogCapabilities({
116
+ ...chosen,
117
+ read: selectReadProfiles(available.read, clientCapabilities),
118
+ });
119
+ }
104
120
  // Seal the attach value into an AEAD envelope bound to the caller's
105
121
  // identity before it leaves the worker (HTTP transport; pass-through
106
122
  // when there is no signing key).
@@ -65,6 +65,10 @@ export {
65
65
  serializeColumnStatistics,
66
66
  BindResultSchema,
67
67
  ScanFunctionResultSchema,
68
+ constraintRecord,
69
+ readConstraintRecord,
70
+ CONSTRAINT_RECORDS_READ,
71
+ ROW_SCALAR_EXPRESSION,
68
72
  } from "./index.core.js";
69
73
 
70
74
  export type {
@@ -86,6 +90,8 @@ export type {
86
90
  RowTransformConfig,
87
91
  RowTransformProcessParams,
88
92
  TableInOutBindParams,
93
+ ConstraintRecordSpec,
94
+ ConstraintRecordView,
89
95
  } from "./index.core.js";
90
96
 
91
97
  export type { ProtocolConfig } from "./protocol/dispatch.js";