@query-farm/vgi 0.50.1 → 0.52.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.
Files changed (84) hide show
  1. package/README.md +45 -3
  2. package/dist/client-entry.js +833 -775
  3. package/dist/client-entry.js.map +10 -10
  4. package/dist/functions/aggregate.d.ts +25 -21
  5. package/dist/functions/execution-cache.d.ts +11 -0
  6. package/dist/functions/storage-blobs.d.ts +173 -0
  7. package/dist/functions/storage-cf-do.d.ts +50 -0
  8. package/dist/functions/storage-seal.d.ts +27 -0
  9. package/dist/functions/storage.d.ts +71 -1
  10. package/dist/functions/table-buffering.d.ts +30 -0
  11. package/dist/functions/table.d.ts +6 -1
  12. package/dist/generated/vgi-client.d.ts +7 -1
  13. package/dist/generated/vgi-protocol-schemas.d.ts +10 -9
  14. package/dist/generated/vgi-protocol-types.d.ts +244 -2
  15. package/dist/generated/vgi-service.d.ts +1 -1
  16. package/dist/hosted.d.ts +117 -0
  17. package/dist/http/blob-vendor.d.ts +33 -0
  18. package/dist/http/fetch.d.ts +60 -2
  19. package/dist/http/hosted-auth.d.ts +45 -0
  20. package/dist/index.core.d.ts +11 -3
  21. package/dist/index.js +8661 -6677
  22. package/dist/index.js.map +52 -34
  23. package/dist/protocol/arguments-ref.d.ts +107 -0
  24. package/dist/protocol/dispatch.d.ts +12 -2
  25. package/dist/protocol/handlers/aggregate.d.ts +1 -1
  26. package/dist/protocol/handlers/catalog/shared.d.ts +10 -0
  27. package/dist/protocol/handlers/function.d.ts +23 -0
  28. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  29. package/dist/protocol/serialize.d.ts +1 -1
  30. package/dist/protocol/serializers/bind.d.ts +27 -1
  31. package/dist/protocol/serializers/cardinality.d.ts +1 -1
  32. package/dist/protocol/serializers/splits.d.ts +7 -0
  33. package/dist/protocol/state-serializer.d.ts +8 -7
  34. package/dist/protocol/stream-init.d.ts +17 -0
  35. package/dist/protocol/types.d.ts +32 -0
  36. package/dist/secrets/lookups.d.ts +31 -0
  37. package/dist/serve-entry.d.ts +41 -6
  38. package/dist/serve-entry.js +8531 -6302
  39. package/dist/serve-entry.js.map +52 -35
  40. package/dist/worker-cf-entry.d.ts +5 -0
  41. package/dist/worker-cf-entry.js +7191 -4990
  42. package/dist/worker-cf-entry.js.map +59 -41
  43. package/package.json +5 -4
  44. package/src/functions/aggregate.ts +101 -152
  45. package/src/functions/copy-from.ts +2 -2
  46. package/src/functions/execution-cache.ts +59 -0
  47. package/src/functions/storage-blobs.ts +654 -0
  48. package/src/functions/storage-cf-do.ts +176 -22
  49. package/src/functions/storage-seal.ts +208 -0
  50. package/src/functions/storage.ts +174 -8
  51. package/src/functions/table-buffering.ts +104 -18
  52. package/src/functions/table-in-out.ts +3 -1
  53. package/src/functions/table.ts +12 -8
  54. package/src/generated/vgi-client.ts +9 -2
  55. package/src/generated/vgi-protocol-schemas.ts +115 -107
  56. package/src/generated/vgi-protocol-types.ts +640 -3
  57. package/src/generated/vgi-service.ts +2 -2
  58. package/src/hosted.ts +254 -0
  59. package/src/http/blob-vendor.ts +80 -0
  60. package/src/http/fetch.ts +179 -8
  61. package/src/http/hosted-auth.ts +326 -0
  62. package/src/index.core.ts +66 -1
  63. package/src/protocol/arguments-ref.ts +260 -0
  64. package/src/protocol/dispatch.ts +15 -4
  65. package/src/protocol/handlers/aggregate.ts +123 -82
  66. package/src/protocol/handlers/catalog/shared.ts +20 -0
  67. package/src/protocol/handlers/function.ts +135 -59
  68. package/src/protocol/handlers/table-buffering.ts +49 -32
  69. package/src/protocol/serialize.ts +3 -0
  70. package/src/protocol/serializers/bind.ts +96 -69
  71. package/src/protocol/serializers/cardinality.ts +4 -7
  72. package/src/protocol/serializers/init.ts +5 -11
  73. package/src/protocol/serializers/splits.ts +31 -4
  74. package/src/protocol/state-serializer.ts +27 -39
  75. package/src/protocol/stream-init.ts +87 -0
  76. package/src/protocol/types.ts +33 -0
  77. package/src/secrets/lookups.ts +53 -0
  78. package/src/serve-entry.ts +138 -11
  79. package/src/worker-cf-entry.ts +33 -0
  80. package/src/worker.ts +25 -0
  81. package/dist/protocol/carried-init-request.d.ts +0 -28
  82. package/dist/util/zstd-sync.d.ts +0 -7
  83. package/src/protocol/carried-init-request.ts +0 -139
  84. package/src/util/zstd-sync.ts +0 -50
@@ -3,10 +3,13 @@
3
3
  // ArrowSerializableDataclass field declaration order so the format is
4
4
  // positional-compatible with the Python reader.
5
5
 
6
- import { type VgiSchema, schema, field, type VgiBatch, type VgiDataType, utf8, binary, bool, struct, dictionary, int16, list } from "../../arrow/index.js";
7
- import { Arguments } from "../../arguments/arguments.js";
6
+ import type { VgiSchema, VgiBatch } from "../../arrow/index.js";
8
7
  import { FunctionType } from "../../types.js";
9
- import type { BindRequest, BindResponse, BindRepeatability, CopyFromContext, CopyToContext } from "../types.js";
8
+ import type { ArgumentsLocation, BindRequest, BindResponse, BindRepeatability, CopyFromContext, CopyToContext } from "../types.js";
9
+ import { BindRequestSchema } from "../../generated/vgi-protocol-schemas.js";
10
+ import { nestedBindRequest, type BindRequest as WireBindRequest, type Nested } from "../../generated/vgi-protocol-types.js";
11
+ import { toUint8Array as toUint8ArrayBase } from "../../util/bytes.js";
12
+ import { invalidArgumentsRef, invalidBindRequest, unresolvedArguments } from "../arguments-ref.js";
10
13
  import {
11
14
  serializeSchema,
12
15
  deserializeSchema,
@@ -16,62 +19,44 @@ import {
16
19
  import { toUint8Array, buildSingleRowBatch } from "./shared.js";
17
20
  import { serializeArguments, deserializeArguments } from "./arguments.js";
18
21
 
19
- // The BindRequest wire record. This must equal `BindRequestSchema` in
20
- // src/generated/vgi-protocol-schemas.ts EXACTLY — same columns, same order,
21
- // same types, same nullability — and src/__tests__/wire-schema-completeness.ts
22
- // asserts that it does.
23
- //
24
- // Exactly, not approximately. It is tempting to reason that every peer reads
25
- // these columns by name, so a nullable column with nothing to say can be left
26
- // out and a bind that opens no COPY scan can keep a shorter "legacy" shape.
27
- // That is what this file used to do, and it is wrong: vgi-rpc-go validates a
28
- // request against its declared parameter contract with `arrow.Schema.Equal`,
29
- // which is order-, name-, type- AND nullability-sensitive. A record short one
30
- // nullable column fails EVERY call of that shape, with a message that prints
31
- // two schemas in full and leaves the reader to diff them by eye.
32
- //
33
- // So `copy_from` and `copy_to` are always present and null on a non-COPY bind,
34
- // `schema_path` and `argument_names` are last, and `function_type` is a dictionary
35
- // rather than plain utf8.
36
- const COPY_FROM_STRUCT_TYPE = struct([
37
- field("format", utf8(), false),
38
- field("file_path", utf8(), false),
39
- field("expected_schema", binary(), false),
40
- ]);
41
-
42
- const COPY_TO_STRUCT_TYPE = struct([
43
- field("format", utf8(), false),
44
- field("file_path", utf8(), false),
45
- ]);
46
-
47
- const BIND_REQUEST_SCHEMA = schema([
48
- field("function_name", utf8(), false),
49
- field("arguments", binary(), false),
50
- field("function_type", dictionary(utf8(), int16()), false),
51
- field("input_schema", binary(), true),
52
- field("settings", binary(), true),
53
- field("secrets", binary(), true),
54
- field("attach_opaque_data", binary(), true),
55
- field("transaction_opaque_data", binary(), true),
56
- field("resolved_secrets_provided", bool(), false),
57
- // Time travel AT clause. Both null when the scan has no AT clause.
58
- field("at_unit", utf8(), true),
59
- field("at_value", utf8(), true),
60
- // Null unless this bind opens a COPY scan / sink.
61
- field("copy_from", COPY_FROM_STRUCT_TYPE, true),
62
- field("copy_to", COPY_TO_STRUCT_TYPE, true),
63
- // Catalog schema owning the function. A worker may register one name in
64
- // several schemas, so the bare name is not a unique key — resolution is by
65
- // (schema_path, function_name). Null for callers with no catalog context.
66
- field("schema_path", list(field("item", utf8(), true)), true),
67
- // Complete resolved logical signature, including const args and varargs.
68
- field("argument_names", list(field("item", utf8(), true)), true),
69
- ]);
22
+ // The BindRequest wire record is the GENERATED `BindRequestSchema`
23
+ // (src/generated/vgi-protocol-schemas.ts), not a hand-written copy. A copy
24
+ // has to equal it exactly -- vgi-rpc-go validates a request against its
25
+ // declared parameter contract with `arrow.Schema.Equal`, which is order-,
26
+ // name-, type- AND nullability-sensitive -- and the hand-written one this file
27
+ // used to carry went stale the moment protocol 3.4 made `arguments` nullable
28
+ // and appended `arguments_location`.
29
+ const BIND_REQUEST_SCHEMA = BindRequestSchema as unknown as VgiSchema;
30
+
31
+ /**
32
+ * The bytes each decoded bind call was received as, held in the generated
33
+ * raw-preserving wrapper (vgi docs/large-values-3.4.md §3.3). Keyed by the
34
+ * domain object, so a copy (`{ ...bindCall, x }`) has none and serializes from
35
+ * its fields, while the decoded object itself -- even after the framework
36
+ * opened its sealed attach / transaction in place -- re-encodes as exactly the
37
+ * bytes the client sent (§3.3 rule 11: opened values live beside the wrapper,
38
+ * never in it).
39
+ */
40
+ const receivedBindCalls = new WeakMap<object, Nested<WireBindRequest>>();
41
+
42
+ /** The wrapper holding the bytes `bindCall` was decoded from, or `undefined` for one built from fields. */
43
+ export function receivedBindCall(bindCall: BindRequest): Nested<WireBindRequest> | undefined {
44
+ return receivedBindCalls.get(bindCall);
45
+ }
46
+
47
+ /** The bind call's wire bytes: the bytes it was received as, else a fresh serialization of its fields. */
48
+ export function bindCallBytes(bindCall: BindRequest): Uint8Array {
49
+ return receivedBindCalls.get(bindCall)?.bytes ?? serializeBatch(serializeBindRequest(bindCall));
50
+ }
70
51
 
71
52
  export function serializeBindRequest(req: BindRequest): VgiBatch {
53
+ // A bind call that arrived by reference re-serializes as that reference,
54
+ // never as the resolved value (large-values spec §6: anything that
55
+ // re-serializes an init request emits `arguments_location`).
56
+ const location = req.arguments_location ?? null;
72
57
  return buildSingleRowBatch(BIND_REQUEST_SCHEMA, {
73
58
  function_name: req.function_name,
74
- arguments: serializeArguments(req.arguments),
59
+ arguments: location ? null : serializeArguments(req.arguments),
75
60
  // The wire carries the Python enum member NAME ("TABLE"), not the TS
76
61
  // enum's value ("table"); each FunctionType value upper-cases to its name.
77
62
  function_type: req.function_type == null ? req.function_type : String(req.function_type).toUpperCase(),
@@ -95,6 +80,9 @@ export function serializeBindRequest(req: BindRequest): VgiBatch {
95
80
  : null,
96
81
  schema_path: req.schema_path ?? null,
97
82
  argument_names: req.argument_names ?? null,
83
+ arguments_location: location
84
+ ? { ref: location.ref, size: BigInt(location.size), sha256: location.sha256 }
85
+ : null,
98
86
  });
99
87
  }
100
88
 
@@ -123,14 +111,41 @@ function parseCopyToContext(raw: any): CopyToContext | null {
123
111
  return { format: String(format), file_path: String(filePath) };
124
112
  }
125
113
 
114
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
115
+
116
+ /** Validate and normalise a received `arguments_location` (large-values spec §2). */
117
+ function parseArgumentsLocation(raw: any): ArgumentsLocation {
118
+ const size = typeof raw.size === "bigint" ? Number(raw.size) : Number(raw.size);
119
+ if (!Number.isSafeInteger(size) || size < 1) {
120
+ throw invalidArgumentsRef("arguments_location.size must be a positive byte count");
121
+ }
122
+ const sha256 = raw.sha256 == null ? "" : String(raw.sha256);
123
+ if (!SHA256_HEX.test(sha256)) {
124
+ throw invalidArgumentsRef("arguments_location.sha256 must be 64 lowercase hex digits");
125
+ }
126
+ if (raw.ref == null) throw invalidArgumentsRef("arguments_location.ref is missing");
127
+ return { ref: toUint8ArrayBase(raw.ref), size, sha256 };
128
+ }
129
+
130
+ /**
131
+ * Decode a bind request from a dict of its wire columns (the generated
132
+ * decoder's record, or `batchToScalarDict` of the one-row batch).
133
+ *
134
+ * Exactly one of `arguments` and `arguments_location` must be set (protocol
135
+ * 3.4); anything else is refused with `invalid_bind_request`. When the
136
+ * arguments came by reference the returned bind call's `arguments` is a
137
+ * placeholder that throws until the framework resolves it at the turn's entry
138
+ * (`resolveBindCall`, protocol/arguments-ref.ts); `arguments_location` keeps
139
+ * the location it arrived with.
140
+ */
126
141
  export function deserializeBindRequest(
127
142
  params: Record<string, any>
128
143
  ): BindRequest {
129
- // params come from the RPC layer - already extracted from a single-row batch
130
- // arguments may be null/undefined when DuckDB sends empty args
131
- const args = params.arguments
132
- ? deserializeArguments(toUint8Array(params.arguments))
133
- : new Arguments();
144
+ const hasArguments = params.arguments != null;
145
+ const hasLocation = params.arguments_location != null;
146
+ if (hasArguments === hasLocation) throw invalidBindRequest();
147
+ const location = hasLocation ? parseArgumentsLocation(params.arguments_location) : null;
148
+ const args = location ? unresolvedArguments() : deserializeArguments(toUint8ArrayBase(params.arguments));
134
149
 
135
150
  // function_type might be a string directly or enum name
136
151
  let functionType: FunctionType;
@@ -181,9 +196,26 @@ export function deserializeBindRequest(
181
196
  copy_from: parseCopyFromContext(params.copy_from),
182
197
  // COPY ... TO context — absent for ordinary scans / COPY FROM.
183
198
  copy_to: parseCopyToContext(params.copy_to),
199
+ arguments_location: location,
184
200
  };
185
201
  }
186
202
 
203
+ /**
204
+ * Decode a received bind call from its bytes through the generated
205
+ * raw-preserving wrapper: the domain object re-encodes as exactly these bytes
206
+ * ({@link bindCallBytes}) for as long as it lives, whatever the framework opens
207
+ * on it in place.
208
+ *
209
+ * @param source The bind call's bytes, or a wrapper already holding them.
210
+ * @param path The field path decode errors name (`InitRequest.bind_call`).
211
+ */
212
+ export function decodeBindCall(source: Uint8Array | Nested<WireBindRequest>, path = "BindRequest"): BindRequest {
213
+ const nested = source instanceof Uint8Array ? nestedBindRequest(source, path) : source;
214
+ const bindCall = deserializeBindRequest(nested.get() as Record<string, any>);
215
+ receivedBindCalls.set(bindCall, nested);
216
+ return bindCall;
217
+ }
218
+
187
219
  /** Validate required wire enum values, including rejecting NULL and absent values. */
188
220
  export function parseBindRepeatability(value: unknown): BindRepeatability {
189
221
  if (value !== "UNKNOWN" && value !== "STABLE_WITHIN_QUERY")
@@ -229,13 +261,8 @@ export function deserializeBindResponse(
229
261
  };
230
262
  }
231
263
 
232
- // BIND_REQUEST_SCHEMA has no codegen counterpart — the generated
233
- // BindParamsSchema is only the `{request: binary}` envelope, so the inner
234
- // record is spelled out above. The BindResponse copy that used to sit beside
235
- // it did have one, and the two had already drifted: this file called
236
- // `opaque_data` nullable where the generated BindResultSchema calls it
237
- // non-null. Nobody read the copy (handlers/function.ts wraps with the
238
- // generated schema), which is exactly how a duplicate goes stale unnoticed —
239
- // and a stale copy is how a *correct* client ends up rejected at its first
240
- // call. Use BindResultSchema from src/generated/vgi-protocol-schemas.ts.
264
+ // The BindResponse copy that used to sit beside the request schema had
265
+ // already drifted from the generated BindResultSchema (it called
266
+ // `opaque_data` nullable where the protocol says non-null). Use
267
+ // BindResultSchema from src/generated/vgi-protocol-schemas.ts.
241
268
  export { BIND_REQUEST_SCHEMA };
@@ -3,9 +3,8 @@
3
3
 
4
4
  import { type VgiSchema, schema, type VgiField, field, type VgiDataType, binary } from "../../arrow/index.js";
5
5
  import type { TableFunctionCardinalityRequest, TableCardinality } from "../types.js";
6
- import { deserializeBatch, batchToScalarDict } from "../../util/arrow/index.js";
7
6
  import { toUint8Array } from "./shared.js";
8
- import { deserializeBindRequest } from "./bind.js";
7
+ import { decodeBindCall } from "./bind.js";
9
8
 
10
9
  const TABLE_FUNCTION_CARDINALITY_REQUEST_SCHEMA = schema([
11
10
  field("bind_call", binary(), false),
@@ -13,12 +12,10 @@ const TABLE_FUNCTION_CARDINALITY_REQUEST_SCHEMA = schema([
13
12
  ]);
14
13
 
15
14
  export function deserializeCardinalityRequest(
16
- params: Record<string, any>
15
+ params: Record<string, any>,
16
+ path = "TableFunctionCardinalityRequest",
17
17
  ): TableFunctionCardinalityRequest {
18
- const bindCallBytes = toUint8Array(params.bind_call);
19
- const bindCallBatch = deserializeBatch(bindCallBytes);
20
- const bindParams = batchToScalarDict(bindCallBatch);
21
- const bindCall = deserializeBindRequest(bindParams);
18
+ const bindCall = decodeBindCall(toUint8Array(params.bind_call), `${path}.bind_call`);
22
19
 
23
20
  return {
24
21
  bind_call: bindCall,
@@ -43,7 +43,7 @@ import {
43
43
  batchToScalarDict,
44
44
  } from "../../util/arrow/index.js";
45
45
  import { toUint8Array, buildSingleRowBatch } from "./shared.js";
46
- import { serializeBindRequest, deserializeBindRequest } from "./bind.js";
46
+ import { bindCallBytes, decodeBindCall } from "./bind.js";
47
47
  import { decodeDictValue } from "../../util/arrow/index.js";
48
48
 
49
49
  // The InitRequest wire record. This must equal `InitRequestSchema` in
@@ -100,11 +100,10 @@ const GLOBAL_INIT_RESPONSE_SCHEMA = makeSchema([
100
100
  ]);
101
101
 
102
102
  export function serializeInitRequest(req: InitRequest): VgiBatch {
103
- const bindCallBatch = serializeBindRequest(req.bind_call);
104
- const bindCallBytes = serializeBatch(bindCallBatch);
105
-
106
103
  const row: Record<string, any> = {
107
- bind_call: bindCallBytes,
104
+ // The bytes the bind call was received as when it was received (the
105
+ // raw-preserving wrapper, §3.3 rules 4 and 11), else its fields.
106
+ bind_call: bindCallBytes(req.bind_call),
108
107
  output_schema: serializeSchema(req.output_schema),
109
108
  bind_opaque_data: req.bind_opaque_data ?? null,
110
109
  projection_ids: req.projection_ids?.map((n) => BigInt(n)) ?? null,
@@ -132,12 +131,7 @@ export function serializeInitRequest(req: InitRequest): VgiBatch {
132
131
  export function deserializeInitRequest(
133
132
  params: Record<string, any>
134
133
  ): InitRequest {
135
- const bindCallBytes = toUint8Array(params.bind_call);
136
- const bindCallBatch = deserializeBatch(bindCallBytes);
137
- // Extract the single row as params via the codec/canonical path.
138
- const bindParams = batchToScalarDict(bindCallBatch);
139
-
140
- const bindCall = deserializeBindRequest(bindParams);
134
+ const bindCall = decodeBindCall(toUint8Array(params.bind_call), "InitRequest.bind_call");
141
135
 
142
136
  // Parse projection_ids - may be a list/array of Int32
143
137
  let projectionIds: number[] | null = null;
@@ -13,7 +13,8 @@ import type { BindRequest } from "../types.js";
13
13
  import { OrderByDirection, OrderByNullOrder } from "../types.js";
14
14
  import { deserializeBatch, batchToScalarDict } from "../../util/arrow/index.js";
15
15
  import { toUint8Array } from "./shared.js";
16
- import { deserializeBindRequest } from "./bind.js";
16
+ import { toUint8Array as bytesOf } from "../../util/bytes.js";
17
+ import { decodeBindCall } from "./bind.js";
17
18
 
18
19
  /**
19
20
  * One named, independently redeemable unit of scan work.
@@ -164,8 +165,7 @@ export const PLAN_RESPONSE_SCHEMA: VgiSchema = TableFunctionPlanResultSchema as
164
165
  * not set — so every field but `bind_call` is read defensively.
165
166
  */
166
167
  export function deserializePlanRequest(params: Record<string, any>): TableFunctionPlanRequest {
167
- const bindCallBytes = toUint8Array(params.bind_call);
168
- const bindCall = deserializeBindRequest(batchToScalarDict(deserializeBatch(bindCallBytes)));
168
+ const bindCall = decodeBindCall(toUint8Array(params.bind_call), "TableFunctionPlanRequest.bind_call");
169
169
 
170
170
  let projectionIds: number[] | null = null;
171
171
  if (params.projection_ids != null) {
@@ -224,6 +224,13 @@ export function deserializePlanRequest(params: Record<string, any>): TableFuncti
224
224
  * that minted a token and the init that redeems it. A decoded-then-re-encoded
225
225
  * argument list is not guaranteed to round-trip to identical bytes; the wire
226
226
  * bytes are.
227
+ *
228
+ * `args` is tagged (large-values spec §5a, "Split-token fingerprints"):
229
+ * inline arguments contribute `0x00 || u64le(len) || IPC bytes`; an argument
230
+ * reference contributes `0x01 || u64le(size) || sha256[32]`, never the sealed
231
+ * `ref` (it holds a random nonce). Without the location branch every bind of
232
+ * externalized arguments would fingerprint the same empty bytes, and a split
233
+ * token would redeem across different large arguments.
227
234
  */
228
235
  export function fingerprintInputs(bindCallBytes: Uint8Array): {
229
236
  schemaPath: string[];
@@ -237,11 +244,31 @@ export function fingerprintInputs(bindCallBytes: Uint8Array): {
237
244
  ? []
238
245
  : (Array.isArray(dict.schema_path) ? dict.schema_path : [...dict.schema_path]).map(String),
239
246
  functionName: String(dict.function_name ?? ""),
240
- args: dict.arguments ? toUint8Array(dict.arguments) : new Uint8Array(0),
247
+ args: argumentsFingerprintInput(dict.arguments, dict.arguments_location),
241
248
  settings: dict.settings ? toUint8Array(dict.settings) : new Uint8Array(0),
242
249
  };
243
250
  }
244
251
 
252
+ const ARGS_INLINE = 0x00;
253
+ const ARGS_LOCATION = 0x01;
254
+
255
+ function argumentsFingerprintInput(argumentsValue: unknown, location: any): Uint8Array {
256
+ if (location != null) {
257
+ const sha = String(location.sha256 ?? "");
258
+ const out = new Uint8Array(1 + 8 + 32);
259
+ out[0] = ARGS_LOCATION;
260
+ new DataView(out.buffer).setBigUint64(1, BigInt(location.size ?? 0), true);
261
+ for (let i = 0; i < 32; i++) out[9 + i] = parseInt(sha.slice(i * 2, i * 2 + 2), 16) || 0;
262
+ return out;
263
+ }
264
+ const raw = argumentsValue != null ? bytesOf(argumentsValue) : new Uint8Array(0);
265
+ const out = new Uint8Array(1 + 8 + raw.byteLength);
266
+ out[0] = ARGS_INLINE;
267
+ new DataView(out.buffer).setBigUint64(1, BigInt(raw.byteLength), true);
268
+ out.set(raw, 9);
269
+ return out;
270
+ }
271
+
245
272
  /** Build the row dict for one `ScanSplit`. */
246
273
  export function scanSplitRow(split: ScanSplit, token: Uint8Array): Record<string, any> {
247
274
  const asBigInt = (v: number | bigint | null | undefined): bigint | null =>
@@ -25,9 +25,8 @@ import {
25
25
  } from "../arrow/index.js";
26
26
  import { codecFor } from "../arrow/codec/registry.js";
27
27
  import type { StateSerializer } from "@query-farm/vgi-rpc";
28
- import { toUint8Array } from "../util/bytes.js";
29
28
  import { decodeFilterHistory, encodeFilterHistory } from "../filter-pushdown/history.js";
30
- import { packInitRequest } from "./carried-init-request.js";
29
+ import { StateRef } from "@query-farm/vgi-rpc";
31
30
 
32
31
  /**
33
32
  * The fields of the exchange state an HTTP cursor carries, by name and type.
@@ -38,12 +37,11 @@ import { packInitRequest } from "./carried-init-request.js";
38
37
  */
39
38
  export const EXCHANGE_STATE_SCHEMA = makeSchema([
40
39
  field("function_name", binary(), false),
41
- // The init request, packed by carried-init-request.ts (a codec byte, then
42
- // the IPC bytes, zstd-compressed where the runtime can).
43
- field("init_request", binary(), false),
44
- field("execution_id", binary(), false),
45
- field("max_workers", int64(), false),
46
- field("opaque_data", binary(), true),
40
+ // The stream's `init`: a vgi-rpc StateRef (its encoded bytes) to the init
41
+ // request as received plus the worker's init response (stream-init.ts).
42
+ // Inline and compressed in the common case, a sealed stored tag for a large
43
+ // init. Created on the init turn only; every continuation copies it.
44
+ field("init", binary(), false),
47
45
  field("is_producer", bool(), false),
48
46
  field("user_state", binary(), true),
49
47
  // The stream's compacted dynamic-filter history (filter-pushdown/history.ts),
@@ -59,9 +57,8 @@ const TEXT_ENCODER = new TextEncoder();
59
57
  const TEXT_DECODER = new TextDecoder();
60
58
 
61
59
  /** Version byte of the exchange state frame (never 0xFF, the first byte of an Arrow IPC stream). */
62
- const STATE_FORMAT_VERSION = 1;
60
+ const STATE_FORMAT_VERSION = 2;
63
61
  const FLAG_PRODUCER = 1;
64
- const FLAG_OPAQUE_DATA = 2;
65
62
  const FLAG_USER_STATE = 4;
66
63
  const FLAG_FILTER_HISTORY = 8;
67
64
  const FLAG_MORE_PENDING = 16;
@@ -223,44 +220,41 @@ export function deserializeUserState(bytes: Uint8Array | null): any {
223
220
  * {@link EXCHANGE_STATE_SCHEMA} names; `user_state` stays Arrow IPC inside the
224
221
  * frame, because it carries typed user values.
225
222
  *
226
- * Layout (little-endian): `u8 version | u8 flags | f64 max_workers |
227
- * bytes function_name | bytes init_request | bytes execution_id |
228
- * [bytes opaque_data] [bytes user_state] [bytes filter_history]`, where
229
- * `bytes` is `u32 length, payload` and a bracketed field is present only when
230
- * its flag bit is set. The frame never leaves this worker unsealed, so the
231
- * version byte exists to turn a token minted by another build into a clean
232
- * refusal rather than a misread.
223
+ * Layout (little-endian): `u8 version | u8 flags | bytes function_name |
224
+ * bytes init | [bytes user_state] [bytes filter_history]`, where `bytes` is
225
+ * `u32 length, payload` and a bracketed field is present only when its flag
226
+ * bit is set. `init` is the encoded vgi-rpc StateRef the init handler created
227
+ * (`StateRef.toBytes()`; vgi-rpc decides its form while minting the token and
228
+ * caches the encoding, so continuations re-emit the same bytes). The frame
229
+ * never leaves this worker unsealed, so the version byte exists to turn a
230
+ * token minted by another build into a clean refusal rather than a misread.
233
231
  *
234
232
  * The name is kept for API stability; the Arrow in it is the user state.
235
233
  */
236
234
  export const arrowStateSerializer: StateSerializer = {
237
235
  serialize(state: any): Uint8Array {
238
236
  const functionName = TEXT_ENCODER.encode(state.functionName ?? "");
239
- // Packed on the init turn (the only one holding the raw bytes); every
240
- // continuation carries the packed bytes through unchanged.
241
- const initRequest: Uint8Array = state.initRequestPacked ?? packInitRequest(state.initRequestIpc);
242
- const executionId = toUint8Array(state.executionId);
243
- const opaqueData = state.opaqueData != null ? toUint8Array(state.opaqueData) : null;
237
+ if (!StateRef.isStateRef(state.init)) {
238
+ throw new Error("exchange state carries no init StateRef (the stream's init handler creates it)");
239
+ }
240
+ const init = (state.init as StateRef).toBytes();
244
241
  const userState = serializeUserState(state.userState);
245
242
  const filterHistory = encodeFilterHistory(state.filterHistory);
246
243
  const flags =
247
244
  (state.isProducer ? FLAG_PRODUCER : 0) |
248
- (opaqueData ? FLAG_OPAQUE_DATA : 0) |
249
245
  (userState ? FLAG_USER_STATE : 0) |
250
246
  (filterHistory ? FLAG_FILTER_HISTORY : 0) |
251
247
  (state.morePending ? FLAG_MORE_PENDING : 0);
252
- const chunks = [functionName, initRequest, executionId];
253
- if (opaqueData) chunks.push(opaqueData);
248
+ const chunks = [functionName, init];
254
249
  if (userState) chunks.push(userState);
255
250
  if (filterHistory) chunks.push(filterHistory);
256
- let size = 2 + 8;
251
+ let size = 2;
257
252
  for (const chunk of chunks) size += 4 + chunk.byteLength;
258
253
  const out = new Uint8Array(size);
259
254
  const view = new DataView(out.buffer);
260
255
  out[0] = STATE_FORMAT_VERSION;
261
256
  out[1] = flags;
262
- view.setFloat64(2, Number(state.maxWorkers ?? 1), true);
263
- let offset = 10;
257
+ let offset = 2;
264
258
  for (const chunk of chunks) {
265
259
  view.setUint32(offset, chunk.byteLength, true);
266
260
  out.set(chunk, offset + 4);
@@ -271,12 +265,11 @@ export const arrowStateSerializer: StateSerializer = {
271
265
 
272
266
  deserialize(bytes: Uint8Array): any {
273
267
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
274
- if (bytes.byteLength < 10 || bytes[0] !== STATE_FORMAT_VERSION) {
268
+ if (bytes.byteLength < 2 || bytes[0] !== STATE_FORMAT_VERSION) {
275
269
  throw new Error("exchange state has an unknown format (minted by another build of this worker?)");
276
270
  }
277
- const flags = bytes[1]!; // in range: byteLength >= 10 was checked above
278
- const maxWorkers = view.getFloat64(2, true);
279
- let offset = 10;
271
+ const flags = bytes[1]!; // in range: byteLength >= 2 was checked above
272
+ let offset = 2;
280
273
  // Each field is copied out, not viewed: Arrow readers want a buffer of
281
274
  // their own (byteOffset 0), and nothing should pin the whole frame.
282
275
  const take = (): Uint8Array => {
@@ -289,19 +282,14 @@ export const arrowStateSerializer: StateSerializer = {
289
282
  return chunk;
290
283
  };
291
284
  const functionName = TEXT_DECODER.decode(take());
292
- const initRequestPacked = take();
293
- const executionId = take();
294
- const opaqueData = flags & FLAG_OPAQUE_DATA ? take() : null;
285
+ const init = StateRef.fromBytes(take());
295
286
  const userStateBytes = flags & FLAG_USER_STATE ? take() : null;
296
287
  const filterHistoryBytes = flags & FLAG_FILTER_HISTORY ? take() : null;
297
288
  if (offset !== bytes.byteLength) throw new Error("exchange state has trailing bytes");
298
289
  const isProducer = (flags & FLAG_PRODUCER) !== 0;
299
290
  return {
300
291
  functionName,
301
- initRequestPacked,
302
- executionId,
303
- maxWorkers,
304
- opaqueData,
292
+ init,
305
293
  isProducer,
306
294
  // vgi-rpc dispatch reads __isProducer to choose producer vs exchange mode
307
295
  __isProducer: isProducer,
@@ -0,0 +1,87 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // The value of an HTTP stream's `init` StateRef (vgi docs/large-values-3.4.md §6).
3
+ //
4
+ // An HTTP stream has no memory between turns, so its cursor has to carry what
5
+ // the init turn knew: the init request as received (bind call, output schema,
6
+ // filters, join keys, split tokens, opaque data) and the worker's init response.
7
+ // Both are immutable for the life of the stream, so they ride as ONE vgi-rpc
8
+ // StateRef field, `init`, created with `ctx.stateRef()` in the init handler and
9
+ // copied unchanged by every later turn:
10
+ //
11
+ // - small inits (the common case) are inline: vgi-rpc compresses the payload
12
+ // inside the ref, which is why this SDK no longer packs (zstd) the init
13
+ // request itself;
14
+ // - a large init (a 1000-value IN list) is stored once at /init and costs a
15
+ // ~130-byte sealed tag per turn after that.
16
+ //
17
+ // With argument references the init request holds the reference, never the
18
+ // argument, so it normally stays inline even for a very large argument.
19
+ //
20
+ // There is deliberately no per-process parse memo (spec decision 3): an inline
21
+ // init is decompressed and parsed on every turn, which measured as immaterial.
22
+ // The 128-entry LRU this SDK used to keep pinned parsed requests, and with them
23
+ // resolved arguments of any size.
24
+
25
+ /** Version byte of the value; a different build's frame is a clean refusal, not a misread. */
26
+ const STREAM_INIT_VERSION = 1;
27
+ const FLAG_OPAQUE_DATA = 1;
28
+
29
+ /** What an HTTP stream's `init` StateRef holds. */
30
+ export interface StreamInit {
31
+ /** The init request's IPC bytes exactly as received (the `request` column of the init call). */
32
+ initRequestIpc: Uint8Array;
33
+ /** The worker's init response. */
34
+ executionId: Uint8Array;
35
+ maxWorkers: number;
36
+ opaqueData: Uint8Array | null;
37
+ }
38
+
39
+ /**
40
+ * Encode the `init` value: `u8 version | u8 flags | f64 max_workers |
41
+ * bytes init_request | bytes execution_id | [bytes opaque_data]`, `bytes`
42
+ * being `u32 length (LE), payload`.
43
+ */
44
+ export function encodeStreamInit(init: StreamInit): Uint8Array {
45
+ const chunks = [init.initRequestIpc, init.executionId];
46
+ if (init.opaqueData != null) chunks.push(init.opaqueData);
47
+ let size = 2 + 8;
48
+ for (const chunk of chunks) size += 4 + chunk.byteLength;
49
+ const out = new Uint8Array(size);
50
+ const view = new DataView(out.buffer);
51
+ out[0] = STREAM_INIT_VERSION;
52
+ out[1] = init.opaqueData != null ? FLAG_OPAQUE_DATA : 0;
53
+ view.setFloat64(2, Number(init.maxWorkers ?? 1), true);
54
+ let offset = 10;
55
+ for (const chunk of chunks) {
56
+ view.setUint32(offset, chunk.byteLength, true);
57
+ out.set(chunk, offset + 4);
58
+ offset += 4 + chunk.byteLength;
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /** Decode an `init` value written by {@link encodeStreamInit}. */
64
+ export function decodeStreamInit(bytes: Uint8Array): StreamInit {
65
+ if (bytes.byteLength < 10 || bytes[0] !== STREAM_INIT_VERSION) {
66
+ throw new Error("stream init state has an unknown format (minted by another build of this worker?)");
67
+ }
68
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
69
+ const flags = bytes[1]!;
70
+ const maxWorkers = view.getFloat64(2, true);
71
+ let offset = 10;
72
+ const take = (): Uint8Array => {
73
+ if (offset + 4 > bytes.byteLength) throw new Error("stream init state is truncated");
74
+ const length = view.getUint32(offset, true);
75
+ offset += 4;
76
+ if (offset + length > bytes.byteLength) throw new Error("stream init state is truncated");
77
+ // Copied, not viewed: Arrow readers want a buffer of their own.
78
+ const chunk = bytes.slice(offset, offset + length);
79
+ offset += length;
80
+ return chunk;
81
+ };
82
+ const initRequestIpc = take();
83
+ const executionId = take();
84
+ const opaqueData = flags & FLAG_OPAQUE_DATA ? take() : null;
85
+ if (offset !== bytes.byteLength) throw new Error("stream init state has trailing bytes");
86
+ return { initRequestIpc, executionId, maxWorkers, opaqueData };
87
+ }
@@ -56,8 +56,26 @@ export interface CopyToContext {
56
56
  file_path: string;
57
57
  }
58
58
 
59
+ /**
60
+ * Where a bind's externalized arguments live (protocol 3.4 argument
61
+ * references, vgi docs/large-values-3.4.md §2). The client uploaded the
62
+ * arguments IPC stream once through this worker's `__upload_url__` grant;
63
+ * `ref` is the grant's sealed reference, `size` / `sha256` describe exactly
64
+ * the uploaded bytes. Mirrors vgi-python's `protocol.ArgumentsLocation`.
65
+ */
66
+ export interface ArgumentsLocation {
67
+ ref: Uint8Array;
68
+ size: number;
69
+ sha256: string;
70
+ }
71
+
59
72
  export interface BindRequest {
60
73
  function_name: string;
74
+ /**
75
+ * The bound arguments. When the bind arrived by reference
76
+ * (`arguments_location`), the framework resolves them at the entry of every
77
+ * request before any function code runs, so this always holds the value.
78
+ */
61
79
  arguments: Arguments;
62
80
  function_type: FunctionType;
63
81
  input_schema: VgiSchema | null;
@@ -66,6 +84,14 @@ export interface BindRequest {
66
84
  attach_opaque_data: Uint8Array | null;
67
85
  transaction_opaque_data: Uint8Array | null;
68
86
  resolved_secrets_provided: boolean;
87
+ /**
88
+ * Framework-derived, never on the wire: the FunctionStorage shard key
89
+ * (`att-<uuid hex>`) of this call's attach, stamped when the framework opens
90
+ * the attach and strips its UUID (which the function body never sees).
91
+ * Absent / "" when the call is not bound to an ATTACH. Read it with
92
+ * `shardKeyOf(bindCall)`; `BoundStorage` routes and seals by it.
93
+ */
94
+ storage_shard_key?: string | null;
69
95
  /**
70
96
  * COPY ... FROM context — `null`/absent unless this bind/init opens a
71
97
  * COPY-FROM scan. Additive + name-keyed, so ordinary scans (which omit it on
@@ -102,6 +128,13 @@ export interface BindRequest {
102
128
  * named varargs retain the caller-provided name. `null` means unavailable.
103
129
  */
104
130
  argument_names?: (string | null)[] | null;
131
+ /**
132
+ * Protocol 3.4: the location the arguments arrived by, when the client sent
133
+ * them as an argument reference instead of inline; `null`/absent for inline
134
+ * arguments. `arguments` still holds the resolved value; this is what the
135
+ * bind call re-serializes as (never the value).
136
+ */
137
+ arguments_location?: ArgumentsLocation | null;
105
138
  }
106
139
 
107
140
  /** Equivalent scans of one bound state within a query; independent binds may differ. */