@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
@@ -1,31 +1,24 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // SPDX-License-Identifier: LicenseRef-QueryFarm-Source-Available-1.0
3
3
 
4
- // catalog_contents: the worker side of the protocol 2.1.0 bulk enumeration,
4
+ // catalog_contents: the worker side of the wire 2.2 bulk enumeration,
5
5
  // with etag revalidation and the frozen-catalog response cache. Mirrors
6
6
  // vgi-python's Worker.catalog_contents / _catalog_contents_response.
7
7
 
8
- import {
9
- encodeSchemaInfo,
10
- encodeTableInfo,
11
- encodeViewInfo,
12
- encodeMacroInfo,
13
- encodeIndexInfo,
14
- } from "../../../generated/vgi-client.js";
15
8
  import {
16
9
  buildCatalogContentsResponse,
17
- buildSchemaContents,
18
10
  type CatalogContentsResponse,
19
- type SchemaContents,
20
11
  } from "../../../generated/vgi-protocol-types.js";
12
+ import { ExternalRef, type CallContext } from "@query-farm/vgi-rpc";
13
+ import { CatalogSnapshotManager, type CatalogSnapshotPolicy } from "../../../catalog/publication.js";
21
14
  import { CatalogContentsResultSchema } from "../../../generated/vgi-protocol-schemas.js";
22
- import { encodeFunctionInfoOnce } from "../../../catalog/item-encoding.js";
15
+ import { encodeCatalogStreams, decodeCatalogStreams } from "../../../catalog/contents-codec.js";
23
16
  import type { AttachOpaqueData, CatalogInterface } from "../../../catalog/interface.js";
24
17
  import { catalogContentsDigest } from "../../../catalog/contents-digest.js";
25
- import { schemaPathKey } from "../../../schema-path.js";
26
18
  import { wrapResult } from "../shared.js";
27
19
 
28
20
  type Wire = { result: Uint8Array };
21
+ const schemaPathKey = (path: readonly string[]) => JSON.stringify(path.map((part) => part.toLowerCase()));
29
22
 
30
23
  /** One cached answer per catalog instance, valid for one catalog version. */
31
24
  interface ContentsSnapshot {
@@ -39,6 +32,8 @@ interface ContentsSnapshot {
39
32
  * (weak, so a dropped catalog takes its snapshot with it). Holds the build
40
33
  * promise, so concurrent first calls build once.
41
34
  */
35
+ const PUBLICATIONS = new WeakMap<CatalogSnapshotPolicy, CatalogSnapshotManager>();
36
+
42
37
  const CACHE = new WeakMap<CatalogInterface, Promise<ContentsSnapshot>>();
43
38
 
44
39
  /**
@@ -47,9 +42,8 @@ const CACHE = new WeakMap<CatalogInterface, Promise<ContentsSnapshot>>();
47
42
  * Enforces the revalidation rules: `not_modified` needs an etag equal to
48
43
  * `ifNoneMatch` and no schemas; a catalog with no etag never yields
49
44
  * `not_modified` (and so ignores `ifNoneMatch`). Validates the schema paths
50
- * (unique, parent present) and orders them parent-first. Every item is
51
- * encoded with the SAME encoder its per-schema RPC uses, so items are
52
- * byte-identical to catalog_schemas / catalog_schema_contents_* items.
45
+ * (unique, parent present) and orders them parent-first. The six collection
46
+ * streams retain the fields used by the existing per-schema RPC metadata.
53
47
  */
54
48
  export async function buildCatalogContents(
55
49
  cat: CatalogInterface,
@@ -83,31 +77,17 @@ export async function buildCatalogContents(
83
77
  }
84
78
  }
85
79
 
86
- // Same parent-before-child order catalog_schemas guarantees (stable sort).
87
- const schemas: SchemaContents[] = infos
88
- .sort((a, b) => a.schema.path.length - b.schema.path.length)
89
- .map((c) =>
90
- buildSchemaContents({
91
- path: [...c.schema.path],
92
- schema: encodeSchemaInfo(c.schema),
93
- tables: c.tables.map((t) => encodeTableInfo(t)),
94
- views: c.views.map((v) => encodeViewInfo(v)),
95
- scalar_functions: c.scalar_functions.map((f) => encodeFunctionInfoOnce(f)),
96
- aggregate_functions: c.aggregate_functions.map((f) => encodeFunctionInfoOnce(f)),
97
- table_functions: c.table_functions.map((f) => encodeFunctionInfoOnce(f)),
98
- scalar_macros: c.scalar_macros.map((m) => encodeMacroInfo(m)),
99
- table_macros: c.table_macros.map((m) => encodeMacroInfo(m)),
100
- indexes: c.indexes.map((i) => encodeIndexInfo(i)),
101
- }),
102
- );
80
+ const streams = encodeCatalogStreams(infos.sort((a, b) => a.schema.path.length - b.schema.path.length));
103
81
  let etag = etag0;
104
82
  if (etag === null && owner.catalogContentsEtag === "content-hash") {
105
- etag = await catalogContentsDigest(schemas);
83
+ etag = await catalogContentsDigest(streams, version);
106
84
  }
107
85
  if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) {
108
86
  return buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true });
109
87
  }
110
- return buildCatalogContentsResponse({ catalog_version: version, etag, schemas });
88
+ const response = buildCatalogContentsResponse({ catalog_version: version, etag, ...streams });
89
+ decodeCatalogStreams(response);
90
+ return response;
111
91
  }
112
92
 
113
93
  /**
@@ -123,9 +103,44 @@ export async function serveCatalogContents(
123
103
  cat: CatalogInterface,
124
104
  attach: AttachOpaqueData,
125
105
  ifNoneMatch: string | null,
126
- ): Promise<Wire> {
106
+ callContext?: CallContext,
107
+ sealedAttach: Uint8Array = attach,
108
+ ): Promise<Wire | ExternalRef> {
127
109
  const owner = cat.catalogContentsOwner(attach);
128
110
  const version = Number(await cat.version(attach));
111
+ const policy = owner.catalogSnapshotPolicy;
112
+ if (policy?.delivery === "published") {
113
+ const request = { catalog: cat, attachOpaqueData: attach, callContext, catalogVersion: version };
114
+ const inline = (etag: string) => wrapResult(buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true }), CatalogContentsResultSchema);
115
+ const cheapEtag = await policy.etag?.(request);
116
+ if (cheapEtag != null && cheapEtag === ifNoneMatch) return inline(cheapEtag);
117
+ let manager = PUBLICATIONS.get(policy);
118
+ if (!manager) { manager = new CatalogSnapshotManager(policy); PUBLICATIONS.set(policy, manager); }
119
+ const scopeBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", sealedAttach as BufferSource));
120
+ const attachmentScope = "attachment:" + Array.from(scopeBytes, (b) => b.toString(16).padStart(2, "0")).join("");
121
+ const identify = async (input: typeof request) => { const id = await policy.identity(input); return { ...id, visibilityScope: id.visibilityScope ?? attachmentScope }; };
122
+ const identity = await identify(request);
123
+ if (identity.catalogVersion !== version) throw new Error("snapshot identity version differs from the attached catalog");
124
+ const assertCurrentIdentity = async () => {
125
+ const currentVersion = Number(await cat.version(attach));
126
+ const current = await identify({ ...request, catalogVersion: currentVersion });
127
+ if (currentVersion !== version || await manager!.key(identity) !== await manager!.key(current)) throw new Error("catalog changed while resolving its publication");
128
+ };
129
+ const buildSnapshot = async (validator: string | null) => {
130
+ const response = await buildCatalogContents(cat, owner, attach, version, validator);
131
+ await assertCurrentIdentity();
132
+ return response;
133
+ };
134
+ try {
135
+ const manifest = await manager.warm(identity, () => buildSnapshot(null));
136
+ await assertCurrentIdentity();
137
+ if (manifest.etag === ifNoneMatch) return inline(manifest.etag);
138
+ return new ExternalRef(manifest.url, manifest.sha256);
139
+ } catch (error) {
140
+ if (policy.onPublicationFailure !== "ordinary") throw error;
141
+ return wrapResult(await buildSnapshot(ifNoneMatch), CatalogContentsResultSchema);
142
+ }
143
+ }
129
144
  if (owner.catalogContentsCacheable()) {
130
145
  let pending = CACHE.get(owner);
131
146
  let snapshot = pending ? await pending.catch(() => null) : null;
@@ -6,6 +6,7 @@ import type { OverloadContext } from "../../functions/registry.js";
6
6
  import { batchToScalarDict, deserializeBatch, serializeBatch, batchFromColumns } from "../../util/arrow/index.js";
7
7
  import { toUint8Array } from "../../util/bytes.js";
8
8
  import { normalizeSchemaPath } from "../../schema-path.js";
9
+ import { conformRecord } from "../../codec/conform.js";
9
10
 
10
11
  // The Python vgi-rpc framework wraps ALL non-void unary results in a single
11
12
  // "result" column. For ArrowSerializableDataclass types, the result is serialized
@@ -39,7 +40,8 @@ export function normalizeRequestSchemaPaths(params: Record<string, any>): void {
39
40
 
40
41
  /**
41
42
  * Wrap a dict of values into a single "result" Binary column.
42
- * Builds a 1-row batch from the values using the given schema,
43
+ * Builds a 1-row batch from the values using the given schema (conformed to
44
+ * the protocol's container rules, see `conformRecord`),
43
45
  * serializes it to IPC bytes, and returns { result: bytes }.
44
46
  */
45
47
  export function wrapResult(
@@ -47,8 +49,12 @@ export function wrapResult(
47
49
  innerSchema: VgiSchema | import("../../arrow/index.js").VgiSchema,
48
50
  ): { result: Uint8Array } {
49
51
  const a = innerSchema as VgiSchema;
52
+ // Python's container rules (a non-nullable list/map is never null, list
53
+ // items never are): `conformRecord` writes `[]` where a handler left a list
54
+ // out, and an unset list item as its zero value.
55
+ const row = conformRecord(a, values);
50
56
  const batch = batchFromColumns(
51
- Object.fromEntries(a.fields.map(f => [f.name, [values[f.name] ?? null]])),
57
+ Object.fromEntries(a.fields.map(f => [f.name, [row[f.name] ?? null]])),
52
58
  a,
53
59
  );
54
60
  return { result: serializeBatch(batch) };
@@ -72,7 +72,9 @@ export function serializeBindRequest(req: BindRequest): VgiBatch {
72
72
  return buildSingleRowBatch(BIND_REQUEST_SCHEMA, {
73
73
  function_name: req.function_name,
74
74
  arguments: serializeArguments(req.arguments),
75
- function_type: req.function_type,
75
+ // The wire carries the Python enum member NAME ("TABLE"), not the TS
76
+ // enum's value ("table"); each FunctionType value upper-cases to its name.
77
+ function_type: req.function_type == null ? req.function_type : String(req.function_type).toUpperCase(),
76
78
  input_schema: req.input_schema ? serializeSchema(req.input_schema) : null,
77
79
  settings: req.settings ? serializeBatch(req.settings) : null,
78
80
  secrets: req.secrets ? serializeBatch(req.secrets) : null,
@@ -8,6 +8,7 @@ import {
8
8
  batchFromColumns,
9
9
  } from "../../arrow/index.js";
10
10
  import { toUint8Array as toUint8ArrayBase } from "../../util/bytes.js";
11
+ import { conformRecord } from "../../codec/conform.js";
11
12
 
12
13
  /**
13
14
  * Coerce a wire value (string / Uint8Array / Buffer / etc.) to a Uint8Array.
@@ -25,7 +26,8 @@ export function toUint8Array(val: any): Uint8Array {
25
26
 
26
27
  /**
27
28
  * Build a single-row RecordBatch from a {fieldName: value} dict matching the
28
- * given schema. Auto-coerces JS numbers to BigInt for Int64 fields.
29
+ * given schema. Auto-coerces JS numbers to BigInt for Int64 fields, and
30
+ * applies the protocol's container rules (`conformRecord`).
29
31
  */
30
32
  export function buildSingleRowBatch(
31
33
  schema: VgiSchema,
@@ -35,8 +37,9 @@ export function buildSingleRowBatch(
35
37
  // declares one — vectorFromArray/columnFromArray rejects plain Number for
36
38
  // 64-bit ints under both backends.
37
39
  const cols: Record<string, any[]> = {};
40
+ const row = conformRecord(schema, values);
38
41
  for (const f of schema.fields) {
39
- let val = values[f.name];
42
+ let val = row[f.name];
40
43
  if (isInt(f.type) && (f.type as any).bitWidth === 64 && typeof val === "number") {
41
44
  val = BigInt(val);
42
45
  }
package/src/rpc-server.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  // 2. The worker's `hostedProtocols()`, in the order returned -- on EVERY
14
14
  // transport.
15
15
  // 3. `vgi_rpc.Reflection.v1` -- on every transport.
16
- // 4. `vgi_rpc.Identity.v1` -- HTTP only, and only when the worker supplies
16
+ // 4. `vgi_rpc.Identity.v2` -- HTTP only, and only when the worker supplies
17
17
  // `resolveToken` and/or `mintGrant` (or grant keys are configured).
18
18
  // 5. `vgi.attach_tickets.v1` -- HTTP only, and only when the signing key was
19
19
  // configured explicitly (never a generated one) *and* the worker can
@@ -44,7 +44,7 @@ export type ServerTransport = "pipe" | "unix" | "tcp" | "iroh" | "stream" | "htt
44
44
  const TRANSPORTS: ReadonlySet<string> = new Set<ServerTransport>(["pipe", "unix", "tcp", "iroh", "stream", "http"]);
45
45
 
46
46
  /** Transports that authenticate their callers, and so may host
47
- * `vgi_rpc.Identity.v1`. Identity answers questions about *other* callers'
47
+ * `vgi_rpc.Identity.v2`. Identity answers questions about *other* callers'
48
48
  * credentials; its allowlist is a list of principals, which a transport with
49
49
  * no caller identity cannot check. */
50
50
  const IDENTITY_TRANSPORTS: ReadonlySet<string> = new Set<ServerTransport>(["http"]);
@@ -78,14 +78,14 @@ export interface HostingOptions {
78
78
  *
79
79
  * Each needs a distinct wire name, which may not be `vgi.v2` and may not
80
80
  * use the reserved `vgi_rpc.` prefix: reflection is hosted automatically and
81
- * `vgi_rpc.Identity.v1` is enabled through {@link resolveToken} /
81
+ * `vgi_rpc.Identity.v2` is enabled through {@link resolveToken} /
82
82
  * {@link mintGrant}. Violations are a startup error naming this hook.
83
83
  */
84
84
  hostedProtocols?: () => Iterable<Protocol>;
85
85
 
86
86
  /**
87
87
  * Resolve an opaque bearer credential to the identity it authenticates as.
88
- * Supplying it hosts `vgi_rpc.Identity.v1`'s `introspect_token` -- on HTTP,
88
+ * Supplying it hosts `vgi_rpc.Identity.v2`'s `introspect_token` -- on HTTP,
89
89
  * the transport that authenticates callers. Absent, the method is absent
90
90
  * (not hosted-and-refusing), which keeps a dependency upgrade from growing a
91
91
  * credential-to-identity oracle on every existing worker.
@@ -232,7 +232,7 @@ function validatedHostedProtocols(hosting: HostingOptions, primary: Protocol): P
232
232
  throw new Error(
233
233
  `${owner} entry ${index} is named '${name}', which claims the reserved '${RESERVED_PREFIX}' prefix. ` +
234
234
  "Framework protocols are not supplied through this hook: reflection is hosted automatically, and " +
235
- "vgi_rpc.Identity.v1 is enabled by supplying resolveToken and/or mintGrant.",
235
+ "vgi_rpc.Identity.v2 is enabled by supplying resolveToken and/or mintGrant.",
236
236
  );
237
237
  }
238
238
  if (!/^[A-Za-z_][A-Za-z0-9_.]*$/.test(name)) {
@@ -259,7 +259,7 @@ function validatedHostedProtocols(hosting: HostingOptions, primary: Protocol): P
259
259
  return out;
260
260
  }
261
261
 
262
- /** Build the `vgi_rpc.Identity.v1` implementation, or `undefined`.
262
+ /** Build the `vgi_rpc.Identity.v2` implementation, or `undefined`.
263
263
  *
264
264
  * `undefined` unless the worker supplies at least one hook -- and that is the
265
265
  * point: the server then does not host the protocol at all, rather than
@@ -329,7 +329,7 @@ function resolveIntrospectPrincipals(
329
329
  }
330
330
  if (principals.length === 0) {
331
331
  throw new Error(
332
- "This worker supplies resolveToken, which hosts the vgi_rpc.Identity.v1 protocol, but no " +
332
+ "This worker supplies resolveToken, which hosts the vgi_rpc.Identity.v2 protocol, but no " +
333
333
  `introspector allowlist was configured. Set ${INTROSPECT_PRINCIPALS_ENV} (comma-separated) or pass ` +
334
334
  "introspectPrincipals.\n\n" +
335
335
  "There is no permissive default on purpose: introspection is a separate capability from " +