@query-farm/vgi 0.45.0 → 0.46.0

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.45.0",
3
+ "version": "0.46.0",
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)",
@@ -87,16 +87,16 @@
87
87
  },
88
88
  "dependencies": {
89
89
  "@noble/ciphers": "^2.3.0",
90
- "@query-farm/flechette": "^2.4.1"
90
+ "@query-farm/flechette": "^2.7.1"
91
91
  },
92
92
  "peerDependencies": {
93
93
  "@query-farm/apache-arrow": "^21.1.1",
94
- "@query-farm/vgi-rpc": "^0.29.1"
94
+ "@query-farm/vgi-rpc": "^0.29.2"
95
95
  },
96
96
  "devDependencies": {
97
97
  "@duckdb/node-api": "^1.5.5-r.4",
98
98
  "@query-farm/apache-arrow": "^21.1.1",
99
- "@query-farm/vgi-rpc": "^0.29.1",
99
+ "@query-farm/vgi-rpc": "^0.29.2",
100
100
  "@types/bun": "latest",
101
101
  "typescript": "^7.0.2"
102
102
  },
@@ -9,9 +9,10 @@
9
9
  //
10
10
  // flechette's `columnFromArray` already handles the complex cases (List, Map,
11
11
  // Struct, Decimal, Timestamp[ns]) when given the right options, so the WRITE
12
- // side is mostly delegation. The one wrinkle is Date: flechette stores a Date
13
- // column correctly only when fed JS `Date` objects, but our canonical date32 is
14
- // a day-number and date64 is ms-bigint — so we convert canonical -> Date here.
12
+ // side is mostly delegation. Date32 needs epoch milliseconds rather than our
13
+ // canonical day-number. Date64 takes canonical bigint milliseconds directly:
14
+ // Flechette 2.7.1 preserves raw bigint storage, while Date/number inputs are
15
+ // normalized to midnight and would lose an existing time-of-day component.
15
16
  //
16
17
  // On the READ side, flechette's Column/Data `.at()` already decodes every
17
18
  // scalar to its canonical JS value LOSSLESSLY (timestamp/duration/time64 ->
@@ -88,7 +89,7 @@ export function writeCanonicalBatch(
88
89
 
89
90
  /**
90
91
  * Convert canonical values into the shape flechette's columnFromArray needs.
91
- * Date columns: canonical day-number / ms-bigint -> JS Date. Map columns:
92
+ * Date32 columns: canonical day-number -> JS Date; Date64 stays ms-bigint. Map columns:
92
93
  * canonical Array<[k,v]> -> Map. Struct/List recurse. Everything else passes
93
94
  * through.
94
95
  */
@@ -101,9 +102,10 @@ export function prepareForFlechette(type: VgiDataType, values: unknown[]): unkno
101
102
  const isDay = (type as any).unit === 0;
102
103
  return values.map((v) => {
103
104
  if (v == null) return null;
105
+ if (!isDay) return typeof v === "bigint" ? v : BigInt(v instanceof Date ? v.getTime() : v as number);
104
106
  if (v instanceof Date) return v;
105
107
  const n = typeof v === "bigint" ? Number(v) : (v as number);
106
- return new Date(isDay ? n * MS_PER_DAY : n);
108
+ return new Date(n * MS_PER_DAY);
107
109
  });
108
110
  }
109
111
  if (tid === 11 && (type as any).unit === MONTH_DAY_NANO) {
@@ -687,6 +687,12 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
687
687
  // mirrors Python's `input_from_args=False if is_scalar else ...`.
688
688
  input_from_args:
689
689
  f.kind === "table_in_out" && f.meta.inputFromArgs === true,
690
+ // Blended only: the most input rows per worker call (null = a whole
691
+ // chunk). Mirrors Python's `None if is_scalar else ...`.
692
+ input_rows_per_call:
693
+ f.kind === "table_in_out" && f.meta.inputFromArgs === true
694
+ ? (f.meta.inputRowsPerCall ?? null)
695
+ : null,
690
696
  required_settings: meta.requiredSettings,
691
697
  required_secrets: requiredSecrets.map((s) => ({
692
698
  secret_type: s.secret_type,
@@ -7,7 +7,9 @@ import { type VgiSchema, schema as schema_, type VgiField, field, type VgiBatch,
7
7
  // emits `import {} from "@query-farm/vgi-rpc"`, a side-effect import of the
8
8
  // package root — which re-exports the whole framework, server included, into
9
9
  // every browser bundle. See the note in ./errors.
10
- import type { RpcClient, StreamSession } from "@query-farm/vgi-rpc";
10
+ import type { RawStreamSession, RpcClient, StreamSession } from "@query-farm/vgi-rpc";
11
+ import { CACHE_NOT_MODIFIED_KEY } from "../cache-control.js";
12
+ import { CONTINUE, HAVE_MORE_OUTPUT, STATUS_KEY } from "../functions/continuation.js";
11
13
  import {
12
14
  serializeBindRequest,
13
15
  deserializeBindResponse,
@@ -25,6 +27,7 @@ import { Arguments } from "../arguments/arguments.js";
25
27
  import {
26
28
  batchFromRows,
27
29
  batchFromColumns,
30
+ emptyBatch,
28
31
  iterRows,
29
32
  } from "../util/arrow/index.js";
30
33
  import {
@@ -86,6 +89,74 @@ function onConflictName(onConflict: OnCreateConflict): string {
86
89
  return String(onConflict).toUpperCase();
87
90
  }
88
91
 
92
+ /** Whether reply metadata carries `vgi.cache.not_modified` set. */
93
+ function isNotModified(md: Map<string, string>): boolean {
94
+ const v = md.get(CACHE_NOT_MODIFIED_KEY);
95
+ return v != null && v !== "0" && v.toLowerCase() !== "false";
96
+ }
97
+
98
+ /**
99
+ * Send one input batch on a table-in-out exchange and yield the rows of every
100
+ * reply it gets (continued output, docs/table_in_out.md "Continued Output").
101
+ *
102
+ * A reply saying `vgi.status: HAVE_MORE_OUTPUT` has more output for the same
103
+ * input: ask for the next with a continuation tick (a zero-row batch of the
104
+ * input schema carrying `vgi.status: CONTINUE`) until a reply stops saying
105
+ * more. Only then may the next input go out, or the input close. The row-level
106
+ * `StreamSession.exchange` drops reply metadata, so this uses the raw exchange
107
+ * every transport's session implements.
108
+ *
109
+ * Refused, as the extension refuses them: `not_modified` on a reply that says
110
+ * more or answers a tick (a 304 stands for an input's whole output), and the
111
+ * worker ending the stream while output is pending.
112
+ *
113
+ * Exported for tests only (not re-exported from the package entry points).
114
+ * @internal
115
+ */
116
+ export async function* exchangeContinued(
117
+ session: StreamSession,
118
+ functionName: string,
119
+ input: VgiBatch,
120
+ ): AsyncGenerator<Record<string, any>[]> {
121
+ const raw = session as unknown as Partial<Pick<RawStreamSession, "exchangeRaw">>;
122
+ if (typeof raw.exchangeRaw !== "function") {
123
+ throw new VgiClientError(
124
+ `tableInOutFunction(${functionName}): the transport's stream session has no exchangeRaw(), ` +
125
+ `which continued output needs to read each reply's vgi.status`,
126
+ );
127
+ }
128
+ const exchangeRaw = raw.exchangeRaw.bind(session);
129
+ let tick = false;
130
+ let reply = await exchangeRaw({ batch: input as any, metadata: new Map() });
131
+ for (;;) {
132
+ if (reply === null) {
133
+ if (tick) {
134
+ throw new VgiClientError(
135
+ `tableInOutFunction(${functionName}): the worker ended the stream while output was pending`,
136
+ );
137
+ }
138
+ return;
139
+ }
140
+ const md = new Map<string, string>([...((reply.batch as any).metadata ?? []), ...reply.metadata]);
141
+ const more = md.get(STATUS_KEY) === HAVE_MORE_OUTPUT;
142
+ if (isNotModified(md) && (more || tick)) {
143
+ throw new VgiClientError(
144
+ `tableInOutFunction(${functionName}): the worker answered not_modified on a continued reply ` +
145
+ `(${tick ? "answering a continuation tick" : "one saying HAVE_MORE_OUTPUT"}); ` +
146
+ `not_modified must be an input's only reply`,
147
+ );
148
+ }
149
+ const rows = [...iterRows(reply.batch as unknown as VgiBatch)];
150
+ if (rows.length > 0) yield rows;
151
+ if (!more) return;
152
+ tick = true;
153
+ reply = await exchangeRaw({
154
+ batch: emptyBatch(input.schema) as any,
155
+ metadata: new Map([[STATUS_KEY, CONTINUE]]),
156
+ });
157
+ }
158
+ }
159
+
89
160
  /**
90
161
  * High-level client for calling VGI worker functions and catalog API.
91
162
  *
@@ -426,12 +497,9 @@ export class VgiClient {
426
497
  );
427
498
 
428
499
  try {
429
- const outRows = await inputSession.exchange([...iterRows(firstBatch)]);
430
- if (outRows.length > 0) yield outRows;
431
-
500
+ yield* exchangeContinued(inputSession, opts.functionName, firstBatch);
432
501
  for await (const batch of { [Symbol.asyncIterator]: () => inputIter }) {
433
- const result = await inputSession.exchange([...iterRows(batch)]);
434
- if (result.length > 0) yield result;
502
+ yield* exchangeContinued(inputSession, opts.functionName, batch);
435
503
  }
436
504
  } finally {
437
505
  inputSession.close();
@@ -507,12 +575,13 @@ export class VgiClient {
507
575
 
508
576
  const outputSchema = bindResp.output_schema;
509
577
  try {
510
- const outRows = await inputSession.exchange([...iterRows(firstBatch)]);
511
- if (outRows.length > 0) yield batchFromRows(outRows, outputSchema);
512
-
578
+ for await (const rows of exchangeContinued(inputSession, opts.functionName, firstBatch)) {
579
+ yield batchFromRows(rows, outputSchema);
580
+ }
513
581
  for await (const batch of { [Symbol.asyncIterator]: () => inputIter }) {
514
- const result = await inputSession.exchange([...iterRows(batch)]);
515
- if (result.length > 0) yield batchFromRows(result, outputSchema);
582
+ for await (const rows of exchangeContinued(inputSession, opts.functionName, batch)) {
583
+ yield batchFromRows(rows, outputSchema);
584
+ }
516
585
  }
517
586
  } finally {
518
587
  inputSession.close();
@@ -5,7 +5,8 @@
5
5
 
6
6
  import { type VgiBatch, type VgiSchema, isBatch } from "../arrow/index.js";
7
7
  import type { OutputCollector } from "@query-farm/vgi-rpc";
8
- import { batchFromColumns } from "../util/arrow/index.js";
8
+ import { batchFromColumns, filterBatch } from "../util/arrow/index.js";
9
+ import { decodeParentRows, encodeParentRows, PARENT_ROW_METADATA_KEY } from "../util/parent-rows.js";
9
10
  import { ComparisonOp, type FilterExpression } from "./types.js";
10
11
  import { expressionToSql, PushdownFilters } from "./evaluate.js";
11
12
 
@@ -108,6 +109,21 @@ export class FilteringOutputCollector {
108
109
  } else {
109
110
  batch = batchFromColumns(batchOrColumns as Record<string, any[]>, this.inner.outputSchema as any);
110
111
  }
112
+ const encoded = metadata?.get(PARENT_ROW_METADATA_KEY);
113
+ if (encoded !== undefined && batch.numRows > 0 && this.filters.filters.length > 0) {
114
+ // Provenance is per output row, so it must lose the rows the filter
115
+ // does: filter both with one mask. Mirrors vgi-python's
116
+ // _FilteringOutputCollector.
117
+ const mask = this.filters.evaluate(batch as any);
118
+ const parents = decodeParentRows(encoded);
119
+ const kept: number[] = [];
120
+ for (let i = 0; i < parents.length; i++) if (mask[i]) kept.push(parents[i]);
121
+ const md = new Map(metadata);
122
+ if (kept.length > 0) md.set(PARENT_ROW_METADATA_KEY, encodeParentRows(kept));
123
+ else md.delete(PARENT_ROW_METADATA_KEY);
124
+ this.inner.emit(filterBatch(batch as any, mask) as any, md);
125
+ return;
126
+ }
111
127
  const filtered = this.filters.apply(batch as any);
112
128
  this.inner.emit(filtered as any, metadata);
113
129
  }
@@ -0,0 +1,202 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Continued output (table-in-out exchange).
3
+ //
4
+ // A table-in-out exchange answers each input batch with one reply. A function
5
+ // can answer one input with several: it emits each reply but the last with
6
+ // `moreOutputMetadata(true)`, which puts `vgi.status: HAVE_MORE_OUTPUT` on the
7
+ // reply. The client then asks for the next reply with a continuation tick -- a
8
+ // zero-row batch of the input schema carrying `vgi.status: CONTINUE` -- and the
9
+ // framework answers it by calling the function's `resume()`. Every reply's
10
+ // parent rows index the last real (non-tick) input batch.
11
+ //
12
+ // `resume()` gets no input, so the function's state must hold where to resume.
13
+ // Over HTTP that state reaches the next turn only inside the stream's state
14
+ // token, so keep it small: positions to resume from, never buffered output rows.
15
+ //
16
+ // The protocol is strict, with no capability negotiation: while output is
17
+ // pending a tick is the only valid input, and a tick is valid only then. Cache
18
+ // control may only ride an input's first reply, and "more" is refused outside a
19
+ // table-in-out exchange. Mirrors vgi-python's `emit(more=True)` / `resume()`.
20
+
21
+ import type { OutputCollector } from "@query-farm/vgi-rpc";
22
+ import type { VgiBatch } from "../arrow/index.js";
23
+
24
+ /** Metadata key carrying a table-in-out exchange status, on the batch itself. */
25
+ export const STATUS_KEY = "vgi.status";
26
+ /** Reply status: this input has more output; ask for it with a tick. */
27
+ export const HAVE_MORE_OUTPUT = "HAVE_MORE_OUTPUT";
28
+ /** Input status: a continuation tick, asking for the last input's next reply. */
29
+ export const CONTINUE = "CONTINUE";
30
+
31
+ const CACHE_KEY_PREFIX = "vgi.cache.";
32
+
33
+ /**
34
+ * Mark an emitted table-in-out reply as one of several for the same input
35
+ * batch when `more` is true: the client asks for the next one with a
36
+ * continuation tick, which the framework answers through the function's
37
+ * `resume()`. `false` adds nothing, so the last reply can pass its own
38
+ * condition. Composes with {@link parentRowsMetadata} and
39
+ * `cacheControlMetadata` via `extra`:
40
+ *
41
+ * ```ts
42
+ * out.emit(batch, moreOutputMetadata(state.row < state.counts.length,
43
+ * parentRowsMetadata(parents, batch.numRows)));
44
+ * ```
45
+ *
46
+ * Valid only from the `process()` or `resume()` of a table-in-out function
47
+ * that implements `resume()`; the framework reads it off the emitted reply.
48
+ */
49
+ export function moreOutputMetadata(more: boolean, extra?: Map<string, string>): Map<string, string> {
50
+ const md = new Map<string, string>(extra ?? []);
51
+ if (more) md.set(STATUS_KEY, HAVE_MORE_OUTPUT);
52
+ return md;
53
+ }
54
+
55
+ /** The metadata the turn's data batch went out with (per-emit over batch-carried). */
56
+ function replyMetadata(out: OutputCollector): Map<string, string> | null {
57
+ const idx = out.dataBatchIdx;
58
+ if (idx == null) return null;
59
+ const emitted = out.batches[idx];
60
+ const md = new Map<string, string>((emitted.batch as any).metadata ?? []);
61
+ for (const [k, v] of emitted.metadata ?? []) md.set(k, v);
62
+ return md;
63
+ }
64
+
65
+ /**
66
+ * Refuse "more" on a stream that cannot continue: anything but a table-in-out
67
+ * exchange, where the client would never send the tick. Run by the dispatcher
68
+ * after every non-table-in-out turn.
69
+ */
70
+ export function refuseMoreOutput(name: string, out: OutputCollector): void {
71
+ if (replyMetadata(out)?.get(STATUS_KEY) === HAVE_MORE_OUTPUT) {
72
+ throw new Error(
73
+ `${name}: HAVE_MORE_OUTPUT (moreOutputMetadata) is only valid in a table-in-out ` +
74
+ `function's process() or resume()`,
75
+ );
76
+ }
77
+ }
78
+
79
+ /** The exchange state a continuable table-in-out turn reads and updates. */
80
+ export interface ContinuationState {
81
+ /**
82
+ * Whether the last reply said HAVE_MORE_OUTPUT, so the next input must be a
83
+ * tick. Carried in the HTTP state token (see protocol/state-serializer.ts).
84
+ */
85
+ morePending?: boolean;
86
+ }
87
+
88
+ /**
89
+ * Run one table-in-out exchange turn under the continued-output rules.
90
+ *
91
+ * Classifies the input (a tick or real input), refuses the inputs the protocol
92
+ * forbids, calls `run(tick)` -- which calls `process()` for real input and
93
+ * `resume()` for a tick -- and records from the emitted reply whether output is
94
+ * now pending.
95
+ *
96
+ * `resumable` is whether the function implements `resume()`: one that does not
97
+ * may not say more.
98
+ */
99
+ export async function continuationTurn(
100
+ name: string,
101
+ eState: ContinuationState,
102
+ input: VgiBatch,
103
+ out: OutputCollector,
104
+ resumable: boolean,
105
+ run: (tick: boolean) => Promise<void>,
106
+ ): Promise<void> {
107
+ // The status rides the input batch's own metadata; vgi-rpc also surfaces it
108
+ // on the collector, so read either.
109
+ const inputStatus =
110
+ ((input as any)?.metadata as Map<string, string> | undefined)?.get(STATUS_KEY) ??
111
+ out.inputMetadata?.get(STATUS_KEY);
112
+ const tick = inputStatus === CONTINUE;
113
+ if (tick && !eState.morePending) {
114
+ throw new Error(`${name}: continuation tick received, but no output is pending`);
115
+ }
116
+ if (tick && input.numRows !== 0) {
117
+ throw new Error(`${name}: a continuation tick must have no rows, got ${input.numRows}`);
118
+ }
119
+ if (!tick && eState.morePending) {
120
+ throw new Error(`${name}: input received while output is pending; expected a continuation tick`);
121
+ }
122
+
123
+ await run(tick);
124
+
125
+ const md = replyMetadata(out);
126
+ // One reply per turn: a turn that emits none leaves the client waiting on
127
+ // the byte-stream transports (and, over HTTP, answers with a token-only body
128
+ // the client cannot tell from an empty result). An empty answer is a 0-row
129
+ // batch. Matches vgi-rpc-python's OutputCollector.validate(). (Several data
130
+ // batches are already refused by vgi-rpc's OutputCollector.emit.)
131
+ if (md == null) {
132
+ throw new Error(
133
+ tick
134
+ ? `${name}: resume() must emit a batch for every continuation tick`
135
+ : `${name}: process() must emit a batch for every input batch (No data batch was emitted)`,
136
+ );
137
+ }
138
+ const more = md.get(STATUS_KEY) === HAVE_MORE_OUTPUT;
139
+ if (more && !resumable) {
140
+ throw new Error(`${name}: emitted HAVE_MORE_OUTPUT but does not implement resume()`);
141
+ }
142
+ if (tick) {
143
+ // Every tick must be answered (above), and never with cache control.
144
+ for (const key of md.keys()) {
145
+ if (key.startsWith(CACHE_KEY_PREFIX)) {
146
+ throw new Error(
147
+ `${name}: cache control is only valid on an input's first reply, ` +
148
+ `not on one answering a continuation tick (${key})`,
149
+ );
150
+ }
151
+ }
152
+ }
153
+ eState.morePending = more;
154
+ }
155
+
156
+ /**
157
+ * Refuse, at definition, a continuable function the client cannot drive.
158
+ *
159
+ * `resume()` continues from the function's state alone, so it needs an
160
+ * `initialState` (the state is what the HTTP token carries between turns).
161
+ * `maxWorkers: 1` runs the function on one connection shared by every
162
+ * pipeline, which cannot leave output pending while another's input waits.
163
+ */
164
+ export function checkResumeContract(
165
+ name: string,
166
+ config: { resume?: unknown; initialState?: unknown; maxWorkers?: number },
167
+ ): void {
168
+ if (config.resume == null) return;
169
+ if (typeof config.resume !== "function") {
170
+ throw new Error(`${name}: resume must be a function`);
171
+ }
172
+ if (config.maxWorkers === 1) {
173
+ throw new Error(
174
+ `${name}: resume() (continued output) is not supported with maxWorkers: 1; ` +
175
+ `the client runs such a function on one shared connection.`,
176
+ );
177
+ }
178
+ if (config.initialState == null) {
179
+ throw new Error(
180
+ `${name}: resume() continues from its state alone, so the function must ` +
181
+ `declare an initialState holding where to resume.`,
182
+ );
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Check `inputRowsPerCall`: a positive integer, on a blended row-transform
188
+ * function only (the extension refuses it at bind too).
189
+ */
190
+ export function checkInputRowsPerCall(name: string, value: unknown, blended: boolean): number | undefined {
191
+ if (value == null) return undefined;
192
+ if (!blended) {
193
+ throw new Error(
194
+ `${name}: inputRowsPerCall applies only to a blended row-transform function, ` +
195
+ `whose per-row input the client can split into calls`,
196
+ );
197
+ }
198
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) {
199
+ throw new Error(`${name}: inputRowsPerCall must be a positive integer, got ${String(value)}`);
200
+ }
201
+ return value;
202
+ }