@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
@@ -12,8 +12,9 @@ import { exchangeStream, type VgiService } from "../../generated/vgi-service.js"
12
12
  import type { FunctionRegistry } from "../../functions/registry.js";
13
13
  import type { StreamHandlers, HandlerState } from "../../functions/types.js";
14
14
  import { refuseMoreOutput } from "../../functions/continuation.js";
15
+ import { persistBufferingInit } from "../../functions/table-buffering.js";
16
+ import { TableInOutPhase } from "../../types.js";
15
17
  import {
16
- deserializeBindRequest,
17
18
  serializeBindResponse,
18
19
  deserializeInitRequest,
19
20
  serializeGlobalInitResponse,
@@ -21,7 +22,7 @@ import {
21
22
  serializeTableCardinality,
22
23
  } from "../serialize.js";
23
24
  import type { GlobalInitResponse } from "../types.js";
24
- import { batchToScalarDict, deserializeBatch, adoptArrowJsShape } from "../../util/arrow/index.js";
25
+ import { adoptArrowJsShape } from "../../util/arrow/index.js";
25
26
  import { toUint8Array } from "../../util/bytes.js";
26
27
  import { serializeColumnStatistics } from "../../util/statistics.js";
27
28
  import {
@@ -33,8 +34,10 @@ import {
33
34
  TableFunctionDynamicToStringResultSchema,
34
35
  } from "../../generated/vgi-protocol-schemas.js";
35
36
  import { unwrapRequest, wrapResult, overloadContext } from "./shared.js";
36
- import { parseCarriedInitRequest } from "../carried-init-request.js";
37
- import { openAttach, openTransaction } from "./catalog/shared.js";
37
+ import { bindCallBytes, decodeBindCall } from "../serializers/bind.js";
38
+ import { resolveBindCall } from "../arguments-ref.js";
39
+ import { decodeStreamInit, encodeStreamInit } from "../stream-init.js";
40
+ import { openAttach, openAttachWithShard, openTransaction, shardKeyForAttach } from "./catalog/shared.js";
38
41
  import { currentRequestAuth } from "../../request-auth.js";
39
42
  import { batchFromColumns, serializeBatch } from "../../util/arrow/index.js";
40
43
  import {
@@ -58,6 +61,8 @@ export interface FunctionHandlerConfig {
58
61
  signingKey?: Uint8Array | undefined;
59
62
  /** Explicit root key for secret ATTACH options (see attach-secret-options.ts). */
60
63
  attachSecretKey?: Uint8Array | undefined;
64
+ /** Seal ikm for framework storage payloads (see ProtocolConfig.storageSealKey). */
65
+ storageSealKey?: Uint8Array | undefined;
61
66
  /**
62
67
  * Used to map a bind's `attach_opaque_data` to its catalog, so resolution can
63
68
  * be scoped when two catalogs declare the same schema and function name.
@@ -204,9 +209,50 @@ async function resolveSplitPayloads(
204
209
  }
205
210
  }
206
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
+
207
252
  /** The per-function lifecycle's `vgi.v3` handlers. */
208
253
  export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiService> {
209
254
  const { registry, signingKey, catalogInterface, attachSecretKey } = config;
255
+ const storageSealKey = config.storageSealKey ?? signingKey;
210
256
 
211
257
  // The framework mints every attach as uuid(16) || catalog_bytes (sealed on
212
258
  // HTTP, plaintext on subprocess). Function bodies — like catalog bodies —
@@ -218,31 +264,15 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
218
264
  // the same principal. Getting an authenticated caller's identity wrong here
219
265
  // is not a degraded lookup but a hard `OpaqueDataRejectedError`: the envelope
220
266
  // is sealed under `attachAad(auth)`.
221
- async function stripAttach(attach: any, ctx: any): Promise<Uint8Array | null> {
222
- if (attach == null) return null;
223
- const env = toUint8Array(attach);
224
- if (env.length === 0) return env;
225
- return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
226
- }
227
-
228
267
  // Unseal a bind call's opaque values in place, as the catalog handlers do:
229
268
  // the transaction first (its envelope binds the *sealed* attach), then the
230
269
  // attach. Every function-side request goes through this, so function bodies
231
270
  // see the same transaction plaintext that transactionCommit/Rollback get.
232
271
  async function openOpaque(
233
- bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null },
272
+ bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null; storage_shard_key?: string | null },
234
273
  ctx: any,
235
274
  ): Promise<void> {
236
- const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
237
- if (bindCall.transaction_opaque_data != null) {
238
- bindCall.transaction_opaque_data = await openTransaction(
239
- toUint8Array(bindCall.transaction_opaque_data),
240
- sealedAttach,
241
- ctx?.auth ?? currentRequestAuth(),
242
- signingKey,
243
- );
244
- }
245
- bindCall.attach_opaque_data = await stripAttach(bindCall.attach_opaque_data, ctx);
275
+ await openBindCallOpaque(bindCall, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
246
276
  }
247
277
 
248
278
  // Build an overload context whose attach has been unsealed, so catalog
@@ -276,8 +306,10 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
276
306
  // bind (unary)
277
307
  // --------------------------------------------------------------------------
278
308
  const bind: VgiService["bind"] = async (params, ctx) => {
279
- const innerParams = unwrapRequest(params.request);
280
- 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);
281
313
  await openOpaque(request, ctx);
282
314
  const func = registry.get(request.function_name, overloadContext(request, catalogInterface));
283
315
  const response = await func.bind(request);
@@ -315,6 +347,9 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
315
347
  // attach_opaque_data not recognized` on its first scan, i.e. this worker
316
348
  // could not serve authenticated traffic at all.
317
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);
318
353
  await openOpaque(request.bind_call, ctx);
319
354
 
320
355
  // Verify and strip the split envelopes BEFORE any user code runs, so an
@@ -333,6 +368,14 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
333
368
  // FunctionStorage (e.g. Cloudflare DO).
334
369
  const initResponse = await func.globalInit(request);
335
370
 
371
+ // A buffered (sink+source) sink init persists its init context, sealed,
372
+ // so any worker can serve the unary process/combine RPCs that follow.
373
+ // Done here rather than in the function because only this layer holds
374
+ // the signing key the seal derives from.
375
+ if ((func as any).kind === "table_buffering" && request.phase === TableInOutPhase.TABLE_BUFFERING) {
376
+ await persistBufferingInit(request, initResponse, storageSealKey);
377
+ }
378
+
336
379
  // A FINALIZE stream reads its accumulated states from storage, where
337
380
  // every INPUT turn persisted them. Its `init_opaque_data` is the primary
338
381
  // init's opaque data echoed back (vgi-python's InitRequest), never a
@@ -357,9 +400,22 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
357
400
  // Build state object with raw binary data (no base64/hex encoding).
358
401
  // The Arrow state serializer picks fields by name; live objects
359
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
+ });
360
414
  const state: any = {
361
415
  functionName: request.bind_call.function_name,
362
- 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`).
363
419
  executionId: initResponse.execution_id,
364
420
  maxWorkers: Number(initResponse.max_workers),
365
421
  opaqueData: initResponse.opaque_data ?? null,
@@ -403,17 +459,21 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
403
459
  // Deserialized from token — reconstruct from serializable refs.
404
460
  // Infrastructure (processParams, BoundStorage) is recreated fresh.
405
461
  // Mutable user state is merged from state.userState.
406
- // Parsed once per process per stream (carried-init-request.ts): the
407
- // cursor carries the packed request unchanged on every turn.
408
- const carried = parseCarriedInitRequest(state.initRequestPacked);
409
- 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);
410
472
  // The cursor carries the wire request, whose attach is still the sealed
411
473
  // envelope. Strip it exactly as the init turn did, before any user code
412
474
  // or split resolution sees it: every turn of a stream must hand the
413
475
  // function the catalog's own bytes, not just the first. (Unopenable is
414
476
  // a hard error here, as on the init turn: the cursor is caller-bound.)
415
- // `carried.request.bind_call` is a per-call copy, so this does not
416
- // disturb the memoised parse other turns share.
417
477
  await openOpaque(request.bind_call, undefined);
418
478
  // Re-derive the split payloads. The cursor carries the wire request,
419
479
  // which has `split_tokens` but not the opened `split_payloads` — that
@@ -423,13 +483,14 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
423
483
  // splits at all". checkAnchor is false: redemption was already decided
424
484
  // on the init turn, and re-checking here would let a mid-scan catalog
425
485
  // bump fail a query that had already been admitted.
426
- // fingerprintInputs hashes the RAW bind_call bytes, so pass the
427
- // pre-deserialization blob from the cursor — handing it the decoded
428
- // object hashes a different shape and every token fails as
429
- // SPLIT_TOKEN_INVALID "minted for a different bind".
430
- 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) }, {
431
492
  // Same principal the tokens were sealed under. The exchange dispatch
432
- // gets no ctx (see stripAttach above), so the request-scoped identity
493
+ // gets no ctx (see openOpaque above), so the request-scoped identity
433
494
  // is the only source — opening under the anonymous tail would fail
434
495
  // authentication for every authenticated caller's own tokens.
435
496
  auth: currentRequestAuth(),
@@ -441,12 +502,10 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
441
502
  // Already stripped above, so resolve directly (strippedContext would try
442
503
  // to open the plaintext again and fall back to an unscoped lookup).
443
504
  const func = registry.get(state.functionName, overloadContext(request.bind_call, catalogInterface));
444
- const executionId = state.executionId;
445
- const opaqueData = state.opaqueData ?? null;
446
505
  const initResponse: GlobalInitResponse = {
447
- execution_id: executionId,
448
- max_workers: Number(state.maxWorkers ?? 1),
449
- opaque_data: opaqueData,
506
+ execution_id: carried.executionId,
507
+ max_workers: Number(carried.maxWorkers ?? 1),
508
+ opaque_data: carried.opaqueData,
450
509
  };
451
510
 
452
511
  // The cursor's compacted dynamic-filter history: without it every turn
@@ -515,10 +574,11 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
515
574
  // --------------------------------------------------------------------------
516
575
  // table_function_cardinality (unary)
517
576
  // --------------------------------------------------------------------------
518
- const tableFunctionCardinality: VgiService["tableFunctionCardinality"] = async (params) => {
577
+ const tableFunctionCardinality: VgiService["tableFunctionCardinality"] = async (params, ctx?: any) => {
519
578
  const innerParams = unwrapRequest(params.request);
520
579
  const request = deserializeCardinalityRequest(innerParams);
521
- 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));
522
582
  let cardResult: Record<string, any>;
523
583
  if (func.cardinality) {
524
584
  cardResult = serializeTableCardinality(await func.cardinality(request));
@@ -542,9 +602,10 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
542
602
  const tableFunctionPlan: VgiService["tableFunctionPlan"] = async (params, ctx?: any) => {
543
603
  const innerParams = unwrapRequest(params.request);
544
604
  const request = deserializePlanRequest(innerParams);
605
+ await resolveBindCall(request.bind_call, ctx);
545
606
  const func = registry.get(
546
607
  request.bind_call.function_name,
547
- await strippedContext(request.bind_call),
608
+ await strippedContext(request.bind_call, ctx),
548
609
  );
549
610
 
550
611
  const plan: PlanResult = func.plan
@@ -614,10 +675,11 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
614
675
  // the function declared a statistics() hook and it produced a non-empty
615
676
  // list, else null. DuckDB uses the bounds for plan-time filter elimination
616
677
  // (folds impossible filters to EMPTY_RESULT).
617
- const tableFunctionStatistics: VgiService["tableFunctionStatistics"] = async (params) => {
678
+ const tableFunctionStatistics: VgiService["tableFunctionStatistics"] = async (params, ctx?: any) => {
618
679
  const innerParams = unwrapRequest(params.request);
619
- const request = deserializeCardinalityRequest(innerParams);
620
- 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));
621
683
  if (!func.statistics) return { result: null };
622
684
  const stats = func.statistics(request);
623
685
  if (!stats || stats.length === 0) return { result: null };
@@ -633,18 +695,28 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
633
695
  // intrinsics (Function, Rows Read, Threads). When the function doesn't
634
696
  // declare dynamicToString, return empty maps so the C++ side falls back
635
697
  // to intrinsics only.
636
- const tableFunctionDynamicToString: VgiService["tableFunctionDynamicToString"] = async (params) => {
698
+ const tableFunctionDynamicToString: VgiService["tableFunctionDynamicToString"] = async (params, ctx?: any) => {
637
699
  const innerParams = unwrapRequest(params.request);
638
- const bindCallBytes = toUint8Array(innerParams.bind_call);
639
- const bindCallBatch = deserializeBatch(bindCallBytes);
640
- // Single-row bind_call batch -> dict via the codec/canonical path.
641
- const bindParams = batchToScalarDict(bindCallBatch);
642
- const bindCall = deserializeBindRequest(bindParams);
700
+ const bindCall = decodeBindCall(
701
+ toUint8Array(innerParams.bind_call),
702
+ "TableFunctionDynamicToStringRequest.bind_call",
703
+ );
704
+ await resolveBindCall(bindCall, ctx);
643
705
  const globalExecutionId = toUint8Array(innerParams.global_execution_id);
644
706
  const bindOpaqueData = innerParams.bind_opaque_data
645
707
  ? toUint8Array(innerParams.bind_opaque_data)
646
708
  : null;
647
- const func = registry.get(bindCall.function_name, await strippedContext(bindCall));
709
+ const func = registry.get(bindCall.function_name, await strippedContext(bindCall, ctx));
710
+ // Its BoundStorage must reach the same attach shard as the scan's.
711
+ try {
712
+ bindCall.storage_shard_key = await shardKeyForAttach(
713
+ bindCall.attach_opaque_data ?? undefined,
714
+ currentRequestAuth(),
715
+ signingKey,
716
+ );
717
+ } catch {
718
+ bindCall.storage_shard_key = "";
719
+ }
648
720
  const map = func.dynamicToString
649
721
  ? await func.dynamicToString({ bindCall, bindOpaqueData, globalExecutionId })
650
722
  : {};
@@ -655,6 +727,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
655
727
 
656
728
  const tableFunctionProjection: VgiService["tableFunctionProjection"] = async (
657
729
  params,
730
+ ctx?: any,
658
731
  ) => {
659
732
  if (toUint8Array(params.request).length > 8 * 1024 * 1024)
660
733
  throw new Error("projection exceeds 8MiB");
@@ -668,10 +741,13 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
668
741
  (v) => toUint8Array(v).length,
669
742
  ).reduce((a, b) => a + b, 0);
670
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);
671
749
  const proposal: ProjectionProposal = {
672
- bindCall: deserializeBindRequest(
673
- projectionRecord(toUint8Array(inner.bind_call), BindRequestSchema),
674
- ),
750
+ bindCall,
675
751
  bindResult: deserializeBindResponse(
676
752
  projectionRecord(toUint8Array(inner.bind_result), BindResultSchema),
677
753
  ),
@@ -681,7 +757,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
681
757
  validateProjectionProposal(proposal);
682
758
  const func = registry.get(
683
759
  proposal.bindCall.function_name,
684
- await strippedContext(proposal.bindCall),
760
+ await strippedContext(proposal.bindCall, ctx),
685
761
  );
686
762
  if (func.kind !== "table")
687
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";
@@ -20,17 +21,16 @@ import {
20
21
  TableBufferingProcessResultSchema,
21
22
  } from "../../generated/vgi-protocol-schemas.js";
22
23
  import { unwrapRequest, wrapResult } from "./shared.js";
23
- import { openAttach } from "./catalog/shared.js";
24
+ import { openAttachWithShard, openTransaction } from "./catalog/shared.js";
25
+ import { BoundStorage, storage as defaultStorage } from "../../functions/storage.js";
24
26
  import {
25
- BoundStorage,
26
- storage as defaultStorage,
27
- FrameworkNS,
28
- } from "../../functions/storage.js";
29
- import {
30
- decodeBufferingInit,
27
+ bufferingInitCache,
28
+ loadBufferingInit,
31
29
  type TableBufferingVgiFunction,
32
30
  type TableBufferingParams,
33
31
  } from "../../functions/table-buffering.js";
32
+ import type { InitRequest } from "../types.js";
33
+ import { currentRequestAuth } from "../../request-auth.js";
34
34
  import { Arguments } from "../../arguments/arguments.js";
35
35
 
36
36
  /** The table_buffering lifecycle's `vgi.v3` handlers. */
@@ -38,6 +38,7 @@ export function tableBufferingHandlers(
38
38
  registry: FunctionRegistry,
39
39
  signingKey?: Uint8Array,
40
40
  attachSecretKey?: Uint8Array,
41
+ storageSealKey: Uint8Array | undefined = signingKey,
41
42
  ): Partial<VgiService> {
42
43
  // `schemaPath` scopes resolution to the schema the caller named. The
43
44
  // buffering process/combine RPCs carry it (protocol 1.2.0), so a name
@@ -67,31 +68,42 @@ export function tableBufferingHandlers(
67
68
  ): Promise<{ func: TableBufferingVgiFunction; params: TableBufferingParams<any> }> {
68
69
  const functionName: string = inner.function_name;
69
70
  const executionId = toUint8Array(inner.execution_id);
71
+ const auth = ctx?.auth ?? currentRequestAuth();
70
72
  // Unseal attach_opaque_data so combine()/process() see the SAME plaintext,
71
- // attach-scoped bytes that bind()/init() and plain table functions see.
72
- // Without this, on HTTP transport the buffering RPCs would scope persistent
73
- // BoundStorage by the *sealed* envelope while reads scope by the plaintext,
74
- // so attach-scoped state written in combine() is invisible to later reads.
73
+ // attach-scoped bytes that bind()/init() and plain table functions see,
74
+ // and derive the storage shard from its framework UUID: the init context
75
+ // and every BoundStorage call of this execution live in that shard.
75
76
  const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
76
- const attach =
77
- rawAttach && rawAttach.length > 0
78
- ? await openAttach(rawAttach, ctx?.auth, signingKey, attachSecretKey)
79
- : rawAttach;
77
+ const { attach, shardKey } = await openAttachWithShard(rawAttach, auth, signingKey, attachSecretKey);
80
78
  const transactionId = inner.transaction_id ? toUint8Array(inner.transaction_id) : null;
81
79
 
82
80
  const func = resolveBuffering(functionName, inner.schema_path ?? null);
83
- const bound = new BoundStorage(defaultStorage, executionId);
84
- const payload = await bound.stateGet(
85
- FrameworkNS.BUFFERING_INIT,
86
- BoundStorage.packIntKey(-1),
87
- );
88
- if (payload == null) {
89
- throw new Error(
90
- `table_buffering: unknown execution_id ${hex(executionId)} ` +
91
- `(init never ran or destructor already fired)`,
92
- );
81
+ const bound = new BoundStorage(defaultStorage, executionId, null, shardKey);
82
+ // Cached per (shard, execution) after the first load; storage (sealed) is
83
+ // authoritative on a miss. The stored request carries no attach or
84
+ // transaction: they come from this request, opened as the init turn did.
85
+ const init = await loadBufferingInit(bound, storageSealKey);
86
+ let txnPlain = transactionId;
87
+ if (txnPlain && txnPlain.length > 0 && signingKey && rawAttach) {
88
+ try {
89
+ txnPlain = await openTransaction(txnPlain, rawAttach, auth, signingKey);
90
+ } catch {
91
+ // Not a sealed transaction value: keep it as given.
92
+ }
93
93
  }
94
- const { request } = decodeBufferingInit(payload);
94
+ const request: InitRequest = {
95
+ ...init.request,
96
+ bind_call: {
97
+ ...init.request.bind_call,
98
+ attach_opaque_data: attach,
99
+ transaction_opaque_data: txnPlain,
100
+ storage_shard_key: shardKey,
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);
95
107
  const args = func.bufferingExtractArgs(request.bind_call);
96
108
  const settings = batchToScalarDict(request.bind_call.settings);
97
109
  const secrets = batchToSecretDict(request.bind_call.secrets);
@@ -159,11 +171,20 @@ export function tableBufferingHandlers(
159
171
  // ------------------------------------------------------------------------
160
172
  // table_buffering_destructor — best-effort end-of-query cleanup (unary)
161
173
  // ------------------------------------------------------------------------
162
- const tableBufferingDestructor: VgiService["tableBufferingDestructor"] = async (rpcParams) => {
174
+ const tableBufferingDestructor: VgiService["tableBufferingDestructor"] = async (rpcParams, ctx?: any) => {
163
175
  try {
164
176
  const inner = unwrapRequest(rpcParams.request);
165
177
  const executionId = toUint8Array(inner.execution_id);
166
- const bound = new BoundStorage(defaultStorage, executionId);
178
+ const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
179
+ // The execution's state lives in its attach's shard, not the default one.
180
+ const { shardKey } = await openAttachWithShard(
181
+ rawAttach,
182
+ ctx?.auth ?? currentRequestAuth(),
183
+ signingKey,
184
+ attachSecretKey,
185
+ );
186
+ bufferingInitCache.delete(shardKey, executionId);
187
+ const bound = new BoundStorage(defaultStorage, executionId, null, shardKey);
167
188
  await bound.executionClear();
168
189
  } catch {
169
190
  // Teardown path — swallow; the entry is wiped when the worker exits.
@@ -195,7 +216,3 @@ function decodeBytesList(raw: any): Uint8Array[] {
195
216
  }
196
217
  return out;
197
218
  }
198
-
199
- function hex(buf: Uint8Array): string {
200
- return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
201
- }
@@ -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";