@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
@@ -41,6 +41,15 @@ export interface ProtocolConfig {
41
41
  * receive a given attach must use the same key.
42
42
  */
43
43
  attachSecretKey?: Uint8Array | undefined;
44
+ /**
45
+ * Input key material for sealed framework storage payloads
46
+ * (src/functions/storage-seal.ts). The cross-SDK v1 rule is the UTF-8 bytes
47
+ * of `VGI_SIGNING_KEY` exactly as configured (not its hex-decoded form), so a
48
+ * deployment's one key derives the same payload key in every SDK. Defaults
49
+ * to `signingKey` (bytes passed as bytes are used unchanged); with neither,
50
+ * the host-local key file. The attach / state-token keys are unaffected.
51
+ */
52
+ storageSealKey?: Uint8Array | undefined;
44
53
  }
45
54
 
46
55
  /**
@@ -100,9 +109,10 @@ export function buildVgiService(config: ProtocolConfig): VgiService {
100
109
  signingKey: config.signingKey,
101
110
  attachSecretKey: config.attachSecretKey,
102
111
  catalogInterface: config.catalogInterface,
112
+ storageSealKey: config.storageSealKey ?? config.signingKey,
103
113
  }),
104
- ...aggregateHandlers(config.registry),
105
- ...tableBufferingHandlers(config.registry, config.signingKey, config.attachSecretKey),
114
+ ...aggregateHandlers(config.registry, config.signingKey, config.attachSecretKey, config.storageSealKey ?? config.signingKey),
115
+ ...tableBufferingHandlers(config.registry, config.signingKey, config.attachSecretKey, config.storageSealKey ?? config.signingKey),
106
116
  ...catalogHandlers(config.catalogInterface, config.signingKey, config.attachSecretKey),
107
117
  };
108
118
  }
@@ -24,19 +24,30 @@ import {
24
24
  AggregateFinalizeResultSchema,
25
25
  } from "../../generated/vgi-protocol-schemas.js";
26
26
  import {
27
- getExecutionState,
28
- setExecutionState,
29
- persistGroupStates,
30
27
  GROUP_COLUMN_NAME,
28
+ AGGREGATE_CONTEXT_KEY,
29
+ aggregateContextCache,
30
+ encodeAggregateContext,
31
+ decodeAggregateContext,
32
+ loadGroupStates,
33
+ storeGroupStates,
31
34
  type AggregateFunctionConfig,
32
35
  type AggregateBindParams,
33
36
  } from "../../functions/aggregate.js";
37
+ import { BoundStorage, FrameworkNS, storage as defaultStorage } from "../../functions/storage.js";
38
+ import { openAttachWithShard } from "./catalog/shared.js";
39
+ import { currentRequestAuth } from "../../request-auth.js";
34
40
  import { Arguments } from "../../arguments/arguments.js";
35
41
  import { validateConstConstraints } from "../../arguments/argument-spec.js";
36
42
  import { unwrapRequest, wrapResult } from "./shared.js";
37
43
 
38
44
  /** The aggregate lifecycle's `vgi.v3` handlers. */
39
- export function aggregateHandlers(registry: FunctionRegistry): Partial<VgiService> {
45
+ export function aggregateHandlers(
46
+ registry: FunctionRegistry,
47
+ signingKey?: Uint8Array,
48
+ attachSecretKey?: Uint8Array,
49
+ storageSealKey: Uint8Array | undefined = signingKey,
50
+ ): Partial<VgiService> {
40
51
  // `schemaPath` scopes resolution to the schema the caller named. Every
41
52
  // aggregate RPC carries it (protocol 1.2.0), so an aggregate name declared in
42
53
  // two schemas dispatches to the one the request names rather than colliding
@@ -57,52 +68,96 @@ export function aggregateHandlers(registry: FunctionRegistry): Partial<VgiServic
57
68
  return func.aggregateConfig as AggregateFunctionConfig<any, any>;
58
69
  }
59
70
 
71
+ // The execution's storage: its attach's shard (derived from the request's
72
+ // authenticated attach, as for every other function kind), scoped by the
73
+ // execution id.
74
+ async function boundFor(innerParams: Record<string, any>, ctx: any, executionId: Uint8Array): Promise<BoundStorage> {
75
+ const raw = innerParams.attach_opaque_data ? toUint8Array(innerParams.attach_opaque_data) : null;
76
+ const { shardKey } = await openAttachWithShard(raw, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
77
+ return new BoundStorage(defaultStorage, executionId, null, shardKey);
78
+ }
79
+
80
+ // The bind context of an execution: cached in-process, else the sealed
81
+ // storage copy (authoritative). Throws when the execution is unknown.
82
+ async function loadContext(
83
+ cfg: AggregateFunctionConfig<any, any>,
84
+ storage: BoundStorage,
85
+ rpc: string,
86
+ ): Promise<AggregateBindParams<any>> {
87
+ const cached = aggregateContextCache.get(storage.shardKey, storage.executionId);
88
+ if (cached) return cached;
89
+ const payload = await storage.sealedGet(FrameworkNS.AGGREGATE_STATE, AGGREGATE_CONTEXT_KEY, storageSealKey);
90
+ if (payload == null) {
91
+ throw new Error(`${rpc}: unknown execution_id for '${cfg.name}' (bind missing or state dropped)`);
92
+ }
93
+ const stored = decodeAggregateContext(payload);
94
+ const args = deserializeArguments(stored.argumentsIpc);
95
+ const params: AggregateBindParams<any> = {
96
+ args: extractArgMap(cfg, args),
97
+ arguments: args,
98
+ inputSchema: stored.inputSchemaIpc ? deserializeSchema(stored.inputSchemaIpc) : null,
99
+ settings: {},
100
+ // Secret values are delivered on aggregate_bind only, and never stored.
101
+ secrets: {},
102
+ argumentNames: stored.argumentNames,
103
+ };
104
+ aggregateContextCache.set(storage.shardKey, storage.executionId, params);
105
+ return params;
106
+ }
107
+
60
108
  // ------------------------------------------------------------------------
61
109
  // aggregate_bind — allocate execution_id, return output schema
62
110
  // ------------------------------------------------------------------------
63
- const aggregateBind: VgiService["aggregateBind"] = async (params) => {
111
+ const aggregateBind: VgiService["aggregateBind"] = async (params, ctx?: any) => {
64
112
  const innerParams = unwrapRequest(params.request);
65
113
  const functionName: string = innerParams.function_name;
66
114
  const cfg = resolveAggregate(functionName, innerParams.schema_path ?? null);
67
115
  const argBytes = toUint8Array(innerParams.arguments);
68
116
  const args = deserializeArguments(argBytes);
69
- const inputSchema = innerParams.input_schema
70
- ? deserializeSchema(toUint8Array(innerParams.input_schema))
71
- : null;
117
+ const inputSchemaIpc = innerParams.input_schema ? toUint8Array(innerParams.input_schema) : null;
118
+ const inputSchema = inputSchemaIpc && inputSchemaIpc.length > 0 ? deserializeSchema(inputSchemaIpc) : null;
72
119
  // Decode the resolved-secrets batch the extension pre-resolves for
73
120
  // aggregates that declared `requiredSecrets`. Mirrors the table-buffering
74
121
  // handler (batchToSecretDict). The secret VALUES are delivered only here,
75
- // at bind time — update/combine/finalize see no secrets by design.
122
+ // at bind time — update/combine/finalize see no secrets by design, and
123
+ // they are never written to storage.
76
124
  const secretsBytes = innerParams.secrets ? toUint8Array(innerParams.secrets) : null;
77
125
  const secretsBatch =
78
126
  secretsBytes && secretsBytes.length > 0 ? deserializeBatch(secretsBytes) : null;
79
127
  const secrets = secretsBatch ? batchToSecretDict(secretsBatch) : {};
128
+ const argumentNames: (string | null)[] | null = innerParams.argument_names
129
+ ? (Array.isArray(innerParams.argument_names)
130
+ ? innerParams.argument_names
131
+ : [...innerParams.argument_names])
132
+ .map((value: unknown) => value == null ? null : String(value))
133
+ : null;
80
134
  const bindParams: AggregateBindParams<any> = {
81
135
  args: extractArgMap(cfg, args),
82
136
  arguments: args,
83
137
  inputSchema,
84
138
  settings: {},
85
139
  secrets,
86
- argumentNames: innerParams.argument_names
87
- ? (Array.isArray(innerParams.argument_names)
88
- ? innerParams.argument_names
89
- : [...innerParams.argument_names])
90
- .map((value: unknown) => value == null ? null : String(value))
91
- : null,
140
+ argumentNames,
92
141
  };
93
- const executionId = new Uint8Array(16);
94
- crypto.getRandomValues(executionId);
95
- setExecutionState(executionId, {
96
- states: new Map(),
97
- bindArgs: args,
98
- bindParams,
99
- });
100
142
  // Output schema is a single "result" column. Type comes from the
101
143
  // optional onBind hook (for aggregates whose return type depends on
102
144
  // input — e.g. vgi_generic_sum takes ANY and returns the same type);
103
145
  // otherwise the declared cfg.outputType.
104
146
  const outType = cfg.onBind ? await cfg.onBind(bindParams) : cfg.outputType;
105
147
  const outSchema = makeSchema([field("result", outType, true)]);
148
+
149
+ const executionId = new Uint8Array(16);
150
+ crypto.getRandomValues(executionId);
151
+ // Persist the bind context (sealed; no secrets) so any worker can serve
152
+ // this execution's update/combine/finalize RPCs.
153
+ const storage = await boundFor(innerParams, ctx, executionId);
154
+ await storage.sealedPut(
155
+ FrameworkNS.AGGREGATE_STATE,
156
+ AGGREGATE_CONTEXT_KEY,
157
+ encodeAggregateContext({ argumentsIpc: argBytes, inputSchemaIpc, argumentNames }),
158
+ storageSealKey,
159
+ );
160
+ aggregateContextCache.set(storage.shardKey, executionId, { ...bindParams, secrets: {} });
106
161
  return wrapResult(
107
162
  { output_schema: serializeSchema(outSchema), execution_id: executionId },
108
163
  AggregateBindResultSchema,
@@ -112,7 +167,7 @@ export function aggregateHandlers(registry: FunctionRegistry): Partial<VgiServic
112
167
  // ------------------------------------------------------------------------
113
168
  // aggregate_update — fold the incoming batch into per-group state
114
169
  // ------------------------------------------------------------------------
115
- const aggregateUpdate: VgiService["aggregateUpdate"] = (params) => {
170
+ const aggregateUpdate: VgiService["aggregateUpdate"] = async (params, ctx?: any) => {
116
171
  const innerParams = unwrapRequest(params.request);
117
172
  const functionName: string = innerParams.function_name;
118
173
  const executionId = toUint8Array(innerParams.execution_id);
@@ -133,10 +188,13 @@ export function aggregateHandlers(registry: FunctionRegistry): Partial<VgiServic
133
188
  groupIds.push(g);
134
189
  uniqueGids.add(g);
135
190
  }
136
- const exec = getExecutionState(executionId, uniqueGids);
137
- if (!exec) {
138
- throw new Error(`aggregate_update: unknown execution_id for '${functionName}' (bind missing or state dropped)`);
139
- }
191
+ const storage = await boundFor(innerParams, ctx, executionId);
192
+ const bindParams = await loadContext(cfg, storage, "aggregate_update");
193
+ // One batched read of every group this batch touches. Always from
194
+ // storage: a sibling worker may have just written a newer value, and a
195
+ // cached copy would overwrite it (read-modify-write race).
196
+ const gids = [...uniqueGids];
197
+ const states = await loadGroupStates(storage, gids);
140
198
 
141
199
  // Build column-arg arrays — every non-__vgi_group_id column, in
142
200
  // schema order — and pass to user's update(). We deliberately do NOT
@@ -149,33 +207,30 @@ export function aggregateHandlers(registry: FunctionRegistry): Partial<VgiServic
149
207
  columns.push(batch.getChildAt(i));
150
208
  }
151
209
  const ensureState = (gid: bigint) => {
152
- let s = exec.states.get(gid);
210
+ let s = states.get(gid);
153
211
  if (s === undefined) {
154
- s = cfg.initialState(exec.bindParams);
155
- exec.states.set(gid, s);
212
+ s = cfg.initialState(bindParams);
213
+ states.set(gid, s);
156
214
  }
157
215
  return s;
158
216
  };
159
217
  cfg.update({
160
- states: exec.states,
218
+ states,
161
219
  groupIds,
162
220
  columns,
163
- args: exec.bindParams.args,
221
+ args: bindParams.args,
164
222
  ensureState,
165
223
  });
166
- // Flush mutated states to disk so sibling workers see them. We persist
167
- // every group that was referenced this call — some may be unchanged
168
- // (skipped by NULL handling), in which case the file simply reflects
169
- // the pre-existing initial state; the idempotent rewrite is cheap
170
- // relative to the RPC overhead.
171
- persistGroupStates(executionId, uniqueGids);
224
+ // One batched write of every referenced group that has a state (groups
225
+ // skipped by NULL handling stay absent, so finalize sees null).
226
+ await storeGroupStates(storage, states, gids);
172
227
  return wrapResult({}, makeSchema([]));
173
228
  };
174
229
 
175
230
  // ------------------------------------------------------------------------
176
231
  // aggregate_combine — merge (source_group_id, target_group_id) pairs
177
232
  // ------------------------------------------------------------------------
178
- const aggregateCombine: VgiService["aggregateCombine"] = (params) => {
233
+ const aggregateCombine: VgiService["aggregateCombine"] = async (params, ctx?: any) => {
179
234
  const innerParams = unwrapRequest(params.request);
180
235
  const functionName: string = innerParams.function_name;
181
236
  const executionId = toUint8Array(innerParams.execution_id);
@@ -194,33 +249,29 @@ export function aggregateHandlers(registry: FunctionRegistry): Partial<VgiServic
194
249
  srcIds.push(src); tgtIds.push(tgt);
195
250
  referencedGids.add(src); referencedGids.add(tgt);
196
251
  }
197
- const exec = getExecutionState(executionId, referencedGids);
198
- if (!exec) {
199
- throw new Error(
200
- `aggregate_combine: unknown execution_id for '${functionName}' ` +
201
- `(context missing on disk — bind may have failed or been cleaned up)`,
202
- );
203
- }
252
+ const storage = await boundFor(innerParams, ctx, executionId);
253
+ const bindParams = await loadContext(cfg, storage, "aggregate_combine");
254
+ const states = await loadGroupStates(storage, [...referencedGids]);
204
255
  const touchedTargets = new Set<bigint>();
205
256
  for (let i = 0; i < batch.numRows; i++) {
206
257
  const src = srcIds[i]!;
207
258
  const tgt = tgtIds[i]!;
208
- const srcHas = exec.states.has(src);
209
- const tgtHas = exec.states.has(tgt);
259
+ const srcHas = states.has(src);
260
+ const tgtHas = states.has(tgt);
210
261
  if (!srcHas && !tgtHas) continue;
211
- const srcState = srcHas ? exec.states.get(src)! : cfg.initialState(exec.bindParams);
212
- const tgtState = tgtHas ? exec.states.get(tgt)! : cfg.initialState(exec.bindParams);
213
- exec.states.set(tgt, cfg.combine(srcState, tgtState, exec.bindParams));
262
+ const srcState = srcHas ? states.get(src)! : cfg.initialState(bindParams);
263
+ const tgtState = tgtHas ? states.get(tgt)! : cfg.initialState(bindParams);
264
+ states.set(tgt, cfg.combine(srcState, tgtState, bindParams));
214
265
  touchedTargets.add(tgt);
215
266
  }
216
- persistGroupStates(executionId, touchedTargets);
267
+ await storeGroupStates(storage, states, touchedTargets);
217
268
  return wrapResult({}, makeSchema([]));
218
269
  };
219
270
 
220
271
  // ------------------------------------------------------------------------
221
272
  // aggregate_finalize — emit one result row per requested group_id
222
273
  // ------------------------------------------------------------------------
223
- const aggregateFinalize: VgiService["aggregateFinalize"] = (params) => {
274
+ const aggregateFinalize: VgiService["aggregateFinalize"] = async (params, ctx?: any) => {
224
275
  const innerParams = unwrapRequest(params.request);
225
276
  const functionName: string = innerParams.function_name;
226
277
  const executionId = toUint8Array(innerParams.execution_id);
@@ -238,18 +289,17 @@ export function aggregateHandlers(registry: FunctionRegistry): Partial<VgiServic
238
289
  uniqueGids.add(g);
239
290
  }
240
291
  }
241
- const exec = getExecutionState(executionId, uniqueGids);
242
- if (!exec) {
243
- throw new Error(`aggregate_finalize: unknown execution_id for '${functionName}'`);
244
- }
292
+ const storage = await boundFor(innerParams, ctx, executionId);
293
+ const bindParams = await loadContext(cfg, storage, "aggregate_finalize");
294
+ const stored = await loadGroupStates(storage, [...uniqueGids]);
245
295
  // Groups never updated pass state = null so finalize() can emit SQL NULL
246
296
  // (matches Python semantics for SUM/AVG/MIN/MAX over zero rows).
247
297
  const states = new Map<bigint, any | null>();
248
298
  for (const gid of groupIds) {
249
- states.set(gid, exec.states.has(gid) ? exec.states.get(gid) : null);
299
+ states.set(gid, stored.has(gid) ? stored.get(gid) : null);
250
300
  }
251
301
  const resultBatch = cfg.finalize({
252
- groupIds, states, outputSchema, args: exec.bindParams.args,
302
+ groupIds, states, outputSchema, args: bindParams.args,
253
303
  });
254
304
  return wrapResult(
255
305
  { result_batch: serializeBatchWithSchema(resultBatch) },
@@ -258,32 +308,23 @@ export function aggregateHandlers(registry: FunctionRegistry): Partial<VgiServic
258
308
  };
259
309
 
260
310
  // ------------------------------------------------------------------------
261
- // aggregate_destructor — drop state for finished groups (best-effort)
311
+ // aggregate_destructor — drop the execution's state (best-effort)
262
312
  //
263
- // DuckDB sends a batch of group_ids to discard; we remove each from the
264
- // in-memory state map. We DO NOT tear down the entire execution on an
265
- // empty batch — DuckDB may still call finalize afterwards in some plans
266
- // (matches Python's conservative behavior; the execution entry is cleaned
267
- // up when the worker process exits).
313
+ // The extension calls this once, when every group state of the execution
314
+ // has been destroyed (it counts destroys against allocated group ids), so
315
+ // it clears the whole execution -- group states and the sealed bind
316
+ // context -- and evicts the in-process cache, as vgi-python does.
268
317
  // ------------------------------------------------------------------------
269
- const aggregateDestructor: VgiService["aggregateDestructor"] = (params) => {
270
- const innerParams = unwrapRequest(params.request);
271
- const executionId = toUint8Array(innerParams.execution_id);
272
- const exec = getExecutionState(executionId);
273
- if (!exec) return wrapResult({}, makeSchema([]));
274
- const gidBatch = readSingleBatch(toUint8Array(innerParams.group_ids_batch));
275
- if (!gidBatch || gidBatch.numRows === 0) return wrapResult({}, makeSchema([]));
276
- const col = gidBatch.getChild("group_id")!;
277
- const toDrop = new Set<bigint>();
278
- for (let i = 0; i < gidBatch.numRows; i++) {
279
- const v = col.get(i);
280
- const g = typeof v === "bigint" ? v : BigInt(v as any);
281
- exec.states.delete(g);
282
- toDrop.add(g);
318
+ const aggregateDestructor: VgiService["aggregateDestructor"] = async (params, ctx?: any) => {
319
+ try {
320
+ const innerParams = unwrapRequest(params.request);
321
+ const executionId = toUint8Array(innerParams.execution_id);
322
+ const storage = await boundFor(innerParams, ctx, executionId);
323
+ aggregateContextCache.delete(storage.shardKey, executionId);
324
+ await storage.executionClear();
325
+ } catch {
326
+ // Teardown path — best-effort.
283
327
  }
284
- // Persist deletions (unlinks the per-group file so sibling workers
285
- // don't revive the state via getExecutionState's lazy disk load).
286
- persistGroupStates(executionId, toDrop);
287
328
  return wrapResult({}, makeSchema([]));
288
329
  };
289
330
 
@@ -119,6 +119,26 @@ export async function openAttach(
119
119
  return openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
120
120
  }
121
121
 
122
+ /**
123
+ * Open an attach envelope once, returning both what the function body sees
124
+ * (the catalog's own bytes, UUID and options trailer stripped) and the
125
+ * FunctionStorage shard key of its framework UUID. An empty / absent attach
126
+ * yields `{ attach: <as given>, shardKey: "" }`.
127
+ */
128
+ export async function openAttachWithShard(
129
+ envelope: Uint8Array | null | undefined,
130
+ auth: AuthContext | undefined,
131
+ signingKey: Uint8Array | undefined,
132
+ attachSecretKey?: Uint8Array,
133
+ ): Promise<{ attach: Uint8Array | null; shardKey: string }> {
134
+ if (envelope == null) return { attach: null, shardKey: "" };
135
+ if (envelope.length === 0) return { attach: envelope, shardKey: "" };
136
+ const full = await openAttachFull(envelope, auth, signingKey);
137
+ const shardKey = full.length >= ATTACH_UUID_LEN ? deriveShardKey(full.subarray(0, ATTACH_UUID_LEN)) : "";
138
+ const attach = await openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
139
+ return { attach, shardKey };
140
+ }
141
+
122
142
  /** Hex of a byte array (lowercase). */
123
143
  function toHex(b: Uint8Array): string {
124
144
  let s = "";
@@ -12,6 +12,8 @@ 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
18
  deserializeBindRequest,
17
19
  serializeBindResponse,
@@ -34,7 +36,7 @@ import {
34
36
  } from "../../generated/vgi-protocol-schemas.js";
35
37
  import { unwrapRequest, wrapResult, overloadContext } from "./shared.js";
36
38
  import { parseCarriedInitRequest } from "../carried-init-request.js";
37
- import { openAttach, openTransaction } from "./catalog/shared.js";
39
+ import { openAttach, openAttachWithShard, openTransaction, shardKeyForAttach } from "./catalog/shared.js";
38
40
  import { currentRequestAuth } from "../../request-auth.js";
39
41
  import { batchFromColumns, serializeBatch } from "../../util/arrow/index.js";
40
42
  import {
@@ -58,6 +60,8 @@ export interface FunctionHandlerConfig {
58
60
  signingKey?: Uint8Array | undefined;
59
61
  /** Explicit root key for secret ATTACH options (see attach-secret-options.ts). */
60
62
  attachSecretKey?: Uint8Array | undefined;
63
+ /** Seal ikm for framework storage payloads (see ProtocolConfig.storageSealKey). */
64
+ storageSealKey?: Uint8Array | undefined;
61
65
  /**
62
66
  * Used to map a bind's `attach_opaque_data` to its catalog, so resolution can
63
67
  * be scoped when two catalogs declare the same schema and function name.
@@ -207,6 +211,7 @@ async function resolveSplitPayloads(
207
211
  /** The per-function lifecycle's `vgi.v3` handlers. */
208
212
  export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiService> {
209
213
  const { registry, signingKey, catalogInterface, attachSecretKey } = config;
214
+ const storageSealKey = config.storageSealKey ?? signingKey;
210
215
 
211
216
  // The framework mints every attach as uuid(16) || catalog_bytes (sealed on
212
217
  // HTTP, plaintext on subprocess). Function bodies — like catalog bodies —
@@ -218,19 +223,12 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
218
223
  // the same principal. Getting an authenticated caller's identity wrong here
219
224
  // is not a degraded lookup but a hard `OpaqueDataRejectedError`: the envelope
220
225
  // 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
226
  // Unseal a bind call's opaque values in place, as the catalog handlers do:
229
227
  // the transaction first (its envelope binds the *sealed* attach), then the
230
228
  // attach. Every function-side request goes through this, so function bodies
231
229
  // see the same transaction plaintext that transactionCommit/Rollback get.
232
230
  async function openOpaque(
233
- bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null },
231
+ bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null; storage_shard_key?: string | null },
234
232
  ctx: any,
235
233
  ): Promise<void> {
236
234
  const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
@@ -242,7 +240,18 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
242
240
  signingKey,
243
241
  );
244
242
  }
245
- bindCall.attach_opaque_data = await stripAttach(bindCall.attach_opaque_data, ctx);
243
+ // One open yields both what the body sees and the storage shard of the
244
+ // attach's framework UUID, which the strip removes. Stamped on the bind
245
+ // call (in memory only, never serialized) so every BoundStorage the
246
+ // function builds routes to this attach's shard.
247
+ const opened = await openAttachWithShard(
248
+ bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : null,
249
+ ctx?.auth ?? currentRequestAuth(),
250
+ signingKey,
251
+ attachSecretKey,
252
+ );
253
+ bindCall.attach_opaque_data = opened.attach;
254
+ (bindCall as { storage_shard_key?: string }).storage_shard_key = opened.shardKey;
246
255
  }
247
256
 
248
257
  // Build an overload context whose attach has been unsealed, so catalog
@@ -333,6 +342,14 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
333
342
  // FunctionStorage (e.g. Cloudflare DO).
334
343
  const initResponse = await func.globalInit(request);
335
344
 
345
+ // A buffered (sink+source) sink init persists its init context, sealed,
346
+ // so any worker can serve the unary process/combine RPCs that follow.
347
+ // Done here rather than in the function because only this layer holds
348
+ // the signing key the seal derives from.
349
+ if ((func as any).kind === "table_buffering" && request.phase === TableInOutPhase.TABLE_BUFFERING) {
350
+ await persistBufferingInit(request, initResponse, storageSealKey);
351
+ }
352
+
336
353
  // A FINALIZE stream reads its accumulated states from storage, where
337
354
  // every INPUT turn persisted them. Its `init_opaque_data` is the primary
338
355
  // init's opaque data echoed back (vgi-python's InitRequest), never a
@@ -429,7 +446,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
429
446
  // SPLIT_TOKEN_INVALID "minted for a different bind".
430
447
  await resolveSplitPayloads(request, { bind_call: carried.bindCallIpc }, {
431
448
  // Same principal the tokens were sealed under. The exchange dispatch
432
- // gets no ctx (see stripAttach above), so the request-scoped identity
449
+ // gets no ctx (see openOpaque above), so the request-scoped identity
433
450
  // is the only source — opening under the anonymous tail would fail
434
451
  // authentication for every authenticated caller's own tokens.
435
452
  auth: currentRequestAuth(),
@@ -645,6 +662,16 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
645
662
  ? toUint8Array(innerParams.bind_opaque_data)
646
663
  : null;
647
664
  const func = registry.get(bindCall.function_name, await strippedContext(bindCall));
665
+ // Its BoundStorage must reach the same attach shard as the scan's.
666
+ try {
667
+ bindCall.storage_shard_key = await shardKeyForAttach(
668
+ bindCall.attach_opaque_data ?? undefined,
669
+ currentRequestAuth(),
670
+ signingKey,
671
+ );
672
+ } catch {
673
+ bindCall.storage_shard_key = "";
674
+ }
648
675
  const map = func.dynamicToString
649
676
  ? await func.dynamicToString({ bindCall, bindOpaqueData, globalExecutionId })
650
677
  : {};
@@ -20,17 +20,16 @@ import {
20
20
  TableBufferingProcessResultSchema,
21
21
  } from "../../generated/vgi-protocol-schemas.js";
22
22
  import { unwrapRequest, wrapResult } from "./shared.js";
23
- import { openAttach } from "./catalog/shared.js";
23
+ import { openAttachWithShard, openTransaction } from "./catalog/shared.js";
24
+ import { BoundStorage, storage as defaultStorage } from "../../functions/storage.js";
24
25
  import {
25
- BoundStorage,
26
- storage as defaultStorage,
27
- FrameworkNS,
28
- } from "../../functions/storage.js";
29
- import {
30
- decodeBufferingInit,
26
+ bufferingInitCache,
27
+ loadBufferingInit,
31
28
  type TableBufferingVgiFunction,
32
29
  type TableBufferingParams,
33
30
  } from "../../functions/table-buffering.js";
31
+ import type { InitRequest } from "../types.js";
32
+ import { currentRequestAuth } from "../../request-auth.js";
34
33
  import { Arguments } from "../../arguments/arguments.js";
35
34
 
36
35
  /** The table_buffering lifecycle's `vgi.v3` handlers. */
@@ -38,6 +37,7 @@ export function tableBufferingHandlers(
38
37
  registry: FunctionRegistry,
39
38
  signingKey?: Uint8Array,
40
39
  attachSecretKey?: Uint8Array,
40
+ storageSealKey: Uint8Array | undefined = signingKey,
41
41
  ): Partial<VgiService> {
42
42
  // `schemaPath` scopes resolution to the schema the caller named. The
43
43
  // buffering process/combine RPCs carry it (protocol 1.2.0), so a name
@@ -67,31 +67,38 @@ export function tableBufferingHandlers(
67
67
  ): Promise<{ func: TableBufferingVgiFunction; params: TableBufferingParams<any> }> {
68
68
  const functionName: string = inner.function_name;
69
69
  const executionId = toUint8Array(inner.execution_id);
70
+ const auth = ctx?.auth ?? currentRequestAuth();
70
71
  // 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.
72
+ // attach-scoped bytes that bind()/init() and plain table functions see,
73
+ // and derive the storage shard from its framework UUID: the init context
74
+ // and every BoundStorage call of this execution live in that shard.
75
75
  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;
76
+ const { attach, shardKey } = await openAttachWithShard(rawAttach, auth, signingKey, attachSecretKey);
80
77
  const transactionId = inner.transaction_id ? toUint8Array(inner.transaction_id) : null;
81
78
 
82
79
  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
- );
80
+ const bound = new BoundStorage(defaultStorage, executionId, null, shardKey);
81
+ // Cached per (shard, execution) after the first load; storage (sealed) is
82
+ // authoritative on a miss. The stored request carries no attach or
83
+ // transaction: they come from this request, opened as the init turn did.
84
+ const init = await loadBufferingInit(bound, storageSealKey);
85
+ let txnPlain = transactionId;
86
+ if (txnPlain && txnPlain.length > 0 && signingKey && rawAttach) {
87
+ try {
88
+ txnPlain = await openTransaction(txnPlain, rawAttach, auth, signingKey);
89
+ } catch {
90
+ // Not a sealed transaction value: keep it as given.
91
+ }
93
92
  }
94
- const { request } = decodeBufferingInit(payload);
93
+ const request: InitRequest = {
94
+ ...init.request,
95
+ bind_call: {
96
+ ...init.request.bind_call,
97
+ attach_opaque_data: attach,
98
+ transaction_opaque_data: txnPlain,
99
+ storage_shard_key: shardKey,
100
+ },
101
+ };
95
102
  const args = func.bufferingExtractArgs(request.bind_call);
96
103
  const settings = batchToScalarDict(request.bind_call.settings);
97
104
  const secrets = batchToSecretDict(request.bind_call.secrets);
@@ -159,11 +166,20 @@ export function tableBufferingHandlers(
159
166
  // ------------------------------------------------------------------------
160
167
  // table_buffering_destructor — best-effort end-of-query cleanup (unary)
161
168
  // ------------------------------------------------------------------------
162
- const tableBufferingDestructor: VgiService["tableBufferingDestructor"] = async (rpcParams) => {
169
+ const tableBufferingDestructor: VgiService["tableBufferingDestructor"] = async (rpcParams, ctx?: any) => {
163
170
  try {
164
171
  const inner = unwrapRequest(rpcParams.request);
165
172
  const executionId = toUint8Array(inner.execution_id);
166
- const bound = new BoundStorage(defaultStorage, executionId);
173
+ const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
174
+ // The execution's state lives in its attach's shard, not the default one.
175
+ const { shardKey } = await openAttachWithShard(
176
+ rawAttach,
177
+ ctx?.auth ?? currentRequestAuth(),
178
+ signingKey,
179
+ attachSecretKey,
180
+ );
181
+ bufferingInitCache.delete(shardKey, executionId);
182
+ const bound = new BoundStorage(defaultStorage, executionId, null, shardKey);
167
183
  await bound.executionClear();
168
184
  } catch {
169
185
  // Teardown path — swallow; the entry is wiped when the worker exits.
@@ -195,7 +211,3 @@ function decodeBytesList(raw: any): Uint8Array[] {
195
211
  }
196
212
  return out;
197
213
  }
198
-
199
- function hex(buf: Uint8Array): string {
200
- return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
201
- }
@@ -66,6 +66,14 @@ export interface BindRequest {
66
66
  attach_opaque_data: Uint8Array | null;
67
67
  transaction_opaque_data: Uint8Array | null;
68
68
  resolved_secrets_provided: boolean;
69
+ /**
70
+ * Framework-derived, never on the wire: the FunctionStorage shard key
71
+ * (`att-<uuid hex>`) of this call's attach, stamped when the framework opens
72
+ * the attach and strips its UUID (which the function body never sees).
73
+ * Absent / "" when the call is not bound to an ATTACH. Read it with
74
+ * `shardKeyOf(bindCall)`; `BoundStorage` routes and seals by it.
75
+ */
76
+ storage_shard_key?: string | null;
69
77
  /**
70
78
  * COPY ... FROM context — `null`/absent unless this bind/init opens a
71
79
  * COPY-FROM scan. Additive + name-keyed, so ordinary scans (which omit it on