@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/README.md CHANGED
@@ -31,6 +31,26 @@ ATTACH 'demo' AS demo (TYPE vgi, LOCATION '/path/to/your-worker');
31
31
  SELECT demo.upper_case(name) FROM users;
32
32
  ```
33
33
 
34
+ ## Start a new worker
35
+
36
+ The fastest way to a new TypeScript worker is the
37
+ [**vgi-starter-typescript**](https://github.com/Query-farm/vgi-starter-typescript) template: a complete,
38
+ tested worker with a scalar, a table function and a paginated REST API example, recipes for
39
+ common data-engineering tasks, SQL and unit tests, metadata that scores 100 on
40
+ [vgi-lint](https://github.com/Query-farm/vgi-lint-check), CI, Docker, signed release workflows,
41
+ and an `AGENTS.md` for coding agents.
42
+
43
+ ```bash
44
+ gh repo create my-worker --template Query-farm/vgi-starter-typescript --private --clone
45
+ cd my-worker
46
+ make init NAME=my_worker # rename the catalog, package and binary
47
+ make check # everything CI runs
48
+ ```
49
+
50
+ Or click **Use this template** on GitHub. See
51
+ [starter templates](https://query.farm/vgi/docs/concepts/starter-templates/) for details. The
52
+ rest of this README covers the SDK itself.
53
+
34
54
  ## Install
35
55
 
36
56
  ```bash
@@ -108,7 +128,10 @@ const upperCase = defineScalarFunction({
108
128
  // position (column 0 = first arg); return one output value per row (null ok).
109
129
  // Full signature: compute(batch, consts, info) where
110
130
  // consts → values of any `constParams` (literals folded at bind time)
111
- // info → { settings, secrets, auth } — session settings, secrets, caller
131
+ // info → { settings, secrets, auth, bindCall } — session settings,
132
+ // secrets, caller, and the bind request (its attach_opaque_data
133
+ // carries the catalog's attach-time state, already unsealed)
134
+ // compute may be async: return a Promise to call a service per batch.
112
135
  compute: (batch) => {
113
136
  const values = batch.getChildAt(0)!; // first positional argument
114
137
  return Array.from(values, (v) =>
@@ -1,5 +1,6 @@
1
1
  import type { VgiSchema, VgiDataType } from "../arrow/index.js";
2
2
  import type { AttachCatalogInfo } from "./interface.js";
3
+ import type { AttachOptionSpec } from "./attach-option.js";
3
4
  import type { VgiFunction } from "../functions/types.js";
4
5
  import type { Arguments } from "../arguments/arguments.js";
5
6
  import type { ColumnStatistics } from "../util/statistics.js";
@@ -163,6 +164,19 @@ export interface CatalogDescriptor {
163
164
  schemas: SchemaDescriptor[];
164
165
  settings?: SettingDescriptor[];
165
166
  secretTypes?: SecretTypeDescriptor[];
167
+ /**
168
+ * Options the catalog accepts at `ATTACH` time
169
+ * (`ATTACH 'x' (TYPE vgi, LOCATION '...', region 'eu', api_key '...')`).
170
+ * Advertised in the catalog's discovery record so the DuckDB extension
171
+ * validates and casts them (and redacts `secret` ones), and `required` ones
172
+ * are enforced at attach. Mirrors vgi-python's
173
+ * `ReadOnlyCatalogInterface.attach_option_specs`.
174
+ *
175
+ * The values reach `attach()` as its `options`; to hand them to functions,
176
+ * override `attach()` and carry them in `attach_opaque_data`
177
+ * (examples/attach-options-worker.ts), which every function call receives.
178
+ */
179
+ attachOptions?: AttachOptionSpec[];
166
180
  /**
167
181
  * Companion catalogs (lakehouse federation) the client should ATTACH when this
168
182
  * VGI catalog attaches. Surfaced via `catalog_attach.attach_catalogs`.
@@ -79,11 +79,10 @@ export declare class ReadOnlyCatalogInterface extends CatalogInterface {
79
79
  /**
80
80
  * Attach-time options this catalog declares, for the named catalog.
81
81
  *
82
- * Empty by default — the declarative descriptor path carries no attach
83
- * options. A subclass that advertises specs in `catalogsInfo()` should
84
- * return the same specs here so `attach()` enforces the `required` ones it
85
- * advertised. Takes the catalog name because one interface may serve
86
- * several catalogs with different option sets.
82
+ * The descriptor's `attachOptions` (empty when it declares none). A
83
+ * subclass serving several catalogs with different option sets overrides
84
+ * this; `catalogsInfo()` advertises whatever it returns and `attach()`
85
+ * enforces the `required` ones, so the two never disagree.
87
86
  */
88
87
  attachOptionSpecs(_name: string): AttachOptionSpec[];
89
88
  catalogsInfo(): CatalogInfo[];
@@ -24,6 +24,7 @@ export declare class FunctionRegistry {
24
24
  private _functions;
25
25
  private _bySchema;
26
26
  private _byCatalog;
27
+ /** Add `func` to the by-name index. Idempotent for the same function object. */
27
28
  register(func: VgiFunction): void;
28
29
  /**
29
30
  * Record that `func` is declared in `schemaPath`, in addition to the flat
@@ -62,6 +62,21 @@ export type ScalarOutputValue<R extends VgiDataType, M extends Repr> = ValueFor<
62
62
  * expects a `Date`), is a COMPILE error.
63
63
  */
64
64
  export type ScalarComputeResult<R extends VgiDataType, M extends Repr> = Array<ScalarOutputValue<R, M>> | Iterable<ScalarOutputValue<R, M>> | VgiBatch;
65
+ /** Per-batch context handed to a scalar's `compute`. */
66
+ export interface ScalarComputeInfo {
67
+ settings: Record<string, any>;
68
+ secrets: Record<string, Record<string, any>>;
69
+ auth: AuthContext;
70
+ /**
71
+ * The bind request this execution was initialized with: the catalog's
72
+ * `attach_opaque_data` (already unsealed, as every function body sees it),
73
+ * `transaction_opaque_data`, arguments, settings and secrets. Mirrors the
74
+ * `init_call.bind_call` vgi-python's `ScalarFunction.process` receives, so a
75
+ * scalar can read attach-time state (e.g. connection options a catalog
76
+ * packed into its attach data).
77
+ */
78
+ bindCall: BindRequest;
79
+ }
65
80
  export interface ScalarFunctionConfig<P extends Record<string, VgiDataType> = Record<string, VgiDataType>, R extends VgiDataType = VgiDataType, M extends Repr = "rich"> {
66
81
  name: string;
67
82
  description?: string;
@@ -98,11 +113,7 @@ export interface ScalarFunctionConfig<P extends Record<string, VgiDataType> = Re
98
113
  * output column as an array/iterable of values (statically typed from
99
114
  * `returns` and `repr`) or a pre-built VgiBatch.
100
115
  */
101
- compute: (batch: VgiBatch, consts: Record<string, any>, info: {
102
- settings: Record<string, any>;
103
- secrets: Record<string, Record<string, any>>;
104
- auth: AuthContext;
105
- }) => ScalarComputeResult<NoInfer<R>, NoInfer<M>>;
116
+ compute: (batch: VgiBatch, consts: Record<string, any>, info: ScalarComputeInfo) => ScalarComputeResult<NoInfer<R>, NoInfer<M>> | Promise<ScalarComputeResult<NoInfer<R>, NoInfer<M>>>;
106
117
  stability?: FunctionStability;
107
118
  nullHandling?: NullHandling;
108
119
  /** One scalar monotonicity claim per ordered parameter declaration. */
@@ -189,10 +189,14 @@ export interface FunctionMeta {
189
189
  /** Optional free-text comment surfaced by `vgi_copy_formats()`. */
190
190
  copyToComment?: string | null | undefined;
191
191
  }
192
+ /** The user state a rebuilt HTTP turn restores, boxed so `null` state survives. */
193
+ export interface RestoredUserState {
194
+ state: unknown;
195
+ }
192
196
  export interface StreamHandlers {
193
- producerInit?: (() => any) | undefined;
197
+ producerInit?: ((restored?: RestoredUserState) => any) | undefined;
194
198
  producerFn?: ((state: any, out: OutputCollector) => void | Promise<void>) | undefined;
195
- exchangeInit?: (() => any) | undefined;
199
+ exchangeInit?: ((restored?: RestoredUserState) => any) | undefined;
196
200
  exchangeFn?: (state: any, input: VgiBatch, out: OutputCollector) => void | Promise<void>;
197
201
  outputSchema: VgiSchema;
198
202
  inputSchema?: VgiSchema | undefined;
@@ -1,5 +1,5 @@
1
1
  export { CACHE_ETAG_KEY, CACHE_EXPIRES_KEY, CACHE_IF_MODIFIED_SINCE_KEY, CACHE_IF_NONE_MATCH_KEY, CACHE_LAST_MODIFIED_KEY, CACHE_NO_STORE_KEY, CACHE_NOT_MODIFIED_KEY, CACHE_PARTITION_SCOPE_KEY, CACHE_PER_VALUE_KEY, CACHE_REVALIDATABLE_KEY, CACHE_SCOPE_CATALOG, CACHE_SCOPE_KEY, CACHE_SCOPE_TRANSACTION, CACHE_STALE_IF_ERROR_KEY, CACHE_STALE_WHILE_REVALIDATE_KEY, CACHE_TTL_KEY, type CacheControl, cacheControlMetadata, type CacheScope, } from "./cache-control.js";
2
- export { defineScalarFunction, type ScalarFunctionConfig, type ScalarBindParameters, type ScalarParameterDef } from "./functions/scalar.js";
2
+ export { defineScalarFunction, type ScalarFunctionConfig, type ScalarBindParameters, type ScalarComputeInfo, type ScalarParameterDef } from "./functions/scalar.js";
3
3
  export { defineTableFunction, type TableFunctionConfig, type TableBindParams, type TableProcessParams } from "./functions/table.js";
4
4
  export { defineAggregate, GROUP_COLUMN_NAME, type AggregateFunctionConfig, type AggregateBindParams, type AggregateUpdateParams, type AggregateFinalizeParams, } from "./functions/aggregate.js";
5
5
  export { defineTableInOutFunction, defineRowTransformFunction, parentRowsMetadata, PARENT_ROW_METADATA_KEY, type TableInOutConfig, type TableInOutBindParams, type TableInOutProcessParams, type RowTransformConfig, type RowTransformProcessParams, } from "./functions/table-in-out.js";
package/dist/index.js CHANGED
@@ -3155,8 +3155,15 @@ function defineScalarFunction(config) {
3155
3155
  outputSchema,
3156
3156
  inputSchema: inputSchema ?? undefined,
3157
3157
  exchangeInit: () => ({}),
3158
- exchangeFn: (state, input, out) => {
3159
- const result = config.compute(input, constArgs, { settings, secrets, auth: out.auth });
3158
+ exchangeFn: async (state, input, out) => {
3159
+ let result = config.compute(input, constArgs, {
3160
+ settings,
3161
+ secrets,
3162
+ auth: out.auth,
3163
+ bindCall: request.bind_call
3164
+ });
3165
+ if (result != null && typeof result.then === "function")
3166
+ result = await result;
3160
3167
  let outputBatch;
3161
3168
  if (isBatch(result)) {
3162
3169
  outputBatch = result;
@@ -5009,11 +5016,10 @@ function defineTableFunction(config) {
5009
5016
  if (request.phase != null) {
5010
5017
  throw new Error(`${config.name}: is a plain table function (it takes no input row ` + `stream) but was called with an init phase set -- call it via ` + `table_function(), not table_in_out_function().`);
5011
5018
  }
5012
- const state = config.initialState ? config.initialState(processParams) : null;
5013
5019
  return {
5014
5020
  outputSchema,
5015
- producerInit: () => ({
5016
- state,
5021
+ producerInit: (restored) => ({
5022
+ state: restored ? restored.state : config.initialState ? config.initialState(processParams) : null,
5017
5023
  processParams,
5018
5024
  filterHistory: carriedFilterHistory
5019
5025
  }),
@@ -6403,7 +6409,8 @@ function defineTableInOutFunction(config) {
6403
6409
  name: "data",
6404
6410
  position: posIdx++,
6405
6411
  arrowType: nullType2(),
6406
- isTableInput: true
6412
+ isTableInput: true,
6413
+ ...config.argDocs?.data !== undefined ? { doc: config.argDocs.data } : {}
6407
6414
  });
6408
6415
  if (config.namedArgs) {
6409
6416
  for (const [name, type] of Object.entries(config.namedArgs)) {
@@ -6537,7 +6544,7 @@ function defineTableInOutFunction(config) {
6537
6544
  for (const bytes of stored) {
6538
6545
  finalizeStates.push(deserializeUserState(bytes));
6539
6546
  }
6540
- if (finalizeStates.length === 0) {
6547
+ if (finalizeStates.length === 0 && config.finalize) {
6541
6548
  finalizeStates.push(config.initialState ? config.initialState(processParams) : null);
6542
6549
  }
6543
6550
  const batches = config.finalize ? await config.finalize(processParams, finalizeStates) : [];
@@ -6560,7 +6567,7 @@ function defineTableInOutFunction(config) {
6560
6567
  if (request.bind_call.input_schema == null) {
6561
6568
  throw new Error(`${config.name}: is a table-in-out function (it requires an input row ` + `stream) but no input schema was supplied -- call it via ` + `table_in_out_function(input=...), not table_function().`);
6562
6569
  }
6563
- const state = config.initialState ? config.initialState(processParams) : null;
6570
+ const freshState = () => config.initialState ? config.initialState(processParams) : null;
6564
6571
  const processFn = config.process ?? ((_params, _state, batch, out) => {
6565
6572
  out.emit(projIds ? projectBatch(projIds, batch) : batch);
6566
6573
  });
@@ -6568,7 +6575,12 @@ function defineTableInOutFunction(config) {
6568
6575
  outputSchema,
6569
6576
  inputSchema: request.bind_call.input_schema,
6570
6577
  continuesOutput: true,
6571
- exchangeInit: () => ({ state, processParams, filterHistory: carriedFilterHistory, morePending: false }),
6578
+ exchangeInit: (restored) => ({
6579
+ state: restored ? restored.state : freshState(),
6580
+ processParams,
6581
+ filterHistory: carriedFilterHistory,
6582
+ morePending: false
6583
+ }),
6572
6584
  exchangeFn: async (eState, input, out) => {
6573
6585
  await continuationTurn(config.name, eState, input, out, config.resume != null, async (tick) => {
6574
6586
  applyRevalidationValidators(eState.processParams, input);
@@ -6822,12 +6834,17 @@ function defineRowTransformFunction(config) {
6822
6834
  if (request.bind_call.input_schema == null) {
6823
6835
  throw new Error(`${config.name}: is a table-in-out function (its positional args are ` + `per-row input columns) but no input schema was supplied -- call it ` + `via table_in_out_function(input=...), not table_function().`);
6824
6836
  }
6825
- const state = config.initialState ? config.initialState(processParams) : null;
6837
+ const freshState = () => config.initialState ? config.initialState(processParams) : null;
6826
6838
  return {
6827
6839
  outputSchema,
6828
6840
  inputSchema: request.bind_call.input_schema,
6829
6841
  continuesOutput: true,
6830
- exchangeInit: () => ({ state, processParams, filterHistory: carriedFilterHistory, morePending: false }),
6842
+ exchangeInit: (restored) => ({
6843
+ state: restored ? restored.state : freshState(),
6844
+ processParams,
6845
+ filterHistory: carriedFilterHistory,
6846
+ morePending: false
6847
+ }),
6831
6848
  exchangeFn: async (eState, input, out) => {
6832
6849
  await continuationTurn(config.name, eState, input, out, config.resume != null, async (tick) => {
6833
6850
  applyRevalidationValidators(eState.processParams, input);
@@ -6878,7 +6895,8 @@ function defineTableBufferingFunction(config) {
6878
6895
  name: "data",
6879
6896
  position: posIdx++,
6880
6897
  arrowType: nullType2(),
6881
- isTableInput: true
6898
+ isTableInput: true,
6899
+ ...config.argDocs?.data !== undefined ? { doc: config.argDocs.data } : {}
6882
6900
  });
6883
6901
  if (config.namedArgs) {
6884
6902
  for (const [name, type] of Object.entries(config.namedArgs)) {
@@ -11296,8 +11314,10 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
11296
11314
  for (const tbl of sch.tables ?? []) {
11297
11315
  for (const key of ["function", "insertFunction", "updateFunction", "deleteFunction"]) {
11298
11316
  const fn = tbl[key];
11299
- if (fn)
11300
- registry.registerInSchema(fn, schemaDescriptorPath(sch), descriptor.name);
11317
+ if (!fn)
11318
+ continue;
11319
+ registry.registerInSchema(fn, schemaDescriptorPath(sch), descriptor.name);
11320
+ registry.register(fn);
11301
11321
  }
11302
11322
  }
11303
11323
  }
@@ -11313,14 +11333,14 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
11313
11333
  return [this._descriptor.name];
11314
11334
  }
11315
11335
  attachOptionSpecs(_name) {
11316
- return [];
11336
+ return this._descriptor.attachOptions ?? [];
11317
11337
  }
11318
11338
  catalogsInfo() {
11319
11339
  return [{
11320
11340
  name: this._descriptor.name,
11321
11341
  implementation_version: null,
11322
11342
  data_version_spec: null,
11323
- attach_option_specs: [],
11343
+ attach_option_specs: serializeAttachOptionSpecs(this.attachOptionSpecs(this._descriptor.name)),
11324
11344
  releases: [],
11325
11345
  source_url: this._descriptor.sourceUrl ?? null
11326
11346
  }];
@@ -13180,10 +13200,12 @@ class FunctionRegistry {
13180
13200
  _byCatalog = new Map;
13181
13201
  register(func) {
13182
13202
  const name = func.meta.name;
13183
- if (!this._functions.has(name)) {
13184
- this._functions.set(name, []);
13203
+ const bucket = this._functions.get(name);
13204
+ if (!bucket) {
13205
+ this._functions.set(name, [func]);
13206
+ } else if (!bucket.includes(func)) {
13207
+ bucket.push(func);
13185
13208
  }
13186
- this._functions.get(name).push(func);
13187
13209
  }
13188
13210
  registerInSchema(func, schemaPath, catalogName) {
13189
13211
  const add = (map, key) => {
@@ -15602,13 +15624,14 @@ function functionHandlers(config) {
15602
15624
  } else {
15603
15625
  const carried = parseCarriedInitRequest(state.initRequestPacked);
15604
15626
  const request = carried.request;
15627
+ request.bind_call.attach_opaque_data = await stripAttach(request.bind_call.attach_opaque_data, undefined);
15605
15628
  await resolveSplitPayloads(request, { bind_call: carried.bindCallIpc }, {
15606
15629
  auth: currentRequestAuth(),
15607
15630
  signingKey,
15608
15631
  catalogInterface,
15609
15632
  checkAnchor: false
15610
15633
  });
15611
- const func = registry.get(state.functionName, await strippedContext(request.bind_call));
15634
+ const func = registry.get(state.functionName, overloadContext(request.bind_call, catalogInterface));
15612
15635
  const executionId = state.executionId;
15613
15636
  const opaqueData = state.opaqueData ?? null;
15614
15637
  const initResponse = {
@@ -15617,10 +15640,11 @@ function functionHandlers(config) {
15617
15640
  opaque_data: opaqueData
15618
15641
  };
15619
15642
  handlers = func.createStreamHandlers(request, initResponse, state.filterHistory ?? null);
15643
+ const restored = state.userState != null ? { state: state.userState } : undefined;
15620
15644
  if (handlers.producerInit) {
15621
- handlerState = handlers.producerInit();
15645
+ handlerState = handlers.producerInit(restored);
15622
15646
  } else if (handlers.exchangeInit) {
15623
- handlerState = handlers.exchangeInit();
15647
+ handlerState = handlers.exchangeInit(restored);
15624
15648
  }
15625
15649
  if (state.userState != null && handlerState?.state !== undefined) {
15626
15650
  handlerState.state = state.userState;
@@ -19700,4 +19724,4 @@ export {
19700
19724
  validateTableConstraints
19701
19725
  };
19702
19726
 
19703
- //# debugId=9CC3A9354AA50B4D64756E2164756E21
19727
+ //# debugId=0D39EB7B8CA153F964756E2164756E21