@query-farm/vgi 0.48.1 → 0.48.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.48.1",
3
+ "version": "0.48.2",
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)",
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { VgiSchema, VgiDataType } from "../arrow/index.js";
5
5
  import type { AttachCatalogInfo } from "./interface.js";
6
+ import type { AttachOptionSpec } from "./attach-option.js";
6
7
  import type { VgiFunction } from "../functions/types.js";
7
8
  import type { Arguments } from "../arguments/arguments.js";
8
9
  import type { ColumnStatistics } from "../util/statistics.js";
@@ -178,6 +179,19 @@ export interface CatalogDescriptor {
178
179
  schemas: SchemaDescriptor[];
179
180
  settings?: SettingDescriptor[];
180
181
  secretTypes?: SecretTypeDescriptor[];
182
+ /**
183
+ * Options the catalog accepts at `ATTACH` time
184
+ * (`ATTACH 'x' (TYPE vgi, LOCATION '...', region 'eu', api_key '...')`).
185
+ * Advertised in the catalog's discovery record so the DuckDB extension
186
+ * validates and casts them (and redacts `secret` ones), and `required` ones
187
+ * are enforced at attach. Mirrors vgi-python's
188
+ * `ReadOnlyCatalogInterface.attach_option_specs`.
189
+ *
190
+ * The values reach `attach()` as its `options`; to hand them to functions,
191
+ * override `attach()` and carry them in `attach_opaque_data`
192
+ * (examples/attach-options-worker.ts), which every function call receives.
193
+ */
194
+ attachOptions?: AttachOptionSpec[];
181
195
  /**
182
196
  * Companion catalogs (lakehouse federation) the client should ATTACH when this
183
197
  * VGI catalog attaches. Surfaced via `catalog_attach.attach_catalogs`.
@@ -28,7 +28,7 @@ import type { FunctionRegistry } from "../functions/registry.js";
28
28
  import { argumentSpecsToSchema } from "../arguments/argument-spec.js";
29
29
  import { serializeSchema, serializeBatch, emptyBatch, batchFromColumns } from "../util/arrow/index.js";
30
30
  import { resolveMetadata } from "../metadata/resolve.js";
31
- import { type AttachOptionSpec, validateRequiredAttachOptions } from "./attach-option.js";
31
+ import { type AttachOptionSpec, serializeAttachOptionSpecs, validateRequiredAttachOptions } from "./attach-option.js";
32
32
  import { FunctionStability, NullHandling, OrderPreservation, DEFAULT_MAX_WORKERS } from "../types.js";
33
33
  import { Arguments } from "../arguments/arguments.js";
34
34
  import { normalizeSchemaPath, schemaPathDisplay, schemaPathsEqual } from "../schema-path.js";
@@ -123,7 +123,14 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
123
123
  for (const tbl of sch.tables ?? []) {
124
124
  for (const key of ["function", "insertFunction", "updateFunction", "deleteFunction"] as const) {
125
125
  const fn = (tbl as any)[key];
126
- if (fn) registry.registerInSchema(fn, schemaDescriptorPath(sch), descriptor.name);
126
+ if (!fn) continue;
127
+ registry.registerInSchema(fn, schemaDescriptorPath(sch), descriptor.name);
128
+ // A table's scan/write functions need not also be listed in the
129
+ // schema's `functions`. Index them by name too, so a bind that
130
+ // resolves by name (a scan whose ScanFunctionResult carries no
131
+ // schema path, because no schema lists the function) finds them.
132
+ // Mirrors vgi-python's Worker._build_registry auto-registration.
133
+ registry.register(fn);
127
134
  }
128
135
  }
129
136
  }
@@ -159,26 +166,24 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
159
166
  /**
160
167
  * Attach-time options this catalog declares, for the named catalog.
161
168
  *
162
- * Empty by default — the declarative descriptor path carries no attach
163
- * options. A subclass that advertises specs in `catalogsInfo()` should
164
- * return the same specs here so `attach()` enforces the `required` ones it
165
- * advertised. Takes the catalog name because one interface may serve
166
- * several catalogs with different option sets.
169
+ * The descriptor's `attachOptions` (empty when it declares none). A
170
+ * subclass serving several catalogs with different option sets overrides
171
+ * this; `catalogsInfo()` advertises whatever it returns and `attach()`
172
+ * enforces the `required` ones, so the two never disagree.
167
173
  */
168
174
  attachOptionSpecs(_name: string): AttachOptionSpec[] {
169
- return [];
175
+ return this._descriptor.attachOptions ?? [];
170
176
  }
171
177
 
172
- // Advertise the catalog's discovery record. The declarative path carries no
173
- // version metadata or attach option specs, but it does surface the optional
174
- // `source_url` from the descriptor so it flows through `catalog_catalogs`
175
- // (DuckDB's `duckdb_databases()`).
178
+ // Advertise the catalog's discovery record: its attach option specs and the
179
+ // optional `source_url`, which flows through `catalog_catalogs` (DuckDB's
180
+ // `duckdb_databases()`). The declarative path carries no version metadata.
176
181
  override catalogsInfo(): CatalogInfo[] {
177
182
  return [{
178
183
  name: this._descriptor.name,
179
184
  implementation_version: null,
180
185
  data_version_spec: null,
181
- attach_option_specs: [],
186
+ attach_option_specs: serializeAttachOptionSpecs(this.attachOptionSpecs(this._descriptor.name)),
182
187
  releases: [],
183
188
  source_url: this._descriptor.sourceUrl ?? null,
184
189
  }];
@@ -226,12 +226,15 @@ export class FunctionRegistry {
226
226
  // because two catalogs in one worker may declare the same schema AND name.
227
227
  private _byCatalog: Map<string, VgiFunction[]> = new Map();
228
228
 
229
+ /** Add `func` to the by-name index. Idempotent for the same function object. */
229
230
  register(func: VgiFunction): void {
230
231
  const name = func.meta.name;
231
- if (!this._functions.has(name)) {
232
- this._functions.set(name, []);
232
+ const bucket = this._functions.get(name);
233
+ if (!bucket) {
234
+ this._functions.set(name, [func]);
235
+ } else if (!bucket.includes(func)) {
236
+ bucket.push(func);
233
237
  }
234
- this._functions.get(name)!.push(func);
235
238
  }
236
239
 
237
240
  /**
@@ -127,6 +127,22 @@ export type ScalarComputeResult<R extends VgiDataType, M extends Repr> =
127
127
  | Iterable<ScalarOutputValue<R, M>>
128
128
  | VgiBatch;
129
129
 
130
+ /** Per-batch context handed to a scalar's `compute`. */
131
+ export interface ScalarComputeInfo {
132
+ settings: Record<string, any>;
133
+ secrets: Record<string, Record<string, any>>;
134
+ auth: AuthContext;
135
+ /**
136
+ * The bind request this execution was initialized with: the catalog's
137
+ * `attach_opaque_data` (already unsealed, as every function body sees it),
138
+ * `transaction_opaque_data`, arguments, settings and secrets. Mirrors the
139
+ * `init_call.bind_call` vgi-python's `ScalarFunction.process` receives, so a
140
+ * scalar can read attach-time state (e.g. connection options a catalog
141
+ * packed into its attach data).
142
+ */
143
+ bindCall: BindRequest;
144
+ }
145
+
130
146
  export interface ScalarFunctionConfig<
131
147
  P extends Record<string, VgiDataType> = Record<string, VgiDataType>,
132
148
  R extends VgiDataType = VgiDataType,
@@ -170,14 +186,12 @@ export interface ScalarFunctionConfig<
170
186
  compute: (
171
187
  batch: VgiBatch,
172
188
  consts: Record<string, any>,
173
- info: {
174
- settings: Record<string, any>;
175
- secrets: Record<string, Record<string, any>>;
176
- auth: AuthContext;
177
- }
189
+ info: ScalarComputeInfo,
178
190
  // NoInfer pins R/M from `returns`/`repr` so the compute return type is
179
191
  // CHECKED against them rather than widening them to fit a wrong value.
180
- ) => ScalarComputeResult<NoInfer<R>, NoInfer<M>>;
192
+ // May be async: a scalar that calls a service (an HTTP API, a database)
193
+ // returns a Promise and the framework awaits it before emitting.
194
+ ) => ScalarComputeResult<NoInfer<R>, NoInfer<M>> | Promise<ScalarComputeResult<NoInfer<R>, NoInfer<M>>>;
181
195
  // Metadata
182
196
  stability?: FunctionStability;
183
197
  nullHandling?: NullHandling;
@@ -415,8 +429,16 @@ export function defineScalarFunction<
415
429
  outputSchema,
416
430
  inputSchema: inputSchema ?? undefined,
417
431
  exchangeInit: () => ({}),
418
- exchangeFn: (state: any, input: VgiBatch, out: OutputCollector) => {
419
- const result = config.compute(input as any, constArgs, { settings, secrets, auth: out.auth });
432
+ exchangeFn: async (state: any, input: VgiBatch, out: OutputCollector) => {
433
+ let result: any = config.compute(input as any, constArgs, {
434
+ settings,
435
+ secrets,
436
+ auth: out.auth,
437
+ bindCall: request.bind_call,
438
+ });
439
+ // Await only a thenable, so a synchronous compute costs no extra
440
+ // microtask per batch.
441
+ if (result != null && typeof result.then === "function") result = await result;
420
442
 
421
443
  // Build output batch
422
444
  let outputBatch: VgiBatch;
@@ -220,11 +220,14 @@ export function defineTableBufferingFunction<
220
220
  });
221
221
  }
222
222
  }
223
+ // The TABLE argument is documented like any other: `argDocs.data`
224
+ // (vgi-python: the TableInput field's own `Arg(doc=...)`).
223
225
  specs.push({
224
226
  name: "data",
225
227
  position: posIdx++,
226
228
  arrowType: nullType(),
227
229
  isTableInput: true,
230
+ ...(config.argDocs?.data !== undefined ? { doc: config.argDocs.data } : {}),
228
231
  });
229
232
  if (config.namedArgs) {
230
233
  for (const [name, type] of Object.entries(config.namedArgs)) {
@@ -17,6 +17,7 @@ import type {
17
17
  FunctionMeta,
18
18
  StreamHandlers,
19
19
  FunctionExample,
20
+ RestoredUserState,
20
21
  } from "./types.js";
21
22
  import type { ArgumentConstraints, ArgumentSpec } from "../arguments/argument-spec.js";
22
23
  import {
@@ -211,11 +212,14 @@ export function defineTableInOutFunction<
211
212
  }
212
213
 
213
214
  // Table-in-out always has a table input (after positional args)
215
+ // The TABLE argument is documented like any other: `argDocs.data`
216
+ // (vgi-python: the TableInput field's own `Arg(doc=...)`).
214
217
  specs.push({
215
218
  name: "data",
216
219
  position: posIdx++,
217
220
  arrowType: nullType(),
218
221
  isTableInput: true,
222
+ ...(config.argDocs?.data !== undefined ? { doc: config.argDocs.data } : {}),
219
223
  });
220
224
 
221
225
  if (config.namedArgs) {
@@ -434,7 +438,11 @@ export function defineTableInOutFunction<
434
438
  for (const bytes of stored) {
435
439
  finalizeStates.push(deserializeUserState(bytes) as TState);
436
440
  }
437
- if (finalizeStates.length === 0) {
441
+ // A fresh state stands in for "no input arrived" -- but only a
442
+ // function with a finalize() can use it. Without one, calling
443
+ // initialState here just re-ran user code (validation, I/O) once
444
+ // more per query, on a stream that never processes input.
445
+ if (finalizeStates.length === 0 && config.finalize) {
438
446
  finalizeStates.push(
439
447
  config.initialState
440
448
  ? config.initialState(processParams)
@@ -490,9 +498,9 @@ export function defineTableInOutFunction<
490
498
  );
491
499
  }
492
500
 
493
- const state = config.initialState
494
- ? config.initialState(processParams)
495
- : (null as TState);
501
+ // initialState runs only for a fresh stream (see exchangeInit below).
502
+ const freshState = (): TState =>
503
+ config.initialState ? config.initialState(processParams) : (null as TState);
496
504
 
497
505
  const processFn =
498
506
  config.process ??
@@ -510,7 +518,13 @@ export function defineTableInOutFunction<
510
518
  outputSchema,
511
519
  inputSchema: request.bind_call.input_schema,
512
520
  continuesOutput: true,
513
- exchangeInit: () => ({ state, processParams, filterHistory: carriedFilterHistory, morePending: false }),
521
+ // A rebuilt HTTP turn adopts the state its cursor carried.
522
+ exchangeInit: (restored?: RestoredUserState) => ({
523
+ state: restored ? (restored.state as TState) : freshState(),
524
+ processParams,
525
+ filterHistory: carriedFilterHistory,
526
+ morePending: false,
527
+ }),
514
528
  exchangeFn: async (
515
529
  eState: {
516
530
  state: TState;
@@ -1079,15 +1093,21 @@ export function defineRowTransformFunction<
1079
1093
  );
1080
1094
  }
1081
1095
 
1082
- const state = config.initialState
1083
- ? config.initialState(processParams)
1084
- : (null as TState);
1096
+ // initialState runs only for a fresh stream (see exchangeInit below).
1097
+ const freshState = (): TState =>
1098
+ config.initialState ? config.initialState(processParams) : (null as TState);
1085
1099
 
1086
1100
  return {
1087
1101
  outputSchema,
1088
1102
  inputSchema: request.bind_call.input_schema,
1089
1103
  continuesOutput: true,
1090
- exchangeInit: () => ({ state, processParams, filterHistory: carriedFilterHistory, morePending: false }),
1104
+ // A rebuilt HTTP turn adopts the state its cursor carried.
1105
+ exchangeInit: (restored?: RestoredUserState) => ({
1106
+ state: restored ? (restored.state as TState) : freshState(),
1107
+ processParams,
1108
+ filterHistory: carriedFilterHistory,
1109
+ morePending: false,
1110
+ }),
1091
1111
  exchangeFn: async (
1092
1112
  eState: {
1093
1113
  state: TState;
@@ -32,6 +32,7 @@ import type {
32
32
  FunctionMeta,
33
33
  StreamHandlers,
34
34
  FunctionExample,
35
+ RestoredUserState,
35
36
  } from "./types.js";
36
37
  import {
37
38
  constraintSpecFields,
@@ -598,14 +599,16 @@ export function defineTableFunction<
598
599
  );
599
600
  }
600
601
 
601
- const state = config.initialState
602
- ? config.initialState(processParams)
603
- : (null as TState);
604
-
605
602
  return {
606
603
  outputSchema,
607
- producerInit: (): TableHandlerState<TArgs, TState> => ({
608
- state,
604
+ // initialState runs only for a fresh stream; a rebuilt HTTP turn
605
+ // adopts the state its cursor carried.
606
+ producerInit: (restored?: RestoredUserState): TableHandlerState<TArgs, TState> => ({
607
+ state: restored
608
+ ? (restored.state as TState)
609
+ : config.initialState
610
+ ? config.initialState(processParams)
611
+ : (null as TState),
609
612
  processParams,
610
613
  filterHistory: carriedFilterHistory,
611
614
  }),
@@ -213,12 +213,22 @@ export interface FunctionMeta {
213
213
  copyToComment?: string | null | undefined;
214
214
  }
215
215
 
216
+ /** The user state a rebuilt HTTP turn restores, boxed so `null` state survives. */
217
+ export interface RestoredUserState {
218
+ state: unknown;
219
+ }
220
+
216
221
  export interface StreamHandlers {
217
- // For producer streams (table functions, finalize phase)
218
- producerInit?: (() => any) | undefined;
222
+ // For producer streams (table functions, finalize phase).
223
+ //
224
+ // `restored` is the user state an HTTP turn carried in its cursor. When it
225
+ // is given the handler must adopt it instead of computing a fresh one, so
226
+ // `initialState` runs once per stream, not once per turn (a rebuilt turn
227
+ // used to call it and then discard the result).
228
+ producerInit?: ((restored?: RestoredUserState) => any) | undefined;
219
229
  producerFn?: ((state: any, out: OutputCollector) => void | Promise<void>) | undefined;
220
230
  // For exchange streams (scalar, table-in-out input phase)
221
- exchangeInit?: (() => any) | undefined;
231
+ exchangeInit?: ((restored?: RestoredUserState) => any) | undefined;
222
232
  exchangeFn?: (
223
233
  state: any,
224
234
  input: VgiBatch,
package/src/index.core.ts CHANGED
@@ -31,7 +31,7 @@ export {
31
31
  } from "./cache-control.js";
32
32
 
33
33
  // Function factories (primary API)
34
- export { defineScalarFunction, type ScalarFunctionConfig, type ScalarBindParameters, type ScalarParameterDef } from "./functions/scalar.js";
34
+ export { defineScalarFunction, type ScalarFunctionConfig, type ScalarBindParameters, type ScalarComputeInfo, type ScalarParameterDef } from "./functions/scalar.js";
35
35
  export { defineTableFunction, type TableFunctionConfig, type TableBindParams, type TableProcessParams } from "./functions/table.js";
36
36
  export {
37
37
  defineAggregate,
@@ -374,6 +374,14 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
374
374
  // cursor carries the packed request unchanged on every turn.
375
375
  const carried = parseCarriedInitRequest(state.initRequestPacked);
376
376
  const request = carried.request;
377
+ // The cursor carries the wire request, whose attach is still the sealed
378
+ // envelope. Strip it exactly as the init turn did, before any user code
379
+ // or split resolution sees it: every turn of a stream must hand the
380
+ // function the catalog's own bytes, not just the first. (Unopenable is
381
+ // a hard error here, as on the init turn: the cursor is caller-bound.)
382
+ // `carried.request.bind_call` is a per-call copy, so this does not
383
+ // disturb the memoised parse other turns share.
384
+ request.bind_call.attach_opaque_data = await stripAttach(request.bind_call.attach_opaque_data, undefined);
377
385
  // Re-derive the split payloads. The cursor carries the wire request,
378
386
  // which has `split_tokens` but not the opened `split_payloads` — that
379
387
  // field only ever existed in memory on the init turn. Without this a
@@ -396,7 +404,9 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
396
404
  catalogInterface,
397
405
  checkAnchor: false,
398
406
  });
399
- const func = registry.get(state.functionName, await strippedContext(request.bind_call));
407
+ // Already stripped above, so resolve directly (strippedContext would try
408
+ // to open the plaintext again and fall back to an unscoped lookup).
409
+ const func = registry.get(state.functionName, overloadContext(request.bind_call, catalogInterface));
400
410
  const executionId = state.executionId;
401
411
  const opaqueData = state.opaqueData ?? null;
402
412
  const initResponse: GlobalInitResponse = {
@@ -409,10 +419,13 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
409
419
  // after the one that received a delta would scan under the init
410
420
  // snapshot again, because the extension sends each delta only once.
411
421
  handlers = func.createStreamHandlers(request, initResponse, state.filterHistory ?? null);
422
+ // Hand the carried user state to the init hook, so a handler that
423
+ // supports it skips initialState (which already ran on the init turn).
424
+ const restored = state.userState != null ? { state: state.userState } : undefined;
412
425
  if (handlers.producerInit) {
413
- handlerState = handlers.producerInit();
426
+ handlerState = handlers.producerInit(restored);
414
427
  } else if (handlers.exchangeInit) {
415
- handlerState = handlers.exchangeInit();
428
+ handlerState = handlers.exchangeInit(restored);
416
429
  }
417
430
  // Merge preserved user state (e.g. { remaining, currentIndex })
418
431
  if (state.userState != null && handlerState?.state !== undefined) {