@query-farm/vgi 0.51.0 → 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 (70) 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/storage-blobs.d.ts +173 -0
  5. package/dist/functions/storage-cf-do.d.ts +12 -0
  6. package/dist/functions/storage.d.ts +22 -0
  7. package/dist/functions/table.d.ts +6 -1
  8. package/dist/generated/vgi-client.d.ts +7 -1
  9. package/dist/generated/vgi-protocol-schemas.d.ts +10 -9
  10. package/dist/generated/vgi-protocol-types.d.ts +244 -2
  11. package/dist/generated/vgi-service.d.ts +1 -1
  12. package/dist/hosted.d.ts +117 -0
  13. package/dist/http/blob-vendor.d.ts +33 -0
  14. package/dist/http/fetch.d.ts +53 -2
  15. package/dist/http/hosted-auth.d.ts +45 -0
  16. package/dist/index.core.d.ts +9 -2
  17. package/dist/index.js +5238 -3619
  18. package/dist/index.js.map +44 -28
  19. package/dist/protocol/arguments-ref.d.ts +107 -0
  20. package/dist/protocol/dispatch.d.ts +3 -2
  21. package/dist/protocol/handlers/function.d.ts +21 -0
  22. package/dist/protocol/serialize.d.ts +1 -1
  23. package/dist/protocol/serializers/bind.d.ts +27 -1
  24. package/dist/protocol/serializers/cardinality.d.ts +1 -1
  25. package/dist/protocol/serializers/splits.d.ts +7 -0
  26. package/dist/protocol/state-serializer.d.ts +8 -7
  27. package/dist/protocol/stream-init.d.ts +17 -0
  28. package/dist/protocol/types.d.ts +24 -0
  29. package/dist/secrets/lookups.d.ts +31 -0
  30. package/dist/serve-entry.d.ts +25 -4
  31. package/dist/serve-entry.js +2940 -1219
  32. package/dist/serve-entry.js.map +44 -29
  33. package/dist/worker-cf-entry.d.ts +5 -0
  34. package/dist/worker-cf-entry.js +2928 -1223
  35. package/dist/worker-cf-entry.js.map +47 -31
  36. package/package.json +5 -4
  37. package/src/functions/storage-blobs.ts +654 -0
  38. package/src/functions/storage-cf-do.ts +24 -0
  39. package/src/functions/storage.ts +54 -5
  40. package/src/functions/table-buffering.ts +14 -4
  41. package/src/functions/table.ts +8 -4
  42. package/src/generated/vgi-client.ts +9 -2
  43. package/src/generated/vgi-protocol-schemas.ts +115 -107
  44. package/src/generated/vgi-protocol-types.ts +640 -3
  45. package/src/generated/vgi-service.ts +2 -2
  46. package/src/hosted.ts +254 -0
  47. package/src/http/blob-vendor.ts +80 -0
  48. package/src/http/fetch.ts +170 -8
  49. package/src/http/hosted-auth.ts +326 -0
  50. package/src/index.core.ts +64 -1
  51. package/src/protocol/arguments-ref.ts +260 -0
  52. package/src/protocol/dispatch.ts +3 -2
  53. package/src/protocol/handlers/function.ts +109 -60
  54. package/src/protocol/handlers/table-buffering.ts +5 -0
  55. package/src/protocol/serialize.ts +3 -0
  56. package/src/protocol/serializers/bind.ts +96 -69
  57. package/src/protocol/serializers/cardinality.ts +4 -7
  58. package/src/protocol/serializers/init.ts +5 -11
  59. package/src/protocol/serializers/splits.ts +31 -4
  60. package/src/protocol/state-serializer.ts +27 -39
  61. package/src/protocol/stream-init.ts +87 -0
  62. package/src/protocol/types.ts +25 -0
  63. package/src/secrets/lookups.ts +53 -0
  64. package/src/serve-entry.ts +105 -8
  65. package/src/worker-cf-entry.ts +33 -0
  66. package/src/worker.ts +25 -0
  67. package/dist/protocol/carried-init-request.d.ts +0 -28
  68. package/dist/util/zstd-sync.d.ts +0 -7
  69. package/src/protocol/carried-init-request.ts +0 -139
  70. package/src/util/zstd-sync.ts +0 -50
@@ -89,9 +89,10 @@ export { VGI_PROTOCOL_NAME };
89
89
  * hash covers method names, types and the params/result/header schemas only
90
90
  * (WIRE_PROTOCOL.md §14).
91
91
  *
92
- * It changes only with vgi.v3's protocol version (currently 3.3.0: 3.3 removed
92
+ * It changes only with vgi.v3's method surface (3.3 removed
93
93
  * catalog_table_scan_function_get and gave catalog_table_create a `created`
94
- * result). Asserted
94
+ * result; 3.4.0 changed the transport's upload URLs, not the surface, so the
95
+ * hash is unchanged). Asserted
95
96
  * by src/protocol/__tests__/vgi-v3-hash.test.ts; if that test fails, the
96
97
  * surface drifted from the reference -- fix the schemas, do not bump this.
97
98
  */
@@ -15,7 +15,6 @@ import { refuseMoreOutput } from "../../functions/continuation.js";
15
15
  import { persistBufferingInit } from "../../functions/table-buffering.js";
16
16
  import { TableInOutPhase } from "../../types.js";
17
17
  import {
18
- deserializeBindRequest,
19
18
  serializeBindResponse,
20
19
  deserializeInitRequest,
21
20
  serializeGlobalInitResponse,
@@ -23,7 +22,7 @@ import {
23
22
  serializeTableCardinality,
24
23
  } from "../serialize.js";
25
24
  import type { GlobalInitResponse } from "../types.js";
26
- import { batchToScalarDict, deserializeBatch, adoptArrowJsShape } from "../../util/arrow/index.js";
25
+ import { adoptArrowJsShape } from "../../util/arrow/index.js";
27
26
  import { toUint8Array } from "../../util/bytes.js";
28
27
  import { serializeColumnStatistics } from "../../util/statistics.js";
29
28
  import {
@@ -35,7 +34,9 @@ import {
35
34
  TableFunctionDynamicToStringResultSchema,
36
35
  } from "../../generated/vgi-protocol-schemas.js";
37
36
  import { unwrapRequest, wrapResult, overloadContext } from "./shared.js";
38
- import { parseCarriedInitRequest } from "../carried-init-request.js";
37
+ import { bindCallBytes, decodeBindCall } from "../serializers/bind.js";
38
+ import { resolveBindCall } from "../arguments-ref.js";
39
+ import { decodeStreamInit, encodeStreamInit } from "../stream-init.js";
39
40
  import { openAttach, openAttachWithShard, openTransaction, shardKeyForAttach } from "./catalog/shared.js";
40
41
  import { currentRequestAuth } from "../../request-auth.js";
41
42
  import { batchFromColumns, serializeBatch } from "../../util/arrow/index.js";
@@ -208,6 +209,46 @@ async function resolveSplitPayloads(
208
209
  }
209
210
  }
210
211
 
212
+ /**
213
+ * Unseal a decoded bind call's opaque values in place, as the catalog handlers
214
+ * do: the transaction first (its envelope binds the *sealed* attach), then the
215
+ * attach, and stamp the storage shard of the attach's framework UUID (in
216
+ * memory only, never serialized) so every BoundStorage the function builds
217
+ * routes to this attach's shard. Every function-side request goes through
218
+ * this, so function bodies see the same transaction plaintext that
219
+ * transactionCommit/Rollback get.
220
+ *
221
+ * Rule 11 of the raw-preserving wrapper (vgi docs/large-values-3.4.md §3.3):
222
+ * the opened plaintext lives on the domain object, BESIDE the received bytes,
223
+ * never in them. A decoded bind call re-encodes as exactly what the client
224
+ * sent (`bindCallBytes`), sealed envelopes included, so nothing opened here
225
+ * can reach the wire, a state token or storage.
226
+ */
227
+ export async function openBindCallOpaque(
228
+ bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null; storage_shard_key?: string | null },
229
+ auth: AuthContext | undefined,
230
+ signingKey: Uint8Array | undefined,
231
+ attachSecretKey?: Uint8Array,
232
+ ): Promise<void> {
233
+ const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
234
+ if (bindCall.transaction_opaque_data != null) {
235
+ bindCall.transaction_opaque_data = await openTransaction(
236
+ toUint8Array(bindCall.transaction_opaque_data),
237
+ sealedAttach,
238
+ auth,
239
+ signingKey,
240
+ );
241
+ }
242
+ const opened = await openAttachWithShard(
243
+ bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : null,
244
+ auth,
245
+ signingKey,
246
+ attachSecretKey,
247
+ );
248
+ bindCall.attach_opaque_data = opened.attach;
249
+ (bindCall as { storage_shard_key?: string }).storage_shard_key = opened.shardKey;
250
+ }
251
+
211
252
  /** The per-function lifecycle's `vgi.v3` handlers. */
212
253
  export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiService> {
213
254
  const { registry, signingKey, catalogInterface, attachSecretKey } = config;
@@ -231,27 +272,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
231
272
  bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null; storage_shard_key?: string | null },
232
273
  ctx: any,
233
274
  ): Promise<void> {
234
- const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
235
- if (bindCall.transaction_opaque_data != null) {
236
- bindCall.transaction_opaque_data = await openTransaction(
237
- toUint8Array(bindCall.transaction_opaque_data),
238
- sealedAttach,
239
- ctx?.auth ?? currentRequestAuth(),
240
- signingKey,
241
- );
242
- }
243
- // One open yields both what the body sees and the storage shard of the
244
- // attach's framework UUID, which the strip removes. Stamped on the bind
245
- // call (in memory only, never serialized) so every BoundStorage the
246
- // function builds routes to this attach's shard.
247
- const opened = await openAttachWithShard(
248
- bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : null,
249
- ctx?.auth ?? currentRequestAuth(),
250
- signingKey,
251
- attachSecretKey,
252
- );
253
- bindCall.attach_opaque_data = opened.attach;
254
- (bindCall as { storage_shard_key?: string }).storage_shard_key = opened.shardKey;
275
+ await openBindCallOpaque(bindCall, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
255
276
  }
256
277
 
257
278
  // Build an overload context whose attach has been unsealed, so catalog
@@ -285,8 +306,10 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
285
306
  // bind (unary)
286
307
  // --------------------------------------------------------------------------
287
308
  const bind: VgiService["bind"] = async (params, ctx) => {
288
- const innerParams = unwrapRequest(params.request);
289
- const request = deserializeBindRequest(innerParams);
309
+ // The generated raw-preserving decode; arguments sent by reference are
310
+ // resolved before anything (overload resolution included) reads them.
311
+ const request = decodeBindCall(toUint8Array(params.request), "BindRequest");
312
+ await resolveBindCall(request, ctx);
290
313
  await openOpaque(request, ctx);
291
314
  const func = registry.get(request.function_name, overloadContext(request, catalogInterface));
292
315
  const response = await func.bind(request);
@@ -324,6 +347,9 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
324
347
  // attach_opaque_data not recognized` on its first scan, i.e. this worker
325
348
  // could not serve authenticated traffic at all.
326
349
  const auth = ctx?.auth ?? currentRequestAuth();
350
+ // Argument references resolve first (through vgi-rpc's object cache):
351
+ // overload resolution and every function hook read the arguments.
352
+ await resolveBindCall(request.bind_call, ctx);
327
353
  await openOpaque(request.bind_call, ctx);
328
354
 
329
355
  // Verify and strip the split envelopes BEFORE any user code runs, so an
@@ -374,9 +400,22 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
374
400
  // Build state object with raw binary data (no base64/hex encoding).
375
401
  // The Arrow state serializer picks fields by name; live objects
376
402
  // (_handlers, _handlerState, _initResponse, __outputSchema) are ignored.
403
+ // The stream's `init` StateRef (stream-init.ts): the init request exactly
404
+ // as received -- its bind call still the reference, never a resolved
405
+ // argument, and its attach still sealed -- plus the init response. Built
406
+ // here, in the init handler, the one place vgi-rpc allows
407
+ // `stateRef()`; every continuation copies it unchanged.
408
+ const initValue = encodeStreamInit({
409
+ initRequestIpc: requestIpcBytes,
410
+ executionId: initResponse.execution_id,
411
+ maxWorkers: Number(initResponse.max_workers),
412
+ opaqueData: initResponse.opaque_data ?? null,
413
+ });
377
414
  const state: any = {
378
415
  functionName: request.bind_call.function_name,
379
- initRequestIpc: requestIpcBytes,
416
+ init: typeof ctx?.stateRef === "function" ? ctx.stateRef(initValue) : null,
417
+ // The init response, in memory for this turn only (the cursor carries
418
+ // it inside `init`).
380
419
  executionId: initResponse.execution_id,
381
420
  maxWorkers: Number(initResponse.max_workers),
382
421
  opaqueData: initResponse.opaque_data ?? null,
@@ -420,17 +459,21 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
420
459
  // Deserialized from token — reconstruct from serializable refs.
421
460
  // Infrastructure (processParams, BoundStorage) is recreated fresh.
422
461
  // Mutable user state is merged from state.userState.
423
- // Parsed once per process per stream (carried-init-request.ts): the
424
- // cursor carries the packed request unchanged on every turn.
425
- const carried = parseCarriedInitRequest(state.initRequestPacked);
426
- const request = carried.request;
462
+ // The cursor's `init` StateRef, resolved through this turn's context
463
+ // (inline: decompressed here; stored: the object cache, then storage)
464
+ // and parsed afresh: there is no per-process parse memo (vgi
465
+ // docs/large-values-3.4.md §6, decision 3).
466
+ const carried = decodeStreamInit(await out.resolve(state.init));
467
+ const request = deserializeInitRequest(unwrapRequest(carried.initRequestIpc));
468
+ // The bind call holds the reference when the arguments came by one:
469
+ // resolve it (object cache, one storage GET per object per process)
470
+ // before overload resolution or any user code reads it.
471
+ await resolveBindCall(request.bind_call, out);
427
472
  // The cursor carries the wire request, whose attach is still the sealed
428
473
  // envelope. Strip it exactly as the init turn did, before any user code
429
474
  // or split resolution sees it: every turn of a stream must hand the
430
475
  // function the catalog's own bytes, not just the first. (Unopenable is
431
476
  // a hard error here, as on the init turn: the cursor is caller-bound.)
432
- // `carried.request.bind_call` is a per-call copy, so this does not
433
- // disturb the memoised parse other turns share.
434
477
  await openOpaque(request.bind_call, undefined);
435
478
  // Re-derive the split payloads. The cursor carries the wire request,
436
479
  // which has `split_tokens` but not the opened `split_payloads` — that
@@ -440,11 +483,12 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
440
483
  // splits at all". checkAnchor is false: redemption was already decided
441
484
  // on the init turn, and re-checking here would let a mid-scan catalog
442
485
  // bump fail a query that had already been admitted.
443
- // fingerprintInputs hashes the RAW bind_call bytes, so pass the
444
- // pre-deserialization blob from the cursor — handing it the decoded
445
- // object hashes a different shape and every token fails as
446
- // SPLIT_TOKEN_INVALID "minted for a different bind".
447
- await resolveSplitPayloads(request, { bind_call: carried.bindCallIpc }, {
486
+ // fingerprintInputs hashes the RAW bind_call bytes, so pass the bytes
487
+ // the bind call was received as (held by its raw-preserving wrapper,
488
+ // untouched by the open above) — handing it a re-encoding hashes a
489
+ // different shape and every token fails as SPLIT_TOKEN_INVALID
490
+ // "minted for a different bind".
491
+ await resolveSplitPayloads(request, { bind_call: bindCallBytes(request.bind_call) }, {
448
492
  // Same principal the tokens were sealed under. The exchange dispatch
449
493
  // gets no ctx (see openOpaque above), so the request-scoped identity
450
494
  // is the only source — opening under the anonymous tail would fail
@@ -458,12 +502,10 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
458
502
  // Already stripped above, so resolve directly (strippedContext would try
459
503
  // to open the plaintext again and fall back to an unscoped lookup).
460
504
  const func = registry.get(state.functionName, overloadContext(request.bind_call, catalogInterface));
461
- const executionId = state.executionId;
462
- const opaqueData = state.opaqueData ?? null;
463
505
  const initResponse: GlobalInitResponse = {
464
- execution_id: executionId,
465
- max_workers: Number(state.maxWorkers ?? 1),
466
- opaque_data: opaqueData,
506
+ execution_id: carried.executionId,
507
+ max_workers: Number(carried.maxWorkers ?? 1),
508
+ opaque_data: carried.opaqueData,
467
509
  };
468
510
 
469
511
  // The cursor's compacted dynamic-filter history: without it every turn
@@ -532,10 +574,11 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
532
574
  // --------------------------------------------------------------------------
533
575
  // table_function_cardinality (unary)
534
576
  // --------------------------------------------------------------------------
535
- const tableFunctionCardinality: VgiService["tableFunctionCardinality"] = async (params) => {
577
+ const tableFunctionCardinality: VgiService["tableFunctionCardinality"] = async (params, ctx?: any) => {
536
578
  const innerParams = unwrapRequest(params.request);
537
579
  const request = deserializeCardinalityRequest(innerParams);
538
- const func = registry.get(request.bind_call.function_name, await strippedContext(request.bind_call));
580
+ await resolveBindCall(request.bind_call, ctx);
581
+ const func = registry.get(request.bind_call.function_name, await strippedContext(request.bind_call, ctx));
539
582
  let cardResult: Record<string, any>;
540
583
  if (func.cardinality) {
541
584
  cardResult = serializeTableCardinality(await func.cardinality(request));
@@ -559,9 +602,10 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
559
602
  const tableFunctionPlan: VgiService["tableFunctionPlan"] = async (params, ctx?: any) => {
560
603
  const innerParams = unwrapRequest(params.request);
561
604
  const request = deserializePlanRequest(innerParams);
605
+ await resolveBindCall(request.bind_call, ctx);
562
606
  const func = registry.get(
563
607
  request.bind_call.function_name,
564
- await strippedContext(request.bind_call),
608
+ await strippedContext(request.bind_call, ctx),
565
609
  );
566
610
 
567
611
  const plan: PlanResult = func.plan
@@ -631,10 +675,11 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
631
675
  // the function declared a statistics() hook and it produced a non-empty
632
676
  // list, else null. DuckDB uses the bounds for plan-time filter elimination
633
677
  // (folds impossible filters to EMPTY_RESULT).
634
- const tableFunctionStatistics: VgiService["tableFunctionStatistics"] = async (params) => {
678
+ const tableFunctionStatistics: VgiService["tableFunctionStatistics"] = async (params, ctx?: any) => {
635
679
  const innerParams = unwrapRequest(params.request);
636
- const request = deserializeCardinalityRequest(innerParams);
637
- const func = registry.get(request.bind_call.function_name, await strippedContext(request.bind_call));
680
+ const request = deserializeCardinalityRequest(innerParams, "TableFunctionStatisticsRequest");
681
+ await resolveBindCall(request.bind_call, ctx);
682
+ const func = registry.get(request.bind_call.function_name, await strippedContext(request.bind_call, ctx));
638
683
  if (!func.statistics) return { result: null };
639
684
  const stats = func.statistics(request);
640
685
  if (!stats || stats.length === 0) return { result: null };
@@ -650,18 +695,18 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
650
695
  // intrinsics (Function, Rows Read, Threads). When the function doesn't
651
696
  // declare dynamicToString, return empty maps so the C++ side falls back
652
697
  // to intrinsics only.
653
- const tableFunctionDynamicToString: VgiService["tableFunctionDynamicToString"] = async (params) => {
698
+ const tableFunctionDynamicToString: VgiService["tableFunctionDynamicToString"] = async (params, ctx?: any) => {
654
699
  const innerParams = unwrapRequest(params.request);
655
- const bindCallBytes = toUint8Array(innerParams.bind_call);
656
- const bindCallBatch = deserializeBatch(bindCallBytes);
657
- // Single-row bind_call batch -> dict via the codec/canonical path.
658
- const bindParams = batchToScalarDict(bindCallBatch);
659
- const bindCall = deserializeBindRequest(bindParams);
700
+ const bindCall = decodeBindCall(
701
+ toUint8Array(innerParams.bind_call),
702
+ "TableFunctionDynamicToStringRequest.bind_call",
703
+ );
704
+ await resolveBindCall(bindCall, ctx);
660
705
  const globalExecutionId = toUint8Array(innerParams.global_execution_id);
661
706
  const bindOpaqueData = innerParams.bind_opaque_data
662
707
  ? toUint8Array(innerParams.bind_opaque_data)
663
708
  : null;
664
- const func = registry.get(bindCall.function_name, await strippedContext(bindCall));
709
+ const func = registry.get(bindCall.function_name, await strippedContext(bindCall, ctx));
665
710
  // Its BoundStorage must reach the same attach shard as the scan's.
666
711
  try {
667
712
  bindCall.storage_shard_key = await shardKeyForAttach(
@@ -682,6 +727,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
682
727
 
683
728
  const tableFunctionProjection: VgiService["tableFunctionProjection"] = async (
684
729
  params,
730
+ ctx?: any,
685
731
  ) => {
686
732
  if (toUint8Array(params.request).length > 8 * 1024 * 1024)
687
733
  throw new Error("projection exceeds 8MiB");
@@ -695,10 +741,13 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
695
741
  (v) => toUint8Array(v).length,
696
742
  ).reduce((a, b) => a + b, 0);
697
743
  if (size > 8 * 1024 * 1024) throw new Error("projection exceeds 8MiB");
744
+ // The strict record check first (exact generated schema), then the
745
+ // raw-preserving decode.
746
+ projectionRecord(toUint8Array(inner.bind_call), BindRequestSchema);
747
+ const bindCall = decodeBindCall(toUint8Array(inner.bind_call), "TableFunctionProjectionRequest.bind_call");
748
+ await resolveBindCall(bindCall, ctx);
698
749
  const proposal: ProjectionProposal = {
699
- bindCall: deserializeBindRequest(
700
- projectionRecord(toUint8Array(inner.bind_call), BindRequestSchema),
701
- ),
750
+ bindCall,
702
751
  bindResult: deserializeBindResponse(
703
752
  projectionRecord(toUint8Array(inner.bind_result), BindResultSchema),
704
753
  ),
@@ -708,7 +757,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
708
757
  validateProjectionProposal(proposal);
709
758
  const func = registry.get(
710
759
  proposal.bindCall.function_name,
711
- await strippedContext(proposal.bindCall),
760
+ await strippedContext(proposal.bindCall, ctx),
712
761
  );
713
762
  if (func.kind !== "table")
714
763
  throw new Error("projection requires an ordinary table");
@@ -9,6 +9,7 @@
9
9
  // execution_id), then rebuilds the user-facing TableBufferingParams. Mirrors
10
10
  // vgi-python's worker._load_table_buffering_params.
11
11
 
12
+ import { resolveBindCall } from "../arguments-ref.js";
12
13
  import { deserializeBatch } from "../../arrow/index.js";
13
14
  import type { VgiService } from "../../generated/vgi-service.js";
14
15
  import type { FunctionRegistry } from "../../functions/registry.js";
@@ -99,6 +100,10 @@ export function tableBufferingHandlers(
99
100
  storage_shard_key: shardKey,
100
101
  },
101
102
  };
103
+ // The stored init holds an argument reference as the reference: resolve
104
+ // it for this request (vgi-rpc's object cache, one storage GET per object
105
+ // per process) before anything reads the arguments.
106
+ await resolveBindCall(request.bind_call, ctx);
102
107
  const args = func.bufferingExtractArgs(request.bind_call);
103
108
  const settings = batchToScalarDict(request.bind_call.settings);
104
109
  const secrets = batchToSecretDict(request.bind_call.secrets);
@@ -8,6 +8,9 @@ export { serializeArguments, deserializeArguments } from "./serializers/argument
8
8
  export {
9
9
  serializeBindRequest,
10
10
  deserializeBindRequest,
11
+ decodeBindCall,
12
+ bindCallBytes,
13
+ receivedBindCall,
11
14
  serializeBindResponse,
12
15
  deserializeBindResponse,
13
16
  } from "./serializers/bind.js";
@@ -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;