@query-farm/vgi 0.44.0 → 0.46.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 (73) hide show
  1. package/README.md +8 -1
  2. package/dist/arrow/impl-arrowjs/index.d.ts +1 -1
  3. package/dist/arrow/impl-arrowjs/ipc.d.ts +6 -0
  4. package/dist/arrow/impl-flechette/build.d.ts +2 -2
  5. package/dist/arrow/impl-flechette/canonical.d.ts +2 -2
  6. package/dist/arrow/impl-flechette/index.d.ts +1 -1
  7. package/dist/arrow/impl-flechette/ipc.d.ts +6 -0
  8. package/dist/arrow/impl-flechette/schema.d.ts +19 -5
  9. package/dist/arrow/index.d.ts +1 -1
  10. package/dist/catalog/contents-codec.d.ts +7 -0
  11. package/dist/catalog/contents-digest.d.ts +2 -1
  12. package/dist/catalog/interface.d.ts +3 -0
  13. package/dist/catalog/publication-envelope.d.ts +1 -0
  14. package/dist/catalog/publication.d.ts +142 -0
  15. package/dist/catalog/s3-publication.d.ts +38 -0
  16. package/dist/client/client.d.ts +20 -1
  17. package/dist/client-entry.js +189 -37
  18. package/dist/client-entry.js.map +15 -12
  19. package/dist/codec/asd.d.ts +4 -0
  20. package/dist/functions/continuation.d.ts +69 -0
  21. package/dist/functions/table-in-out.d.ts +51 -7
  22. package/dist/functions/types.d.ts +20 -0
  23. package/dist/generated/vgi-client.d.ts +7 -14
  24. package/dist/generated/vgi-protocol-schemas.d.ts +2 -0
  25. package/dist/generated/vgi-protocol-types.d.ts +26 -3
  26. package/dist/generated/vgi-service.d.ts +3 -3
  27. package/dist/index.core.d.ts +1 -0
  28. package/dist/index.d.ts +4 -0
  29. package/dist/index.js +981 -138
  30. package/dist/index.js.map +31 -25
  31. package/dist/protocol/dispatch.d.ts +1 -1
  32. package/dist/protocol/handlers/catalog/contents.d.ts +4 -4
  33. package/dist/serve-entry.js +643 -81
  34. package/dist/serve-entry.js.map +22 -18
  35. package/dist/util/parent-rows.d.ts +8 -0
  36. package/dist/worker-cf-entry.d.ts +1 -1
  37. package/dist/worker-cf-entry.js +821 -131
  38. package/dist/worker-cf-entry.js.map +29 -24
  39. package/package.json +4 -4
  40. package/src/arrow/impl-arrowjs/index.ts +1 -0
  41. package/src/arrow/impl-arrowjs/ipc.ts +23 -0
  42. package/src/arrow/impl-flechette/build.ts +4 -2
  43. package/src/arrow/impl-flechette/canonical.ts +14 -7
  44. package/src/arrow/impl-flechette/index.ts +1 -0
  45. package/src/arrow/impl-flechette/ipc.ts +19 -0
  46. package/src/arrow/index.ts +1 -1
  47. package/src/catalog/contents-codec.ts +77 -0
  48. package/src/catalog/contents-digest.ts +20 -17
  49. package/src/catalog/interface.ts +3 -0
  50. package/src/catalog/publication-envelope.ts +62 -0
  51. package/src/catalog/publication.ts +290 -0
  52. package/src/catalog/read-only.ts +6 -2
  53. package/src/catalog/s3-publication.ts +81 -0
  54. package/src/client/client.ts +82 -30
  55. package/src/codec/asd.ts +40 -1
  56. package/src/codec/conform.ts +2 -1
  57. package/src/filter-pushdown/collector.ts +17 -1
  58. package/src/functions/continuation.ts +202 -0
  59. package/src/functions/table-in-out.ts +131 -56
  60. package/src/functions/types.ts +20 -0
  61. package/src/generated/vgi-client.ts +8 -16
  62. package/src/generated/vgi-protocol-schemas.ts +14 -6
  63. package/src/generated/vgi-protocol-types.ts +39 -5
  64. package/src/generated/vgi-service.ts +4 -3
  65. package/src/index.core.ts +6 -0
  66. package/src/index.ts +5 -0
  67. package/src/protocol/dispatch.ts +1 -1
  68. package/src/protocol/handlers/catalog/admin.ts +7 -4
  69. package/src/protocol/handlers/catalog/contents.ts +50 -35
  70. package/src/protocol/handlers/function.ts +12 -0
  71. package/src/protocol/state-serializer.ts +7 -1
  72. package/src/util/parent-rows.ts +41 -0
  73. package/src/worker-cf-entry.ts +3 -0
@@ -0,0 +1,290 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Immutable, validated catalog publications. The caller authenticates before lookup.
3
+ import { ExternalRef, publishExternalResult, resolveExternalLocation, type ExternalStorage, type ExternalLocationConfig, type CallContext } from "@query-farm/vgi-rpc";
4
+ import { schema, field, binary, typeSignature } from "../arrow/index.js";
5
+ import { decodeASDCollection, encodeASD } from "../codec/asd.js";
6
+ import { CatalogContentsResultSchema, VGI_CATALOG_CONTRACT_HASH } from "../generated/vgi-protocol-schemas.js";
7
+ import type { CatalogContentsResponse } from "../generated/vgi-client.js";
8
+ import { VGI_PROTOCOL_NAME, VGI_PROTOCOL_VERSION } from "../generated/vgi-service.js";
9
+ import { decodeCatalogStreams, CATALOG_STREAM_KINDS } from "./contents-codec.js";
10
+ import { catalogContentsDigest } from "./contents-digest.js";
11
+ import { validateCatalogPublicationEnvelope } from "./publication-envelope.js";
12
+ import type { AttachOpaqueData, CatalogInterface } from "./interface.js";
13
+
14
+ export interface SnapshotIdentity {
15
+ catalogNamespace: string;
16
+ sourceRevision: string;
17
+ /** Explicit equivalence class for sharing; omitted by a handler defaults to the sealed attachment hash. */
18
+ visibilityScope?: string;
19
+ catalogVersion: number;
20
+ }
21
+ export interface SnapshotRequest {
22
+ catalog: CatalogInterface;
23
+ attachOpaqueData: AttachOpaqueData;
24
+ callContext?: CallContext;
25
+ catalogVersion: number;
26
+ }
27
+ export interface CatalogPublicationManifest {
28
+ formatVersion: 1;
29
+ /** Unique repository generation for conditional invalidation and URL renewal. */
30
+ manifestId: string;
31
+ key: string;
32
+ protocolName: string;
33
+ protocolVersion: string;
34
+ contractHash: string;
35
+ codecRevision: 1;
36
+ catalogVersion: number;
37
+ etag: string;
38
+ sha256: string;
39
+ rawSize: number;
40
+ storedSize: number;
41
+ url: string;
42
+ objectId?: string;
43
+ expiresAt?: number;
44
+ retainUntil?: number;
45
+ stable: boolean;
46
+ validated: true;
47
+ }
48
+ export interface CatalogPublicationRepository {
49
+ /** Change when storage credentials, namespace or delivery profile change. */
50
+ readonly profile: string;
51
+ readonly storage: ExternalStorage;
52
+ /** Supply a bounded resolver (URL policy, fetch implementation, caps). */
53
+ readonly resolver: ExternalLocationConfig;
54
+ lookup(key: string): Promise<CatalogPublicationManifest | null>;
55
+ /** Atomic create-if-absent; return the committed manifest, including another publisher's winner. */
56
+ commitIfAbsent(manifest: CatalogPublicationManifest): Promise<CatalogPublicationManifest>;
57
+ invalidate(key: string, expected: CatalogPublicationManifest): Promise<void>;
58
+ /** Renew the URL without changing the object's identity, content or retention. */
59
+ renew?(manifest: CatalogPublicationManifest): Promise<CatalogPublicationManifest | null>;
60
+ /** Require either explicit stability or a URL expiration time. */
61
+ describe(url: string): Promise<Pick<CatalogPublicationManifest, "objectId" | "expiresAt" | "retainUntil" | "stable">>;
62
+ }
63
+ export interface CatalogSnapshotPolicy {
64
+ delivery: "ordinary" | "published";
65
+ repository: CatalogPublicationRepository;
66
+ identity(request: SnapshotRequest): SnapshotIdentity | Promise<SnapshotIdentity>;
67
+ onPublicationFailure?: "error" | "ordinary";
68
+ compression?: "identity" | "gzip" | "zstd";
69
+ maxRawBytes?: number;
70
+ maxStoredBytes?: number;
71
+ maxCachedManifests?: number;
72
+ referenceGraceMs?: number;
73
+ /** Optional cheap validator; avoids constructing even a first publication for a conditional hit. */
74
+ etag?(request: SnapshotRequest): string | null | Promise<string | null>;
75
+ }
76
+
77
+ const OUTER_SCHEMA = schema([field("result", binary(), false)]);
78
+ const DEFAULT_MAX = 64 * 1024 * 1024;
79
+ const utf8 = new TextEncoder();
80
+ const equalBytes = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((v, i) => v === b[i]);
81
+ async function digest(value: string): Promise<string> {
82
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8.encode(value)));
83
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
84
+ }
85
+ function assertRenewedPublication(before: CatalogPublicationManifest, after: CatalogPublicationManifest) {
86
+ const unchanged = (m: CatalogPublicationManifest) => JSON.stringify([m.key, m.formatVersion, m.protocolName, m.protocolVersion, m.contractHash, m.codecRevision, m.catalogVersion, m.etag, m.sha256, m.rawSize, m.storedSize, m.objectId, m.retainUntil, m.stable, m.validated]);
87
+ if (unchanged(before) !== unchanged(after)) throw new Error("renewal changed immutable catalog identity");
88
+ }
89
+ const manifestSame = (a: CatalogPublicationManifest, b: CatalogPublicationManifest) => a.manifestId === b.manifestId;
90
+
91
+ /** Memory repository is useful for tests and process-local reuse; storage stays caller-owned. */
92
+ export class MemoryCatalogPublicationRepository implements CatalogPublicationRepository {
93
+ private manifests = new Map<string, CatalogPublicationManifest>();
94
+ constructor(readonly profile: string, readonly storage: ExternalStorage, readonly resolver: ExternalLocationConfig, readonly describe: CatalogPublicationRepository["describe"]) {}
95
+ async lookup(key: string) { return this.manifests.get(key) ?? null; }
96
+ async commitIfAbsent(manifest: CatalogPublicationManifest) {
97
+ const existing = this.manifests.get(manifest.key);
98
+ if (existing) return existing;
99
+ const committed = Object.freeze({ ...manifest });
100
+ this.manifests.set(manifest.key, committed);
101
+ return committed;
102
+ }
103
+ async invalidate(key: string, expected: CatalogPublicationManifest) {
104
+ const current = this.manifests.get(key);
105
+ if (current && manifestSame(current, expected)) this.manifests.delete(key);
106
+ }
107
+ }
108
+
109
+ /** A small S3-compatible client surface; adapters map these conditions to If-None-Match / If-Match. */
110
+ export interface CatalogManifestObjectStore {
111
+ get(key: string): Promise<{ body: Uint8Array; etag: string } | null>;
112
+ put(key: string, body: Uint8Array, condition: { ifNoneMatch: "*" } | { ifMatch: string }): Promise<boolean>;
113
+ delete(key: string, condition: { ifMatch: string }): Promise<boolean>;
114
+ }
115
+ /** Durable manifest repository, usable with S3/R2 conditional object operations and any RPC uploader. */
116
+ export class S3CatalogPublicationRepository implements CatalogPublicationRepository {
117
+ renewReference?: (manifest: CatalogPublicationManifest) => Promise<CatalogPublicationManifest | null>;
118
+ constructor(readonly profile: string, readonly storage: ExternalStorage, readonly resolver: ExternalLocationConfig,
119
+ private readonly objects: CatalogManifestObjectStore, readonly describe: CatalogPublicationRepository["describe"], private readonly prefix = "vgi/catalog-manifests/") {}
120
+ private objectKey(key: string) { if (!/^[0-9a-f]{64}$/.test(key)) throw new Error("invalid publication key"); return `${this.prefix}${key}.json`; }
121
+ async lookup(key: string) {
122
+ const value = await this.objects.get(this.objectKey(key));
123
+ if (!value) return null;
124
+ if (value.body.byteLength > 64 * 1024) throw new Error("catalog manifest exceeds 64 KiB");
125
+ return JSON.parse(new TextDecoder().decode(value.body)) as CatalogPublicationManifest;
126
+ }
127
+ async commitIfAbsent(manifest: CatalogPublicationManifest) {
128
+ const stored = await this.objects.put(this.objectKey(manifest.key), utf8.encode(JSON.stringify(manifest)), { ifNoneMatch: "*" });
129
+ if (stored) return manifest;
130
+ const current = await this.lookup(manifest.key);
131
+ if (!current) throw new Error("catalog manifest changed during commit");
132
+ return current;
133
+ }
134
+ async renew(manifest: CatalogPublicationManifest) {
135
+ if (!this.renewReference) return null;
136
+ const current = await this.objects.get(this.objectKey(manifest.key));
137
+ if (!current) return null;
138
+ const existing = JSON.parse(new TextDecoder().decode(current.body)) as CatalogPublicationManifest;
139
+ if (!manifestSame(existing, manifest)) return existing;
140
+ const renewed = await this.renewReference(manifest);
141
+ if (!renewed) return null;
142
+ assertRenewedPublication(manifest, renewed);
143
+ if (await this.objects.put(this.objectKey(manifest.key), utf8.encode(JSON.stringify(renewed)), { ifMatch: current.etag })) return renewed;
144
+ return this.lookup(manifest.key);
145
+ }
146
+ async invalidate(key: string, expected: CatalogPublicationManifest) {
147
+ const current = await this.objects.get(this.objectKey(key));
148
+ if (current && manifestSame(JSON.parse(new TextDecoder().decode(current.body)), expected)) {
149
+ await this.objects.delete(this.objectKey(key), { ifMatch: current.etag });
150
+ }
151
+ }
152
+ }
153
+
154
+ export class CatalogSnapshotManager {
155
+ private cached = new Map<string, CatalogPublicationManifest>();
156
+ private pending = new Map<string, Promise<CatalogPublicationManifest>>();
157
+ constructor(readonly policy: CatalogSnapshotPolicy) {
158
+ for (const value of [policy.maxRawBytes, policy.maxStoredBytes, policy.maxCachedManifests]) {
159
+ if (value != null && (!Number.isSafeInteger(value) || value <= 0)) throw new Error("catalog publication limits must be positive safe integers");
160
+ }
161
+ if (policy.referenceGraceMs != null && (!Number.isSafeInteger(policy.referenceGraceMs) || policy.referenceGraceMs < 0)) throw new Error("catalog publication reference grace must be a nonnegative safe integer");
162
+ }
163
+ private usable(m: CatalogPublicationManifest) {
164
+ const deadline = Date.now() + (this.policy.referenceGraceMs ?? 60_000);
165
+ return (m.stable || m.expiresAt != null) && (m.expiresAt == null || m.expiresAt > deadline) && (m.retainUntil == null || m.retainUntil > deadline);
166
+ }
167
+ async key(identity: SnapshotIdentity): Promise<string> {
168
+ for (const value of [identity.catalogNamespace, identity.sourceRevision, identity.visibilityScope]) if (!value) throw new Error("published catalogs require explicit namespace, revision and visibility scope");
169
+ if (!Number.isSafeInteger(identity.catalogVersion)) throw new Error("catalog version is not a safe integer");
170
+ return digest(JSON.stringify([VGI_PROTOCOL_NAME, VGI_PROTOCOL_VERSION, VGI_CATALOG_CONTRACT_HASH, 1,
171
+ identity.catalogNamespace, identity.sourceRevision, identity.visibilityScope, identity.catalogVersion, this.policy.repository.profile, this.policy.compression ?? "identity"]));
172
+ }
173
+ private remember(m: CatalogPublicationManifest) {
174
+ this.cached.delete(m.key); this.cached.set(m.key, Object.freeze({ ...m }));
175
+ while (this.cached.size > (this.policy.maxCachedManifests ?? 128)) this.cached.delete(this.cached.keys().next().value!);
176
+ }
177
+ async invalidate(key: string) {
178
+ await this.pending.get(key)?.catch(() => undefined);
179
+ const m = this.cached.get(key) ?? await this.policy.repository.lookup(key);
180
+ this.cached.delete(key);
181
+ if (m) await this.policy.repository.invalidate(key, m);
182
+ }
183
+ private async validate(m: CatalogPublicationManifest, key: string, identity: SnapshotIdentity, expected?: CatalogContentsResponse) {
184
+ if (m.formatVersion !== 1 || typeof m.manifestId !== "string" || !m.manifestId || m.key !== key || m.protocolName !== VGI_PROTOCOL_NAME || m.protocolVersion !== VGI_PROTOCOL_VERSION
185
+ || m.contractHash !== VGI_CATALOG_CONTRACT_HASH || m.codecRevision !== 1 || m.catalogVersion !== identity.catalogVersion || m.validated !== true || typeof m.stable !== "boolean"
186
+ || typeof m.etag !== "string" || !/^[0-9a-f]{64}$/.test(m.sha256) || !Number.isSafeInteger(m.rawSize) || !Number.isSafeInteger(m.storedSize) || m.rawSize <= 0 || m.storedSize <= 0
187
+ || m.rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX) || m.storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX)
188
+ || !this.usable(m)) throw new Error("invalid or expired catalog publication manifest");
189
+ const ref = new ExternalRef(m.url, m.sha256);
190
+ const configuredFetch = this.policy.repository.resolver.fetch ?? fetch;
191
+ const resolved = await resolveExternalLocation(ref.pointerBatch(OUTER_SCHEMA), {
192
+ ...this.policy.repository.resolver,
193
+ fetch: ((input: RequestInfo | URL, init?: RequestInit) => configuredFetch(input, { ...init, signal: AbortSignal.any([...(init?.signal ? [init.signal] : []), AbortSignal.timeout(30_000)]) })) as typeof fetch,
194
+ maxFetchBytes: Math.min(this.policy.maxStoredBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxFetchBytes ?? Infinity),
195
+ maxDecompressedBytes: Math.min(this.policy.maxRawBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxDecompressedBytes ?? Infinity),
196
+ validateFetchedIpc: (bytes) => {
197
+ this.policy.repository.resolver.validateFetchedIpc?.(bytes);
198
+ if (bytes.length !== m.rawSize) throw new Error("catalog publication raw size mismatch");
199
+ validateCatalogPublicationEnvelope(bytes);
200
+ },
201
+ });
202
+ if (resolved.numRows !== 1 || resolved.schema.fields.length !== 1 || resolved.schema.fields[0].name !== "result"
203
+ || typeSignature(resolved.schema.fields[0].type) !== typeSignature(binary()) || resolved.schema.fields[0].nullable) throw new Error("invalid published RPC envelope");
204
+ const bytes = resolved.getChild("result")?.get(0);
205
+ if (!(bytes instanceof Uint8Array)) throw new Error("published catalog has no result bytes");
206
+ const decoded = decodeASDCollection<CatalogContentsResponse>(CatalogContentsResultSchema, bytes);
207
+ if (decoded.length !== 1) throw new Error("published catalog must contain exactly one response row");
208
+ const response = decoded[0];
209
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion || response.etag !== m.etag) throw new Error("published catalog version or ETag mismatch");
210
+ decodeCatalogStreams(response);
211
+ if (expected) for (const kind of CATALOG_STREAM_KINDS) {
212
+ const a = response[kind], b = expected[kind];
213
+ if ((a == null) !== (b == null) || (a != null && b != null && !equalBytes(a, b))) throw new Error("publication readback changed catalog metadata");
214
+ }
215
+ }
216
+ async import(manifest: CatalogPublicationManifest, identity: SnapshotIdentity) {
217
+ const key = await this.key(identity);
218
+ await this.validate(manifest, key, identity);
219
+ const winner = await this.policy.repository.commitIfAbsent(manifest);
220
+ if (!manifestSame(manifest, winner)) await this.validate(winner, key, identity);
221
+ this.remember(winner);
222
+ return winner;
223
+ }
224
+ async warm(identity: SnapshotIdentity, build: () => Promise<CatalogContentsResponse>): Promise<CatalogPublicationManifest> {
225
+ const key = await this.key(identity);
226
+ const cached = this.cached.get(key);
227
+ if (cached && this.usable(cached)) return cached;
228
+ const active = this.pending.get(key); if (active) return active;
229
+ const pending = this.recoverOrPublish(key, identity, build);
230
+ this.pending.set(key, pending);
231
+ try { const m = await pending; this.remember(m); return m; }
232
+ finally { if (this.pending.get(key) === pending) this.pending.delete(key); }
233
+ }
234
+ private async recoverOrPublish(key: string, identity: SnapshotIdentity, build: () => Promise<CatalogContentsResponse>) {
235
+ const repository = this.policy.repository;
236
+ let existing = await repository.lookup(key);
237
+ if (existing) {
238
+ try {
239
+ if (!this.usable(existing) && repository.renew) { const renewed = await repository.renew(existing); if (renewed) { assertRenewedPublication(existing, renewed); existing = renewed; } }
240
+ await this.validate(existing, key, identity); return existing; }
241
+ catch { await repository.invalidate(key, existing); }
242
+ }
243
+ const response = await build();
244
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion) throw new Error("publication requires a full snapshot of the requested version");
245
+ decodeCatalogStreams(response);
246
+ response.etag ??= await catalogContentsDigest(response, identity.catalogVersion);
247
+ const payload = encodeASD(CatalogContentsResultSchema, response);
248
+ let rawSize = 0, storedSize = 0;
249
+ // Identity encoding keeps the counted bytes identical to the publisher's
250
+ // raw envelope: cap before upload without serializing the envelope twice.
251
+ const bounded: ExternalStorage = { upload: async (data, encoding) => {
252
+ if (encoding) throw new Error("catalog publication uploader requires identity encoding");
253
+ rawSize = data.byteLength;
254
+ if (rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX)) throw new Error("catalog publication exceeds byte limit");
255
+ let body = data;
256
+ const compression = this.policy.compression ?? "identity";
257
+ if (compression !== "identity" && compression !== "gzip" && compression !== "zstd") throw new Error("catalog publication compression must be identity, gzip or zstd");
258
+ if (compression === "gzip") {
259
+ body = new Uint8Array(await new Response(new Blob([data as BlobPart]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer());
260
+ } else if (compression === "zstd") {
261
+ const runtime = (globalThis as any).Bun;
262
+ if (typeof runtime?.zstdCompress === "function") {
263
+ body = new Uint8Array(await runtime.zstdCompress(data));
264
+ } else if (typeof process !== "undefined" && process.versions?.node) {
265
+ // The indirect specifier keeps a Node-only module out of browser/worker bundles.
266
+ const nodeZlib = "node:zlib";
267
+ const zlib = await import(nodeZlib);
268
+ if (typeof zlib.zstdCompressSync !== "function") throw new Error("zstd catalog publication requires Node >=22.15, Bun, or an encoder-capable runtime");
269
+ body = new Uint8Array(zlib.zstdCompressSync(data));
270
+ } else {
271
+ throw new Error("zstd catalog publication requires an encoder-capable runtime; use gzip or identity here");
272
+ }
273
+ }
274
+ storedSize = body.byteLength;
275
+ if (storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX)) throw new Error("catalog publication exceeds byte limit");
276
+ return repository.storage.upload(body, compression === "identity" ? "" : compression);
277
+ } };
278
+ const ref = await publishExternalResult(OUTER_SCHEMA, { result: payload }, bounded, { includeSha256: true });
279
+ const m: CatalogPublicationManifest = {
280
+ formatVersion: 1, manifestId: crypto.randomUUID(), key, protocolName: VGI_PROTOCOL_NAME, protocolVersion: VGI_PROTOCOL_VERSION,
281
+ contractHash: VGI_CATALOG_CONTRACT_HASH, codecRevision: 1, catalogVersion: identity.catalogVersion,
282
+ etag: response.etag, sha256: ref.sha256!, rawSize, storedSize, url: ref.url, validated: true,
283
+ ...await repository.describe(ref.url),
284
+ };
285
+ await this.validate(m, key, identity, response);
286
+ const winner = await repository.commitIfAbsent(m);
287
+ if (!manifestSame(m, winner)) await this.validate(winner, key, identity);
288
+ return winner;
289
+ }
290
+ }
@@ -267,7 +267,6 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
267
267
 
268
268
  schemas(attachOpaqueData: AttachOpaqueData, transactionOpaqueData?: TransactionOpaqueData): SchemaInfo[] {
269
269
  return this._descriptor.schemas.map((s) => ({
270
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
271
270
  path: schemaDescriptorPath(s),
272
271
  comment: s.comment ?? null,
273
272
  tags: s.tags ?? {},
@@ -305,7 +304,6 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
305
304
  const desc = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
306
305
  if (!desc) return null;
307
306
  return {
308
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
309
307
  path: schemaDescriptorPath(desc),
310
308
  comment: desc.comment ?? null,
311
309
  tags: desc.tags ?? {},
@@ -689,6 +687,12 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
689
687
  // mirrors Python's `input_from_args=False if is_scalar else ...`.
690
688
  input_from_args:
691
689
  f.kind === "table_in_out" && f.meta.inputFromArgs === true,
690
+ // Blended only: the most input rows per worker call (null = a whole
691
+ // chunk). Mirrors Python's `None if is_scalar else ...`.
692
+ input_rows_per_call:
693
+ f.kind === "table_in_out" && f.meta.inputFromArgs === true
694
+ ? (f.meta.inputRowsPerCall ?? null)
695
+ : null,
692
696
  required_settings: meta.requiredSettings,
693
697
  required_secrets: requiredSecrets.map((s) => ({
694
698
  secret_type: s.secret_type,
@@ -0,0 +1,81 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ import type { ExternalStorage, ExternalLocationConfig } from "@query-farm/vgi-rpc";
3
+ import { S3CatalogPublicationRepository, type CatalogManifestObjectStore, type CatalogPublicationManifest } from "./publication.js";
4
+
5
+ /** Sign an S3/R2 request using the application's existing credentials/SDK.
6
+ * Include the supplied headers when signing; they are sent exactly as given. */
7
+ export type CatalogS3Signer = (request: {
8
+ key: string; method: "GET" | "PUT" | "DELETE"; headers: Record<string, string>;
9
+ }) => Promise<{ url: string; expiresAt?: number; stable?: boolean }>;
10
+
11
+ /** Concrete S3 HTTP adapter with conditional manifest operations and immutable objects.
12
+ * A signer keeps AWS/R2 credentials out of the framework and stored manifests. */
13
+ export class S3CatalogObjectStorage implements ExternalStorage, CatalogManifestObjectStore {
14
+ private locations = new Map<string, Pick<CatalogPublicationManifest, "objectId" | "expiresAt" | "retainUntil" | "stable">>();
15
+ constructor(readonly sign: CatalogS3Signer, private readonly request: typeof fetch = fetch,
16
+ private readonly objectPrefix = "vgi/catalog-results/", private readonly retentionMs?: number) {}
17
+ async upload(data: Uint8Array, contentEncoding: string): Promise<string> {
18
+ const key = `${this.objectPrefix}${crypto.randomUUID()}.arrow`;
19
+ const headers: Record<string, string> = { "Content-Type": "application/vnd.apache.arrow.stream", "If-None-Match": "*" };
20
+ if (contentEncoding) headers["Content-Encoding"] = contentEncoding;
21
+ const put = await this.sign({ key, method: "PUT", headers });
22
+ const response = await this.request(put.url, { method: "PUT", headers, body: data as BodyInit, redirect: "error", signal: AbortSignal.timeout(30_000) });
23
+ if (!response.ok) throw new Error(`catalog object upload failed (${response.status})`);
24
+ const get = await this.sign({ key, method: "GET", headers: {} });
25
+ if (!get.stable && get.expiresAt == null) throw new Error("S3 catalog signer must declare GET URL expiration or stability");
26
+ this.locations.set(get.url, { objectId: key, expiresAt: get.expiresAt, stable: get.stable ?? false,
27
+ retainUntil: this.retentionMs == null ? undefined : Date.now() + this.retentionMs });
28
+ return get.url;
29
+ }
30
+ async describe(url: string) {
31
+ const value = this.locations.get(url);
32
+ if (!value) throw new Error("unknown catalog object location");
33
+ this.locations.delete(url);
34
+ return value;
35
+ }
36
+ async get(key: string) {
37
+ const signed = await this.sign({ key, method: "GET", headers: {} });
38
+ const response = await this.request(signed.url, { redirect: "error", signal: AbortSignal.timeout(30_000) });
39
+ if (response.status === 404) return null;
40
+ if (!response.ok) throw new Error(`catalog manifest GET failed (${response.status})`);
41
+ const etag = response.headers.get("etag");
42
+ if (!etag) throw new Error("S3 catalog manifest lacks conditional-operation ETag");
43
+ const reader = response.body?.getReader();
44
+ if (!reader) throw new Error("empty catalog manifest body");
45
+ let size = 0; const parts: Uint8Array[] = [];
46
+ while (true) {
47
+ const { done, value } = await reader.read(); if (done) break;
48
+ size += value.byteLength;
49
+ if (size > 64 * 1024) { await reader.cancel(); throw new Error("catalog manifest exceeds 64 KiB"); }
50
+ parts.push(value);
51
+ }
52
+ const body = new Uint8Array(size); let offset = 0;
53
+ for (const part of parts) { body.set(part, offset); offset += part.byteLength; }
54
+ return { body, etag };
55
+ }
56
+ async put(key: string, body: Uint8Array, condition: { ifNoneMatch: "*" } | { ifMatch: string }) {
57
+ const headers = { "Content-Type": "application/json", ...("ifNoneMatch" in condition ? { "If-None-Match": condition.ifNoneMatch } : { "If-Match": condition.ifMatch }) };
58
+ const signed = await this.sign({ key, method: "PUT", headers });
59
+ const response = await this.request(signed.url, { method: "PUT", headers, body: body as BodyInit, redirect: "error", signal: AbortSignal.timeout(30_000) });
60
+ if (response.status === 412 || response.status === 409) return false;
61
+ if (!response.ok) throw new Error(`catalog manifest PUT failed (${response.status})`);
62
+ return true;
63
+ }
64
+ async delete(key: string, condition: { ifMatch: string }) {
65
+ const headers = { "If-Match": condition.ifMatch };
66
+ const signed = await this.sign({ key, method: "DELETE", headers });
67
+ const response = await this.request(signed.url, { method: "DELETE", headers, redirect: "error", signal: AbortSignal.timeout(30_000) });
68
+ if (response.status === 412 || response.status === 404) return false;
69
+ if (!response.ok) throw new Error(`catalog manifest DELETE failed (${response.status})`);
70
+ return true;
71
+ }
72
+ repository(profile: string, resolver: Omit<ExternalLocationConfig, "storage"> = {}, manifestPrefix = "vgi/catalog-manifests/") {
73
+ const repository = new S3CatalogPublicationRepository(profile, this, { ...resolver, storage: this }, this, (url) => this.describe(url), manifestPrefix);
74
+ repository.renewReference = async (manifest) => {
75
+ if (!manifest.objectId) return null;
76
+ const signed = await this.sign({ key: manifest.objectId, method: "GET", headers: {} });
77
+ return { ...manifest, manifestId: crypto.randomUUID(), url: signed.url, expiresAt: signed.expiresAt, stable: signed.stable ?? false };
78
+ };
79
+ return repository;
80
+ }
81
+ }
@@ -7,7 +7,9 @@ import { type VgiSchema, schema as schema_, type VgiField, field, type VgiBatch,
7
7
  // emits `import {} from "@query-farm/vgi-rpc"`, a side-effect import of the
8
8
  // package root — which re-exports the whole framework, server included, into
9
9
  // every browser bundle. See the note in ./errors.
10
- import type { RpcClient, StreamSession } from "@query-farm/vgi-rpc";
10
+ import type { RawStreamSession, RpcClient, StreamSession } from "@query-farm/vgi-rpc";
11
+ import { CACHE_NOT_MODIFIED_KEY } from "../cache-control.js";
12
+ import { CONTINUE, HAVE_MORE_OUTPUT, STATUS_KEY } from "../functions/continuation.js";
11
13
  import {
12
14
  serializeBindRequest,
13
15
  deserializeBindResponse,
@@ -25,6 +27,7 @@ import { Arguments } from "../arguments/arguments.js";
25
27
  import {
26
28
  batchFromRows,
27
29
  batchFromColumns,
30
+ emptyBatch,
28
31
  iterRows,
29
32
  } from "../util/arrow/index.js";
30
33
  import {
@@ -57,6 +60,7 @@ import { VgiClientError, wrapRpcWithErrorEnrichment } from "./errors.js";
57
60
  import { normalizeSchemaPath } from "../schema-path.js";
58
61
  import { encodeASD } from "../codec/asd.js";
59
62
  import { ClientCapabilitiesSchema, MacroCreateRequestSchema } from "../generated/vgi-protocol-schemas.js";
63
+ import { decodeCatalogStreams } from "../catalog/contents-codec.js";
60
64
  import { decodeCatalogContentsResponse } from "../generated/vgi-protocol-types.js";
61
65
  import { deserializeInfoList, deserializeTags, toAsyncIterator } from "./helpers.js";
62
66
 
@@ -85,6 +89,74 @@ function onConflictName(onConflict: OnCreateConflict): string {
85
89
  return String(onConflict).toUpperCase();
86
90
  }
87
91
 
92
+ /** Whether reply metadata carries `vgi.cache.not_modified` set. */
93
+ function isNotModified(md: Map<string, string>): boolean {
94
+ const v = md.get(CACHE_NOT_MODIFIED_KEY);
95
+ return v != null && v !== "0" && v.toLowerCase() !== "false";
96
+ }
97
+
98
+ /**
99
+ * Send one input batch on a table-in-out exchange and yield the rows of every
100
+ * reply it gets (continued output, docs/table_in_out.md "Continued Output").
101
+ *
102
+ * A reply saying `vgi.status: HAVE_MORE_OUTPUT` has more output for the same
103
+ * input: ask for the next with a continuation tick (a zero-row batch of the
104
+ * input schema carrying `vgi.status: CONTINUE`) until a reply stops saying
105
+ * more. Only then may the next input go out, or the input close. The row-level
106
+ * `StreamSession.exchange` drops reply metadata, so this uses the raw exchange
107
+ * every transport's session implements.
108
+ *
109
+ * Refused, as the extension refuses them: `not_modified` on a reply that says
110
+ * more or answers a tick (a 304 stands for an input's whole output), and the
111
+ * worker ending the stream while output is pending.
112
+ *
113
+ * Exported for tests only (not re-exported from the package entry points).
114
+ * @internal
115
+ */
116
+ export async function* exchangeContinued(
117
+ session: StreamSession,
118
+ functionName: string,
119
+ input: VgiBatch,
120
+ ): AsyncGenerator<Record<string, any>[]> {
121
+ const raw = session as unknown as Partial<Pick<RawStreamSession, "exchangeRaw">>;
122
+ if (typeof raw.exchangeRaw !== "function") {
123
+ throw new VgiClientError(
124
+ `tableInOutFunction(${functionName}): the transport's stream session has no exchangeRaw(), ` +
125
+ `which continued output needs to read each reply's vgi.status`,
126
+ );
127
+ }
128
+ const exchangeRaw = raw.exchangeRaw.bind(session);
129
+ let tick = false;
130
+ let reply = await exchangeRaw({ batch: input as any, metadata: new Map() });
131
+ for (;;) {
132
+ if (reply === null) {
133
+ if (tick) {
134
+ throw new VgiClientError(
135
+ `tableInOutFunction(${functionName}): the worker ended the stream while output was pending`,
136
+ );
137
+ }
138
+ return;
139
+ }
140
+ const md = new Map<string, string>([...((reply.batch as any).metadata ?? []), ...reply.metadata]);
141
+ const more = md.get(STATUS_KEY) === HAVE_MORE_OUTPUT;
142
+ if (isNotModified(md) && (more || tick)) {
143
+ throw new VgiClientError(
144
+ `tableInOutFunction(${functionName}): the worker answered not_modified on a continued reply ` +
145
+ `(${tick ? "answering a continuation tick" : "one saying HAVE_MORE_OUTPUT"}); ` +
146
+ `not_modified must be an input's only reply`,
147
+ );
148
+ }
149
+ const rows = [...iterRows(reply.batch as unknown as VgiBatch)];
150
+ if (rows.length > 0) yield rows;
151
+ if (!more) return;
152
+ tick = true;
153
+ reply = await exchangeRaw({
154
+ batch: emptyBatch(input.schema) as any,
155
+ metadata: new Map([[STATUS_KEY, CONTINUE]]),
156
+ });
157
+ }
158
+ }
159
+
88
160
  /**
89
161
  * High-level client for calling VGI worker functions and catalog API.
90
162
  *
@@ -425,12 +497,9 @@ export class VgiClient {
425
497
  );
426
498
 
427
499
  try {
428
- const outRows = await inputSession.exchange([...iterRows(firstBatch)]);
429
- if (outRows.length > 0) yield outRows;
430
-
500
+ yield* exchangeContinued(inputSession, opts.functionName, firstBatch);
431
501
  for await (const batch of { [Symbol.asyncIterator]: () => inputIter }) {
432
- const result = await inputSession.exchange([...iterRows(batch)]);
433
- if (result.length > 0) yield result;
502
+ yield* exchangeContinued(inputSession, opts.functionName, batch);
434
503
  }
435
504
  } finally {
436
505
  inputSession.close();
@@ -506,12 +575,13 @@ export class VgiClient {
506
575
 
507
576
  const outputSchema = bindResp.output_schema;
508
577
  try {
509
- const outRows = await inputSession.exchange([...iterRows(firstBatch)]);
510
- if (outRows.length > 0) yield batchFromRows(outRows, outputSchema);
511
-
578
+ for await (const rows of exchangeContinued(inputSession, opts.functionName, firstBatch)) {
579
+ yield batchFromRows(rows, outputSchema);
580
+ }
512
581
  for await (const batch of { [Symbol.asyncIterator]: () => inputIter }) {
513
- const result = await inputSession.exchange([...iterRows(batch)]);
514
- if (result.length > 0) yield batchFromRows(result, outputSchema);
582
+ for await (const rows of exchangeContinued(inputSession, opts.functionName, batch)) {
583
+ yield batchFromRows(rows, outputSchema);
584
+ }
515
585
  }
516
586
  } finally {
517
587
  inputSession.close();
@@ -721,25 +791,7 @@ export class VgiClient {
721
791
  });
722
792
  if (!result) throw new VgiClientError("catalog_contents returned null");
723
793
  const response = decodeCatalogContentsResponse(toUint8Array(result.result));
724
- const schemas = response.schemas.map((c) => {
725
- const schema = decodeSchemaInfo(c.schema);
726
- if (JSON.stringify(c.path) !== JSON.stringify(schema.path)) {
727
- throw new VgiClientError(
728
- `catalog_contents: SchemaContents.path ${JSON.stringify(c.path)} != SchemaInfo.path ${JSON.stringify(schema.path)}`,
729
- );
730
- }
731
- return {
732
- schema,
733
- tables: c.tables.map(decodeTableInfo),
734
- views: c.views.map(decodeViewInfo),
735
- scalar_functions: c.scalar_functions.map(decodeFunctionInfo),
736
- aggregate_functions: c.aggregate_functions.map(decodeFunctionInfo),
737
- table_functions: c.table_functions.map(decodeFunctionInfo),
738
- scalar_macros: c.scalar_macros.map(decodeMacroInfo),
739
- table_macros: c.table_macros.map(decodeMacroInfo),
740
- indexes: c.indexes.map(decodeIndexInfo),
741
- };
742
- });
794
+ const schemas = decodeCatalogStreams(response, ifNoneMatch);
743
795
  return {
744
796
  catalog_version: Number(response.catalog_version ?? 0),
745
797
  etag: response.etag ?? null,
package/src/codec/asd.ts CHANGED
@@ -30,6 +30,10 @@ import {
30
30
  batchFromRows,
31
31
  serializeBatch,
32
32
  deserializeBatch,
33
+ deserializeSchema,
34
+ deserializeBatches,
35
+ serializeCollectionRows,
36
+ typeSignature,
33
37
  } from "../arrow/index.js";
34
38
  import { conformRecord } from "./conform.js";
35
39
 
@@ -213,7 +217,7 @@ function normalizeValue(raw: any, type: VgiDataType): any {
213
217
  }
214
218
 
215
219
  if (isDictionary(type)) {
216
- return raw == null ? null : String(raw);
220
+ return normalizeValue(raw, (type as any).dictionary as VgiDataType);
217
221
  }
218
222
 
219
223
  if (isBinary(type)) {
@@ -247,3 +251,38 @@ function toUint8Array(val: any): Uint8Array {
247
251
  }
248
252
  return new Uint8Array(0);
249
253
  }
254
+
255
+ /** Encode ordinary metadata records directly, sharing one schema and dictionary per category. */
256
+ export function encodeASDCollection(schema: VgiSchema, records: readonly Record<string, any>[]): Uint8Array | null {
257
+ if (records.length === 0) return null;
258
+ return serializeCollectionRows(schema, records.map((record) => sortMapsForSchema(schema, conformRecord(schema, record))), 1024);
259
+ }
260
+
261
+ /** Decode every row of every batch and reject incompatible collection schemas. */
262
+ export function decodeASDCollection<T>(schema: VgiSchema, bytes: Uint8Array | null | undefined): T[] {
263
+ if (bytes == null) return [];
264
+ const output: T[] = [];
265
+ const batches = deserializeBatches(bytes);
266
+ const validateSchema = (actualSchema: VgiSchema) => {
267
+ if (actualSchema.fields.length !== schema.fields.length || schema.fields.some((field, i) => {
268
+ const actual = actualSchema.fields[i];
269
+ return actual.name !== field.name || actual.nullable !== field.nullable || typeSignature(actual.type) !== typeSignature(field.type);
270
+ })) throw new Error("catalog collection has an incompatible metadata schema");
271
+ };
272
+ // Schema-only streams have no data batch whose schema could otherwise be
273
+ // checked. Empty or malformed bytes must not silently count as null.
274
+ if (batches.length === 0) validateSchema(deserializeSchema(bytes));
275
+ for (const batch of batches) {
276
+ validateSchema(batch.schema);
277
+ for (let row = 0; row < batch.numRows; row++) {
278
+ const item: Record<string, any> = {};
279
+ for (const field of schema.fields) {
280
+ const value = batch.getChild(field.name)?.get(row);
281
+ if (value == null && !field.nullable) throw new Error(`catalog collection has null ${field.name}`);
282
+ item[field.name] = normalizeValue(value, field.type);
283
+ }
284
+ output.push(item as T);
285
+ }
286
+ }
287
+ return output;
288
+ }
@@ -74,7 +74,8 @@ function mapPairs(raw: any): Array<[unknown, unknown]> {
74
74
 
75
75
  /** The value a non-null slot of `type` takes when the sender left it null. */
76
76
  export function zeroValue(type: VgiDataType): unknown {
77
- if (isUtf8(type) || isDictionary(type)) return "";
77
+ if (isDictionary(type)) return zeroValue((type as any).dictionary as VgiDataType);
78
+ if (isUtf8(type)) return "";
78
79
  if (isBinary(type)) return new Uint8Array(0);
79
80
  if (isBool(type)) return false;
80
81
  if (isInt(type)) return (type as any).bitWidth === 64 ? 0n : 0;