@query-farm/vgi 0.43.0 → 0.45.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 +5 -2
  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 +1 -1
  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/index.d.ts +1 -1
  9. package/dist/attach-ticket.d.ts +18 -7
  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-entry.js +349 -114
  17. package/dist/client-entry.js.map +16 -14
  18. package/dist/codec/asd.d.ts +7 -1
  19. package/dist/codec/conform.d.ts +51 -0
  20. package/dist/errors.d.ts +5 -1
  21. package/dist/generated/vgi-client.d.ts +6 -14
  22. package/dist/generated/vgi-protocol-schemas.d.ts +2 -0
  23. package/dist/generated/vgi-protocol-types.d.ts +26 -3
  24. package/dist/generated/vgi-service.d.ts +3 -3
  25. package/dist/index.core.d.ts +1 -1
  26. package/dist/index.d.ts +4 -0
  27. package/dist/index.js +955 -118
  28. package/dist/index.js.map +33 -28
  29. package/dist/protocol/dispatch.d.ts +1 -1
  30. package/dist/protocol/handlers/catalog/contents.d.ts +4 -4
  31. package/dist/protocol/handlers/shared.d.ts +2 -1
  32. package/dist/protocol/serializers/shared.d.ts +2 -1
  33. package/dist/rpc-server.d.ts +2 -2
  34. package/dist/serve-entry.js +867 -165
  35. package/dist/serve-entry.js.map +26 -22
  36. package/dist/worker-cf-entry.js +825 -114
  37. package/dist/worker-cf-entry.js.map +31 -27
  38. package/package.json +3 -3
  39. package/src/arrow/impl-arrowjs/index.ts +1 -0
  40. package/src/arrow/impl-arrowjs/ipc.ts +23 -0
  41. package/src/arrow/impl-flechette/build.ts +4 -2
  42. package/src/arrow/impl-flechette/canonical.ts +7 -2
  43. package/src/arrow/impl-flechette/index.ts +1 -0
  44. package/src/arrow/impl-flechette/ipc.ts +19 -0
  45. package/src/arrow/index.ts +1 -1
  46. package/src/attach-ticket.ts +41 -13
  47. package/src/catalog/composite.ts +2 -1
  48. package/src/catalog/contents-codec.ts +77 -0
  49. package/src/catalog/contents-digest.ts +20 -17
  50. package/src/catalog/interface.ts +8 -4
  51. package/src/catalog/publication-envelope.ts +62 -0
  52. package/src/catalog/publication.ts +290 -0
  53. package/src/catalog/read-only.ts +8 -8
  54. package/src/catalog/s3-publication.ts +81 -0
  55. package/src/client/client.ts +15 -24
  56. package/src/codec/asd.ts +45 -3
  57. package/src/codec/conform.ts +194 -0
  58. package/src/errors.ts +27 -7
  59. package/src/functions/registry.ts +3 -2
  60. package/src/generated/vgi-client.ts +7 -16
  61. package/src/generated/vgi-protocol-schemas.ts +13 -6
  62. package/src/generated/vgi-protocol-types.ts +39 -5
  63. package/src/generated/vgi-service.ts +4 -3
  64. package/src/http/fetch.ts +1 -1
  65. package/src/index.core.ts +3 -1
  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/shared.ts +8 -2
  71. package/src/protocol/serializers/bind.ts +3 -1
  72. package/src/protocol/serializers/shared.ts +5 -2
  73. package/src/rpc-server.ts +7 -7
@@ -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
+ }
@@ -32,6 +32,8 @@ import { FunctionStability, NullHandling, OrderPreservation, DEFAULT_MAX_WORKERS
32
32
  import { Arguments } from "../arguments/arguments.js";
33
33
  import { normalizeSchemaPath, schemaPathDisplay, schemaPathsEqual } from "../schema-path.js";
34
34
  import { ForeignKeyInfoSchema } from "../generated/vgi-protocol-schemas.js";
35
+ import { conformColumns } from "../codec/conform.js";
36
+ import { VgiError } from "../errors.js";
35
37
  import { encodeFunctionInfoOnce, freezeCatalogItem } from "./item-encoding.js";
36
38
 
37
39
  /**
@@ -178,7 +180,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
178
180
  implementationVersion?: string | null,
179
181
  ): CatalogAttachResult | Promise<CatalogAttachResult> {
180
182
  if (!this.catalogs().includes(name)) {
181
- throw new Error(`No worker handles catalog '${name}'`);
183
+ throw new VgiError(`No worker handles catalog '${name}'`, "NOT_FOUND");
182
184
  }
183
185
  // Refuse an attach that omits a declared-required option, so the caller
184
186
  // gets the option name rather than a catalog that looks mysteriously
@@ -265,7 +267,6 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
265
267
 
266
268
  schemas(attachOpaqueData: AttachOpaqueData, transactionOpaqueData?: TransactionOpaqueData): SchemaInfo[] {
267
269
  return this._descriptor.schemas.map((s) => ({
268
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
269
270
  path: schemaDescriptorPath(s),
270
271
  comment: s.comment ?? null,
271
272
  tags: s.tags ?? {},
@@ -303,7 +304,6 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
303
304
  const desc = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
304
305
  if (!desc) return null;
305
306
  return {
306
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
307
307
  path: schemaDescriptorPath(desc),
308
308
  comment: desc.comment ?? null,
309
309
  tags: desc.tags ?? {},
@@ -820,11 +820,11 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
820
820
  // Find the table descriptor
821
821
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), schemaPath));
822
822
  if (!schema || !schema.tables) {
823
- throw new Error(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`);
823
+ throw new VgiError(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`, "NOT_FOUND");
824
824
  }
825
825
  const table = schema.tables.find((t) => t.name === name);
826
826
  if (!table) {
827
- throw new Error(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`);
827
+ throw new VgiError(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`, "NOT_FOUND");
828
828
  }
829
829
 
830
830
  // Reject AT clause on tables that don't support time travel
@@ -958,12 +958,12 @@ function serializeForeignKeys(fks?: ForeignKeyDef[], schemaPath?: string[]): Uin
958
958
  return fks.map((fk) =>
959
959
  serializeBatch(
960
960
  batchFromColumns(
961
- {
961
+ conformColumns(ForeignKeyInfoSchema, {
962
962
  fk_columns: [fk.columns],
963
963
  pk_columns: [fk.referencedColumns],
964
964
  referenced_table: [fk.referencedTable],
965
965
  referenced_schema_path: [fk.referencedSchemaPath ?? schemaPath ?? ["main"]],
966
- },
966
+ }),
967
967
  ForeignKeyInfoSchema
968
968
  )
969
969
  )
@@ -1145,7 +1145,7 @@ function serializeArgsBatch(args: Arguments, argSpecSchema: VgiSchema): Uint8Arr
1145
1145
 
1146
1146
  function validateAtParams(atUnit?: string, atValue?: string): void {
1147
1147
  if (Boolean(atUnit) !== Boolean(atValue)) {
1148
- throw new Error("at_unit and at_value must both be provided or both be absent");
1148
+ throw new VgiError("at_unit and at_value must both be provided or both be absent", "INVALID_ARGUMENT");
1149
1149
  }
1150
1150
  }
1151
1151
 
@@ -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
+ }
@@ -57,6 +57,7 @@ import { VgiClientError, wrapRpcWithErrorEnrichment } from "./errors.js";
57
57
  import { normalizeSchemaPath } from "../schema-path.js";
58
58
  import { encodeASD } from "../codec/asd.js";
59
59
  import { ClientCapabilitiesSchema, MacroCreateRequestSchema } from "../generated/vgi-protocol-schemas.js";
60
+ import { decodeCatalogStreams } from "../catalog/contents-codec.js";
60
61
  import { decodeCatalogContentsResponse } from "../generated/vgi-protocol-types.js";
61
62
  import { deserializeInfoList, deserializeTags, toAsyncIterator } from "./helpers.js";
62
63
 
@@ -77,6 +78,14 @@ import type {
77
78
  LoadCatalogOptions,
78
79
  } from "./types.js";
79
80
 
81
+ /**
82
+ * `on_conflict` as it goes on the wire: the vgi-python `OnConflict` member
83
+ * NAME (`ERROR` / `IGNORE` / `REPLACE`), not the lower-case API spelling.
84
+ */
85
+ function onConflictName(onConflict: OnCreateConflict): string {
86
+ return String(onConflict).toUpperCase();
87
+ }
88
+
80
89
  /**
81
90
  * High-level client for calling VGI worker functions and catalog API.
82
91
  *
@@ -713,25 +722,7 @@ export class VgiClient {
713
722
  });
714
723
  if (!result) throw new VgiClientError("catalog_contents returned null");
715
724
  const response = decodeCatalogContentsResponse(toUint8Array(result.result));
716
- const schemas = response.schemas.map((c) => {
717
- const schema = decodeSchemaInfo(c.schema);
718
- if (JSON.stringify(c.path) !== JSON.stringify(schema.path)) {
719
- throw new VgiClientError(
720
- `catalog_contents: SchemaContents.path ${JSON.stringify(c.path)} != SchemaInfo.path ${JSON.stringify(schema.path)}`,
721
- );
722
- }
723
- return {
724
- schema,
725
- tables: c.tables.map(decodeTableInfo),
726
- views: c.views.map(decodeViewInfo),
727
- scalar_functions: c.scalar_functions.map(decodeFunctionInfo),
728
- aggregate_functions: c.aggregate_functions.map(decodeFunctionInfo),
729
- table_functions: c.table_functions.map(decodeFunctionInfo),
730
- scalar_macros: c.scalar_macros.map(decodeMacroInfo),
731
- table_macros: c.table_macros.map(decodeMacroInfo),
732
- indexes: c.indexes.map(decodeIndexInfo),
733
- };
734
- });
725
+ const schemas = decodeCatalogStreams(response, ifNoneMatch);
735
726
  return {
736
727
  catalog_version: Number(response.catalog_version ?? 0),
737
728
  etag: response.etag ?? null,
@@ -906,7 +897,7 @@ export class VgiClient {
906
897
  }
907
898
  await this.rpc.call("catalog_create", {
908
899
  name,
909
- on_conflict: onConflict,
900
+ on_conflict: onConflictName(onConflict),
910
901
  options: wireOptions,
911
902
  });
912
903
  }
@@ -1013,7 +1004,7 @@ export class VgiClient {
1013
1004
  await this.rpc.call("catalog_schema_create", {
1014
1005
  attach_opaque_data: attachOpaqueData,
1015
1006
  path: normalizeSchemaPath(path),
1016
- on_conflict: opts?.onConflict ?? "error",
1007
+ on_conflict: onConflictName(opts?.onConflict ?? "error"),
1017
1008
  comment: opts?.comment ?? null,
1018
1009
  tags: tagsMap,
1019
1010
  transaction_opaque_data: opts?.transactionOpaqueData ?? null,
@@ -1139,7 +1130,7 @@ export class VgiClient {
1139
1130
  schema_path: normalizeSchemaPath(schemaPath),
1140
1131
  name,
1141
1132
  columns,
1142
- on_conflict: onConflict,
1133
+ on_conflict: onConflictName(onConflict),
1143
1134
  not_null_constraints: notNullConstraints ?? null,
1144
1135
  unique_constraints: uniqueConstraints ?? null,
1145
1136
  check_constraints: checkConstraints ?? null,
@@ -1430,7 +1421,7 @@ export class VgiClient {
1430
1421
  schema_path: normalizeSchemaPath(schemaPath),
1431
1422
  name,
1432
1423
  definition,
1433
- on_conflict: onConflict,
1424
+ on_conflict: onConflictName(onConflict),
1434
1425
  transaction_opaque_data: transactionOpaqueData ?? null,
1435
1426
  });
1436
1427
  }
@@ -1554,7 +1545,7 @@ export class VgiClient {
1554
1545
  macro_type: [macroType],
1555
1546
  parameters: [parameters],
1556
1547
  definition: [definition],
1557
- on_conflict: [onConflict],
1548
+ on_conflict: [onConflictName(onConflict)],
1558
1549
  parameter_default_values: [parameterDefaultValues ?? null],
1559
1550
  arguments_schema: [argumentsSchema ?? null],
1560
1551
  transaction_opaque_data: [transactionOpaqueData ?? null],
package/src/codec/asd.ts CHANGED
@@ -30,17 +30,24 @@ import {
30
30
  batchFromRows,
31
31
  serializeBatch,
32
32
  deserializeBatch,
33
+ deserializeSchema,
34
+ deserializeBatches,
35
+ serializeCollectionRows,
36
+ typeSignature,
33
37
  } from "../arrow/index.js";
38
+ import { conformRecord } from "./conform.js";
34
39
 
35
40
  /**
36
41
  * Encode a typed object as a single-row Arrow IPC stream using `schema`.
37
- * Matches Python's `ArrowSerializableDataclass.serialize_to_bytes()`.
42
+ * Matches Python's `ArrowSerializableDataclass.serialize_to_bytes()`, including
43
+ * its container rules: a non-nullable list/map left out or null is written as
44
+ * empty, and list items / map values are never null (see `conformRecord`).
38
45
  */
39
46
  export function encodeASD(
40
47
  schema: VgiSchema,
41
48
  obj: Record<string, any>,
42
49
  ): Uint8Array {
43
- return serializeBatch(batchFromRows([sortMapsForSchema(schema, obj)], schema));
50
+ return serializeBatch(batchFromRows([sortMapsForSchema(schema, conformRecord(schema, obj))], schema));
44
51
  }
45
52
 
46
53
  // --------------------------------------------------------------------------- //
@@ -210,7 +217,7 @@ function normalizeValue(raw: any, type: VgiDataType): any {
210
217
  }
211
218
 
212
219
  if (isDictionary(type)) {
213
- return raw == null ? null : String(raw);
220
+ return normalizeValue(raw, (type as any).dictionary as VgiDataType);
214
221
  }
215
222
 
216
223
  if (isBinary(type)) {
@@ -244,3 +251,38 @@ function toUint8Array(val: any): Uint8Array {
244
251
  }
245
252
  return new Uint8Array(0);
246
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
+ }