@query-farm/vgi 0.48.1 → 0.48.3

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 (49) hide show
  1. package/README.md +51 -1
  2. package/dist/arrow/impl-arrowjs/iterate.d.ts +7 -3
  3. package/dist/arrow/impl-flechette/iterate.d.ts +2 -1
  4. package/dist/catalog/descriptors.d.ts +14 -0
  5. package/dist/catalog/read-only.d.ts +4 -5
  6. package/dist/client-entry.js +9 -25
  7. package/dist/client-entry.js.map +3 -3
  8. package/dist/functions/aggregate.d.ts +2 -1
  9. package/dist/functions/copy-from.d.ts +2 -1
  10. package/dist/functions/copy-to.d.ts +2 -1
  11. package/dist/functions/registry.d.ts +1 -0
  12. package/dist/functions/scalar.d.ts +18 -6
  13. package/dist/functions/table-buffering.d.ts +2 -1
  14. package/dist/functions/table-in-out.d.ts +3 -2
  15. package/dist/functions/table.d.ts +2 -1
  16. package/dist/functions/types.d.ts +8 -3
  17. package/dist/index.core.d.ts +3 -2
  18. package/dist/index.js +177 -61
  19. package/dist/index.js.map +21 -20
  20. package/dist/metadata/types.d.ts +3 -1
  21. package/dist/secrets/helpers.d.ts +31 -3
  22. package/dist/secrets/requirements.d.ts +38 -0
  23. package/dist/serve-entry.js +14 -28
  24. package/dist/serve-entry.js.map +6 -6
  25. package/dist/worker-cf-entry.d.ts +2 -2
  26. package/dist/worker-cf-entry.js +205 -53
  27. package/dist/worker-cf-entry.js.map +18 -16
  28. package/package.json +1 -1
  29. package/src/arrow/impl-arrowjs/iterate.ts +17 -40
  30. package/src/arrow/impl-flechette/iterate.ts +5 -24
  31. package/src/catalog/descriptors.ts +14 -0
  32. package/src/catalog/read-only.ts +24 -16
  33. package/src/functions/aggregate.ts +3 -2
  34. package/src/functions/copy-from.ts +3 -2
  35. package/src/functions/copy-to.ts +2 -1
  36. package/src/functions/registry.ts +6 -3
  37. package/src/functions/scalar.ts +33 -10
  38. package/src/functions/table-buffering.ts +6 -2
  39. package/src/functions/table-in-out.ts +34 -13
  40. package/src/functions/table.ts +12 -8
  41. package/src/functions/types.ts +15 -4
  42. package/src/index.core.ts +11 -1
  43. package/src/metadata/resolve.ts +2 -1
  44. package/src/metadata/serialize.ts +25 -5
  45. package/src/metadata/types.ts +3 -1
  46. package/src/protocol/handlers/function.ts +16 -3
  47. package/src/secrets/helpers.ts +96 -9
  48. package/src/secrets/requirements.ts +121 -0
  49. package/src/worker-cf-entry.ts +14 -0
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.3",
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)",
@@ -93,9 +93,13 @@ export function decodeDictValue(value: any, index = 0): any {
93
93
  }
94
94
 
95
95
  /**
96
- * Extract single-row batch to a secret dict (column per secret, each value is a struct).
97
- * Handles both named secrets (column name = secret type) and scoped secrets
98
- * (column name = "secret_N" with secret_type in field metadata).
96
+ * Extract a single-row resolved-secrets batch to a dict: one entry per column,
97
+ * keyed by the column name — the secret's unique DuckDB NAME, not its type (an
98
+ * unnamed secret arrives as `__default_<type>`). Each value is the secret's
99
+ * struct as a plain object, including its serialized `type`, `name` and `scope`
100
+ * fields. Select from it with the helpers in `secrets/helpers.ts`
101
+ * (`secretOfType`, `secretByName`, `secretForScopeOfType`, ...), never by
102
+ * indexing it with a type. A null struct (secret not found) is skipped.
99
103
  */
100
104
  export function batchToSecretDict(
101
105
  batch: RecordBatch | VgiBatch | null
@@ -106,43 +110,16 @@ export function batchToSecretDict(
106
110
  const result: Record<string, Record<string, any>> = {};
107
111
  for (const field of a.schema.fields) {
108
112
  const col = a.getChild(field.name);
109
- if (col) {
110
- // Read in RICH form via the canonical reader + codec — a secret column is
111
- // a struct scalar, which surfaces as a plain { field: value } object
112
- // (same path as iterRows), so no Arrow-scalar toJSON() shimming is needed.
113
- const type = field.type as unknown as VgiDataType;
114
- const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
115
-
116
- // Determine the key: for scoped secrets (secret_N), use secret_type from metadata
117
- let key = field.name;
118
- let scope: string | undefined;
119
- if (field.name.startsWith("secret_")) {
120
- const secretType = field.metadata?.get?.("secret_type");
121
- if (secretType) {
122
- key = secretType;
123
- scope = field.metadata?.get?.("scope") ?? undefined;
124
- }
125
- }
126
-
127
- if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
128
- // Struct scalar -> already a plain object from the canonical reader.
129
- const dict: Record<string, any> = { ...(val as Record<string, any>) };
130
- if (key in result) {
131
- throw new Error(
132
- `batchToSecretDict: duplicate secret_type '${key}' (scope=${scope ?? "none"}). ` +
133
- `Use scoped secrets with distinct scopes to avoid collisions.`
134
- );
135
- }
136
- result[key] = dict;
137
- // Store scope-qualified key for disambiguation
138
- if (scope) {
139
- result[`${key}:${scope}`] = dict;
140
- }
141
- } else if (val === null || val === undefined) {
142
- // Skip null struct values (secret not found)
143
- } else {
144
- result[key] = {};
145
- }
113
+ if (!col) continue;
114
+ // Read in RICH form via the canonical reader + codec — a secret column is
115
+ // a struct scalar, which surfaces as a plain { field: value } object
116
+ // (same path as iterRows), so no Arrow-scalar toJSON() shimming is needed.
117
+ const type = field.type as unknown as VgiDataType;
118
+ const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
119
+ if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
120
+ result[field.name] = { ...(val as Record<string, any>) };
121
+ } else if (val !== null && val !== undefined) {
122
+ result[field.name] = {};
146
123
  }
147
124
  }
148
125
  return result;
@@ -66,7 +66,8 @@ export function decodeDictValue(value: any, _index = 0): any {
66
66
  }
67
67
 
68
68
  /**
69
- * Single-row batch → secret dict. Mirrors impl-arrowjs's same-named function.
69
+ * Single-row resolved-secrets batch → dict keyed by column name (the secret's
70
+ * unique DuckDB NAME, not its type). Mirrors impl-arrowjs's same-named function.
70
71
  */
71
72
  export function batchToSecretDict(
72
73
  batch: VgiBatch | null,
@@ -83,30 +84,10 @@ export function batchToSecretDict(
83
84
  // iterRows), identical to the arrow-js backend.
84
85
  const type = f.type as VgiDataType;
85
86
  const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
86
-
87
- let key = f.name;
88
- let scope: string | undefined;
89
- if (f.name.startsWith("secret_")) {
90
- const secretType = f.metadata?.get?.("secret_type");
91
- if (secretType) {
92
- key = secretType;
93
- scope = f.metadata?.get?.("scope") ?? undefined;
94
- }
95
- }
96
-
97
87
  if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
98
- const dict: Record<string, any> = { ...(val as Record<string, any>) };
99
- if (key in result) {
100
- throw new Error(
101
- `batchToSecretDict: duplicate secret_type '${key}' (scope=${scope ?? "none"}).`,
102
- );
103
- }
104
- result[key] = dict;
105
- if (scope) result[`${key}:${scope}`] = dict;
106
- } else if (val === null || val === undefined) {
107
- // skip
108
- } else {
109
- result[key] = {};
88
+ result[f.name] = { ...(val as Record<string, any>) };
89
+ } else if (val !== null && val !== undefined) {
90
+ result[f.name] = {};
110
91
  }
111
92
  }
112
93
  return result;
@@ -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
  }];
@@ -634,9 +639,12 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
634
639
  f.defaultOutputSchema ?? schema_([])
635
640
  );
636
641
 
637
- const requiredSecrets = (meta.requiredSecrets ?? []).map(
638
- (secretType: string) => ({ secret_type: secretType, scope: null, secret_name: null })
639
- );
642
+ // Every validated requirement reaches the wire: type, scope and name.
643
+ const requiredSecrets = meta.requiredSecrets.map((s) => ({
644
+ secret_type: s.secretType,
645
+ scope: s.scope,
646
+ secret_name: s.secretName,
647
+ }));
640
648
 
641
649
  // Function-level tags surfaced into duckdb_functions().tags. The wire
642
650
  // map is string→string, so the metadata linter (vgi-lint-check) and any
@@ -13,6 +13,7 @@
13
13
  // aggregate_finalize → emit one result row per group_id
14
14
  // aggregate_destructor → free states (best-effort; see Python worker.py)
15
15
 
16
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
16
17
  import { type VgiSchema, schema, type VgiField, field, type VgiBatch, type VgiDataType, nullType, isNull } from "../arrow/index.js";
17
18
  import type { Arguments } from "../arguments/arguments.js";
18
19
  import {
@@ -165,7 +166,7 @@ export interface AggregateFunctionConfig<TArgs = Record<string, any>, TState = a
165
166
  * empty ResolvedSecrets. Mirrors vgi-python's `Secret()` annotation on an
166
167
  * aggregate `on_bind`.
167
168
  */
168
- requiredSecrets?: string[];
169
+ requiredSecrets?: RequiredSecret[];
169
170
  }
170
171
 
171
172
  // Per-execution state registry. Value = (gid → state) + bind context.
@@ -376,7 +377,7 @@ export function defineAggregate<TArgs = Record<string, any>, TState = any>(
376
377
  tags: config.tags,
377
378
  parameterDefaultValues: config.parameterDefaultValues,
378
379
  nullHandling: config.nullHandling as any,
379
- requiredSecrets: config.requiredSecrets,
380
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
380
381
  };
381
382
 
382
383
  // The normal VgiFunction methods (bind/globalInit/createStreamHandlers) are
@@ -19,6 +19,7 @@
19
19
  // arrive as the function's normal named arguments. Mirrors vgi-python's
20
20
  // `vgi.copy_from_function.CopyFromFunction`.
21
21
 
22
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
22
23
  import { type VgiSchema, type VgiDataType } from "../arrow/index.js";
23
24
  import type { OutputCollector } from "@query-farm/vgi-rpc";
24
25
  import { DEFAULT_MAX_WORKERS } from "../types.js";
@@ -88,7 +89,7 @@ export interface CopyFromFunctionConfig<TArgs = Record<string, unknown>> {
88
89
  tags?: Record<string, string>;
89
90
  examples?: FunctionExample[];
90
91
  requiredSettings?: string[];
91
- requiredSecrets?: string[];
92
+ requiredSecrets?: RequiredSecret[];
92
93
  /**
93
94
  * Optional secret-bind hook: forward CREATE SECRET credentials for
94
95
  * secret-backed cloud sources (S3/GCS/HTTP/…). Called during bind (only on the
@@ -140,7 +141,7 @@ export function defineCopyFromFunction<TArgs = Record<string, unknown>>(
140
141
  tags: config.tags,
141
142
  examples: config.examples,
142
143
  requiredSettings: config.requiredSettings,
143
- requiredSecrets: config.requiredSecrets,
144
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
144
145
  copyFromFormat: config.format,
145
146
  copyFromDirection: config.direction ?? "from",
146
147
  copyFromComment: config.comment ?? null,
@@ -35,6 +35,7 @@
35
35
  // arguments. The source schema rides `BindRequest.input_schema`. Mirrors
36
36
  // vgi-python's `vgi.copy_to_function.CopyToFunction`.
37
37
 
38
+ import type { RequiredSecret } from "../secrets/requirements.js";
38
39
  import { type VgiSchema, schema, type VgiBatch, type VgiDataType } from "../arrow/index.js";
39
40
  import type { BindRequest } from "../protocol/types.js";
40
41
  import type { FunctionMeta, FunctionExample } from "./types.js";
@@ -134,7 +135,7 @@ export interface CopyToFunctionConfig<TArgs = Record<string, unknown>> {
134
135
  tags?: Record<string, string>;
135
136
  examples?: FunctionExample[];
136
137
  requiredSettings?: string[];
137
- requiredSecrets?: string[];
138
+ requiredSecrets?: RequiredSecret[];
138
139
  /**
139
140
  * Optional secret-bind hook: forward CREATE SECRET credentials for
140
141
  * secret-backed cloud writes (S3/GCS/HTTP/…). Called during bind (only on the
@@ -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
  /**
@@ -3,6 +3,7 @@
3
3
  // Scalar functions receive columnar input and produce a single output column
4
4
  // with 1:1 row mapping.
5
5
 
6
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
6
7
  import {
7
8
  type VgiSchema,
8
9
  type VgiField,
@@ -127,6 +128,22 @@ export type ScalarComputeResult<R extends VgiDataType, M extends Repr> =
127
128
  | Iterable<ScalarOutputValue<R, M>>
128
129
  | VgiBatch;
129
130
 
131
+ /** Per-batch context handed to a scalar's `compute`. */
132
+ export interface ScalarComputeInfo {
133
+ settings: Record<string, any>;
134
+ secrets: Record<string, Record<string, any>>;
135
+ auth: AuthContext;
136
+ /**
137
+ * The bind request this execution was initialized with: the catalog's
138
+ * `attach_opaque_data` (already unsealed, as every function body sees it),
139
+ * `transaction_opaque_data`, arguments, settings and secrets. Mirrors the
140
+ * `init_call.bind_call` vgi-python's `ScalarFunction.process` receives, so a
141
+ * scalar can read attach-time state (e.g. connection options a catalog
142
+ * packed into its attach data).
143
+ */
144
+ bindCall: BindRequest;
145
+ }
146
+
130
147
  export interface ScalarFunctionConfig<
131
148
  P extends Record<string, VgiDataType> = Record<string, VgiDataType>,
132
149
  R extends VgiDataType = VgiDataType,
@@ -170,14 +187,12 @@ export interface ScalarFunctionConfig<
170
187
  compute: (
171
188
  batch: VgiBatch,
172
189
  consts: Record<string, any>,
173
- info: {
174
- settings: Record<string, any>;
175
- secrets: Record<string, Record<string, any>>;
176
- auth: AuthContext;
177
- }
190
+ info: ScalarComputeInfo,
178
191
  // NoInfer pins R/M from `returns`/`repr` so the compute return type is
179
192
  // CHECKED against them rather than widening them to fit a wrong value.
180
- ) => ScalarComputeResult<NoInfer<R>, NoInfer<M>>;
193
+ // May be async: a scalar that calls a service (an HTTP API, a database)
194
+ // returns a Promise and the framework awaits it before emitting.
195
+ ) => ScalarComputeResult<NoInfer<R>, NoInfer<M>> | Promise<ScalarComputeResult<NoInfer<R>, NoInfer<M>>>;
181
196
  // Metadata
182
197
  stability?: FunctionStability;
183
198
  nullHandling?: NullHandling;
@@ -189,7 +204,7 @@ export interface ScalarFunctionConfig<
189
204
  parameterDefaultValues?: VgiBatch | null;
190
205
  maxWorkers?: number;
191
206
  requiredSettings?: string[];
192
- requiredSecrets?: string[];
207
+ requiredSecrets?: RequiredSecret[];
193
208
  /**
194
209
  * Result-cache opt-in: when set, this CacheControl's `vgi.cache.*` metadata
195
210
  * rides every output batch's custom metadata (per-batch — NOT the schema,
@@ -317,7 +332,7 @@ export function defineScalarFunction<
317
332
  parameterDefaultValues: config.parameterDefaultValues,
318
333
  maxWorkers: config.maxWorkers,
319
334
  requiredSettings: config.requiredSettings,
320
- requiredSecrets: config.requiredSecrets,
335
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
321
336
  };
322
337
 
323
338
  // Default output schema for catalog registration.
@@ -415,8 +430,16 @@ export function defineScalarFunction<
415
430
  outputSchema,
416
431
  inputSchema: inputSchema ?? undefined,
417
432
  exchangeInit: () => ({}),
418
- exchangeFn: (state: any, input: VgiBatch, out: OutputCollector) => {
419
- const result = config.compute(input as any, constArgs, { settings, secrets, auth: out.auth });
433
+ exchangeFn: async (state: any, input: VgiBatch, out: OutputCollector) => {
434
+ let result: any = config.compute(input as any, constArgs, {
435
+ settings,
436
+ secrets,
437
+ auth: out.auth,
438
+ bindCall: request.bind_call,
439
+ });
440
+ // Await only a thenable, so a synchronous compute costs no extra
441
+ // microtask per batch.
442
+ if (result != null && typeof result.then === "function") result = await result;
420
443
 
421
444
  // Build output batch
422
445
  let outputBatch: VgiBatch;
@@ -16,6 +16,7 @@
16
16
  // The Source phase may route a finalize_state_id to a worker process that
17
17
  // did NOT run the corresponding process() calls.
18
18
 
19
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
19
20
  import {
20
21
  type VgiSchema,
21
22
  schema,
@@ -179,7 +180,7 @@ export interface TableBufferingConfig<
179
180
  tags?: Record<string, string> | undefined;
180
181
  maxWorkers?: number | undefined;
181
182
  requiredSettings?: string[] | undefined;
182
- requiredSecrets?: string[] | undefined;
183
+ requiredSecrets?: RequiredSecret[] | undefined;
183
184
  }
184
185
 
185
186
  /**
@@ -220,11 +221,14 @@ export function defineTableBufferingFunction<
220
221
  });
221
222
  }
222
223
  }
224
+ // The TABLE argument is documented like any other: `argDocs.data`
225
+ // (vgi-python: the TableInput field's own `Arg(doc=...)`).
223
226
  specs.push({
224
227
  name: "data",
225
228
  position: posIdx++,
226
229
  arrowType: nullType(),
227
230
  isTableInput: true,
231
+ ...(config.argDocs?.data !== undefined ? { doc: config.argDocs.data } : {}),
228
232
  });
229
233
  if (config.namedArgs) {
230
234
  for (const [name, type] of Object.entries(config.namedArgs)) {
@@ -254,7 +258,7 @@ export function defineTableBufferingFunction<
254
258
  parameterDefaultValues: config.parameterDefaultValues,
255
259
  maxWorkers: config.maxWorkers,
256
260
  requiredSettings: config.requiredSettings,
257
- requiredSecrets: config.requiredSecrets,
261
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
258
262
  // The Source phase always runs (it's how output is produced), so a
259
263
  // table_buffering function always advertises has_finalize.
260
264
  hasFinalize: true,
@@ -3,6 +3,7 @@
3
3
  // Two-phase: INPUT phase receives and transforms batches,
4
4
  // FINALIZE phase emits final results.
5
5
 
6
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
6
7
  import { type VgiSchema, schema, type VgiField, type VgiDataType, type VgiBatch, nullType, isNull, withBatchMetadata, serializeBatch, deserializeBatch } from "../arrow/index.js";
7
8
  import type { OutputCollector } from "@query-farm/vgi-rpc";
8
9
  import { DEFAULT_MAX_WORKERS, TableInOutPhase } from "../types.js";
@@ -17,6 +18,7 @@ import type {
17
18
  FunctionMeta,
18
19
  StreamHandlers,
19
20
  FunctionExample,
21
+ RestoredUserState,
20
22
  } from "./types.js";
21
23
  import type { ArgumentConstraints, ArgumentSpec } from "../arguments/argument-spec.js";
22
24
  import {
@@ -178,7 +180,7 @@ export interface TableInOutConfig<
178
180
  tags?: Record<string, string>;
179
181
  maxWorkers?: number;
180
182
  requiredSettings?: string[];
181
- requiredSecrets?: string[];
183
+ requiredSecrets?: RequiredSecret[];
182
184
  }
183
185
 
184
186
  export function defineTableInOutFunction<
@@ -211,11 +213,14 @@ export function defineTableInOutFunction<
211
213
  }
212
214
 
213
215
  // Table-in-out always has a table input (after positional args)
216
+ // The TABLE argument is documented like any other: `argDocs.data`
217
+ // (vgi-python: the TableInput field's own `Arg(doc=...)`).
214
218
  specs.push({
215
219
  name: "data",
216
220
  position: posIdx++,
217
221
  arrowType: nullType(),
218
222
  isTableInput: true,
223
+ ...(config.argDocs?.data !== undefined ? { doc: config.argDocs.data } : {}),
219
224
  });
220
225
 
221
226
  if (config.namedArgs) {
@@ -246,7 +251,7 @@ export function defineTableInOutFunction<
246
251
  parameterDefaultValues: config.parameterDefaultValues,
247
252
  maxWorkers: config.maxWorkers,
248
253
  requiredSettings: config.requiredSettings,
249
- requiredSecrets: config.requiredSecrets,
254
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
250
255
  hasFinalize: !!config.finalize,
251
256
  };
252
257
 
@@ -434,7 +439,11 @@ export function defineTableInOutFunction<
434
439
  for (const bytes of stored) {
435
440
  finalizeStates.push(deserializeUserState(bytes) as TState);
436
441
  }
437
- if (finalizeStates.length === 0) {
442
+ // A fresh state stands in for "no input arrived" -- but only a
443
+ // function with a finalize() can use it. Without one, calling
444
+ // initialState here just re-ran user code (validation, I/O) once
445
+ // more per query, on a stream that never processes input.
446
+ if (finalizeStates.length === 0 && config.finalize) {
438
447
  finalizeStates.push(
439
448
  config.initialState
440
449
  ? config.initialState(processParams)
@@ -490,9 +499,9 @@ export function defineTableInOutFunction<
490
499
  );
491
500
  }
492
501
 
493
- const state = config.initialState
494
- ? config.initialState(processParams)
495
- : (null as TState);
502
+ // initialState runs only for a fresh stream (see exchangeInit below).
503
+ const freshState = (): TState =>
504
+ config.initialState ? config.initialState(processParams) : (null as TState);
496
505
 
497
506
  const processFn =
498
507
  config.process ??
@@ -510,7 +519,13 @@ export function defineTableInOutFunction<
510
519
  outputSchema,
511
520
  inputSchema: request.bind_call.input_schema,
512
521
  continuesOutput: true,
513
- exchangeInit: () => ({ state, processParams, filterHistory: carriedFilterHistory, morePending: false }),
522
+ // A rebuilt HTTP turn adopts the state its cursor carried.
523
+ exchangeInit: (restored?: RestoredUserState) => ({
524
+ state: restored ? (restored.state as TState) : freshState(),
525
+ processParams,
526
+ filterHistory: carriedFilterHistory,
527
+ morePending: false,
528
+ }),
514
529
  exchangeFn: async (
515
530
  eState: {
516
531
  state: TState;
@@ -847,7 +862,7 @@ export interface RowTransformConfig<TArgs = Record<string, any>, TState = null>
847
862
  tags?: Record<string, string>;
848
863
  maxWorkers?: number;
849
864
  requiredSettings?: string[];
850
- requiredSecrets?: string[];
865
+ requiredSecrets?: RequiredSecret[];
851
866
  }
852
867
 
853
868
  /**
@@ -940,7 +955,7 @@ export function defineRowTransformFunction<
940
955
  parameterDefaultValues: config.parameterDefaultValues,
941
956
  maxWorkers: config.maxWorkers,
942
957
  requiredSettings: config.requiredSettings,
943
- requiredSecrets: config.requiredSecrets,
958
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
944
959
  // Map-shaped, per-row: a blended function never has a finalize.
945
960
  hasFinalize: false,
946
961
  inputFromArgs: true,
@@ -1079,15 +1094,21 @@ export function defineRowTransformFunction<
1079
1094
  );
1080
1095
  }
1081
1096
 
1082
- const state = config.initialState
1083
- ? config.initialState(processParams)
1084
- : (null as TState);
1097
+ // initialState runs only for a fresh stream (see exchangeInit below).
1098
+ const freshState = (): TState =>
1099
+ config.initialState ? config.initialState(processParams) : (null as TState);
1085
1100
 
1086
1101
  return {
1087
1102
  outputSchema,
1088
1103
  inputSchema: request.bind_call.input_schema,
1089
1104
  continuesOutput: true,
1090
- exchangeInit: () => ({ state, processParams, filterHistory: carriedFilterHistory, morePending: false }),
1105
+ // A rebuilt HTTP turn adopts the state its cursor carried.
1106
+ exchangeInit: (restored?: RestoredUserState) => ({
1107
+ state: restored ? (restored.state as TState) : freshState(),
1108
+ processParams,
1109
+ filterHistory: carriedFilterHistory,
1110
+ morePending: false,
1111
+ }),
1091
1112
  exchangeFn: async (
1092
1113
  eState: {
1093
1114
  state: TState;
@@ -2,6 +2,7 @@
2
2
  // Table function implementation.
3
3
  // Table functions produce output batches from arguments (no streaming input).
4
4
 
5
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
5
6
  import {
6
7
  type VgiSchema,
7
8
  type VgiBatch,
@@ -32,6 +33,7 @@ import type {
32
33
  FunctionMeta,
33
34
  StreamHandlers,
34
35
  FunctionExample,
36
+ RestoredUserState,
35
37
  } from "./types.js";
36
38
  import {
37
39
  constraintSpecFields,
@@ -330,7 +332,7 @@ export interface TableFunctionConfig<
330
332
  tags?: Record<string, string>;
331
333
  maxWorkers?: number;
332
334
  requiredSettings?: string[];
333
- requiredSecrets?: string[];
335
+ requiredSecrets?: RequiredSecret[];
334
336
  /** Row-order preservation behavior; flows to DuckDB's
335
337
  * TableFunction::order_preservation_type. */
336
338
  preservesOrder?: OrderPreservation;
@@ -412,7 +414,7 @@ export function defineTableFunction<
412
414
  parameterDefaultValues: config.parameterDefaultValues,
413
415
  maxWorkers: config.maxWorkers,
414
416
  requiredSettings: config.requiredSettings,
415
- requiredSecrets: config.requiredSecrets,
417
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
416
418
  preservesOrder: config.preservesOrder,
417
419
  nullHandling: config.nullHandling,
418
420
  orderDependent: config.orderDependent,
@@ -598,14 +600,16 @@ export function defineTableFunction<
598
600
  );
599
601
  }
600
602
 
601
- const state = config.initialState
602
- ? config.initialState(processParams)
603
- : (null as TState);
604
-
605
603
  return {
606
604
  outputSchema,
607
- producerInit: (): TableHandlerState<TArgs, TState> => ({
608
- state,
605
+ // initialState runs only for a fresh stream; a rebuilt HTTP turn
606
+ // adopts the state its cursor carried.
607
+ producerInit: (restored?: RestoredUserState): TableHandlerState<TArgs, TState> => ({
608
+ state: restored
609
+ ? (restored.state as TState)
610
+ : config.initialState
611
+ ? config.initialState(processParams)
612
+ : (null as TState),
609
613
  processParams,
610
614
  filterHistory: carriedFilterHistory,
611
615
  }),