@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
@@ -13,6 +13,9 @@
13
13
  // We resolve all node:* and bun:* dependencies through indirect string
14
14
  // variables that esbuild can't trace statically, so workerd bundles cleanly
15
15
  // without nodejs_compat polyfills for paths we never run.
16
+ import { sealPayload, openPayload, type StorageSlot } from "./storage-seal.js";
17
+ import { wrapStorageFromEnv } from "./storage-blobs.js";
18
+
16
19
  type Database = any;
17
20
  const _BUN_SQLITE_MOD = "bun:sqlite";
18
21
  const _NODE_OS_MOD = "node:os";
@@ -107,6 +110,16 @@ export interface FunctionStorage {
107
110
  // --- Namespaced key/value state (scoped by execution_id) ---
108
111
  stateGet(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null>;
109
112
  statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void>;
113
+ /** Batched read: one value (or null) per key, in key order. One round trip
114
+ * on a remote backend. */
115
+ stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>>;
116
+ /** Batched atomic upsert of `(key, value)` pairs. One round trip on a remote
117
+ * backend; a no-op for an empty list. */
118
+ statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void>;
119
+ /** Optional: delete the given keys of one namespace, returning how many rows
120
+ * went. Missing keys are ignored. Every built-in backend implements it;
121
+ * {@link BoundStorage.stateDelete} refuses on a backend that does not. */
122
+ stateDelete?(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<number>;
110
123
  // --- Append-only log (scoped by execution_id) ---
111
124
  stateAppend(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number>;
112
125
  stateLogScan(
@@ -120,6 +133,15 @@ export interface FunctionStorage {
120
133
  executionClear(scopeId: Uint8Array): Promise<number>;
121
134
  /** Optional cleanup hook. Implementations holding a connection should release it here. */
122
135
  close?(): Promise<void> | void;
136
+ /**
137
+ * Optional: a view of this backend routed to one attach shard. A backend
138
+ * that partitions remotely (the Cloudflare DO, one Durable Object per
139
+ * logical ATTACH) implements it; a local backend that needs no routing
140
+ * omits it. {@link BoundStorage} calls it with the shard key the framework
141
+ * derived from the request's authenticated attach (`att-<uuid hex>`), or
142
+ * `""` when the call is not bound to an ATTACH.
143
+ */
144
+ forShard?(shardKey: string): FunctionStorage;
123
145
  }
124
146
 
125
147
  // FrameworkNS — namespaces the framework itself uses (mirrors Python's
@@ -127,6 +149,9 @@ export interface FunctionStorage {
127
149
  export const FrameworkNS = {
128
150
  BUFFERING_INIT: textBytes("_vgi/buffering_init"),
129
151
  STREAMING_FINALIZE: textBytes("_vgi/streaming_finalize"),
152
+ /** Aggregate group states (key = packIntKey(group_id)) and, at key
153
+ * packIntKey(-2), the sealed bind context. Same bytes as vgi-python. */
154
+ AGGREGATE_STATE: textBytes("_vgi/aggregate_state"),
130
155
  } as const;
131
156
 
132
157
  function textBytes(s: string): Uint8Array {
@@ -156,7 +181,9 @@ function getDefaultDbPath(): string {
156
181
  platform() === "darwin"
157
182
  ? join(home, "Library", "Application Support", "vgi")
158
183
  : join(home, ".local", "state", "vgi");
159
- mkdirSync(stateDir, { recursive: true });
184
+ // Owner-only: the file holds other executions' in-flight state. Framework
185
+ // context in it is sealed (./storage-seal.ts), user state is not.
186
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
160
187
  return join(stateDir, "vgi_storage.db");
161
188
  }
162
189
 
@@ -327,6 +354,51 @@ export class FunctionStorageSqlite implements FunctionStorage {
327
354
  .run(bufferArg(scopeId), bufferArg(ns), bufferArg(key), bufferArg(value));
328
355
  }
329
356
 
357
+ async stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>> {
358
+ if (keys.length === 0) return [];
359
+ const stmt = this._db.prepare("SELECT value FROM function_state WHERE scope_id = ? AND ns = ? AND key = ?");
360
+ const sid = bufferArg(scopeId);
361
+ const nsb = bufferArg(ns);
362
+ return keys.map((k) => {
363
+ const row = stmt.get(sid, nsb, bufferArg(k)) as { value: Uint8Array } | null;
364
+ return row ? new Uint8Array(row.value) : null;
365
+ });
366
+ }
367
+
368
+ async statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void> {
369
+ if (items.length === 0) return;
370
+ const stmt = this._db.prepare(
371
+ "INSERT OR REPLACE INTO function_state (scope_id, ns, key, value) VALUES (?, ?, ?, ?)",
372
+ );
373
+ const sid = bufferArg(scopeId);
374
+ const nsb = bufferArg(ns);
375
+ this._db.exec("BEGIN IMMEDIATE");
376
+ try {
377
+ for (const [k, v] of items) stmt.run(sid, nsb, bufferArg(k), bufferArg(v));
378
+ this._db.exec("COMMIT");
379
+ } catch (e) {
380
+ this._db.exec("ROLLBACK");
381
+ throw e;
382
+ }
383
+ }
384
+
385
+ async stateDelete(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<number> {
386
+ if (keys.length === 0) return 0;
387
+ const stmt = this._db.prepare("DELETE FROM function_state WHERE scope_id = ? AND ns = ? AND key = ?");
388
+ const sid = bufferArg(scopeId);
389
+ const nsb = bufferArg(ns);
390
+ let deleted = 0;
391
+ this._db.exec("BEGIN IMMEDIATE");
392
+ try {
393
+ for (const k of keys) deleted += stmt.run(sid, nsb, bufferArg(k)).changes as number;
394
+ this._db.exec("COMMIT");
395
+ } catch (e) {
396
+ this._db.exec("ROLLBACK");
397
+ throw e;
398
+ }
399
+ return deleted;
400
+ }
401
+
330
402
  async stateAppend(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number> {
331
403
  const res = this._db
332
404
  .prepare("INSERT INTO function_state_log (scope_id, ns, key, value) VALUES (?, ?, ?, ?)")
@@ -444,17 +516,39 @@ export class BoundStorage {
444
516
  private _base: FunctionStorage;
445
517
  private _executionId: Uint8Array;
446
518
  private _substreamId: Uint8Array | null;
519
+ private _shardKey: string;
447
520
 
448
521
  /**
449
522
  * @param substreamId The table-in-out substream this storage serves -- the
450
523
  * client-minted `InitRequest.substream_id`, identical across the
451
524
  * substream's init, every tick and its finalize -- or `null` when the
452
525
  * client sent none. Keys {@link put}.
526
+ * @param shardKey The attach shard every call routes to: `att-<uuid hex>`,
527
+ * derived by the framework from the request's authenticated attach (see
528
+ * {@link shardKeyOf}), or `""` when the call is not bound to an ATTACH. A
529
+ * backend with `forShard` (the Cloudflare DO) routes on it; it is also part
530
+ * of every sealed framework payload's AAD.
453
531
  */
454
- constructor(storage: FunctionStorage, executionId: Uint8Array, substreamId: Uint8Array | null = null) {
455
- this._base = storage;
532
+ constructor(
533
+ storage: FunctionStorage,
534
+ executionId: Uint8Array,
535
+ substreamId: Uint8Array | null = null,
536
+ shardKey: string = "",
537
+ ) {
538
+ this._base = typeof storage.forShard === "function" ? storage.forShard(shardKey) : storage;
456
539
  this._executionId = executionId;
457
540
  this._substreamId = substreamId;
541
+ this._shardKey = shardKey;
542
+ }
543
+
544
+ /** The attach shard this view routes to ("" when not bound to an ATTACH). */
545
+ get shardKey(): string {
546
+ return this._shardKey;
547
+ }
548
+
549
+ /** The execution (scope) id this view is bound to. */
550
+ get executionId(): Uint8Array {
551
+ return this._executionId;
458
552
  }
459
553
 
460
554
  /**
@@ -503,6 +597,26 @@ export class BoundStorage {
503
597
  return this._base.statePut(this._executionId, ns, key, value);
504
598
  }
505
599
 
600
+ /** Batched read, one value (or null) per key. One round trip remotely. */
601
+ stateGetMany(ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>> {
602
+ return this._base.stateGetMany(this._executionId, ns, keys);
603
+ }
604
+
605
+ /** Batched atomic upsert. One round trip remotely. */
606
+ statePutMany(ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void> {
607
+ return this._base.statePutMany(this._executionId, ns, items);
608
+ }
609
+
610
+ /** Delete keys of one namespace; their values' blobs (when externalized)
611
+ * stay until the execution is cleared.
612
+ * @throws Error if the backend does not implement `stateDelete`. */
613
+ stateDelete(ns: Uint8Array, keys: Uint8Array[]): Promise<number> {
614
+ if (typeof this._base.stateDelete !== "function") {
615
+ return Promise.reject(new Error("this FunctionStorage backend does not implement stateDelete"));
616
+ }
617
+ return this._base.stateDelete(this._executionId, ns, keys);
618
+ }
619
+
506
620
  stateAppend(ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number> {
507
621
  return this._base.stateAppend(this._executionId, ns, key, item);
508
622
  }
@@ -520,11 +634,46 @@ export class BoundStorage {
520
634
  return this._base.executionClear(this._executionId);
521
635
  }
522
636
 
637
+ // --- Sealed framework payloads (./storage-seal.ts) ---------------------
638
+ // For framework context only (init requests, bind context): authenticated
639
+ // encryption bound to (shard, execution, ns, key). `signingKey` is the
640
+ // worker's HTTP signing key, or undefined (the host-local key is used).
641
+
642
+ private _slot(ns: Uint8Array, key: Uint8Array): StorageSlot {
643
+ return { shardKey: this._shardKey, scopeId: this._executionId, ns, key };
644
+ }
645
+
646
+ /** Seal `payload` to its slot, store it, and return the stored envelope. */
647
+ async sealedPut(ns: Uint8Array, key: Uint8Array, payload: Uint8Array, signingKey: Uint8Array | undefined): Promise<Uint8Array> {
648
+ const sealed = await sealPayload(payload, signingKey, this._slot(ns, key));
649
+ await this.statePut(ns, key, sealed);
650
+ return sealed;
651
+ }
652
+
653
+ /** Open an envelope from {@link sealedPut} for this slot (StoragePayloadError on failure). */
654
+ openSealed(ns: Uint8Array, key: Uint8Array, sealed: Uint8Array, signingKey: Uint8Array | undefined): Promise<Uint8Array> {
655
+ return openPayload(sealed, signingKey, this._slot(ns, key));
656
+ }
657
+
658
+ /** Read and open a sealed framework payload; null when the slot is empty. */
659
+ async sealedGet(ns: Uint8Array, key: Uint8Array, signingKey: Uint8Array | undefined): Promise<Uint8Array | null> {
660
+ const sealed = await this.stateGet(ns, key);
661
+ return sealed == null ? null : this.openSealed(ns, key, sealed, signingKey);
662
+ }
663
+
523
664
  static packIntKey(i: number | bigint): Uint8Array {
524
665
  return packIntKey(i);
525
666
  }
526
667
  }
527
668
 
669
+ /**
670
+ * The attach shard key the framework stamped on a request's bind call when it
671
+ * opened the attach (`att-<uuid hex>`), or `""` when there is none.
672
+ */
673
+ export function shardKeyOf(bindCall: { storage_shard_key?: string | null | undefined } | null | undefined): string {
674
+ return bindCall?.storage_shard_key ?? "";
675
+ }
676
+
528
677
  // ============================================================================
529
678
  // Backend factory + lazy default storage
530
679
  // ============================================================================
@@ -542,19 +691,25 @@ export class BoundStorage {
542
691
  * (including `:memory:`).
543
692
  * - `cloudflare-do` — `FunctionStorageCfDo`. Requires `VGI_CF_DO_URL`;
544
693
  * optional `VGI_CF_DO_TOKEN` for bearer auth.
694
+ *
695
+ * The backend is wrapped in {@link ExternalizingStorage} (value envelope plus
696
+ * blob-vendor externalization, `./storage-blobs.ts`) always for
697
+ * `cloudflare-do`, and for any other backend with `VGI_STORAGE_EXTERNALIZE=1`;
698
+ * see `wrapStorageFromEnv`.
545
699
  */
546
700
  export function resolveStorageFromEnv(): FunctionStorage {
547
701
  const backend = (process.env.VGI_WORKER_SHARED_STORAGE ?? "sqlite").toLowerCase();
548
702
  if (backend === "memory") {
549
- return new FunctionStorageSqlite(":memory:");
703
+ return wrapStorageFromEnv(new FunctionStorageSqlite(":memory:"));
550
704
  }
551
705
  if (backend === "sqlite") {
552
- return new FunctionStorageSqlite();
706
+ return wrapStorageFromEnv(new FunctionStorageSqlite());
553
707
  }
554
708
  if (backend === "cloudflare-do") {
555
709
  // Lazy require to avoid loading the CF client when sqlite is in use.
556
- const { FunctionStorageCfDo } = require("./storage-cf-do.js") as typeof import("./storage-cf-do.js");
557
- return FunctionStorageCfDo.fromEnv();
710
+ const { FunctionStorageCfDo, MAX_VALUE_BYTES } = require("./storage-cf-do.js") as typeof import("./storage-cf-do.js");
711
+ // Always enveloped (vendor or not) so every process writes one format.
712
+ return wrapStorageFromEnv(FunctionStorageCfDo.fromEnv(), { maxValueBytes: MAX_VALUE_BYTES });
558
713
  }
559
714
  throw new Error(
560
715
  `Unknown VGI_WORKER_SHARED_STORAGE backend: '${backend}'. Supported: 'memory', 'sqlite', 'cloudflare-do'.`,
@@ -578,9 +733,20 @@ function getDefaultStorage(): FunctionStorage {
578
733
  * service-binding Fetcher (the binding lives on `env`, not `process.env`, and a
579
734
  * same-zone public-URL fetch is rejected with CF error 1042). Takes precedence
580
735
  * over `VGI_WORKER_SHARED_STORAGE`.
736
+ *
737
+ * A bare `FunctionStorageCfDo` is wrapped in {@link ExternalizingStorage}, as
738
+ * the env-selected one is, so every process writes the same enveloped format;
739
+ * the blob vendor comes from `VGI_BLOB_VENDOR_URL` in `process.env` when there
740
+ * is one. On Cloudflare Workers, where the vendor's URL and token are `env`
741
+ * bindings, wrap it yourself first --
742
+ * `setStorage(wrapStorageFromEnv(cfDo, { maxValueBytes: MAX_VALUE_BYTES, env }))`
743
+ * -- and it is used as given. Any other backend is used as given.
581
744
  */
582
745
  export function setStorage(impl: FunctionStorage): void {
583
- _resolved = impl;
746
+ _resolved =
747
+ (impl as { storageKind?: string }).storageKind === "cloudflare-do"
748
+ ? wrapStorageFromEnv(impl, { maxValueBytes: (impl as { maxValueBytes?: number }).maxValueBytes })
749
+ : impl;
584
750
  }
585
751
 
586
752
  /** Default FunctionStorage instance. Backend is selected via env on first access. */
@@ -16,7 +16,9 @@
16
16
  // The Source phase may route a finalize_state_id to a worker process that
17
17
  // did NOT run the corresponding process() calls.
18
18
 
19
+ import { unresolvedArguments } from "../protocol/arguments-ref.js";
19
20
  import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
21
+ import { secretLookupWire } from "../secrets/lookups.js";
20
22
  import {
21
23
  type VgiSchema,
22
24
  schema,
@@ -56,7 +58,9 @@ import {
56
58
  type PushdownFilters,
57
59
  } from "../filter-pushdown/index.js";
58
60
  import { FunctionStability } from "../types.js";
59
- import { BoundStorage, storage as defaultStorage, FrameworkNS } from "./storage.js";
61
+ import { BoundStorage, storage as defaultStorage, FrameworkNS, shardKeyOf } from "./storage.js";
62
+ import { ExecutionCache } from "./execution-cache.js";
63
+ import { StoragePayloadError } from "./storage-seal.js";
60
64
  import {
61
65
  serializeInitRequest,
62
66
  deserializeInitRequest,
@@ -307,9 +311,7 @@ export function defineTableBufferingFunction<
307
311
  return {
308
312
  output_schema: result.outputSchema,
309
313
  opaque_data: result.opaqueData ?? null,
310
- lookup_secret_types: result.lookupSecretTypes,
311
- lookup_scopes: result.lookupScopes,
312
- lookup_names: result.lookupNames,
314
+ ...secretLookupWire(config.name, result),
313
315
  };
314
316
  }
315
317
  return {
@@ -333,18 +335,9 @@ export function defineTableBufferingFunction<
333
335
  opaque_data: null,
334
336
  };
335
337
 
336
- // On the sink-side init, persist init metadata so any pool worker can
337
- // cold-load it when serving subsequent process()/combine() unary RPCs
338
- // (which carry no init context themselves). Mirrors Python's
339
- // FrameworkNS.BUFFERING_INIT state_put.
340
- if (request.phase === TableInOutPhase.TABLE_BUFFERING) {
341
- const bound = new BoundStorage(defaultStorage, executionId);
342
- await bound.statePut(
343
- FrameworkNS.BUFFERING_INIT,
344
- BoundStorage.packIntKey(-1),
345
- encodeBufferingInit(request, response),
346
- );
347
- }
338
+ // The sink-side init's context is persisted (sealed) by the init
339
+ // handler right after this returns -- see persistBufferingInit -- so
340
+ // any pool worker can cold-load it for the process()/combine() RPCs.
348
341
  return response;
349
342
  },
350
343
 
@@ -376,6 +369,8 @@ export function defineTableBufferingFunction<
376
369
  const bound = new BoundStorage(
377
370
  defaultStorage,
378
371
  response.execution_id ?? new Uint8Array(16),
372
+ null,
373
+ shardKeyOf(request.bind_call),
379
374
  );
380
375
 
381
376
  const params: TableBufferingParams<TArgs> = {
@@ -532,6 +527,85 @@ function makeProjectingCollector(
532
527
  // Init-metadata persistence (mirrors Python _encode/_decode_table_buffering_init)
533
528
  // ============================================================================
534
529
 
530
+ /** Storage key of the buffered init within FrameworkNS.BUFFERING_INIT. */
531
+ const BUFFERING_INIT_KEY = BoundStorage.packIntKey(-1);
532
+
533
+ /** Decoded buffered init context, as cached and as returned by the loader. */
534
+ export interface BufferingInit {
535
+ request: InitRequest;
536
+ response: GlobalInitResponse;
537
+ }
538
+
539
+ /**
540
+ * Decoded buffered-init context per (shard, execution). The init is written
541
+ * once and read on every process/combine RPC; with this, a process batch costs
542
+ * the function's own storage calls only. Small: one entry per in-flight
543
+ * buffered execution, evicted by the destructor.
544
+ */
545
+ export const bufferingInitCache = new ExecutionCache<BufferingInit>(64);
546
+
547
+ /**
548
+ * Persist a buffered sink init's context so any worker can serve the unary
549
+ * process/combine RPCs that follow, which carry no init context themselves.
550
+ *
551
+ * The stored InitRequest carries `bind_call.secrets`, so it is sealed
552
+ * (./storage-seal.ts) to its (shard, execution, ns, key) slot. Its attach and
553
+ * transaction values are NOT stored: every process/combine request carries
554
+ * them, and the loader fills them in from the request after opening them.
555
+ */
556
+ export async function persistBufferingInit(
557
+ request: InitRequest,
558
+ response: GlobalInitResponse,
559
+ signingKey: Uint8Array | undefined,
560
+ ): Promise<void> {
561
+ const shardKey = shardKeyOf(request.bind_call);
562
+ // A bind call that arrived by reference is stored -- and cached -- as that
563
+ // reference, never the resolved value (vgi docs/large-values-3.4.md §6):
564
+ // serializeBindRequest emits `arguments_location`, and the cached copy holds
565
+ // the unresolved placeholder, so neither storage nor this process's cache
566
+ // pins a large argument. The loader resolves it per request.
567
+ const stored: InitRequest = {
568
+ ...request,
569
+ bind_call: {
570
+ ...request.bind_call,
571
+ arguments: request.bind_call.arguments_location ? unresolvedArguments() : request.bind_call.arguments,
572
+ attach_opaque_data: null,
573
+ transaction_opaque_data: null,
574
+ },
575
+ };
576
+ const bound = new BoundStorage(defaultStorage, response.execution_id, null, shardKey);
577
+ await bound.sealedPut(FrameworkNS.BUFFERING_INIT, BUFFERING_INIT_KEY, encodeBufferingInit(stored, response), signingKey);
578
+ bufferingInitCache.set(shardKey, response.execution_id, { request: stored, response });
579
+ }
580
+
581
+ /**
582
+ * Load a buffered execution's init context: the in-process cache, else the
583
+ * sealed storage copy (opened, decoded, then cached). Throws when the
584
+ * execution is unknown, and StoragePayloadError when the stored copy does not
585
+ * authenticate for this shard / execution.
586
+ */
587
+ export async function loadBufferingInit(
588
+ bound: BoundStorage,
589
+ signingKey: Uint8Array | undefined,
590
+ ): Promise<BufferingInit> {
591
+ const cached = bufferingInitCache.get(bound.shardKey, bound.executionId);
592
+ if (cached) return cached;
593
+ const payload = await bound.sealedGet(FrameworkNS.BUFFERING_INIT, BUFFERING_INIT_KEY, signingKey);
594
+ if (payload == null) {
595
+ throw new Error(
596
+ `table_buffering: unknown execution_id ${hexOf(bound.executionId)} ` +
597
+ `(init never ran or destructor already fired)`,
598
+ );
599
+ }
600
+ const decoded = decodeBufferingInit(payload);
601
+ bufferingInitCache.set(bound.shardKey, bound.executionId, decoded);
602
+ return decoded;
603
+ }
604
+
605
+ function hexOf(buf: Uint8Array): string {
606
+ return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
607
+ }
608
+
535
609
  export function encodeBufferingInit(
536
610
  request: InitRequest,
537
611
  response: GlobalInitResponse,
@@ -593,8 +667,11 @@ function concatLenPrefixed(parts: Uint8Array[]): Uint8Array {
593
667
  return out;
594
668
  }
595
669
 
596
- // Always returns exactly `count` parts (a short buffer throws a RangeError from
597
- // the DataView), which the overloads encode as a tuple.
670
+ // Always returns exactly `count` parts, which the overloads encode as a tuple,
671
+ // and consumes the whole buffer: a truncated header, a length running past
672
+ // the end, or trailing bytes are a StoragePayloadError, never a silently short
673
+ // part. (The payload is authenticated before this runs; this guards the
674
+ // framing itself.)
598
675
  function splitLenPrefixed(buf: Uint8Array, count: 2): [Uint8Array, Uint8Array];
599
676
  function splitLenPrefixed(buf: Uint8Array, count: 3): [Uint8Array, Uint8Array, Uint8Array];
600
677
  function splitLenPrefixed(buf: Uint8Array, count: number): Uint8Array[] {
@@ -602,10 +679,19 @@ function splitLenPrefixed(buf: Uint8Array, count: number): Uint8Array[] {
602
679
  const parts: Uint8Array[] = [];
603
680
  let off = 0;
604
681
  for (let i = 0; i < count; i++) {
682
+ if (off + 4 > buf.length) {
683
+ throw new StoragePayloadError(`table_buffering: truncated init payload (part ${i} header)`);
684
+ }
605
685
  const len = dv.getUint32(off, true);
606
686
  off += 4;
687
+ if (len > buf.length - off) {
688
+ throw new StoragePayloadError(`table_buffering: truncated init payload (part ${i} is ${len} bytes, ${buf.length - off} left)`);
689
+ }
607
690
  parts.push(buf.subarray(off, off + len));
608
691
  off += len;
609
692
  }
693
+ if (off !== buf.length) {
694
+ throw new StoragePayloadError(`table_buffering: ${buf.length - off} trailing bytes in init payload`);
695
+ }
610
696
  return parts;
611
697
  }
@@ -43,7 +43,7 @@ import {
43
43
  replayFilterHistory,
44
44
  } from "../filter-pushdown/history.js";
45
45
  import { FunctionStability } from "../types.js";
46
- import { BoundStorage, storage as defaultStorage, FrameworkNS } from "./storage.js";
46
+ import { BoundStorage, storage as defaultStorage, FrameworkNS, shardKeyOf } from "./storage.js";
47
47
  import { serializeUserState, deserializeUserState } from "../protocol/state-serializer.js";
48
48
  import { PARENT_ROW_METADATA_KEY, encodeParentRows } from "../util/parent-rows.js";
49
49
  import { checkInputRowsPerCall, checkResumeContract, continuationTurn } from "./continuation.js";
@@ -378,6 +378,7 @@ export function defineTableInOutFunction<
378
378
  defaultStorage,
379
379
  response.execution_id ?? new Uint8Array(16),
380
380
  request.substream_id ?? null,
381
+ shardKeyOf(request.bind_call),
381
382
  );
382
383
 
383
384
  const processParams: TableInOutProcessParams<TArgs> = {
@@ -1056,6 +1057,7 @@ export function defineRowTransformFunction<
1056
1057
  defaultStorage,
1057
1058
  response.execution_id ?? new Uint8Array(16),
1058
1059
  request.substream_id ?? null,
1060
+ shardKeyOf(request.bind_call),
1059
1061
  );
1060
1062
 
1061
1063
  const processParams: RowTransformProcessParams<TArgs> = {
@@ -3,6 +3,7 @@
3
3
  // Table functions produce output batches from arguments (no streaming input).
4
4
 
5
5
  import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
6
+ import { secretLookupWire } from "../secrets/lookups.js";
6
7
  import {
7
8
  type VgiSchema,
8
9
  type VgiBatch,
@@ -64,7 +65,7 @@ import {
64
65
  type OrderDependence,
65
66
  type DistinctDependence,
66
67
  } from "../types.js";
67
- import { BoundStorage, storage as globalStorage } from "./storage.js";
68
+ import { BoundStorage, storage as globalStorage, shardKeyOf } from "./storage.js";
68
69
  import { CACHE_IF_MODIFIED_SINCE_KEY, CACHE_IF_NONE_MATCH_KEY } from "../cache-control.js";
69
70
 
70
71
  // Wrap an OutputCollector so each emitted RecordBatch is projected-by-name
@@ -214,7 +215,12 @@ export interface TableFunctionConfig<
214
215
  argConstraints?: Record<string, ArgumentConstraints>;
215
216
  /** Names of args that accept variable number of arguments */
216
217
  varargs?: string[];
217
- /** Bind: return output schema. May be async — handlers `await` the result. */
218
+ /**
219
+ * Bind: return output schema. May be async — handlers `await` the result.
220
+ * To ask DuckDB for secrets, return `lookupSecretTypes` with optional
221
+ * `lookupScopes` / `lookupNames` at the same indexes (see `SecretLookupFields`);
222
+ * a scope or name with no type at its index is a bind error.
223
+ */
218
224
  onBind: (params: TableBindParams<TArgs>) =>
219
225
  | {
220
226
  outputSchema: VgiSchema;
@@ -472,9 +478,7 @@ export function defineTableFunction<
472
478
  opaque_data: result.opaqueData ?? null,
473
479
  projection_expression_profiles: result.projectionExpressionProfiles ?? [],
474
480
  repeatability: result.repeatability === undefined ? "UNKNOWN" : result.repeatability,
475
- lookup_secret_types: result.lookupSecretTypes,
476
- lookup_scopes: result.lookupScopes,
477
- lookup_names: result.lookupNames,
481
+ ...secretLookupWire(config.name, result),
478
482
  };
479
483
  },
480
484
 
@@ -517,7 +521,7 @@ export function defineTableFunction<
517
521
 
518
522
  if (config.onInit) {
519
523
  const args = extractArgs(request.bind_call);
520
- const boundStorage = new BoundStorage(globalStorage, executionId);
524
+ const boundStorage = new BoundStorage(globalStorage, executionId, null, shardKeyOf(request.bind_call));
521
525
  return await config.onInit({
522
526
  args,
523
527
  initCall: request,
@@ -570,7 +574,7 @@ export function defineTableFunction<
570
574
  carriedFilterHistory,
571
575
  );
572
576
 
573
- const boundStorage = new BoundStorage(globalStorage, response.execution_id);
577
+ const boundStorage = new BoundStorage(globalStorage, response.execution_id, null, shardKeyOf(request.bind_call));
574
578
 
575
579
  const processParams: TableProcessParams<TArgs> = {
576
580
  args,
@@ -727,7 +731,7 @@ export function defineTableFunction<
727
731
  const args = extractArgs(request.bindCall);
728
732
  const settings = batchToScalarDict(request.bindCall.settings);
729
733
  const secrets = batchToSecretDict(request.bindCall.secrets);
730
- const storage = new BoundStorage(globalStorage, request.globalExecutionId);
734
+ const storage = new BoundStorage(globalStorage, request.globalExecutionId, null, shardKeyOf(request.bindCall));
731
735
  return config.dynamicToString!(
732
736
  {
733
737
  args,
@@ -2,7 +2,7 @@
2
2
  // GENERATED by vgi.codegen.ts_client. DO NOT EDIT BY HAND.
3
3
  //
4
4
  // Generator: vgi-gen-ts-client v1
5
- // Content hash: da655aba43cc
5
+ // Content hash: 054aee3477d1
6
6
  //
7
7
  // To regenerate:
8
8
  // uv run --project ~/Development/vgi-python vgi-gen-ts-client \
@@ -426,9 +426,15 @@ export interface CopyToContext {
426
426
  file_path: string;
427
427
  }
428
428
 
429
+ export interface ArgumentsLocation {
430
+ ref: Uint8Array;
431
+ size: number;
432
+ sha256: string;
433
+ }
434
+
429
435
  export interface BindRequest {
430
436
  function_name: string;
431
- arguments: /** @vgi-arguments */ Uint8Array;
437
+ arguments?: /** @vgi-arguments */ Uint8Array | null;
432
438
  function_type: InvocationFunctionType;
433
439
  input_schema?: /** @arrow-schema */ Uint8Array | null;
434
440
  settings?: /** @record-batch */ Uint8Array | null;
@@ -442,6 +448,7 @@ export interface BindRequest {
442
448
  copy_to?: CopyToContext | null;
443
449
  schema_path?: string[] | null;
444
450
  argument_names?: (string | null)[] | null;
451
+ arguments_location?: ArgumentsLocation | null;
445
452
  }
446
453
 
447
454
  export interface BindResponse {