@query-farm/vgi 0.48.0 → 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.
Files changed (98) hide show
  1. package/README.md +24 -1
  2. package/dist/arguments/argument-spec.d.ts +17 -11
  3. package/dist/catalog/descriptors.d.ts +16 -2
  4. package/dist/catalog/publication.d.ts +7 -7
  5. package/dist/catalog/read-only.d.ts +4 -5
  6. package/dist/client/client.d.ts +9 -3
  7. package/dist/client/errors.d.ts +2 -2
  8. package/dist/client/types.d.ts +21 -0
  9. package/dist/client-entry.d.ts +1 -1
  10. package/dist/client-entry.js +31 -7
  11. package/dist/client-entry.js.map +20 -20
  12. package/dist/filter-pushdown/deserialize.d.ts +1 -1
  13. package/dist/filter-pushdown/types.d.ts +10 -10
  14. package/dist/functions/registry.d.ts +1 -0
  15. package/dist/functions/scalar.d.ts +17 -6
  16. package/dist/functions/table-buffering.d.ts +20 -20
  17. package/dist/functions/table-in-out.d.ts +4 -4
  18. package/dist/functions/table.d.ts +7 -7
  19. package/dist/functions/types.d.ts +51 -47
  20. package/dist/http/fetch.d.ts +10 -10
  21. package/dist/index.core.d.ts +2 -2
  22. package/dist/index.js +201 -116
  23. package/dist/index.js.map +53 -52
  24. package/dist/protocol/dispatch.d.ts +3 -3
  25. package/dist/protocol/handlers/function.d.ts +2 -2
  26. package/dist/protocol/serializers/cardinality.d.ts +4 -1
  27. package/dist/protocol/types.d.ts +5 -5
  28. package/dist/rpc-server.d.ts +6 -6
  29. package/dist/serve-entry.d.ts +16 -16
  30. package/dist/serve-entry.js +47 -24
  31. package/dist/serve-entry.js.map +38 -37
  32. package/dist/split-token.d.ts +6 -6
  33. package/dist/types.d.ts +9 -2
  34. package/dist/util/defined.d.ts +21 -0
  35. package/dist/worker-cf-entry.js +164 -106
  36. package/dist/worker-cf-entry.js.map +51 -50
  37. package/dist/worker.d.ts +2 -2
  38. package/package.json +6 -4
  39. package/src/arguments/argument-spec.ts +17 -11
  40. package/src/arrow/codec/registry.ts +2 -2
  41. package/src/arrow/impl-arrowjs/build.ts +1 -1
  42. package/src/arrow/impl-arrowjs/canonical.ts +23 -23
  43. package/src/arrow/impl-arrowjs/empty.ts +2 -2
  44. package/src/arrow/impl-arrowjs/ipc.ts +2 -2
  45. package/src/arrow/impl-arrowjs/iterate.ts +2 -2
  46. package/src/arrow/impl-arrowjs/project.ts +2 -2
  47. package/src/arrow/impl-flechette/build.ts +2 -1
  48. package/src/arrow/impl-flechette/canonical.ts +10 -9
  49. package/src/arrow/impl-flechette/compat.ts +3 -3
  50. package/src/arrow/impl-flechette/message-meta.ts +5 -4
  51. package/src/arrow/impl-flechette/statistics.ts +2 -2
  52. package/src/attach-ticket.ts +2 -2
  53. package/src/catalog/column-metadata.ts +1 -1
  54. package/src/catalog/composite.ts +2 -2
  55. package/src/catalog/constraints.ts +9 -9
  56. package/src/catalog/descriptors.ts +15 -1
  57. package/src/catalog/interface.ts +12 -12
  58. package/src/catalog/publication.ts +9 -8
  59. package/src/catalog/read-only.ts +27 -21
  60. package/src/catalog/sql-grammar.ts +6 -6
  61. package/src/client/client.ts +52 -15
  62. package/src/client/errors.ts +1 -1
  63. package/src/client/types.ts +23 -0
  64. package/src/client-entry.ts +2 -0
  65. package/src/codec/asd.ts +3 -3
  66. package/src/codec/conform.ts +3 -3
  67. package/src/filter-pushdown/collector.ts +1 -1
  68. package/src/filter-pushdown/deserialize.ts +13 -10
  69. package/src/filter-pushdown/evaluate.ts +3 -2
  70. package/src/filter-pushdown/history.ts +3 -2
  71. package/src/filter-pushdown/types.ts +10 -10
  72. package/src/functions/continuation.ts +1 -1
  73. package/src/functions/projection.ts +1 -1
  74. package/src/functions/registry.ts +20 -17
  75. package/src/functions/scalar.ts +33 -11
  76. package/src/functions/storage-cf-do.ts +2 -2
  77. package/src/functions/table-buffering.ts +28 -21
  78. package/src/functions/table-in-out.ts +37 -17
  79. package/src/functions/table.ts +36 -31
  80. package/src/functions/types.ts +58 -48
  81. package/src/generated/vgi-service.ts +5 -3
  82. package/src/http/fetch.ts +17 -12
  83. package/src/index.core.ts +3 -1
  84. package/src/protocol/carried-init-request.ts +1 -1
  85. package/src/protocol/dispatch.ts +3 -3
  86. package/src/protocol/handlers/aggregate.ts +8 -7
  87. package/src/protocol/handlers/catalog/shared.ts +1 -1
  88. package/src/protocol/handlers/function.ts +18 -5
  89. package/src/protocol/serializers/cardinality.ts +16 -3
  90. package/src/protocol/state-serializer.ts +1 -1
  91. package/src/protocol/types.ts +5 -5
  92. package/src/rpc-server.ts +13 -12
  93. package/src/serve-entry.ts +18 -18
  94. package/src/split-token.ts +10 -9
  95. package/src/types.ts +9 -2
  96. package/src/util/defined.ts +30 -0
  97. package/src/util/parent-rows.ts +2 -2
  98. package/src/worker.ts +15 -14
@@ -32,12 +32,12 @@ export interface FunctionIdentity {
32
32
 
33
33
  export interface EvaluationContext {
34
34
  profile: string;
35
- timeZone?: string;
36
- calendar?: string;
37
- defaultCollation?: string;
38
- ieeeFloatingPointOps?: boolean;
39
- integerDivision?: boolean;
40
- providerFingerprint?: string;
35
+ timeZone?: string | undefined;
36
+ calendar?: string | undefined;
37
+ defaultCollation?: string | undefined;
38
+ ieeeFloatingPointOps?: boolean | undefined;
39
+ integerDivision?: boolean | undefined;
40
+ providerFingerprint?: string | undefined;
41
41
  }
42
42
 
43
43
  export type FilterExpression =
@@ -56,7 +56,7 @@ export type FilterExpression =
56
56
  node: "call";
57
57
  function: StandardFilterFunction | FunctionIdentity;
58
58
  arguments: FilterExpression[];
59
- options?: Record<string, unknown>;
59
+ options?: Record<string, unknown> | undefined;
60
60
  }
61
61
  | {
62
62
  node: "runtime_filter";
@@ -89,9 +89,9 @@ export interface FilterPredicate {
89
89
  }
90
90
 
91
91
  export interface FilterCapabilities {
92
- extensionFunctions?: ReadonlyArray<FunctionIdentity>;
93
- runtimeAlgorithms?: ReadonlyArray<FunctionIdentity>;
94
- evaluationContexts?: ReadonlyArray<{ profile: string; providerFingerprint?: string | null }>;
92
+ extensionFunctions?: ReadonlyArray<FunctionIdentity> | undefined;
93
+ runtimeAlgorithms?: ReadonlyArray<FunctionIdentity> | undefined;
94
+ evaluationContexts?: ReadonlyArray<{ profile: string; providerFingerprint?: string | null }> | undefined;
95
95
  }
96
96
 
97
97
  // Source aliases ease the protocol-2.0 transition for applications that imported
@@ -56,7 +56,7 @@ export function moreOutputMetadata(more: boolean, extra?: Map<string, string>):
56
56
  function replyMetadata(out: OutputCollector): Map<string, string> | null {
57
57
  const idx = out.dataBatchIdx;
58
58
  if (idx == null) return null;
59
- const emitted = out.batches[idx];
59
+ const emitted = out.batches[idx]!;
60
60
  const md = new Map<string, string>((emitted.batch as any).metadata ?? []);
61
61
  for (const [k, v] of emitted.metadata ?? []) md.set(k, v);
62
62
  return md;
@@ -196,7 +196,7 @@ export function validateProjectionAcceptance(
196
196
  const expected = schema(
197
197
  [
198
198
  ...p.bindResult.output_schema.fields,
199
- ...r.acceptedIndices.map((i) => p.resultSchema.fields[i]),
199
+ ...r.acceptedIndices.map((i) => p.resultSchema.fields[i]!),
200
200
  ],
201
201
  p.bindResult.output_schema.metadata,
202
202
  );
@@ -73,11 +73,11 @@ function scoreTypes(
73
73
  let varArgsSpec: ArgumentSpec | null = null;
74
74
 
75
75
  for (let i = 0; i < specs.length; i++) {
76
- const spec = specs[i];
76
+ const spec = specs[i]!;
77
77
  if (spec.isVarargs) varArgsSpec = spec;
78
78
  if (i >= actualTypes.length) break;
79
79
  if (spec.isAnyType || isNull(spec.arrowType)) continue;
80
- const actual = actualTypes[i];
80
+ const actual = actualTypes[i]!;
81
81
  if (actual === null) continue;
82
82
  if (typesIdentical(actual, spec.arrowType)) {
83
83
  score += EXACT_MATCH_SCORE;
@@ -91,7 +91,7 @@ function scoreTypes(
91
91
  // Score varargs tail beyond declared specs
92
92
  if (varArgsSpec && !varArgsSpec.isAnyType && !isNull(varArgsSpec.arrowType)) {
93
93
  for (let i = specs.length; i < actualTypes.length; i++) {
94
- const actual = actualTypes[i];
94
+ const actual = actualTypes[i]!;
95
95
  if (actual === null) continue;
96
96
  if (typesIdentical(actual, varArgsSpec.arrowType)) {
97
97
  score += EXACT_MATCH_SCORE;
@@ -141,13 +141,13 @@ function filterByArgumentTypes(
141
141
  for (const spec of colSpecs) {
142
142
  if (spec.isVarargs) varArgsColSpec = spec;
143
143
  const pos = spec.position as number;
144
- colTypes.push(pos < inputSchema.fields.length ? inputSchema.fields[pos].type : null);
144
+ colTypes.push(pos < inputSchema.fields.length ? inputSchema.fields[pos]!.type : null);
145
145
  }
146
146
  // Append varargs tail from inputSchema
147
147
  if (varArgsColSpec) {
148
148
  const start = (varArgsColSpec.position as number) + 1;
149
149
  for (let i = start; i < inputSchema.fields.length; i++) {
150
- colTypes.push(inputSchema.fields[i].type);
150
+ colTypes.push(inputSchema.fields[i]!.type);
151
151
  }
152
152
  }
153
153
  const r2 = scoreTypes(colSpecs, colTypes);
@@ -175,11 +175,11 @@ function filterByArgumentTypes(
175
175
  for (const spec of posSpecs) {
176
176
  if (spec.isVarargs) varArgsSpec = spec;
177
177
  const pos = spec.position as number;
178
- posTypes.push(pos < inputSchema.fields.length ? inputSchema.fields[pos].type : null);
178
+ posTypes.push(pos < inputSchema.fields.length ? inputSchema.fields[pos]!.type : null);
179
179
  }
180
180
  if (varArgsSpec) {
181
181
  for (let i = (varArgsSpec.position as number) + 1; i < inputSchema.fields.length; i++) {
182
- posTypes.push(inputSchema.fields[i].type);
182
+ posTypes.push(inputSchema.fields[i]!.type);
183
183
  }
184
184
  }
185
185
  }
@@ -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
  /**
@@ -317,16 +320,16 @@ export class FunctionRegistry {
317
320
  ): VgiFunction {
318
321
  // Fast path: single candidate
319
322
  if (candidates.length === 1) {
320
- return candidates[0];
323
+ return candidates[0]!;
321
324
  }
322
325
 
323
326
  // No context: return first (backward compat)
324
327
  if (!context?.arguments) {
325
- return candidates[0];
328
+ return candidates[0]!;
326
329
  }
327
330
 
328
331
  const args = context.arguments;
329
- const isScalar = context.isScalar ?? (candidates[0].kind === "scalar");
332
+ const isScalar = context.isScalar ?? (candidates[0]!.kind === "scalar");
330
333
 
331
334
  // Stage 1: Count-based filtering
332
335
  let matches: VgiFunction[];
@@ -391,7 +394,7 @@ export class FunctionRegistry {
391
394
  }
392
395
 
393
396
  if (matches.length === 1) {
394
- return matches[0];
397
+ return matches[0]!;
395
398
  }
396
399
 
397
400
  // Stage 2: Type-based filtering
@@ -403,14 +406,14 @@ export class FunctionRegistry {
403
406
  );
404
407
 
405
408
  if (typeFiltered.length === 1) {
406
- return typeFiltered[0];
409
+ return typeFiltered[0]!;
407
410
  }
408
411
  if (typeFiltered.length > 1) {
409
- return typeFiltered[0]; // Best score wins
412
+ return typeFiltered[0]!; // Best score wins
410
413
  }
411
414
 
412
415
  // Fallback: return first candidate
413
- return candidates[0];
416
+ return candidates[0]!;
414
417
  }
415
418
 
416
419
  has(name: string): boolean {
@@ -94,7 +94,7 @@ export interface ScalarParameterDef {
94
94
  gt?: number;
95
95
  /** Exclusive upper bound, `<` (folded into `vgi_range`). */
96
96
  lt?: number;
97
- /** Regex the value must match (surfaced as `vgi_pattern`). */
97
+ /** Regex the value must match (surfaced as `vgi_pattern`); an unanchored search — anchor with `^...$` for a full match. */
98
98
  pattern?: string;
99
99
  /** Default value (surfaced as `vgi_default`, JSON-encoded). */
100
100
  default?: unknown;
@@ -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;
@@ -427,13 +449,13 @@ export function defineScalarFunction<
427
449
  // so complex types (Decimal, BigInt-backed Timestamp/Duration,
428
450
  // List, Map, Struct) are built via our buildColumnData. The `repr`
429
451
  // selects raw<->canonical (branded) vs rich<->canonical conversion.
430
- const fieldName = outputSchema.fields[0].name;
452
+ const fieldName = outputSchema.fields[0]!.name;
431
453
  outputBatch = batchFromColumns({ [fieldName]: result }, outputSchema, repr);
432
454
  } else {
433
455
  // User returned an Arrow Vector / typed-array-shaped column. Iterate
434
456
  // it into a JS array and re-route through batchFromColumns. Adds an
435
457
  // O(n) copy but matches both backends' contract.
436
- const fieldName = outputSchema.fields[0].name;
458
+ const fieldName = outputSchema.fields[0]!.name;
437
459
  outputBatch = batchFromColumns({ [fieldName]: [...(result as Iterable<any>)] }, outputSchema, repr);
438
460
  }
439
461
 
@@ -273,7 +273,7 @@ function newAttemptId(): string {
273
273
  const b = new Uint8Array(16);
274
274
  crypto.getRandomValues(b);
275
275
  let s = "";
276
- for (let i = 0; i < 16; i++) s += b[i].toString(16).padStart(2, "0");
276
+ for (let i = 0; i < 16; i++) s += b[i]!.toString(16).padStart(2, "0");
277
277
  return s;
278
278
  }
279
279
 
@@ -286,7 +286,7 @@ function int64FromKey(b: Uint8Array): number {
286
286
 
287
287
  function bytesToB64(buf: Uint8Array): string {
288
288
  let binary = "";
289
- for (let i = 0; i < buf.length; i++) binary += String.fromCharCode(buf[i]);
289
+ for (let i = 0; i < buf.length; i++) binary += String.fromCharCode(buf[i]!);
290
290
  return btoa(binary);
291
291
  }
292
292
 
@@ -109,16 +109,16 @@ export interface TableBufferingConfig<
109
109
  TState = any,
110
110
  > {
111
111
  name: string;
112
- description?: string;
113
- args?: Record<string, VgiDataType>;
114
- namedArgs?: Record<string, VgiDataType>;
115
- argDefaults?: Record<string, any>;
112
+ description?: string | undefined;
113
+ args?: Record<string, VgiDataType> | undefined;
114
+ namedArgs?: Record<string, VgiDataType> | undefined;
115
+ argDefaults?: Record<string, any> | undefined;
116
116
  /** Authoritative typed defaults: one row, defaulted parameters only. */
117
- parameterDefaultValues?: VgiBatch | null;
117
+ parameterDefaultValues?: VgiBatch | null | undefined;
118
118
  /** Argument descriptions keyed by argument name. */
119
- argDocs?: Record<string, string>;
119
+ argDocs?: Record<string, string> | undefined;
120
120
  /** Discovery constraints, also enforced for scalar arguments at bind. */
121
- argConstraints?: Record<string, ArgumentConstraints>;
121
+ argConstraints?: Record<string, ArgumentConstraints> | undefined;
122
122
  /** Bind: default passes through input schema. May be async. Return non-empty
123
123
  * `lookupSecret*` lists on the first pass to request DuckDB secrets; the
124
124
  * connector then re-binds with `resolvedSecretsProvided` and the resolved
@@ -164,22 +164,22 @@ export interface TableBufferingConfig<
164
164
  params: TableBufferingBindParams<TArgs>,
165
165
  ) => TableCardinality | Promise<TableCardinality>;
166
166
  // Metadata
167
- projectionPushdown?: boolean;
168
- filterPushdown?: boolean;
169
- autoApplyFilters?: boolean;
167
+ projectionPushdown?: boolean | undefined;
168
+ filterPushdown?: boolean | undefined;
169
+ autoApplyFilters?: boolean | undefined;
170
170
  /** Force ParallelSink=false in the C++ operator (single-thread ingest). */
171
- sinkOrderDependent?: boolean;
171
+ sinkOrderDependent?: boolean | undefined;
172
172
  /** Force serial Source drain in finalize_queue order. */
173
- sourceOrderDependent?: boolean;
173
+ sourceOrderDependent?: boolean | undefined;
174
174
  /** Thread DuckDB's per-chunk batch_index into every process() call. */
175
- requiresInputBatchIndex?: boolean;
176
- stability?: FunctionStability;
177
- examples?: FunctionExample[];
178
- categories?: string[];
179
- tags?: Record<string, string>;
180
- maxWorkers?: number;
181
- requiredSettings?: string[];
182
- requiredSecrets?: string[];
175
+ requiresInputBatchIndex?: boolean | undefined;
176
+ stability?: FunctionStability | undefined;
177
+ examples?: FunctionExample[] | undefined;
178
+ categories?: string[] | undefined;
179
+ tags?: Record<string, string> | undefined;
180
+ maxWorkers?: number | undefined;
181
+ requiredSettings?: string[] | undefined;
182
+ requiredSecrets?: string[] | undefined;
183
183
  }
184
184
 
185
185
  /**
@@ -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)) {
@@ -479,7 +482,7 @@ function makeProjectingCollector(
479
482
  function alreadyMatches(batch: VgiBatch): boolean {
480
483
  if (batch.schema.fields.length !== targetSchema.fields.length) return false;
481
484
  for (let i = 0; i < targetSchema.fields.length; i++) {
482
- if (batch.schema.fields[i].name !== targetSchema.fields[i].name) return false;
485
+ if (batch.schema.fields[i]!.name !== targetSchema.fields[i]!.name) return false;
483
486
  }
484
487
  return true;
485
488
  }
@@ -589,6 +592,10 @@ function concatLenPrefixed(parts: Uint8Array[]): Uint8Array {
589
592
  return out;
590
593
  }
591
594
 
595
+ // Always returns exactly `count` parts (a short buffer throws a RangeError from
596
+ // the DataView), which the overloads encode as a tuple.
597
+ function splitLenPrefixed(buf: Uint8Array, count: 2): [Uint8Array, Uint8Array];
598
+ function splitLenPrefixed(buf: Uint8Array, count: 3): [Uint8Array, Uint8Array, Uint8Array];
592
599
  function splitLenPrefixed(buf: Uint8Array, count: number): Uint8Array[] {
593
600
  const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
594
601
  const parts: Uint8Array[] = [];
@@ -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 {
@@ -74,7 +75,7 @@ export interface TableInOutProcessParams<TArgs = Record<string, any>> {
74
75
  outputSchema: VgiSchema;
75
76
  settings: Record<string, any>;
76
77
  secrets: Record<string, Record<string, any>>;
77
- pushdownFilters?: PushdownFilters;
78
+ pushdownFilters?: PushdownFilters | undefined;
78
79
  /** Shared storage for cross-phase and cross-worker data (SQLite-backed). */
79
80
  storage: BoundStorage;
80
81
  /**
@@ -88,7 +89,7 @@ export interface TableInOutProcessParams<TArgs = Record<string, any>> {
88
89
  * `null`/`undefined` for a client that sent none. Mirrors vgi-python's
89
90
  * `ProcessParams.substream_id`.
90
91
  */
91
- substreamId?: Uint8Array | null;
92
+ substreamId?: Uint8Array | null | undefined;
92
93
  /**
93
94
  * Conditional-revalidation validator (exchange-mode result cache): the
94
95
  * client holds a stale cached result for THIS input unit and asks the
@@ -97,10 +98,10 @@ export interface TableInOutProcessParams<TArgs = Record<string, any>> {
97
98
  * of recomputing. Rides the input batch's custom metadata (attached by the
98
99
  * C++ WriteInputBatch). Undefined on a normal call.
99
100
  */
100
- ifNoneMatch?: string;
101
+ ifNoneMatch?: string | undefined;
101
102
  /** RFC 3339 Last-Modified validator for conditional revalidation.
102
103
  * Companion to {@link ifNoneMatch}. Undefined on a normal call. */
103
- ifModifiedSince?: string;
104
+ ifModifiedSince?: string | undefined;
104
105
  }
105
106
 
106
107
  // ============================================================================
@@ -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)
@@ -466,7 +474,7 @@ export function defineTableInOutFunction<
466
474
  out.finish();
467
475
  return;
468
476
  }
469
- const [logId, bytes] = rows[0];
477
+ const [logId, bytes] = rows[0]!;
470
478
  out.emit(deserializeBatch(bytes) as unknown as VgiBatch);
471
479
  pState.state.cursor = logId;
472
480
  },
@@ -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;
@@ -579,7 +593,7 @@ export function defineTableInOutFunction<
579
593
  * see a stale validator.
580
594
  */
581
595
  function applyRevalidationValidators(
582
- params: { ifNoneMatch?: string; ifModifiedSince?: string },
596
+ params: { ifNoneMatch?: string | undefined; ifModifiedSince?: string | undefined },
583
597
  input: VgiBatch,
584
598
  ): void {
585
599
  const md: Map<string, string> | undefined = (input as any)?.metadata;
@@ -594,7 +608,7 @@ function applyRevalidationValidators(
594
608
  * once per stream). See `filter-pushdown/history.ts`.
595
609
  */
596
610
  function applyDynamicFilterUpdate(
597
- eState: { processParams: { pushdownFilters?: PushdownFilters }; filterHistory: FilterDeltaHistory },
611
+ eState: { processParams: { pushdownFilters?: PushdownFilters | undefined }; filterHistory: FilterDeltaHistory },
598
612
  input: VgiBatch,
599
613
  ): void {
600
614
  const encoded = ((input as any)?.metadata as Map<string, string> | undefined)?.get("vgi_pushdown_filters");
@@ -660,7 +674,7 @@ function makeSchemaReconcilingCollector(
660
674
  const batchFields = batch.schema.fields;
661
675
  if (
662
676
  batchFields.length === targetSchema.fields.length &&
663
- targetSchema.fields.every((f, i) => batchFields[i].name === f.name)
677
+ targetSchema.fields.every((f, i) => batchFields[i]!.name === f.name)
664
678
  ) {
665
679
  return batch;
666
680
  }
@@ -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;