@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
@@ -4,6 +4,8 @@ import type { Arguments } from "../arguments/arguments.js";
4
4
  import { type ArgumentConstraints } from "../arguments/argument-spec.js";
5
5
  import type { VgiFunction } from "./types.js";
6
6
  import type { FunctionExample } from "./types.js";
7
+ import { type BoundStorage } from "./storage.js";
8
+ import { ExecutionCache } from "./execution-cache.js";
7
9
  export declare const GROUP_COLUMN_NAME = "__vgi_group_id";
8
10
  export interface AggregateBindParams<TArgs = Record<string, any>> {
9
11
  args: TArgs;
@@ -109,28 +111,31 @@ export interface AggregateFunctionConfig<TArgs = Record<string, any>, TState = a
109
111
  */
110
112
  requiredSecrets?: RequiredSecret[];
111
113
  }
112
- type StateMap = Map<bigint, any>;
113
- interface ExecEntry {
114
- states: StateMap;
115
- bindArgs: Arguments;
116
- bindParams: AggregateBindParams<any>;
117
- loaded: Set<bigint>;
118
- }
119
- /**
120
- * Fetch the execution context — bind args/params + states for requested gids.
121
- * On cache miss, tries to reconstruct from on-disk files written by a
122
- * sibling worker. Returns undefined if the exec never existed anywhere.
123
- * `requestedGids` (optional) tells us which group states to pre-load.
124
- */
125
- export declare function getExecutionState(executionId: Uint8Array, requestedGids?: Iterable<bigint>): ExecEntry | undefined;
126
- export declare function setExecutionState(executionId: Uint8Array, entry: Omit<ExecEntry, "loaded">): void;
114
+ /** Key of the sealed bind context within FrameworkNS.AGGREGATE_STATE. */
115
+ export declare const AGGREGATE_CONTEXT_KEY: Uint8Array<ArrayBufferLike>;
116
+ /** Per-(shard, execution) cache of the decoded bind context. */
117
+ export declare const aggregateContextCache: ExecutionCache<AggregateBindParams<any>>;
118
+ /** Encode one group's state for storage. */
119
+ export declare function encodeGroupState(state: unknown): Uint8Array;
120
+ /** Decode one group's state from storage. */
121
+ export declare function decodeGroupState(bytes: Uint8Array): any;
127
122
  /**
128
- * Persist the given group states to disk so sibling workers can pick them up.
129
- * Deletes the on-disk entry when the in-memory state was removed (gid no
130
- * longer present in states map).
123
+ * The stored bind context: the wire `arguments` and `input_schema` bytes and
124
+ * the argument names, exactly as aggregate_bind received them, so a cold
125
+ * process rebuilds the same AggregateBindParams (args are re-extracted from
126
+ * the arguments with the function's declaration). No secrets.
131
127
  */
132
- export declare function persistGroupStates(executionId: Uint8Array, gids: Iterable<bigint>): void;
133
- export declare function deleteExecutionState(executionId: Uint8Array): void;
128
+ export interface StoredAggregateContext {
129
+ argumentsIpc: Uint8Array;
130
+ inputSchemaIpc: Uint8Array | null;
131
+ argumentNames: (string | null)[] | null;
132
+ }
133
+ export declare function encodeAggregateContext(ctx: StoredAggregateContext): Uint8Array;
134
+ export declare function decodeAggregateContext(bytes: Uint8Array): StoredAggregateContext;
135
+ /** Read the stored states of `gids` (absent groups are left out of the map). */
136
+ export declare function loadGroupStates(storage: BoundStorage, gids: bigint[]): Promise<Map<bigint, any>>;
137
+ /** Write the states of `gids` that are present in `states` (one batched put). */
138
+ export declare function storeGroupStates(storage: BoundStorage, states: Map<bigint, any>, gids: Iterable<bigint>): Promise<void>;
134
139
  /**
135
140
  * Declare an aggregate function. The returned VgiFunction has `kind:
136
141
  * "aggregate"` plus a `config` handle the dispatch layer uses to drive the
@@ -139,4 +144,3 @@ export declare function deleteExecutionState(executionId: Uint8Array): void;
139
144
  export declare function defineAggregate<TArgs = Record<string, any>, TState = any>(config: AggregateFunctionConfig<TArgs, TState>): VgiFunction & {
140
145
  aggregateConfig: AggregateFunctionConfig<TArgs, TState>;
141
146
  };
142
- export {};
@@ -0,0 +1,11 @@
1
+ export declare class ExecutionCache<V> {
2
+ readonly maxEntries: number;
3
+ private readonly _map;
4
+ constructor(maxEntries: number);
5
+ private static _key;
6
+ get(shardKey: string, executionId: Uint8Array): V | undefined;
7
+ set(shardKey: string, executionId: Uint8Array, value: V): void;
8
+ delete(shardKey: string, executionId: Uint8Array): void;
9
+ clear(): void;
10
+ get size(): number;
11
+ }
@@ -0,0 +1,173 @@
1
+ import { VendorBlobClient, type BlobRef } from "@query-farm/vgi-rpc";
2
+ import type { FunctionStorage, WorkerStateKey } from "./storage.js";
3
+ /** Values of at least this many bytes go to the blob vendor (default). */
4
+ export declare const DEFAULT_EXTERNALIZE_BYTES: number;
5
+ /** Largest blob a read will fetch (the vendor's per-object cap). */
6
+ export declare const MAX_BLOB_BYTES: number;
7
+ export declare const ENV_VENDOR_URL = "VGI_BLOB_VENDOR_URL";
8
+ export declare const ENV_VENDOR_TOKEN = "VGI_BLOB_VENDOR_TOKEN";
9
+ export declare const ENV_EXTERNALIZE = "VGI_STORAGE_EXTERNALIZE";
10
+ export declare const ENV_EXTERNALIZE_BYTES = "VGI_STORAGE_EXTERNALIZE_BYTES";
11
+ export declare const ENV_EXTERNALIZE_BYTES_ALIAS = "VGI_CF_DO_EXTERNALIZE_BYTES";
12
+ export declare const TAG_INLINE = 0;
13
+ export declare const TAG_POINTER = 1;
14
+ /** Tag + u64 size + 32-byte SHA-256: the pointer's fixed part. */
15
+ export declare const POINTER_FIXED_BYTES: number;
16
+ type Env = Readonly<Record<string, string | undefined>>;
17
+ /** A value read from storage is not a valid envelope (empty, unknown tag,
18
+ * malformed pointer), or is a pointer read with no blob vendor configured. */
19
+ export declare class StorageEnvelopeError extends Error {
20
+ constructor(message: string);
21
+ }
22
+ /** An externalized storage value's blob could not be read. The message starts
23
+ * `storage blob <object id>`. */
24
+ export declare class StorageBlobError extends Error {
25
+ constructor(message: string);
26
+ }
27
+ /** The downloaded blob does not match the pointer's size or SHA-256. */
28
+ export declare class StorageBlobIntegrityError extends StorageBlobError {
29
+ constructor(message: string);
30
+ }
31
+ /** The blob is gone from the vendor or its storage (expired, deleted, never uploaded). */
32
+ export declare class StorageBlobMissingError extends StorageBlobError {
33
+ constructor(message: string);
34
+ }
35
+ /** A value is too large for the backend and no blob vendor is configured. */
36
+ export declare class StorageValueTooLargeError extends Error {
37
+ constructor(message: string);
38
+ }
39
+ /** The inline envelope of `value`: `0x00 || value`. */
40
+ export declare function encodeInline(value: Uint8Array): Uint8Array;
41
+ /**
42
+ * The pointer envelope for a vendored blob:
43
+ * `0x01 || u64be(size) || sha256 || object_id`.
44
+ * @throws Error if the object id is outside `[A-Za-z0-9._:-]{1,128}`.
45
+ */
46
+ export declare function encodePointer(ref: BlobRef): Uint8Array;
47
+ /** Parse a pointer envelope (tag 0x01).
48
+ * @throws StorageEnvelopeError if it is truncated or its object id is malformed. */
49
+ export declare function decodePointer(envelope: Uint8Array): BlobRef;
50
+ /** The envelope's tag.
51
+ * @throws StorageEnvelopeError for an empty value or an unknown tag. */
52
+ export declare function envelopeTag(envelope: Uint8Array): number;
53
+ /** Vendor `scope.execution_id` for one queue (`q`) or state scope (`s`):
54
+ * `<kind>.<hex ident>`, or `<kind>.h<hex sha256(ident)>` past 128 characters. */
55
+ export declare function blobExecutionId(kind: "q" | "s", ident: Uint8Array): Promise<string>;
56
+ /** Vendor `scope.shard` for a storage shard key: empty becomes `loc-anon`; a key
57
+ * outside `[A-Za-z0-9._-]{1,128}` becomes `h-<hex sha256(utf8 key)>`. */
58
+ export declare function blobShard(shardKey: string): Promise<string>;
59
+ /** Read `VGI_STORAGE_EXTERNALIZE_BYTES` (alias `VGI_CF_DO_EXTERNALIZE_BYTES`);
60
+ * {@link DEFAULT_EXTERNALIZE_BYTES} when unset.
61
+ * @throws Error if the value is not a positive integer. */
62
+ export declare function externalizeBytesFromEnv(env?: Env): number;
63
+ /** The vendor client from `VGI_BLOB_VENDOR_URL` and its token (falling back to
64
+ * `VGI_CF_DO_TOKEN`), or `null` when the URL is unset.
65
+ * @throws Error if the URL is set but no token is. */
66
+ export declare function blobClientFromEnv(env?: Env): VendorBlobClient | null;
67
+ /** Options for {@link wrapStorageFromEnv}. */
68
+ export interface WrapStorageOptions {
69
+ /** The backend's per-value cap, or undefined for none. A backend with a cap
70
+ * (the Cloudflare DO) is always wrapped. */
71
+ maxValueBytes?: number | undefined;
72
+ /** Environment source (default `process.env`; on Cloudflare Workers pass the
73
+ * Worker's `env`). */
74
+ env?: Env | undefined;
75
+ }
76
+ /**
77
+ * Wrap `base` in {@link ExternalizingStorage} when the environment asks for it.
78
+ *
79
+ * A backend with a per-value cap (`maxValueBytes`, i.e. the Cloudflare DO) is
80
+ * always wrapped, vendor or not, so its stored format is the same in every
81
+ * process. Any other backend is wrapped only with `VGI_STORAGE_EXTERNALIZE=1`,
82
+ * which then requires `VGI_BLOB_VENDOR_URL`. An already-wrapped backend is
83
+ * returned unchanged.
84
+ *
85
+ * @throws Error for `VGI_STORAGE_EXTERNALIZE=1` without a vendor, or a malformed variable.
86
+ */
87
+ export declare function wrapStorageFromEnv(base: FunctionStorage, options?: WrapStorageOptions): FunctionStorage;
88
+ /** Options for {@link ExternalizingStorage}. */
89
+ export interface ExternalizingStorageOptions {
90
+ /** The vendor client, or null to keep every value inline. */
91
+ blobClient: VendorBlobClient | null;
92
+ /** With a vendor, values of at least this many bytes are stored as blobs
93
+ * (default {@link DEFAULT_EXTERNALIZE_BYTES}). */
94
+ threshold?: number | undefined;
95
+ /** The backend's per-value cap. The envelope of an inline value must fit, so
96
+ * `threshold` may not exceed it; with no vendor, an over-cap value raises
97
+ * {@link StorageValueTooLargeError}. */
98
+ maxValueBytes?: number | undefined;
99
+ }
100
+ /** State one wrapper shares with its per-shard views. */
101
+ interface SharedState {
102
+ readonly blobs: VendorBlobClient | null;
103
+ readonly threshold: number;
104
+ readonly maxValueBytes: number | undefined;
105
+ readonly pending: Set<Promise<void>>;
106
+ }
107
+ /**
108
+ * A FunctionStorage that envelopes values and externalizes large ones to the
109
+ * blob vendor. Delegates every operation to the wrapped backend; see the module
110
+ * header for the envelope, scoping and clean-up.
111
+ */
112
+ export declare class ExternalizingStorage implements FunctionStorage {
113
+ private readonly _base;
114
+ private readonly _shared;
115
+ private readonly _shardKey;
116
+ /** @throws Error if `threshold` is not positive or exceeds `maxValueBytes`. */
117
+ constructor(base: FunctionStorage, options: ExternalizingStorageOptions);
118
+ /** @internal A per-shard view sharing the vendor client and clean-up. */
119
+ constructor(base: FunctionStorage, options: ExternalizingStorageOptions, shared: SharedState, shardKey: string);
120
+ /** The wrapped backend. */
121
+ get base(): FunctionStorage;
122
+ /** The vendor client, if any. */
123
+ get blobClient(): VendorBlobClient | null;
124
+ /** Values of at least this many bytes are externalized (with a vendor). */
125
+ get threshold(): number;
126
+ /** The shard this view routes to ("" = not bound to an ATTACH). */
127
+ get shardKey(): string;
128
+ /** A view routed to one attach shard (the wrapped backend's own view when it
129
+ * shards remotely), sharing the vendor client and clean-up. */
130
+ forShard(shardKey: string): ExternalizingStorage;
131
+ /** Wait for pending background blob clean-up, then close the backend. */
132
+ close(): Promise<void>;
133
+ /**
134
+ * Envelope each value, uploading large ones first. Each upload carries the
135
+ * idempotency key `<call id>.<index>`, so a vendor-level retry of the same
136
+ * logical write reuses the object.
137
+ */
138
+ encodeValues(values: readonly Uint8Array[], blobExecId: string): Promise<Uint8Array[]>;
139
+ /**
140
+ * Decode envelopes, fetching pointers in parallel (null passes through).
141
+ * @param refsOut When given, receives the blob references that were read.
142
+ * @throws StorageEnvelopeError for an invalid envelope or a pointer read with
143
+ * no vendor configured; StorageBlobError (or a subclass) when a pointer's
144
+ * blob is missing, fails its size or SHA-256 check, or cannot be fetched.
145
+ */
146
+ decodeValues(envelopes: ReadonlyArray<Uint8Array | null>, refsOut?: BlobRef[]): Promise<Array<Uint8Array | null>>;
147
+ private decodeAll;
148
+ private submitCleanup;
149
+ /** Wait for pending background blob clean-up (for tests and shutdown). */
150
+ flushBlobCleanup(): Promise<void>;
151
+ private deleteBlobs;
152
+ private deleteBlobScope;
153
+ workerPut(executionId: Uint8Array, worker: WorkerStateKey, state: Uint8Array): Promise<void>;
154
+ /** Drain and decode; the drained blobs are deleted in the background. */
155
+ workerCollect(executionId: Uint8Array): Promise<Uint8Array[]>;
156
+ workerScan(executionId: Uint8Array): Promise<Array<[number, Uint8Array]>>;
157
+ queuePush(executionId: Uint8Array, items: Uint8Array[]): Promise<number>;
158
+ /** Pop one item; its blob, if any, is deleted once fetched. */
159
+ queuePop(executionId: Uint8Array): Promise<Uint8Array | null>;
160
+ /** Clear the queue and delete its blob scope. */
161
+ queueClear(executionId: Uint8Array): Promise<number>;
162
+ stateGet(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null>;
163
+ statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void>;
164
+ stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>>;
165
+ statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void>;
166
+ /** Delete rows (their blobs stay until the scope is cleared). */
167
+ stateDelete(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<number>;
168
+ stateAppend(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number>;
169
+ stateLogScan(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, afterId?: number, limit?: number | null): Promise<Array<[number, Uint8Array]>>;
170
+ /** Clear the scope and delete its blob scope. */
171
+ executionClear(scopeId: Uint8Array): Promise<number>;
172
+ }
173
+ export {};
@@ -5,8 +5,39 @@ export type FetchLike = (input: string, init?: {
5
5
  method?: string;
6
6
  headers?: Record<string, string>;
7
7
  body?: string;
8
+ signal?: AbortSignal;
8
9
  }) => Promise<Response>;
10
+ /**
11
+ * The storage service's per-value cap (`MAX_VALUE_BYTES` in its src/index.ts).
12
+ * `resolveStorageFromEnv` / `setStorage` wrap this backend in
13
+ * `ExternalizingStorage` with this cap, which envelopes every value and moves
14
+ * large ones to the blob vendor.
15
+ */
16
+ export declare const MAX_VALUE_BYTES: number;
17
+ /** The DO server's shard_key rule (vgi-cloudflare-durable-object-storage). */
18
+ export declare const SHARD_KEY_RE: RegExp;
19
+ /**
20
+ * Shard for a call not bound to an ATTACH (no attach uuid to shard on): one
21
+ * shared DO per tenant, as vgi-python's client does. Every attach-bound call
22
+ * carries its own `att-<uuid hex>` shard instead.
23
+ */
24
+ export declare const ANONYMOUS_SHARD_KEY = "loc-anon";
25
+ /** Retry policy for the DO client. */
26
+ export interface CfDoRetryOptions {
27
+ /** Per-attempt fetch timeout, ms (default 30000; 0 disables). */
28
+ timeoutMs?: number;
29
+ /** Total attempts including the first (default 4). */
30
+ maxAttempts?: number;
31
+ /** First backoff, ms (default 100); doubles per attempt, full jitter. */
32
+ baseDelayMs?: number;
33
+ /** Backoff cap, ms (default 2000). */
34
+ maxDelayMs?: number;
35
+ }
9
36
  export declare class FunctionStorageCfDo implements FunctionStorage {
37
+ /** Marks this backend for `setStorage`, which always envelopes it. */
38
+ readonly storageKind = "cloudflare-do";
39
+ /** The service's per-value cap ({@link MAX_VALUE_BYTES}). */
40
+ readonly maxValueBytes: number;
10
41
  private readonly _baseUrl;
11
42
  private readonly _token;
12
43
  /** Per-attach routing key (att-<hex uuid>); "" until pinned via forShard. */
@@ -16,12 +47,19 @@ export declare class FunctionStorageCfDo implements FunctionStorage {
16
47
  * the same account/zone — a same-zone public-URL fetch is rejected (CF
17
48
  * error 1042), but a service binding routes worker-to-worker directly. */
18
49
  private readonly _fetch;
50
+ private readonly _retry;
51
+ /** Test hook: how the client waits between attempts. */
52
+ private readonly _sleep;
19
53
  constructor(opts: {
20
54
  url: string;
21
55
  token?: string | null;
22
56
  shardKey?: string;
23
57
  fetch?: FetchLike;
58
+ retry?: CfDoRetryOptions;
59
+ sleep?: (ms: number) => Promise<void>;
24
60
  });
61
+ /** The shard this instance routes to ("" = the anonymous shard). */
62
+ get shardKey(): string;
25
63
  /** Build an instance from environment variables. */
26
64
  static fromEnv(): FunctionStorageCfDo;
27
65
  /**
@@ -37,11 +75,23 @@ export declare class FunctionStorageCfDo implements FunctionStorage {
37
75
  queueClear(executionId: Uint8Array): Promise<number>;
38
76
  stateGet(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null>;
39
77
  statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void>;
78
+ stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>>;
79
+ statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void>;
80
+ stateDelete(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<number>;
40
81
  stateAppend(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number>;
41
82
  stateLogScan(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, afterId?: number, limit?: number | null): Promise<Array<[number, Uint8Array]>>;
42
83
  executionClear(scopeId: Uint8Array): Promise<number>;
43
84
  private _statePutMany;
44
85
  /** Drive state_scan / state_drain across pages. attemptId is null for scan. */
45
86
  private _statePaged;
87
+ /**
88
+ * POST one call. The body (and so its `attempt_id`, for destructive ops) is
89
+ * built once and resent unchanged on every retry, so the DO's replay
90
+ * detection makes a retried put/drain/pop a no-op. Retries transport errors,
91
+ * timeouts, 5xx and 429 with exponential backoff and full jitter, bounded by
92
+ * `maxAttempts`. 4xx other than 429 is the caller's error and is not retried.
93
+ * The bearer token never appears in an error message.
94
+ */
46
95
  private _post;
96
+ private _once;
47
97
  }
@@ -0,0 +1,27 @@
1
+ export declare const STORAGE_PAYLOAD_INFO = "vgi.storage.payload.v1";
2
+ export declare const STORAGE_PAYLOAD_VERSION = 1;
3
+ /** A framework payload read from storage could not be authenticated. */
4
+ export declare class StoragePayloadError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ /** The storage slot a payload is bound to. */
8
+ export interface StorageSlot {
9
+ shardKey: string;
10
+ scopeId: Uint8Array;
11
+ ns: Uint8Array;
12
+ key: Uint8Array;
13
+ }
14
+ /** The associated data binding a payload to its storage slot. */
15
+ export declare function storagePayloadAad(slot: StorageSlot): Uint8Array;
16
+ /** `HKDF-SHA256(ikm, salt = "", info = "vgi.storage.payload.v1", 32)` as raw bytes. */
17
+ export declare function deriveStoragePayloadKey(ikm: Uint8Array): Promise<Uint8Array>;
18
+ /** Seal under an explicit `ikm`. `nonce` exists for test vectors only. */
19
+ export declare function sealWith(payload: Uint8Array, ikm: Uint8Array, slot: StorageSlot, nonce?: Uint8Array): Promise<Uint8Array>;
20
+ /** Open under an explicit `ikm`; {@link StoragePayloadError} on any failure. */
21
+ export declare function openWith(blob: Uint8Array, ikm: Uint8Array, slot: StorageSlot): Promise<Uint8Array>;
22
+ /** Test hook: replace the host-local key source (null restores the key file). */
23
+ export declare function setStorageSealHostLocalKey(fn: (() => Promise<Uint8Array>) | null): void;
24
+ /** Seal a framework payload bound to its storage slot. */
25
+ export declare function sealPayload(payload: Uint8Array, signingKey: Uint8Array | undefined, slot: StorageSlot): Promise<Uint8Array>;
26
+ /** Open an envelope from {@link sealPayload} for the same slot. */
27
+ export declare function openPayload(blob: Uint8Array, signingKey: Uint8Array | undefined, slot: StorageSlot): Promise<Uint8Array>;
@@ -22,16 +22,38 @@ export interface FunctionStorage {
22
22
  queueClear(executionId: Uint8Array): Promise<number>;
23
23
  stateGet(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null>;
24
24
  statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void>;
25
+ /** Batched read: one value (or null) per key, in key order. One round trip
26
+ * on a remote backend. */
27
+ stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>>;
28
+ /** Batched atomic upsert of `(key, value)` pairs. One round trip on a remote
29
+ * backend; a no-op for an empty list. */
30
+ statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void>;
31
+ /** Optional: delete the given keys of one namespace, returning how many rows
32
+ * went. Missing keys are ignored. Every built-in backend implements it;
33
+ * {@link BoundStorage.stateDelete} refuses on a backend that does not. */
34
+ stateDelete?(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<number>;
25
35
  stateAppend(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number>;
26
36
  stateLogScan(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, afterId?: number, limit?: number | null): Promise<Array<[number, Uint8Array]>>;
27
37
  /** Wipe all state + log rows for a scope across every namespace. */
28
38
  executionClear(scopeId: Uint8Array): Promise<number>;
29
39
  /** Optional cleanup hook. Implementations holding a connection should release it here. */
30
40
  close?(): Promise<void> | void;
41
+ /**
42
+ * Optional: a view of this backend routed to one attach shard. A backend
43
+ * that partitions remotely (the Cloudflare DO, one Durable Object per
44
+ * logical ATTACH) implements it; a local backend that needs no routing
45
+ * omits it. {@link BoundStorage} calls it with the shard key the framework
46
+ * derived from the request's authenticated attach (`att-<uuid hex>`), or
47
+ * `""` when the call is not bound to an ATTACH.
48
+ */
49
+ forShard?(shardKey: string): FunctionStorage;
31
50
  }
32
51
  export declare const FrameworkNS: {
33
52
  readonly BUFFERING_INIT: Uint8Array<ArrayBufferLike>;
34
53
  readonly STREAMING_FINALIZE: Uint8Array<ArrayBufferLike>;
54
+ /** Aggregate group states (key = packIntKey(group_id)) and, at key
55
+ * packIntKey(-2), the sealed bind context. Same bytes as vgi-python. */
56
+ readonly AGGREGATE_STATE: Uint8Array<ArrayBufferLike>;
35
57
  };
36
58
  /** Encode an int as 8-byte little-endian, matching Python's pack_int_key. */
37
59
  export declare function packIntKey(i: number | bigint): Uint8Array;
@@ -53,6 +75,9 @@ export declare class FunctionStorageSqlite implements FunctionStorage {
53
75
  private _ensureTables;
54
76
  stateGet(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null>;
55
77
  statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void>;
78
+ stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>>;
79
+ statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void>;
80
+ stateDelete(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<number>;
56
81
  stateAppend(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number>;
57
82
  stateLogScan(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, afterId?: number, limit?: number | null): Promise<Array<[number, Uint8Array]>>;
58
83
  executionClear(scopeId: Uint8Array): Promise<number>;
@@ -67,13 +92,23 @@ export declare class BoundStorage {
67
92
  private _base;
68
93
  private _executionId;
69
94
  private _substreamId;
95
+ private _shardKey;
70
96
  /**
71
97
  * @param substreamId The table-in-out substream this storage serves -- the
72
98
  * client-minted `InitRequest.substream_id`, identical across the
73
99
  * substream's init, every tick and its finalize -- or `null` when the
74
100
  * client sent none. Keys {@link put}.
101
+ * @param shardKey The attach shard every call routes to: `att-<uuid hex>`,
102
+ * derived by the framework from the request's authenticated attach (see
103
+ * {@link shardKeyOf}), or `""` when the call is not bound to an ATTACH. A
104
+ * backend with `forShard` (the Cloudflare DO) routes on it; it is also part
105
+ * of every sealed framework payload's AAD.
75
106
  */
76
- constructor(storage: FunctionStorage, executionId: Uint8Array, substreamId?: Uint8Array | null);
107
+ constructor(storage: FunctionStorage, executionId: Uint8Array, substreamId?: Uint8Array | null, shardKey?: string);
108
+ /** The attach shard this view routes to ("" when not bound to an ATTACH). */
109
+ get shardKey(): string;
110
+ /** The execution (scope) id this view is bound to. */
111
+ get executionId(): Uint8Array;
77
112
  /**
78
113
  * Upsert this substream's state into the execution's worker state, which
79
114
  * {@link collect} drains at finalize.
@@ -96,11 +131,33 @@ export declare class BoundStorage {
96
131
  queueClear(): Promise<number>;
97
132
  stateGet(ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null>;
98
133
  statePut(ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void>;
134
+ /** Batched read, one value (or null) per key. One round trip remotely. */
135
+ stateGetMany(ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>>;
136
+ /** Batched atomic upsert. One round trip remotely. */
137
+ statePutMany(ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void>;
138
+ /** Delete keys of one namespace; their values' blobs (when externalized)
139
+ * stay until the execution is cleared.
140
+ * @throws Error if the backend does not implement `stateDelete`. */
141
+ stateDelete(ns: Uint8Array, keys: Uint8Array[]): Promise<number>;
99
142
  stateAppend(ns: Uint8Array, key: Uint8Array, item: Uint8Array): Promise<number>;
100
143
  stateLogScan(ns: Uint8Array, key: Uint8Array, afterId?: number, limit?: number | null): Promise<Array<[number, Uint8Array]>>;
101
144
  executionClear(): Promise<number>;
145
+ private _slot;
146
+ /** Seal `payload` to its slot, store it, and return the stored envelope. */
147
+ sealedPut(ns: Uint8Array, key: Uint8Array, payload: Uint8Array, signingKey: Uint8Array | undefined): Promise<Uint8Array>;
148
+ /** Open an envelope from {@link sealedPut} for this slot (StoragePayloadError on failure). */
149
+ openSealed(ns: Uint8Array, key: Uint8Array, sealed: Uint8Array, signingKey: Uint8Array | undefined): Promise<Uint8Array>;
150
+ /** Read and open a sealed framework payload; null when the slot is empty. */
151
+ sealedGet(ns: Uint8Array, key: Uint8Array, signingKey: Uint8Array | undefined): Promise<Uint8Array | null>;
102
152
  static packIntKey(i: number | bigint): Uint8Array;
103
153
  }
154
+ /**
155
+ * The attach shard key the framework stamped on a request's bind call when it
156
+ * opened the attach (`att-<uuid hex>`), or `""` when there is none.
157
+ */
158
+ export declare function shardKeyOf(bindCall: {
159
+ storage_shard_key?: string | null | undefined;
160
+ } | null | undefined): string;
104
161
  /**
105
162
  * Resolve the FunctionStorage backend from environment variables.
106
163
  *
@@ -114,6 +171,11 @@ export declare class BoundStorage {
114
171
  * (including `:memory:`).
115
172
  * - `cloudflare-do` — `FunctionStorageCfDo`. Requires `VGI_CF_DO_URL`;
116
173
  * optional `VGI_CF_DO_TOKEN` for bearer auth.
174
+ *
175
+ * The backend is wrapped in {@link ExternalizingStorage} (value envelope plus
176
+ * blob-vendor externalization, `./storage-blobs.ts`) always for
177
+ * `cloudflare-do`, and for any other backend with `VGI_STORAGE_EXTERNALIZE=1`;
178
+ * see `wrapStorageFromEnv`.
117
179
  */
118
180
  export declare function resolveStorageFromEnv(): FunctionStorage;
119
181
  /**
@@ -123,6 +185,14 @@ export declare function resolveStorageFromEnv(): FunctionStorage;
123
185
  * service-binding Fetcher (the binding lives on `env`, not `process.env`, and a
124
186
  * same-zone public-URL fetch is rejected with CF error 1042). Takes precedence
125
187
  * over `VGI_WORKER_SHARED_STORAGE`.
188
+ *
189
+ * A bare `FunctionStorageCfDo` is wrapped in {@link ExternalizingStorage}, as
190
+ * the env-selected one is, so every process writes the same enveloped format;
191
+ * the blob vendor comes from `VGI_BLOB_VENDOR_URL` in `process.env` when there
192
+ * is one. On Cloudflare Workers, where the vendor's URL and token are `env`
193
+ * bindings, wrap it yourself first --
194
+ * `setStorage(wrapStorageFromEnv(cfDo, { maxValueBytes: MAX_VALUE_BYTES, env }))`
195
+ * -- and it is used as given. Any other backend is used as given.
126
196
  */
127
197
  export declare function setStorage(impl: FunctionStorage): void;
128
198
  /** Default FunctionStorage instance. Backend is selected via env on first access. */
@@ -7,6 +7,7 @@ import type { VgiFunction, FunctionExample } from "./types.js";
7
7
  import type { ArgumentConstraints } from "../arguments/argument-spec.js";
8
8
  import { FunctionStability } from "../types.js";
9
9
  import { BoundStorage } from "./storage.js";
10
+ import { ExecutionCache } from "./execution-cache.js";
10
11
  export interface TableBufferingBindParams<TArgs = Record<string, any>> {
11
12
  args: TArgs;
12
13
  bindCall: BindRequest;
@@ -102,6 +103,35 @@ export interface TableBufferingVgiFunction extends VgiFunction {
102
103
  bufferingExtractArgs: (request: BindRequest) => any;
103
104
  }
104
105
  export declare function defineTableBufferingFunction<TArgs = Record<string, any>, TState = any>(config: TableBufferingConfig<TArgs, TState>): TableBufferingVgiFunction;
106
+ /** Decoded buffered init context, as cached and as returned by the loader. */
107
+ export interface BufferingInit {
108
+ request: InitRequest;
109
+ response: GlobalInitResponse;
110
+ }
111
+ /**
112
+ * Decoded buffered-init context per (shard, execution). The init is written
113
+ * once and read on every process/combine RPC; with this, a process batch costs
114
+ * the function's own storage calls only. Small: one entry per in-flight
115
+ * buffered execution, evicted by the destructor.
116
+ */
117
+ export declare const bufferingInitCache: ExecutionCache<BufferingInit>;
118
+ /**
119
+ * Persist a buffered sink init's context so any worker can serve the unary
120
+ * process/combine RPCs that follow, which carry no init context themselves.
121
+ *
122
+ * The stored InitRequest carries `bind_call.secrets`, so it is sealed
123
+ * (./storage-seal.ts) to its (shard, execution, ns, key) slot. Its attach and
124
+ * transaction values are NOT stored: every process/combine request carries
125
+ * them, and the loader fills them in from the request after opening them.
126
+ */
127
+ export declare function persistBufferingInit(request: InitRequest, response: GlobalInitResponse, signingKey: Uint8Array | undefined): Promise<void>;
128
+ /**
129
+ * Load a buffered execution's init context: the in-process cache, else the
130
+ * sealed storage copy (opened, decoded, then cached). Throws when the
131
+ * execution is unknown, and StoragePayloadError when the stored copy does not
132
+ * authenticate for this shard / execution.
133
+ */
134
+ export declare function loadBufferingInit(bound: BoundStorage, signingKey: Uint8Array | undefined): Promise<BufferingInit>;
105
135
  export declare function encodeBufferingInit(request: InitRequest, response: GlobalInitResponse): Uint8Array;
106
136
  export declare function decodeBufferingInit(payload: Uint8Array): {
107
137
  request: InitRequest;
@@ -78,7 +78,12 @@ export interface TableFunctionConfig<TArgs = Record<string, any>, TState = null>
78
78
  argConstraints?: Record<string, ArgumentConstraints>;
79
79
  /** Names of args that accept variable number of arguments */
80
80
  varargs?: string[];
81
- /** Bind: return output schema. May be async — handlers `await` the result. */
81
+ /**
82
+ * Bind: return output schema. May be async — handlers `await` the result.
83
+ * To ask DuckDB for secrets, return `lookupSecretTypes` with optional
84
+ * `lookupScopes` / `lookupNames` at the same indexes (see `SecretLookupFields`);
85
+ * a scope or name with no type at its index is a bind error.
86
+ */
82
87
  onBind: (params: TableBindParams<TArgs>) => {
83
88
  outputSchema: VgiSchema;
84
89
  opaqueData?: Uint8Array;
@@ -355,9 +355,14 @@ export interface CopyToContext {
355
355
  format: string;
356
356
  file_path: string;
357
357
  }
358
+ export interface ArgumentsLocation {
359
+ ref: Uint8Array;
360
+ size: number;
361
+ sha256: string;
362
+ }
358
363
  export interface BindRequest {
359
364
  function_name: string;
360
- arguments: Uint8Array;
365
+ arguments?: /** @vgi-arguments */ Uint8Array | null;
361
366
  function_type: InvocationFunctionType;
362
367
  input_schema?: /** @arrow-schema */ Uint8Array | null;
363
368
  settings?: /** @record-batch */ Uint8Array | null;
@@ -371,6 +376,7 @@ export interface BindRequest {
371
376
  copy_to?: CopyToContext | null;
372
377
  schema_path?: string[] | null;
373
378
  argument_names?: (string | null)[] | null;
379
+ arguments_location?: ArgumentsLocation | null;
374
380
  }
375
381
  export interface BindResponse {
376
382
  output_schema: Uint8Array;
@@ -43,6 +43,16 @@ export declare const TableLayoutChangeSchema: import("../index.core.js").VgiSche
43
43
  export declare const OptionChangesSchema: import("../index.core.js").VgiSchema;
44
44
  export declare const OptionStateSchema: import("../index.core.js").VgiSchema;
45
45
  export declare const RequiredFilterPathsSchema: import("../index.core.js").VgiSchema;
46
+ export declare const CopyFromContextSchema: import("../index.core.js").VgiSchema;
47
+ export declare const CopyToContextSchema: import("../index.core.js").VgiSchema;
48
+ export declare const ArgumentsLocationSchema: import("../index.core.js").VgiSchema;
49
+ export declare const BindRequestSchema: import("../index.core.js").VgiSchema;
50
+ export declare const InitRequestSchema: import("../index.core.js").VgiSchema;
51
+ export declare const TableFunctionCardinalityRequestSchema: import("../index.core.js").VgiSchema;
52
+ export declare const TableFunctionStatisticsRequestSchema: import("../index.core.js").VgiSchema;
53
+ export declare const TableFunctionDynamicToStringRequestSchema: import("../index.core.js").VgiSchema;
54
+ export declare const TableFunctionPlanRequestSchema: import("../index.core.js").VgiSchema;
55
+ export declare const TableFunctionProjectionRequestSchema: import("../index.core.js").VgiSchema;
46
56
  export declare const ScanFunctionResultSchema: import("../index.core.js").VgiSchema;
47
57
  export declare const ScanBranchesResultSchema: import("../index.core.js").VgiSchema;
48
58
  export declare const ScanBranchSchema: import("../index.core.js").VgiSchema;
@@ -62,25 +72,16 @@ export declare const AggregateWindowBatchRequestSchema: import("../index.core.js
62
72
  export declare const AggregateWindowDestructorRequestSchema: import("../index.core.js").VgiSchema;
63
73
  export declare const AggregateWindowInitRequestSchema: import("../index.core.js").VgiSchema;
64
74
  export declare const AggregateWindowRequestSchema: import("../index.core.js").VgiSchema;
65
- export declare const BindRequestSchema: import("../index.core.js").VgiSchema;
66
75
  export declare const CatalogAttachRequestSchema: import("../index.core.js").VgiSchema;
67
76
  export declare const CatalogCreateRequestSchema: import("../index.core.js").VgiSchema;
68
77
  export declare const ClientCapabilitiesSchema: import("../index.core.js").VgiSchema;
69
- export declare const CopyFromContextSchema: import("../index.core.js").VgiSchema;
70
- export declare const CopyToContextSchema: import("../index.core.js").VgiSchema;
71
78
  export declare const GlobalInitResponseSchema: import("../index.core.js").VgiSchema;
72
79
  export declare const IndexCreateRequestSchema: import("../index.core.js").VgiSchema;
73
- export declare const InitRequestSchema: import("../index.core.js").VgiSchema;
74
80
  export declare const MacroCreateRequestSchema: import("../index.core.js").VgiSchema;
75
81
  export declare const TableCreateRequestSchema: import("../index.core.js").VgiSchema;
76
82
  export declare const TableBufferingCombineRequestSchema: import("../index.core.js").VgiSchema;
77
83
  export declare const TableBufferingDestructorRequestSchema: import("../index.core.js").VgiSchema;
78
84
  export declare const TableBufferingProcessRequestSchema: import("../index.core.js").VgiSchema;
79
- export declare const TableFunctionCardinalityRequestSchema: import("../index.core.js").VgiSchema;
80
- export declare const TableFunctionDynamicToStringRequestSchema: import("../index.core.js").VgiSchema;
81
- export declare const TableFunctionPlanRequestSchema: import("../index.core.js").VgiSchema;
82
- export declare const TableFunctionProjectionRequestSchema: import("../index.core.js").VgiSchema;
83
- export declare const TableFunctionStatisticsRequestSchema: import("../index.core.js").VgiSchema;
84
85
  export declare const AggregateBindResultSchema: import("../index.core.js").VgiSchema;
85
86
  export declare const AggregateCombineResultSchema: import("../index.core.js").VgiSchema;
86
87
  export declare const AggregateDestructorResultSchema: import("../index.core.js").VgiSchema;