@query-farm/vgi 0.50.1 → 0.51.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 (40) hide show
  1. package/dist/functions/aggregate.d.ts +25 -21
  2. package/dist/functions/execution-cache.d.ts +11 -0
  3. package/dist/functions/storage-cf-do.d.ts +38 -0
  4. package/dist/functions/storage-seal.d.ts +27 -0
  5. package/dist/functions/storage.d.ts +49 -1
  6. package/dist/functions/table-buffering.d.ts +30 -0
  7. package/dist/http/fetch.d.ts +7 -0
  8. package/dist/index.core.d.ts +3 -2
  9. package/dist/index.js +749 -384
  10. package/dist/index.js.map +20 -18
  11. package/dist/protocol/dispatch.d.ts +9 -0
  12. package/dist/protocol/handlers/aggregate.d.ts +1 -1
  13. package/dist/protocol/handlers/catalog/shared.d.ts +10 -0
  14. package/dist/protocol/handlers/function.d.ts +2 -0
  15. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  16. package/dist/protocol/types.d.ts +8 -0
  17. package/dist/serve-entry.d.ts +16 -2
  18. package/dist/serve-entry.js +1034 -526
  19. package/dist/serve-entry.js.map +20 -18
  20. package/dist/worker-cf-entry.js +2713 -2217
  21. package/dist/worker-cf-entry.js.map +26 -24
  22. package/package.json +1 -1
  23. package/src/functions/aggregate.ts +101 -152
  24. package/src/functions/copy-from.ts +2 -2
  25. package/src/functions/execution-cache.ts +59 -0
  26. package/src/functions/storage-cf-do.ts +152 -22
  27. package/src/functions/storage-seal.ts +208 -0
  28. package/src/functions/storage.ts +120 -3
  29. package/src/functions/table-buffering.ts +91 -15
  30. package/src/functions/table-in-out.ts +3 -1
  31. package/src/functions/table.ts +4 -4
  32. package/src/http/fetch.ts +9 -0
  33. package/src/index.core.ts +3 -1
  34. package/src/protocol/dispatch.ts +12 -2
  35. package/src/protocol/handlers/aggregate.ts +123 -82
  36. package/src/protocol/handlers/catalog/shared.ts +20 -0
  37. package/src/protocol/handlers/function.ts +38 -11
  38. package/src/protocol/handlers/table-buffering.ts +44 -32
  39. package/src/protocol/types.ts +8 -0
  40. package/src/serve-entry.ts +33 -3
@@ -0,0 +1,208 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Authenticated encryption of framework payloads written to FunctionStorage.
3
+ //
4
+ // The framework persists some of its own context to shared storage so any
5
+ // worker process can serve any RPC of an execution: the buffered-table init
6
+ // (the InitRequest, including `bind_call.secrets`) and the aggregate bind
7
+ // context (constant arguments, input schema). Storage may be a SQLite file or
8
+ // a Cloudflare Durable Object reached over the network, so none of that may
9
+ // sit there in plaintext, and nothing read back may be trusted unauthenticated.
10
+ //
11
+ // Sealed framework payload v1 (the same format in every VGI SDK; vgi-python's
12
+ // vgi/_storage_seal.py is the reference):
13
+ //
14
+ // K = HKDF-SHA256(ikm, salt = "", info = "vgi.storage.payload.v1", L = 32)
15
+ // ikm is the worker's signing key exactly as this SDK resolved it (the
16
+ // 32 bytes decoded from the VGI_SIGNING_KEY hex, or the explicit
17
+ // `signingKey` option). Without a signing key (stdio / AF_UNIX /
18
+ // launcher) it is the host-local key file every VGI worker process of
19
+ // this user on this host shares (./attach-secret-keyfile.ts), since one
20
+ // query's RPCs are spread over several processes sharing one SQLite file.
21
+ // AEAD = AES-256-GCM (WebCrypto, so it runs on Cloudflare Workers too),
22
+ // random 12-byte nonce, 16-byte tag.
23
+ // AAD = "vgi.storage.payload.v1" || u32be(len)||shard_key
24
+ // || u32be(len)||scope_id || u32be(len)||namespace || u32be(len)||key
25
+ // so a payload copied to another execution, slot or attach shard fails.
26
+ // wire = 0x01 || nonce(12) || ciphertext || tag(16)
27
+ //
28
+ // A payload that fails to open (unknown version, too short, tampered, wrong
29
+ // key, moved, or an unsealed value from an older release) throws
30
+ // StoragePayloadError. There is no plaintext fallback: executions are
31
+ // short-lived and their ids are never reused, so nothing needs migrating.
32
+ //
33
+ // Data user code writes to storage (buffered process() state, aggregate group
34
+ // states, table-in-out state, finalize output, work-queue items) is the
35
+ // function's own data and is not sealed.
36
+
37
+ import { hostLocalAttachSecretKey } from "../attach-secret-keyfile.js";
38
+
39
+ export const STORAGE_PAYLOAD_INFO = "vgi.storage.payload.v1";
40
+ export const STORAGE_PAYLOAD_VERSION = 0x01;
41
+ const KEY_LEN = 32;
42
+ const NONCE_LEN = 12;
43
+ const TAG_LEN = 16;
44
+ const UTF8 = new TextEncoder();
45
+ const INFO_BYTES = UTF8.encode(STORAGE_PAYLOAD_INFO);
46
+
47
+ /** A framework payload read from storage could not be authenticated. */
48
+ export class StoragePayloadError extends Error {
49
+ constructor(message: string) {
50
+ super(message);
51
+ this.name = "StoragePayloadError";
52
+ }
53
+ }
54
+
55
+ /** The storage slot a payload is bound to. */
56
+ export interface StorageSlot {
57
+ shardKey: string;
58
+ scopeId: Uint8Array;
59
+ ns: Uint8Array;
60
+ key: Uint8Array;
61
+ }
62
+
63
+ function lp(b: Uint8Array): Uint8Array {
64
+ const out = new Uint8Array(4 + b.length);
65
+ new DataView(out.buffer).setUint32(0, b.length, false);
66
+ out.set(b, 4);
67
+ return out;
68
+ }
69
+
70
+ function concat(parts: Uint8Array[]): Uint8Array {
71
+ let n = 0;
72
+ for (const p of parts) n += p.length;
73
+ const out = new Uint8Array(n);
74
+ let off = 0;
75
+ for (const p of parts) {
76
+ out.set(p, off);
77
+ off += p.length;
78
+ }
79
+ return out;
80
+ }
81
+
82
+ function hex(b: Uint8Array): string {
83
+ let s = "";
84
+ for (let i = 0; i < b.length; i++) s += b[i]!.toString(16).padStart(2, "0");
85
+ return s;
86
+ }
87
+
88
+ /** The associated data binding a payload to its storage slot. */
89
+ export function storagePayloadAad(slot: StorageSlot): Uint8Array {
90
+ return concat([INFO_BYTES, lp(UTF8.encode(slot.shardKey)), lp(slot.scopeId), lp(slot.ns), lp(slot.key)]);
91
+ }
92
+
93
+ /** `HKDF-SHA256(ikm, salt = "", info = "vgi.storage.payload.v1", 32)` as raw bytes. */
94
+ export async function deriveStoragePayloadKey(ikm: Uint8Array): Promise<Uint8Array> {
95
+ const base = await crypto.subtle.importKey("raw", ikm as BufferSource, "HKDF", false, ["deriveBits"]);
96
+ const bits = await crypto.subtle.deriveBits(
97
+ { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: INFO_BYTES },
98
+ base,
99
+ KEY_LEN * 8,
100
+ );
101
+ return new Uint8Array(bits);
102
+ }
103
+
104
+ // Derived AES keys, by ikm. Tiny (one or two entries in practice: the signing
105
+ // key, or the host-local key), bounded so a test that churns keys cannot grow it.
106
+ const KEY_CACHE_MAX = 16;
107
+ const keyCache = new Map<string, Promise<CryptoKey>>();
108
+
109
+ function aesKey(ikm: Uint8Array): Promise<CryptoKey> {
110
+ const id = hex(ikm);
111
+ let k = keyCache.get(id);
112
+ if (!k) {
113
+ k = (async () => {
114
+ const raw = await deriveStoragePayloadKey(ikm);
115
+ return crypto.subtle.importKey("raw", raw as BufferSource, "AES-GCM", false, ["encrypt", "decrypt"]);
116
+ })();
117
+ if (keyCache.size >= KEY_CACHE_MAX) keyCache.delete(keyCache.keys().next().value!);
118
+ keyCache.set(id, k);
119
+ // A failed derivation must not stay cached.
120
+ k.catch(() => keyCache.delete(id));
121
+ }
122
+ return k;
123
+ }
124
+
125
+ /** Seal under an explicit `ikm`. `nonce` exists for test vectors only. */
126
+ export async function sealWith(
127
+ payload: Uint8Array,
128
+ ikm: Uint8Array,
129
+ slot: StorageSlot,
130
+ nonce?: Uint8Array,
131
+ ): Promise<Uint8Array> {
132
+ if (nonce !== undefined && nonce.length !== NONCE_LEN) throw new Error(`nonce must be ${NONCE_LEN} bytes`);
133
+ const iv = nonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN));
134
+ const ct = new Uint8Array(
135
+ await crypto.subtle.encrypt(
136
+ { name: "AES-GCM", iv: iv as BufferSource, additionalData: storagePayloadAad(slot) as BufferSource, tagLength: TAG_LEN * 8 },
137
+ await aesKey(ikm),
138
+ payload as BufferSource,
139
+ ),
140
+ );
141
+ const out = new Uint8Array(1 + NONCE_LEN + ct.length);
142
+ out[0] = STORAGE_PAYLOAD_VERSION;
143
+ out.set(iv, 1);
144
+ out.set(ct, 1 + NONCE_LEN);
145
+ return out;
146
+ }
147
+
148
+ /** Open under an explicit `ikm`; {@link StoragePayloadError} on any failure. */
149
+ export async function openWith(blob: Uint8Array, ikm: Uint8Array, slot: StorageSlot): Promise<Uint8Array> {
150
+ const what = `framework storage payload ${JSON.stringify(new TextDecoder().decode(slot.ns))} for execution ${hex(slot.scopeId)}`;
151
+ if (blob.length < 1 + NONCE_LEN + TAG_LEN) {
152
+ throw new StoragePayloadError(`${what} is too short to be a sealed payload`);
153
+ }
154
+ if (blob[0] !== STORAGE_PAYLOAD_VERSION) {
155
+ throw new StoragePayloadError(`${what} has unknown seal version 0x${blob[0]!.toString(16).padStart(2, "0")}`);
156
+ }
157
+ const iv = blob.subarray(1, 1 + NONCE_LEN);
158
+ const body = blob.subarray(1 + NONCE_LEN);
159
+ try {
160
+ return new Uint8Array(
161
+ await crypto.subtle.decrypt(
162
+ { name: "AES-GCM", iv: iv as BufferSource, additionalData: storagePayloadAad(slot) as BufferSource, tagLength: TAG_LEN * 8 },
163
+ await aesKey(ikm),
164
+ body as BufferSource,
165
+ ),
166
+ );
167
+ } catch {
168
+ throw new StoragePayloadError(`${what} failed authentication (tampered, moved, or sealed under another key)`);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * The input key material: the worker's signing key, else the host-local key.
174
+ * Overridable for tests (`setStorageSealHostLocalKey`).
175
+ */
176
+ let hostLocalOverride: (() => Promise<Uint8Array>) | null = null;
177
+
178
+ /** Test hook: replace the host-local key source (null restores the key file). */
179
+ export function setStorageSealHostLocalKey(fn: (() => Promise<Uint8Array>) | null): void {
180
+ hostLocalOverride = fn;
181
+ }
182
+
183
+ async function ikmFor(signingKey: Uint8Array | undefined): Promise<Uint8Array> {
184
+ if (signingKey && signingKey.length > 0) return signingKey;
185
+ try {
186
+ return await (hostLocalOverride ?? hostLocalAttachSecretKey)();
187
+ } catch (e: any) {
188
+ throw new StoragePayloadError(`no key to seal framework storage payloads: ${e?.message ?? e}`);
189
+ }
190
+ }
191
+
192
+ /** Seal a framework payload bound to its storage slot. */
193
+ export async function sealPayload(
194
+ payload: Uint8Array,
195
+ signingKey: Uint8Array | undefined,
196
+ slot: StorageSlot,
197
+ ): Promise<Uint8Array> {
198
+ return sealWith(payload, await ikmFor(signingKey), slot);
199
+ }
200
+
201
+ /** Open an envelope from {@link sealPayload} for the same slot. */
202
+ export async function openPayload(
203
+ blob: Uint8Array,
204
+ signingKey: Uint8Array | undefined,
205
+ slot: StorageSlot,
206
+ ): Promise<Uint8Array> {
207
+ return openWith(blob, await ikmFor(signingKey), slot);
208
+ }
@@ -13,6 +13,8 @@
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
+
16
18
  type Database = any;
17
19
  const _BUN_SQLITE_MOD = "bun:sqlite";
18
20
  const _NODE_OS_MOD = "node:os";
@@ -107,6 +109,12 @@ export interface FunctionStorage {
107
109
  // --- Namespaced key/value state (scoped by execution_id) ---
108
110
  stateGet(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null>;
109
111
  statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void>;
112
+ /** Batched read: one value (or null) per key, in key order. One round trip
113
+ * on a remote backend. */
114
+ stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>>;
115
+ /** Batched atomic upsert of `(key, value)` pairs. One round trip on a remote
116
+ * backend; a no-op for an empty list. */
117
+ statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void>;
110
118
  // --- Append-only log (scoped by execution_id) ---
111
119
  stateAppend(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number>;
112
120
  stateLogScan(
@@ -120,6 +128,15 @@ export interface FunctionStorage {
120
128
  executionClear(scopeId: Uint8Array): Promise<number>;
121
129
  /** Optional cleanup hook. Implementations holding a connection should release it here. */
122
130
  close?(): Promise<void> | void;
131
+ /**
132
+ * Optional: a view of this backend routed to one attach shard. A backend
133
+ * that partitions remotely (the Cloudflare DO, one Durable Object per
134
+ * logical ATTACH) implements it; a local backend that needs no routing
135
+ * omits it. {@link BoundStorage} calls it with the shard key the framework
136
+ * derived from the request's authenticated attach (`att-<uuid hex>`), or
137
+ * `""` when the call is not bound to an ATTACH.
138
+ */
139
+ forShard?(shardKey: string): FunctionStorage;
123
140
  }
124
141
 
125
142
  // FrameworkNS — namespaces the framework itself uses (mirrors Python's
@@ -127,6 +144,9 @@ export interface FunctionStorage {
127
144
  export const FrameworkNS = {
128
145
  BUFFERING_INIT: textBytes("_vgi/buffering_init"),
129
146
  STREAMING_FINALIZE: textBytes("_vgi/streaming_finalize"),
147
+ /** Aggregate group states (key = packIntKey(group_id)) and, at key
148
+ * packIntKey(-2), the sealed bind context. Same bytes as vgi-python. */
149
+ AGGREGATE_STATE: textBytes("_vgi/aggregate_state"),
130
150
  } as const;
131
151
 
132
152
  function textBytes(s: string): Uint8Array {
@@ -156,7 +176,9 @@ function getDefaultDbPath(): string {
156
176
  platform() === "darwin"
157
177
  ? join(home, "Library", "Application Support", "vgi")
158
178
  : join(home, ".local", "state", "vgi");
159
- mkdirSync(stateDir, { recursive: true });
179
+ // Owner-only: the file holds other executions' in-flight state. Framework
180
+ // context in it is sealed (./storage-seal.ts), user state is not.
181
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
160
182
  return join(stateDir, "vgi_storage.db");
161
183
  }
162
184
 
@@ -327,6 +349,34 @@ export class FunctionStorageSqlite implements FunctionStorage {
327
349
  .run(bufferArg(scopeId), bufferArg(ns), bufferArg(key), bufferArg(value));
328
350
  }
329
351
 
352
+ async stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>> {
353
+ if (keys.length === 0) return [];
354
+ const stmt = this._db.prepare("SELECT value FROM function_state WHERE scope_id = ? AND ns = ? AND key = ?");
355
+ const sid = bufferArg(scopeId);
356
+ const nsb = bufferArg(ns);
357
+ return keys.map((k) => {
358
+ const row = stmt.get(sid, nsb, bufferArg(k)) as { value: Uint8Array } | null;
359
+ return row ? new Uint8Array(row.value) : null;
360
+ });
361
+ }
362
+
363
+ async statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void> {
364
+ if (items.length === 0) return;
365
+ const stmt = this._db.prepare(
366
+ "INSERT OR REPLACE INTO function_state (scope_id, ns, key, value) VALUES (?, ?, ?, ?)",
367
+ );
368
+ const sid = bufferArg(scopeId);
369
+ const nsb = bufferArg(ns);
370
+ this._db.exec("BEGIN IMMEDIATE");
371
+ try {
372
+ for (const [k, v] of items) stmt.run(sid, nsb, bufferArg(k), bufferArg(v));
373
+ this._db.exec("COMMIT");
374
+ } catch (e) {
375
+ this._db.exec("ROLLBACK");
376
+ throw e;
377
+ }
378
+ }
379
+
330
380
  async stateAppend(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number> {
331
381
  const res = this._db
332
382
  .prepare("INSERT INTO function_state_log (scope_id, ns, key, value) VALUES (?, ?, ?, ?)")
@@ -444,17 +494,39 @@ export class BoundStorage {
444
494
  private _base: FunctionStorage;
445
495
  private _executionId: Uint8Array;
446
496
  private _substreamId: Uint8Array | null;
497
+ private _shardKey: string;
447
498
 
448
499
  /**
449
500
  * @param substreamId The table-in-out substream this storage serves -- the
450
501
  * client-minted `InitRequest.substream_id`, identical across the
451
502
  * substream's init, every tick and its finalize -- or `null` when the
452
503
  * client sent none. Keys {@link put}.
504
+ * @param shardKey The attach shard every call routes to: `att-<uuid hex>`,
505
+ * derived by the framework from the request's authenticated attach (see
506
+ * {@link shardKeyOf}), or `""` when the call is not bound to an ATTACH. A
507
+ * backend with `forShard` (the Cloudflare DO) routes on it; it is also part
508
+ * of every sealed framework payload's AAD.
453
509
  */
454
- constructor(storage: FunctionStorage, executionId: Uint8Array, substreamId: Uint8Array | null = null) {
455
- this._base = storage;
510
+ constructor(
511
+ storage: FunctionStorage,
512
+ executionId: Uint8Array,
513
+ substreamId: Uint8Array | null = null,
514
+ shardKey: string = "",
515
+ ) {
516
+ this._base = typeof storage.forShard === "function" ? storage.forShard(shardKey) : storage;
456
517
  this._executionId = executionId;
457
518
  this._substreamId = substreamId;
519
+ this._shardKey = shardKey;
520
+ }
521
+
522
+ /** The attach shard this view routes to ("" when not bound to an ATTACH). */
523
+ get shardKey(): string {
524
+ return this._shardKey;
525
+ }
526
+
527
+ /** The execution (scope) id this view is bound to. */
528
+ get executionId(): Uint8Array {
529
+ return this._executionId;
458
530
  }
459
531
 
460
532
  /**
@@ -503,6 +575,16 @@ export class BoundStorage {
503
575
  return this._base.statePut(this._executionId, ns, key, value);
504
576
  }
505
577
 
578
+ /** Batched read, one value (or null) per key. One round trip remotely. */
579
+ stateGetMany(ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>> {
580
+ return this._base.stateGetMany(this._executionId, ns, keys);
581
+ }
582
+
583
+ /** Batched atomic upsert. One round trip remotely. */
584
+ statePutMany(ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void> {
585
+ return this._base.statePutMany(this._executionId, ns, items);
586
+ }
587
+
506
588
  stateAppend(ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number> {
507
589
  return this._base.stateAppend(this._executionId, ns, key, item);
508
590
  }
@@ -520,11 +602,46 @@ export class BoundStorage {
520
602
  return this._base.executionClear(this._executionId);
521
603
  }
522
604
 
605
+ // --- Sealed framework payloads (./storage-seal.ts) ---------------------
606
+ // For framework context only (init requests, bind context): authenticated
607
+ // encryption bound to (shard, execution, ns, key). `signingKey` is the
608
+ // worker's HTTP signing key, or undefined (the host-local key is used).
609
+
610
+ private _slot(ns: Uint8Array, key: Uint8Array): StorageSlot {
611
+ return { shardKey: this._shardKey, scopeId: this._executionId, ns, key };
612
+ }
613
+
614
+ /** Seal `payload` to its slot, store it, and return the stored envelope. */
615
+ async sealedPut(ns: Uint8Array, key: Uint8Array, payload: Uint8Array, signingKey: Uint8Array | undefined): Promise<Uint8Array> {
616
+ const sealed = await sealPayload(payload, signingKey, this._slot(ns, key));
617
+ await this.statePut(ns, key, sealed);
618
+ return sealed;
619
+ }
620
+
621
+ /** Open an envelope from {@link sealedPut} for this slot (StoragePayloadError on failure). */
622
+ openSealed(ns: Uint8Array, key: Uint8Array, sealed: Uint8Array, signingKey: Uint8Array | undefined): Promise<Uint8Array> {
623
+ return openPayload(sealed, signingKey, this._slot(ns, key));
624
+ }
625
+
626
+ /** Read and open a sealed framework payload; null when the slot is empty. */
627
+ async sealedGet(ns: Uint8Array, key: Uint8Array, signingKey: Uint8Array | undefined): Promise<Uint8Array | null> {
628
+ const sealed = await this.stateGet(ns, key);
629
+ return sealed == null ? null : this.openSealed(ns, key, sealed, signingKey);
630
+ }
631
+
523
632
  static packIntKey(i: number | bigint): Uint8Array {
524
633
  return packIntKey(i);
525
634
  }
526
635
  }
527
636
 
637
+ /**
638
+ * The attach shard key the framework stamped on a request's bind call when it
639
+ * opened the attach (`att-<uuid hex>`), or `""` when there is none.
640
+ */
641
+ export function shardKeyOf(bindCall: { storage_shard_key?: string | null | undefined } | null | undefined): string {
642
+ return bindCall?.storage_shard_key ?? "";
643
+ }
644
+
528
645
  // ============================================================================
529
646
  // Backend factory + lazy default storage
530
647
  // ============================================================================
@@ -56,7 +56,9 @@ import {
56
56
  type PushdownFilters,
57
57
  } from "../filter-pushdown/index.js";
58
58
  import { FunctionStability } from "../types.js";
59
- import { BoundStorage, storage as defaultStorage, FrameworkNS } from "./storage.js";
59
+ import { BoundStorage, storage as defaultStorage, FrameworkNS, shardKeyOf } from "./storage.js";
60
+ import { ExecutionCache } from "./execution-cache.js";
61
+ import { StoragePayloadError } from "./storage-seal.js";
60
62
  import {
61
63
  serializeInitRequest,
62
64
  deserializeInitRequest,
@@ -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,75 @@ 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
+ const stored: InitRequest = {
563
+ ...request,
564
+ bind_call: { ...request.bind_call, attach_opaque_data: null, transaction_opaque_data: null },
565
+ };
566
+ const bound = new BoundStorage(defaultStorage, response.execution_id, null, shardKey);
567
+ await bound.sealedPut(FrameworkNS.BUFFERING_INIT, BUFFERING_INIT_KEY, encodeBufferingInit(stored, response), signingKey);
568
+ bufferingInitCache.set(shardKey, response.execution_id, { request: stored, response });
569
+ }
570
+
571
+ /**
572
+ * Load a buffered execution's init context: the in-process cache, else the
573
+ * sealed storage copy (opened, decoded, then cached). Throws when the
574
+ * execution is unknown, and StoragePayloadError when the stored copy does not
575
+ * authenticate for this shard / execution.
576
+ */
577
+ export async function loadBufferingInit(
578
+ bound: BoundStorage,
579
+ signingKey: Uint8Array | undefined,
580
+ ): Promise<BufferingInit> {
581
+ const cached = bufferingInitCache.get(bound.shardKey, bound.executionId);
582
+ if (cached) return cached;
583
+ const payload = await bound.sealedGet(FrameworkNS.BUFFERING_INIT, BUFFERING_INIT_KEY, signingKey);
584
+ if (payload == null) {
585
+ throw new Error(
586
+ `table_buffering: unknown execution_id ${hexOf(bound.executionId)} ` +
587
+ `(init never ran or destructor already fired)`,
588
+ );
589
+ }
590
+ const decoded = decodeBufferingInit(payload);
591
+ bufferingInitCache.set(bound.shardKey, bound.executionId, decoded);
592
+ return decoded;
593
+ }
594
+
595
+ function hexOf(buf: Uint8Array): string {
596
+ return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
597
+ }
598
+
535
599
  export function encodeBufferingInit(
536
600
  request: InitRequest,
537
601
  response: GlobalInitResponse,
@@ -593,8 +657,11 @@ function concatLenPrefixed(parts: Uint8Array[]): Uint8Array {
593
657
  return out;
594
658
  }
595
659
 
596
- // Always returns exactly `count` parts (a short buffer throws a RangeError from
597
- // the DataView), which the overloads encode as a tuple.
660
+ // Always returns exactly `count` parts, which the overloads encode as a tuple,
661
+ // and consumes the whole buffer: a truncated header, a length running past
662
+ // the end, or trailing bytes are a StoragePayloadError, never a silently short
663
+ // part. (The payload is authenticated before this runs; this guards the
664
+ // framing itself.)
598
665
  function splitLenPrefixed(buf: Uint8Array, count: 2): [Uint8Array, Uint8Array];
599
666
  function splitLenPrefixed(buf: Uint8Array, count: 3): [Uint8Array, Uint8Array, Uint8Array];
600
667
  function splitLenPrefixed(buf: Uint8Array, count: number): Uint8Array[] {
@@ -602,10 +669,19 @@ function splitLenPrefixed(buf: Uint8Array, count: number): Uint8Array[] {
602
669
  const parts: Uint8Array[] = [];
603
670
  let off = 0;
604
671
  for (let i = 0; i < count; i++) {
672
+ if (off + 4 > buf.length) {
673
+ throw new StoragePayloadError(`table_buffering: truncated init payload (part ${i} header)`);
674
+ }
605
675
  const len = dv.getUint32(off, true);
606
676
  off += 4;
677
+ if (len > buf.length - off) {
678
+ throw new StoragePayloadError(`table_buffering: truncated init payload (part ${i} is ${len} bytes, ${buf.length - off} left)`);
679
+ }
607
680
  parts.push(buf.subarray(off, off + len));
608
681
  off += len;
609
682
  }
683
+ if (off !== buf.length) {
684
+ throw new StoragePayloadError(`table_buffering: ${buf.length - off} trailing bytes in init payload`);
685
+ }
610
686
  return parts;
611
687
  }
@@ -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> = {
@@ -64,7 +64,7 @@ import {
64
64
  type OrderDependence,
65
65
  type DistinctDependence,
66
66
  } from "../types.js";
67
- import { BoundStorage, storage as globalStorage } from "./storage.js";
67
+ import { BoundStorage, storage as globalStorage, shardKeyOf } from "./storage.js";
68
68
  import { CACHE_IF_MODIFIED_SINCE_KEY, CACHE_IF_NONE_MATCH_KEY } from "../cache-control.js";
69
69
 
70
70
  // Wrap an OutputCollector so each emitted RecordBatch is projected-by-name
@@ -517,7 +517,7 @@ export function defineTableFunction<
517
517
 
518
518
  if (config.onInit) {
519
519
  const args = extractArgs(request.bind_call);
520
- const boundStorage = new BoundStorage(globalStorage, executionId);
520
+ const boundStorage = new BoundStorage(globalStorage, executionId, null, shardKeyOf(request.bind_call));
521
521
  return await config.onInit({
522
522
  args,
523
523
  initCall: request,
@@ -570,7 +570,7 @@ export function defineTableFunction<
570
570
  carriedFilterHistory,
571
571
  );
572
572
 
573
- const boundStorage = new BoundStorage(globalStorage, response.execution_id);
573
+ const boundStorage = new BoundStorage(globalStorage, response.execution_id, null, shardKeyOf(request.bind_call));
574
574
 
575
575
  const processParams: TableProcessParams<TArgs> = {
576
576
  args,
@@ -727,7 +727,7 @@ export function defineTableFunction<
727
727
  const args = extractArgs(request.bindCall);
728
728
  const settings = batchToScalarDict(request.bindCall.settings);
729
729
  const secrets = batchToSecretDict(request.bindCall.secrets);
730
- const storage = new BoundStorage(globalStorage, request.globalExecutionId);
730
+ const storage = new BoundStorage(globalStorage, request.globalExecutionId, null, shardKeyOf(request.bindCall));
731
731
  return config.dynamicToString!(
732
732
  {
733
733
  args,
package/src/http/fetch.ts CHANGED
@@ -43,6 +43,13 @@ export interface VgiFetchOptions extends HostingOptions {
43
43
  * grants): tickets sealed under a generated key would die on restart.
44
44
  * Defaults to `true`, since this factory requires the key to be passed. */
45
45
  signingKeyConfigured?: boolean | undefined;
46
+ /**
47
+ * Input key material for sealed framework storage payloads. Pass the
48
+ * configured `VGI_SIGNING_KEY` *string* (its UTF-8 bytes are the cross-SDK
49
+ * ikm, so Python, Java and TypeScript workers of one deployment agree), or
50
+ * bytes to use unchanged. Defaults to {@link signingKey}'s bytes.
51
+ */
52
+ storageSealKey?: Uint8Array | string | undefined;
46
53
  /** State-token TTL in seconds (default 3600). */
47
54
  tokenTtl?: number | undefined;
48
55
  /** URL path prefix for VGI requests (default "/vgi"). Pass "" to mount at
@@ -203,6 +210,8 @@ export function createVgiFetch(opts: VgiFetchOptions): (req: Request) => Promise
203
210
 
204
211
  const protocol: Protocol = buildVgiProtocol({
205
212
  signingKey: opts.signingKey,
213
+ storageSealKey:
214
+ typeof opts.storageSealKey === "string" ? new TextEncoder().encode(opts.storageSealKey) : opts.storageSealKey,
206
215
  ...opts.protocol,
207
216
  });
208
217
 
package/src/index.core.ts CHANGED
@@ -412,9 +412,11 @@ export {
412
412
  UnknownInvocationError,
413
413
  resolveStorageFromEnv,
414
414
  setStorage,
415
+ shardKeyOf,
415
416
  storage as functionStorage,
416
417
  } from "./functions/storage.js";
417
- export { FunctionStorageCfDo, type FetchLike } from "./functions/storage-cf-do.js";
418
+ export { FunctionStorageCfDo, type FetchLike, type CfDoRetryOptions } from "./functions/storage-cf-do.js";
419
+ export { StoragePayloadError } from "./functions/storage-seal.js";
418
420
 
419
421
  // Client
420
422
  export { VgiClient, VgiClientError } from "./client/client.js";