@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
@@ -1729,7 +1729,26 @@ function deserializeBatch(bytes) {
1729
1729
  }
1730
1730
  return batches[0];
1731
1731
  }
1732
+ function deserializeBatches(bytes) {
1733
+ return [...RecordBatchReader.from(bytes)];
1734
+ }
1735
+ function serializeBatches(batches, schema) {
1736
+ const writer = new RecordBatchStreamWriter;
1737
+ writer.reset(undefined, schema);
1738
+ for (const batch of batches)
1739
+ writer._writeRecordBatch(batch);
1740
+ writer.close();
1741
+ return writer.toUint8Array(true);
1742
+ }
1743
+ function serializeCollectionRows(schema, rows, maxBatchRows) {
1744
+ const batch = batchFromRows(rows, schema);
1745
+ const batches = [];
1746
+ for (let offset = 0;offset < batch.numRows; offset += maxBatchRows)
1747
+ batches.push(batch.slice(offset, offset + maxBatchRows));
1748
+ return serializeBatches(batches, schema);
1749
+ }
1732
1750
  var init_ipc = __esm(() => {
1751
+ init_build();
1733
1752
  init_empty();
1734
1753
  });
1735
1754
 
@@ -1883,6 +1902,7 @@ __export(exports_impl_arrowjs, {
1883
1902
  decodeDictValue: () => decodeDictValue,
1884
1903
  denseUnion: () => denseUnion,
1885
1904
  deserializeBatch: () => deserializeBatch,
1905
+ deserializeBatches: () => deserializeBatches,
1886
1906
  deserializeSchema: () => deserializeSchema,
1887
1907
  dictionary: () => dictionary,
1888
1908
  duration: () => duration,
@@ -1912,6 +1932,8 @@ __export(exports_impl_arrowjs, {
1912
1932
  safeNumber: () => safeNumber,
1913
1933
  schema: () => schema,
1914
1934
  serializeBatch: () => serializeBatch,
1935
+ serializeBatches: () => serializeBatches,
1936
+ serializeCollectionRows: () => serializeCollectionRows,
1915
1937
  serializeSchema: () => serializeSchema,
1916
1938
  sparseUnion: () => sparseUnion,
1917
1939
  struct: () => struct,
@@ -4186,7 +4208,9 @@ function mapPairs(raw) {
4186
4208
  return Object.entries(raw);
4187
4209
  }
4188
4210
  function zeroValue(type) {
4189
- if (isUtf8(type) || isDictionary(type))
4211
+ if (isDictionary(type))
4212
+ return zeroValue(type.dictionary);
4213
+ if (isUtf8(type))
4190
4214
  return "";
4191
4215
  if (isBinary(type))
4192
4216
  return new Uint8Array(0);
@@ -4652,7 +4676,8 @@ var EXCHANGE_STATE_SCHEMA = schema2([
4652
4676
  field2("opaque_data", binary2(), true),
4653
4677
  field2("is_producer", bool2(), false),
4654
4678
  field2("user_state", binary2(), true),
4655
- field2("filter_history", binary2(), true)
4679
+ field2("filter_history", binary2(), true),
4680
+ field2("more_pending", bool2(), false)
4656
4681
  ]);
4657
4682
  var TEXT_ENCODER = new TextEncoder;
4658
4683
  var TEXT_DECODER = new TextDecoder;
@@ -4661,6 +4686,7 @@ var FLAG_PRODUCER = 1;
4661
4686
  var FLAG_OPAQUE_DATA = 2;
4662
4687
  var FLAG_USER_STATE = 4;
4663
4688
  var FLAG_FILTER_HISTORY = 8;
4689
+ var FLAG_MORE_PENDING = 16;
4664
4690
  var LIST_CHILD_NAME = "item";
4665
4691
  var emptyListElementType = () => utf82();
4666
4692
  function inferElementType(values) {
@@ -4766,7 +4792,7 @@ var arrowStateSerializer = {
4766
4792
  const opaqueData = state.opaqueData != null ? toUint8Array(state.opaqueData) : null;
4767
4793
  const userState = serializeUserState(state.userState);
4768
4794
  const filterHistory = encodeFilterHistory(state.filterHistory);
4769
- const flags = (state.isProducer ? FLAG_PRODUCER : 0) | (opaqueData ? FLAG_OPAQUE_DATA : 0) | (userState ? FLAG_USER_STATE : 0) | (filterHistory ? FLAG_FILTER_HISTORY : 0);
4795
+ const flags = (state.isProducer ? FLAG_PRODUCER : 0) | (opaqueData ? FLAG_OPAQUE_DATA : 0) | (userState ? FLAG_USER_STATE : 0) | (filterHistory ? FLAG_FILTER_HISTORY : 0) | (state.morePending ? FLAG_MORE_PENDING : 0);
4770
4796
  const chunks = [functionName, initRequest, executionId];
4771
4797
  if (opaqueData)
4772
4798
  chunks.push(opaqueData);
@@ -4827,7 +4853,8 @@ var arrowStateSerializer = {
4827
4853
  isProducer,
4828
4854
  __isProducer: isProducer,
4829
4855
  userState: deserializeUserState(userStateBytes),
4830
- filterHistory: decodeFilterHistory(filterHistoryBytes)
4856
+ filterHistory: decodeFilterHistory(filterHistoryBytes),
4857
+ morePending: (flags & FLAG_MORE_PENDING) !== 0
4831
4858
  };
4832
4859
  }
4833
4860
  };
@@ -4839,7 +4866,7 @@ import {
4839
4866
  Protocol
4840
4867
  } from "@query-farm/vgi-rpc";
4841
4868
  var VGI_PROTOCOL_NAME = "vgi.v2";
4842
- var VGI_PROTOCOL_VERSION = "2.1.0";
4869
+ var VGI_PROTOCOL_VERSION = "2.2.0";
4843
4870
  function exchangeStream(callbacks) {
4844
4871
  return { kind: "exchange", ...callbacks };
4845
4872
  }
@@ -6090,6 +6117,87 @@ function createVgiProtocol(service) {
6090
6117
  // src/protocol/handlers/function.ts
6091
6118
  init_arrow();
6092
6119
 
6120
+ // src/functions/continuation.ts
6121
+ var STATUS_KEY = "vgi.status";
6122
+ var HAVE_MORE_OUTPUT = "HAVE_MORE_OUTPUT";
6123
+ var CONTINUE = "CONTINUE";
6124
+ var CACHE_KEY_PREFIX = "vgi.cache.";
6125
+ function moreOutputMetadata(more, extra) {
6126
+ const md = new Map(extra ?? []);
6127
+ if (more)
6128
+ md.set(STATUS_KEY, HAVE_MORE_OUTPUT);
6129
+ return md;
6130
+ }
6131
+ function replyMetadata(out) {
6132
+ const idx = out.dataBatchIdx;
6133
+ if (idx == null)
6134
+ return null;
6135
+ const emitted = out.batches[idx];
6136
+ const md = new Map(emitted.batch.metadata ?? []);
6137
+ for (const [k, v] of emitted.metadata ?? [])
6138
+ md.set(k, v);
6139
+ return md;
6140
+ }
6141
+ function refuseMoreOutput(name, out) {
6142
+ if (replyMetadata(out)?.get(STATUS_KEY) === HAVE_MORE_OUTPUT) {
6143
+ throw new Error(`${name}: HAVE_MORE_OUTPUT (moreOutputMetadata) is only valid in a table-in-out ` + `function's process() or resume()`);
6144
+ }
6145
+ }
6146
+ async function continuationTurn(name, eState, input, out, resumable, run) {
6147
+ const inputStatus = input?.metadata?.get(STATUS_KEY) ?? out.inputMetadata?.get(STATUS_KEY);
6148
+ const tick = inputStatus === CONTINUE;
6149
+ if (tick && !eState.morePending) {
6150
+ throw new Error(`${name}: continuation tick received, but no output is pending`);
6151
+ }
6152
+ if (tick && input.numRows !== 0) {
6153
+ throw new Error(`${name}: a continuation tick must have no rows, got ${input.numRows}`);
6154
+ }
6155
+ if (!tick && eState.morePending) {
6156
+ throw new Error(`${name}: input received while output is pending; expected a continuation tick`);
6157
+ }
6158
+ await run(tick);
6159
+ const md = replyMetadata(out);
6160
+ if (md == null) {
6161
+ throw new Error(tick ? `${name}: resume() must emit a batch for every continuation tick` : `${name}: process() must emit a batch for every input batch (No data batch was emitted)`);
6162
+ }
6163
+ const more = md.get(STATUS_KEY) === HAVE_MORE_OUTPUT;
6164
+ if (more && !resumable) {
6165
+ throw new Error(`${name}: emitted HAVE_MORE_OUTPUT but does not implement resume()`);
6166
+ }
6167
+ if (tick) {
6168
+ for (const key of md.keys()) {
6169
+ if (key.startsWith(CACHE_KEY_PREFIX)) {
6170
+ throw new Error(`${name}: cache control is only valid on an input's first reply, ` + `not on one answering a continuation tick (${key})`);
6171
+ }
6172
+ }
6173
+ }
6174
+ eState.morePending = more;
6175
+ }
6176
+ function checkResumeContract(name, config) {
6177
+ if (config.resume == null)
6178
+ return;
6179
+ if (typeof config.resume !== "function") {
6180
+ throw new Error(`${name}: resume must be a function`);
6181
+ }
6182
+ if (config.maxWorkers === 1) {
6183
+ throw new Error(`${name}: resume() (continued output) is not supported with maxWorkers: 1; ` + `the client runs such a function on one shared connection.`);
6184
+ }
6185
+ if (config.initialState == null) {
6186
+ throw new Error(`${name}: resume() continues from its state alone, so the function must ` + `declare an initialState holding where to resume.`);
6187
+ }
6188
+ }
6189
+ function checkInputRowsPerCall(name, value, blended) {
6190
+ if (value == null)
6191
+ return;
6192
+ if (!blended) {
6193
+ throw new Error(`${name}: inputRowsPerCall applies only to a blended row-transform function, ` + `whose per-row input the client can split into calls`);
6194
+ }
6195
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) {
6196
+ throw new Error(`${name}: inputRowsPerCall must be a positive integer, got ${String(value)}`);
6197
+ }
6198
+ return value;
6199
+ }
6200
+
6093
6201
  // src/util/statistics.ts
6094
6202
  init_arrow();
6095
6203
  function serializeColumnStatistics(stats, _cacheMaxAgeSeconds) {
@@ -6098,6 +6206,7 @@ function serializeColumnStatistics(stats, _cacheMaxAgeSeconds) {
6098
6206
 
6099
6207
  // src/generated/vgi-protocol-schemas.ts
6100
6208
  init_arrow();
6209
+ var VGI_CATALOG_CONTRACT_HASH = "0aa39285365f5f4326ce85c4d41d2705ea992dee41cf98d07640a2767b6ac3fb";
6101
6210
  var CatalogInfoSchema = schema2([
6102
6211
  field2("name", utf82(), false),
6103
6212
  field2("implementation_version", utf82(), true),
@@ -6109,7 +6218,6 @@ var CatalogInfoSchema = schema2([
6109
6218
  var SchemaInfoSchema = schema2([
6110
6219
  field2("comment", utf82(), true),
6111
6220
  field2("tags", map2(field2("key", utf82(), false), field2("value", utf82(), true), false), false),
6112
- field2("attach_opaque_data", binary2(), false),
6113
6221
  field2("path", list2(field2("item", utf82(), true)), false),
6114
6222
  field2("estimated_object_count", map2(field2("key", utf82(), false), field2("value", int642(), true), false), true)
6115
6223
  ]);
@@ -6150,9 +6258,9 @@ var FunctionInfoSchema = schema2([
6150
6258
  field2("name", utf82(), false),
6151
6259
  field2("schema_path", list2(field2("item", utf82(), true)), false),
6152
6260
  field2("function_type", dictionary2(utf82(), int162()), false),
6153
- field2("arguments", binary2(), false),
6154
- field2("output_schema", binary2(), false),
6155
- field2("parameter_default_values", binary2(), true),
6261
+ field2("arguments", dictionary2(binary2(), int322()), false),
6262
+ field2("output_schema", dictionary2(binary2(), int322()), false),
6263
+ field2("parameter_default_values", dictionary2(binary2(), int322()), true),
6156
6264
  field2("stability", dictionary2(utf82(), int162()), true),
6157
6265
  field2("null_handling", dictionary2(utf82(), int162()), true),
6158
6266
  field2("argument_monotonicity", list2(field2("item", utf82(), true)), true),
@@ -6184,6 +6292,7 @@ var FunctionInfoSchema = schema2([
6184
6292
  field2("sink_order_dependent", bool2(), false),
6185
6293
  field2("requires_input_batch_index", bool2(), false),
6186
6294
  field2("input_from_args", bool2(), false),
6295
+ field2("input_rows_per_call", int642(), true),
6187
6296
  field2("required_settings", list2(field2("item", utf82(), true)), false),
6188
6297
  field2("required_secrets", list2(field2("item", struct2([field2("secret_type", utf82(), false), field2("scope", utf82(), true), field2("secret_name", utf82(), true)]), true)), false)
6189
6298
  ]);
@@ -6613,7 +6722,12 @@ var CatalogContentsResultSchema = schema2([
6613
6722
  field2("catalog_version", int642(), false),
6614
6723
  field2("etag", utf82(), true),
6615
6724
  field2("not_modified", bool2(), false),
6616
- field2("schemas", list2(field2("item", struct2([field2("path", list2(field2("item", utf82(), true)), false), field2("schema", binary2(), false), field2("tables", list2(field2("item", binary2(), true)), false), field2("views", list2(field2("item", binary2(), true)), false), field2("scalar_functions", list2(field2("item", binary2(), true)), false), field2("aggregate_functions", list2(field2("item", binary2(), true)), false), field2("table_functions", list2(field2("item", binary2(), true)), false), field2("scalar_macros", list2(field2("item", binary2(), true)), false), field2("table_macros", list2(field2("item", binary2(), true)), false), field2("indexes", list2(field2("item", binary2(), true)), false)]), true)), false)
6725
+ field2("schemas", binary2(), true),
6726
+ field2("tables", binary2(), true),
6727
+ field2("views", binary2(), true),
6728
+ field2("functions", binary2(), true),
6729
+ field2("macros", binary2(), true),
6730
+ field2("indexes", binary2(), true)
6617
6731
  ]);
6618
6732
  var CatalogCopyFromFormatsResultSchema = schema2([
6619
6733
  field2("items", list2(field2("item", binary2(), true)), false)
@@ -8377,6 +8491,9 @@ function functionHandlers(config) {
8377
8491
  if (state.userState != null && handlerState?.state !== undefined) {
8378
8492
  handlerState.state = state.userState;
8379
8493
  }
8494
+ if (handlers.continuesOutput) {
8495
+ handlerState.morePending = state.morePending === true;
8496
+ }
8380
8497
  }
8381
8498
  if (state.isProducer && handlers.producerFn) {
8382
8499
  out.finish = () => {
@@ -8389,10 +8506,14 @@ function functionHandlers(config) {
8389
8506
  } else if (handlers.exchangeFn) {
8390
8507
  await handlers.exchangeFn(handlerState, input, out);
8391
8508
  }
8509
+ if (!handlers.continuesOutput) {
8510
+ refuseMoreOutput(state.functionName, out);
8511
+ }
8392
8512
  if (handlerState?.state !== undefined) {
8393
8513
  state.userState = handlerState.state;
8394
8514
  }
8395
8515
  state.filterHistory = handlerState?.filterHistory ?? null;
8516
+ state.morePending = handlerState?.morePending === true;
8396
8517
  },
8397
8518
  headerInit: (params, state, ctx) => {
8398
8519
  if (!state._initResponse) {
@@ -9094,6 +9215,41 @@ init_arrow();
9094
9215
  init_storage();
9095
9216
  // src/filter-pushdown/collector.ts
9096
9217
  init_arrow();
9218
+
9219
+ // src/util/parent-rows.ts
9220
+ var PARENT_ROW_METADATA_KEY = "vgi_rpc.parent_row#b64";
9221
+ function encodeParentRows(parentRows) {
9222
+ const raw = new Uint8Array(parentRows.length * 4);
9223
+ const dv = new DataView(raw.buffer);
9224
+ for (let i = 0;i < parentRows.length; i++) {
9225
+ dv.setInt32(i * 4, parentRows[i], true);
9226
+ }
9227
+ if (typeof globalThis.Buffer !== "undefined") {
9228
+ return globalThis.Buffer.from(raw).toString("base64");
9229
+ }
9230
+ let bin = "";
9231
+ for (let i = 0;i < raw.length; i++)
9232
+ bin += String.fromCharCode(raw[i]);
9233
+ return globalThis.btoa(bin);
9234
+ }
9235
+ function decodeParentRows(encoded) {
9236
+ let raw;
9237
+ if (typeof globalThis.Buffer !== "undefined") {
9238
+ raw = new Uint8Array(globalThis.Buffer.from(encoded, "base64"));
9239
+ } else {
9240
+ const bin = globalThis.atob(encoded);
9241
+ raw = new Uint8Array(bin.length);
9242
+ for (let i = 0;i < bin.length; i++)
9243
+ raw[i] = bin.charCodeAt(i);
9244
+ }
9245
+ const dv = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
9246
+ const out = new Int32Array(raw.byteLength >> 2);
9247
+ for (let i = 0;i < out.length; i++)
9248
+ out[i] = dv.getInt32(i * 4, true);
9249
+ return out;
9250
+ }
9251
+
9252
+ // src/filter-pushdown/collector.ts
9097
9253
  class FilteringOutputCollector {
9098
9254
  inner;
9099
9255
  filters;
@@ -9114,6 +9270,22 @@ class FilteringOutputCollector {
9114
9270
  } else {
9115
9271
  batch = batchFromColumns(batchOrColumns, this.inner.outputSchema);
9116
9272
  }
9273
+ const encoded = metadata?.get(PARENT_ROW_METADATA_KEY);
9274
+ if (encoded !== undefined && batch.numRows > 0 && this.filters.filters.length > 0) {
9275
+ const mask = this.filters.evaluate(batch);
9276
+ const parents = decodeParentRows(encoded);
9277
+ const kept = [];
9278
+ for (let i = 0;i < parents.length; i++)
9279
+ if (mask[i])
9280
+ kept.push(parents[i]);
9281
+ const md = new Map(metadata);
9282
+ if (kept.length > 0)
9283
+ md.set(PARENT_ROW_METADATA_KEY, encodeParentRows(kept));
9284
+ else
9285
+ md.delete(PARENT_ROW_METADATA_KEY);
9286
+ this.inner.emit(filterBatch(batch, mask), md);
9287
+ return;
9288
+ }
9117
9289
  const filtered = this.filters.apply(batch);
9118
9290
  this.inner.emit(filtered, metadata);
9119
9291
  }
@@ -9351,6 +9523,109 @@ function sortMapsForSchema(schema, obj) {
9351
9523
  }
9352
9524
  return out ?? obj;
9353
9525
  }
9526
+ function normalizeValue(raw, type) {
9527
+ if (raw == null)
9528
+ return null;
9529
+ if (isList(type)) {
9530
+ const childType = type.children[0].type;
9531
+ const out = [];
9532
+ for (const item of raw)
9533
+ out.push(normalizeValue(item, childType));
9534
+ return out;
9535
+ }
9536
+ if (isMap(type)) {
9537
+ const entries = type.children[0].type;
9538
+ const valueType = entries.children[1].type;
9539
+ const out = {};
9540
+ const put = (k, v) => {
9541
+ out[String(k)] = normalizeValue(v, valueType);
9542
+ };
9543
+ if (raw[Symbol.iterator]) {
9544
+ for (const entry of raw) {
9545
+ if (Array.isArray(entry)) {
9546
+ put(entry[0], entry[1]);
9547
+ } else if (entry && typeof entry === "object") {
9548
+ put(entry.key ?? entry[0], entry.value ?? entry[1]);
9549
+ }
9550
+ }
9551
+ } else if (typeof raw === "object") {
9552
+ for (const [k, v] of Object.entries(raw))
9553
+ put(k, v);
9554
+ }
9555
+ return out;
9556
+ }
9557
+ if (isStruct(type)) {
9558
+ const childFields = type.children;
9559
+ const out = {};
9560
+ for (const cf of childFields) {
9561
+ out[cf.name] = normalizeValue(raw[cf.name], cf.type);
9562
+ }
9563
+ return out;
9564
+ }
9565
+ if (isDictionary(type)) {
9566
+ return normalizeValue(raw, type.dictionary);
9567
+ }
9568
+ if (isBinary(type)) {
9569
+ return toUint8Array3(raw);
9570
+ }
9571
+ if (isInt(type) && type.bitWidth === 64) {
9572
+ if (typeof raw === "bigint") {
9573
+ if (raw >= BigInt(Number.MIN_SAFE_INTEGER) && raw <= BigInt(Number.MAX_SAFE_INTEGER)) {
9574
+ return Number(raw);
9575
+ }
9576
+ return raw;
9577
+ }
9578
+ return raw;
9579
+ }
9580
+ if (isBool(type)) {
9581
+ return Boolean(raw);
9582
+ }
9583
+ return raw;
9584
+ }
9585
+ function toUint8Array3(val) {
9586
+ if (val instanceof Uint8Array)
9587
+ return val;
9588
+ if (val instanceof ArrayBuffer)
9589
+ return new Uint8Array(val);
9590
+ if (val && val.buffer instanceof ArrayBuffer) {
9591
+ return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
9592
+ }
9593
+ return new Uint8Array(0);
9594
+ }
9595
+ function encodeASDCollection(schema, records) {
9596
+ if (records.length === 0)
9597
+ return null;
9598
+ return serializeCollectionRows(schema, records.map((record) => sortMapsForSchema(schema, conformRecord(schema, record))), 1024);
9599
+ }
9600
+ function decodeASDCollection(schema, bytes) {
9601
+ if (bytes == null)
9602
+ return [];
9603
+ const output = [];
9604
+ const batches = deserializeBatches(bytes);
9605
+ const validateSchema = (actualSchema) => {
9606
+ if (actualSchema.fields.length !== schema.fields.length || schema.fields.some((field, i) => {
9607
+ const actual = actualSchema.fields[i];
9608
+ return actual.name !== field.name || actual.nullable !== field.nullable || typeSignature(actual.type) !== typeSignature(field.type);
9609
+ }))
9610
+ throw new Error("catalog collection has an incompatible metadata schema");
9611
+ };
9612
+ if (batches.length === 0)
9613
+ validateSchema(deserializeSchema(bytes));
9614
+ for (const batch of batches) {
9615
+ validateSchema(batch.schema);
9616
+ for (let row = 0;row < batch.numRows; row++) {
9617
+ const item = {};
9618
+ for (const field of schema.fields) {
9619
+ const value = batch.getChild(field.name)?.get(row);
9620
+ if (value == null && !field.nullable)
9621
+ throw new Error(`catalog collection has null ${field.name}`);
9622
+ item[field.name] = normalizeValue(value, field.type);
9623
+ }
9624
+ output.push(item);
9625
+ }
9626
+ }
9627
+ return output;
9628
+ }
9354
9629
 
9355
9630
  // src/generated/vgi-client.ts
9356
9631
  var encodeCatalogInfo = (v) => encodeASD(CatalogInfoSchema, v);
@@ -9384,68 +9659,111 @@ function buildCatalogAttachResult(init) {
9384
9659
  supports_catalog_contents: init.supports_catalog_contents ?? false
9385
9660
  };
9386
9661
  }
9387
- function buildSchemaContents(init) {
9388
- return {
9389
- path: init.path,
9390
- schema: init.schema,
9391
- tables: init.tables ?? [],
9392
- views: init.views ?? [],
9393
- scalar_functions: init.scalar_functions ?? [],
9394
- aggregate_functions: init.aggregate_functions ?? [],
9395
- table_functions: init.table_functions ?? [],
9396
- scalar_macros: init.scalar_macros ?? [],
9397
- table_macros: init.table_macros ?? [],
9398
- indexes: init.indexes ?? []
9399
- };
9400
- }
9401
9662
  function buildCatalogContentsResponse(init) {
9402
9663
  return {
9403
9664
  catalog_version: init.catalog_version,
9404
9665
  etag: init.etag ?? null,
9405
9666
  not_modified: init.not_modified ?? false,
9406
- schemas: init.schemas ?? []
9667
+ schemas: init.schemas ?? null,
9668
+ tables: init.tables ?? null,
9669
+ views: init.views ?? null,
9670
+ functions: init.functions ?? null,
9671
+ macros: init.macros ?? null,
9672
+ indexes: init.indexes ?? null
9407
9673
  };
9408
9674
  }
9409
9675
 
9410
- // src/catalog/item-encoding.ts
9411
- var ENCODED = new WeakMap;
9412
- function freezeCatalogItem(item) {
9413
- deepFreeze(item);
9414
- return item;
9415
- }
9416
- function deepFreeze(value) {
9417
- if (value === null || typeof value !== "object" || Object.isFrozen(value) || ArrayBuffer.isView(value))
9418
- return;
9419
- const proto = Object.getPrototypeOf(value);
9420
- if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)
9421
- return;
9422
- for (const child of Object.values(value))
9423
- deepFreeze(child);
9424
- Object.freeze(value);
9676
+ // src/protocol/handlers/catalog/contents.ts
9677
+ import { ExternalRef as ExternalRef2 } from "@query-farm/vgi-rpc";
9678
+
9679
+ // src/catalog/publication.ts
9680
+ init_arrow();
9681
+ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@query-farm/vgi-rpc";
9682
+
9683
+ // src/catalog/contents-codec.ts
9684
+ var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
9685
+ var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
9686
+ function encodeCatalogStreams(inventory) {
9687
+ const streams = {
9688
+ schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
9689
+ tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
9690
+ views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
9691
+ functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
9692
+ macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
9693
+ indexes: encodeASDCollection(IndexInfoSchema, inventory.flatMap((s) => s.indexes))
9694
+ };
9695
+ return streams;
9425
9696
  }
9426
- function encodeFunctionInfoOnce(info) {
9427
- if (!Object.isFrozen(info))
9428
- return encodeFunctionInfo(info);
9429
- let encoded = ENCODED.get(info);
9430
- if (encoded === undefined) {
9431
- encoded = encodeFunctionInfo(info);
9432
- ENCODED.set(info, encoded);
9697
+ function decodeCatalogStreams(response, ifNoneMatch) {
9698
+ if (response.not_modified) {
9699
+ if (response.etag == null || ifNoneMatch !== undefined && response.etag !== ifNoneMatch || CATALOG_STREAM_KINDS.some((kind) => response[kind] != null)) {
9700
+ throw new Error("invalid catalog_contents not_modified response");
9701
+ }
9702
+ return [];
9433
9703
  }
9434
- return encoded;
9704
+ const infos = decodeASDCollection(SchemaInfoSchema, response.schemas);
9705
+ const schemas = [];
9706
+ const index = new Map;
9707
+ for (const schema of infos) {
9708
+ if (!Array.isArray(schema.path) || schema.path.length === 0)
9709
+ throw new Error("catalog schema has an empty path");
9710
+ const key = schemaPathKey2(schema.path);
9711
+ if (index.has(key))
9712
+ throw new Error("catalog contains duplicate schema paths");
9713
+ if (schema.path.length > 1 && !index.has(schemaPathKey2(schema.path.slice(0, -1)))) {
9714
+ throw new Error("catalog schema is missing its preceding parent");
9715
+ }
9716
+ const entry = { schema, tables: [], views: [], scalar_functions: [], aggregate_functions: [], table_functions: [], scalar_macros: [], table_macros: [], indexes: [] };
9717
+ index.set(key, entry);
9718
+ schemas.push(entry);
9719
+ }
9720
+ const owner = (item) => {
9721
+ const entry = index.get(schemaPathKey2(item.schema_path));
9722
+ if (!entry)
9723
+ throw new Error("catalog object references an absent schema");
9724
+ return entry;
9725
+ };
9726
+ for (const item of decodeASDCollection(TableInfoSchema, response.tables))
9727
+ owner(item).tables.push(item);
9728
+ for (const item of decodeASDCollection(ViewInfoSchema, response.views))
9729
+ owner(item).views.push(item);
9730
+ for (const item of decodeASDCollection(FunctionInfoSchema, response.functions)) {
9731
+ const entry = owner(item);
9732
+ switch (String(item.function_type).toUpperCase()) {
9733
+ case "SCALAR":
9734
+ entry.scalar_functions.push(item);
9735
+ break;
9736
+ case "AGGREGATE":
9737
+ entry.aggregate_functions.push(item);
9738
+ break;
9739
+ case "TABLE":
9740
+ case "TABLE_BUFFERING":
9741
+ entry.table_functions.push(item);
9742
+ break;
9743
+ default:
9744
+ throw new Error(`unknown catalog function type ${item.function_type}`);
9745
+ }
9746
+ }
9747
+ for (const item of decodeASDCollection(MacroInfoSchema, response.macros)) {
9748
+ const entry = owner(item);
9749
+ switch (String(item.macro_type).toUpperCase()) {
9750
+ case "SCALAR":
9751
+ entry.scalar_macros.push(item);
9752
+ break;
9753
+ case "TABLE":
9754
+ entry.table_macros.push(item);
9755
+ break;
9756
+ default:
9757
+ throw new Error(`unknown catalog macro type ${item.macro_type}`);
9758
+ }
9759
+ }
9760
+ for (const item of decodeASDCollection(IndexInfoSchema, response.indexes))
9761
+ owner(item).indexes.push(item);
9762
+ return schemas;
9435
9763
  }
9436
9764
 
9437
9765
  // src/catalog/contents-digest.ts
9438
- var KINDS = [
9439
- "tables",
9440
- "views",
9441
- "scalar_functions",
9442
- "aggregate_functions",
9443
- "table_functions",
9444
- "scalar_macros",
9445
- "table_macros",
9446
- "indexes"
9447
- ];
9448
- async function catalogContentsDigest(schemas) {
9766
+ async function catalogContentsDigest(streams, version = 0) {
9449
9767
  const utf8 = new TextEncoder;
9450
9768
  const parts = [];
9451
9769
  let total = 0;
@@ -9465,12 +9783,23 @@ async function catalogContentsDigest(schemas) {
9465
9783
  for (const v of values)
9466
9784
  chunk(v);
9467
9785
  };
9468
- count(schemas.length);
9469
- for (const entry of schemas) {
9470
- chunks(entry.path.map((p) => utf8.encode(p)));
9471
- chunk(entry.schema);
9472
- for (const kind of KINDS)
9473
- chunks(entry[kind]);
9786
+ if (Array.isArray(streams)) {
9787
+ count(streams.length);
9788
+ for (const entry of streams) {
9789
+ chunks(entry.path.map((p) => utf8.encode(p)));
9790
+ chunk(entry.schema);
9791
+ for (const kind of ["tables", "views", "scalar_functions", "aggregate_functions", "table_functions", "scalar_macros", "table_macros", "indexes"])
9792
+ chunks(entry[kind]);
9793
+ }
9794
+ } else {
9795
+ chunk(utf8.encode("vgi.catalog-contents.2.2"));
9796
+ count(version);
9797
+ for (const kind of CATALOG_STREAM_KINDS) {
9798
+ const value = streams[kind];
9799
+ count(value == null ? 0 : 1);
9800
+ if (value != null)
9801
+ chunk(value);
9802
+ }
9474
9803
  }
9475
9804
  const buf = new Uint8Array(total);
9476
9805
  let off = 0;
@@ -9485,7 +9814,297 @@ async function catalogContentsDigest(schemas) {
9485
9814
  return hex;
9486
9815
  }
9487
9816
 
9817
+ // src/catalog/publication-envelope.ts
9818
+ function validateCatalogPublicationEnvelope(bytes) {
9819
+ try {
9820
+ const stream = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9821
+ let position = 0, messages = 0;
9822
+ while (position < bytes.length) {
9823
+ let length = stream.getInt32(position, true);
9824
+ position += 4;
9825
+ if (length === -1) {
9826
+ length = stream.getInt32(position, true);
9827
+ position += 4;
9828
+ }
9829
+ if (length === 0) {
9830
+ if (position !== bytes.length)
9831
+ throw new Error("trailing data");
9832
+ break;
9833
+ }
9834
+ if (length < 4 || length > bytes.length - position)
9835
+ throw new Error("invalid message length");
9836
+ const head = new DataView(bytes.buffer, bytes.byteOffset + position, length);
9837
+ const tableField = (table, field) => {
9838
+ const vtable = table - head.getInt32(table, true);
9839
+ const vlength = head.getUint16(vtable, true);
9840
+ if (vlength < 4 || vlength % 2 || vtable + vlength > length)
9841
+ throw new Error("invalid vtable");
9842
+ if (4 + 2 * field >= vlength)
9843
+ return null;
9844
+ const offset = head.getUint16(vtable + 4 + 2 * field, true);
9845
+ return offset === 0 ? null : table + offset;
9846
+ };
9847
+ const follow = (pointer) => pointer + head.getUint32(pointer, true);
9848
+ const root = head.getUint32(0, true);
9849
+ const typePosition = tableField(root, 1);
9850
+ const type = typePosition == null ? 0 : head.getUint8(typePosition);
9851
+ if (type !== (messages === 0 ? 1 : messages === 1 ? 3 : -1))
9852
+ throw new Error("expected one schema and one record batch");
9853
+ if (type === 3) {
9854
+ const header = tableField(root, 2);
9855
+ if (header == null)
9856
+ throw new Error("missing record header");
9857
+ const rows = tableField(follow(header), 0);
9858
+ if (rows == null || head.getBigInt64(rows, true) !== 1n)
9859
+ throw new Error("expected one response row");
9860
+ }
9861
+ const metadata = tableField(root, 4);
9862
+ if (metadata != null) {
9863
+ const vector = follow(metadata), count = head.getUint32(vector, true);
9864
+ if (count > length / 4)
9865
+ throw new Error("invalid metadata vector");
9866
+ for (let i = 0;i < count; i++) {
9867
+ const keyPointer = tableField(follow(vector + 4 + 4 * i), 0);
9868
+ if (keyPointer == null)
9869
+ continue;
9870
+ const keyStart = follow(keyPointer), keyLength = head.getUint32(keyStart, true);
9871
+ if (keyStart + 4 + keyLength > length)
9872
+ throw new Error("invalid metadata key");
9873
+ const key = new TextDecoder().decode(new Uint8Array(head.buffer, head.byteOffset + keyStart + 4, keyLength));
9874
+ if (key === "vgi_rpc.location" || key === "vgi_rpc.log_level")
9875
+ throw new Error("pointer/log metadata is not a catalog result");
9876
+ }
9877
+ }
9878
+ const bodyPosition = tableField(root, 3);
9879
+ const bodyLength = bodyPosition == null ? 0 : Number(head.getBigInt64(bodyPosition, true));
9880
+ position += length;
9881
+ if (!Number.isSafeInteger(bodyLength) || bodyLength < 0 || bodyLength > bytes.length - position)
9882
+ throw new Error("invalid body length");
9883
+ position += bodyLength;
9884
+ messages++;
9885
+ }
9886
+ if (messages !== 2)
9887
+ throw new Error("missing response batch");
9888
+ } catch (error) {
9889
+ throw new Error(`invalid published RPC envelope: ${error instanceof Error ? error.message : String(error)}`);
9890
+ }
9891
+ }
9892
+
9893
+ // src/catalog/publication.ts
9894
+ var OUTER_SCHEMA = schema2([field2("result", binary2(), false)]);
9895
+ var DEFAULT_MAX = 64 * 1024 * 1024;
9896
+ var utf83 = new TextEncoder;
9897
+ var equalBytes3 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
9898
+ async function digest(value) {
9899
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", utf83.encode(value)));
9900
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
9901
+ }
9902
+ function assertRenewedPublication(before, after) {
9903
+ const unchanged = (m) => 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]);
9904
+ if (unchanged(before) !== unchanged(after))
9905
+ throw new Error("renewal changed immutable catalog identity");
9906
+ }
9907
+ var manifestSame = (a, b) => a.manifestId === b.manifestId;
9908
+ class CatalogSnapshotManager {
9909
+ policy;
9910
+ cached = new Map;
9911
+ pending = new Map;
9912
+ constructor(policy) {
9913
+ this.policy = policy;
9914
+ for (const value of [policy.maxRawBytes, policy.maxStoredBytes, policy.maxCachedManifests]) {
9915
+ if (value != null && (!Number.isSafeInteger(value) || value <= 0))
9916
+ throw new Error("catalog publication limits must be positive safe integers");
9917
+ }
9918
+ if (policy.referenceGraceMs != null && (!Number.isSafeInteger(policy.referenceGraceMs) || policy.referenceGraceMs < 0))
9919
+ throw new Error("catalog publication reference grace must be a nonnegative safe integer");
9920
+ }
9921
+ usable(m) {
9922
+ const deadline = Date.now() + (this.policy.referenceGraceMs ?? 60000);
9923
+ return (m.stable || m.expiresAt != null) && (m.expiresAt == null || m.expiresAt > deadline) && (m.retainUntil == null || m.retainUntil > deadline);
9924
+ }
9925
+ async key(identity) {
9926
+ for (const value of [identity.catalogNamespace, identity.sourceRevision, identity.visibilityScope])
9927
+ if (!value)
9928
+ throw new Error("published catalogs require explicit namespace, revision and visibility scope");
9929
+ if (!Number.isSafeInteger(identity.catalogVersion))
9930
+ throw new Error("catalog version is not a safe integer");
9931
+ return digest(JSON.stringify([
9932
+ VGI_PROTOCOL_NAME,
9933
+ VGI_PROTOCOL_VERSION,
9934
+ VGI_CATALOG_CONTRACT_HASH,
9935
+ 1,
9936
+ identity.catalogNamespace,
9937
+ identity.sourceRevision,
9938
+ identity.visibilityScope,
9939
+ identity.catalogVersion,
9940
+ this.policy.repository.profile,
9941
+ this.policy.compression ?? "identity"
9942
+ ]));
9943
+ }
9944
+ remember(m) {
9945
+ this.cached.delete(m.key);
9946
+ this.cached.set(m.key, Object.freeze({ ...m }));
9947
+ while (this.cached.size > (this.policy.maxCachedManifests ?? 128))
9948
+ this.cached.delete(this.cached.keys().next().value);
9949
+ }
9950
+ async invalidate(key) {
9951
+ await this.pending.get(key)?.catch(() => {
9952
+ return;
9953
+ });
9954
+ const m = this.cached.get(key) ?? await this.policy.repository.lookup(key);
9955
+ this.cached.delete(key);
9956
+ if (m)
9957
+ await this.policy.repository.invalidate(key, m);
9958
+ }
9959
+ async validate(m, key, identity, expected) {
9960
+ if (m.formatVersion !== 1 || typeof m.manifestId !== "string" || !m.manifestId || m.key !== key || m.protocolName !== VGI_PROTOCOL_NAME || m.protocolVersion !== VGI_PROTOCOL_VERSION || m.contractHash !== VGI_CATALOG_CONTRACT_HASH || m.codecRevision !== 1 || m.catalogVersion !== identity.catalogVersion || m.validated !== true || typeof m.stable !== "boolean" || 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 || m.rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX) || m.storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX) || !this.usable(m))
9961
+ throw new Error("invalid or expired catalog publication manifest");
9962
+ const ref = new ExternalRef(m.url, m.sha256);
9963
+ const configuredFetch = this.policy.repository.resolver.fetch ?? fetch;
9964
+ const resolved = await resolveExternalLocation(ref.pointerBatch(OUTER_SCHEMA), {
9965
+ ...this.policy.repository.resolver,
9966
+ fetch: (input, init) => configuredFetch(input, { ...init, signal: AbortSignal.any([...init?.signal ? [init.signal] : [], AbortSignal.timeout(30000)]) }),
9967
+ maxFetchBytes: Math.min(this.policy.maxStoredBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxFetchBytes ?? Infinity),
9968
+ maxDecompressedBytes: Math.min(this.policy.maxRawBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxDecompressedBytes ?? Infinity),
9969
+ validateFetchedIpc: (bytes) => {
9970
+ this.policy.repository.resolver.validateFetchedIpc?.(bytes);
9971
+ if (bytes.length !== m.rawSize)
9972
+ throw new Error("catalog publication raw size mismatch");
9973
+ validateCatalogPublicationEnvelope(bytes);
9974
+ }
9975
+ });
9976
+ if (resolved.numRows !== 1 || resolved.schema.fields.length !== 1 || resolved.schema.fields[0].name !== "result" || typeSignature(resolved.schema.fields[0].type) !== typeSignature(binary2()) || resolved.schema.fields[0].nullable)
9977
+ throw new Error("invalid published RPC envelope");
9978
+ const bytes = resolved.getChild("result")?.get(0);
9979
+ if (!(bytes instanceof Uint8Array))
9980
+ throw new Error("published catalog has no result bytes");
9981
+ const decoded = decodeASDCollection(CatalogContentsResultSchema, bytes);
9982
+ if (decoded.length !== 1)
9983
+ throw new Error("published catalog must contain exactly one response row");
9984
+ const response = decoded[0];
9985
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion || response.etag !== m.etag)
9986
+ throw new Error("published catalog version or ETag mismatch");
9987
+ decodeCatalogStreams(response);
9988
+ if (expected)
9989
+ for (const kind of CATALOG_STREAM_KINDS) {
9990
+ const a = response[kind], b = expected[kind];
9991
+ if (a == null !== (b == null) || a != null && b != null && !equalBytes3(a, b))
9992
+ throw new Error("publication readback changed catalog metadata");
9993
+ }
9994
+ }
9995
+ async import(manifest, identity) {
9996
+ const key = await this.key(identity);
9997
+ await this.validate(manifest, key, identity);
9998
+ const winner = await this.policy.repository.commitIfAbsent(manifest);
9999
+ if (!manifestSame(manifest, winner))
10000
+ await this.validate(winner, key, identity);
10001
+ this.remember(winner);
10002
+ return winner;
10003
+ }
10004
+ async warm(identity, build) {
10005
+ const key = await this.key(identity);
10006
+ const cached = this.cached.get(key);
10007
+ if (cached && this.usable(cached))
10008
+ return cached;
10009
+ const active = this.pending.get(key);
10010
+ if (active)
10011
+ return active;
10012
+ const pending = this.recoverOrPublish(key, identity, build);
10013
+ this.pending.set(key, pending);
10014
+ try {
10015
+ const m = await pending;
10016
+ this.remember(m);
10017
+ return m;
10018
+ } finally {
10019
+ if (this.pending.get(key) === pending)
10020
+ this.pending.delete(key);
10021
+ }
10022
+ }
10023
+ async recoverOrPublish(key, identity, build) {
10024
+ const repository = this.policy.repository;
10025
+ let existing = await repository.lookup(key);
10026
+ if (existing) {
10027
+ try {
10028
+ if (!this.usable(existing) && repository.renew) {
10029
+ const renewed = await repository.renew(existing);
10030
+ if (renewed) {
10031
+ assertRenewedPublication(existing, renewed);
10032
+ existing = renewed;
10033
+ }
10034
+ }
10035
+ await this.validate(existing, key, identity);
10036
+ return existing;
10037
+ } catch {
10038
+ await repository.invalidate(key, existing);
10039
+ }
10040
+ }
10041
+ const response = await build();
10042
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion)
10043
+ throw new Error("publication requires a full snapshot of the requested version");
10044
+ decodeCatalogStreams(response);
10045
+ response.etag ??= await catalogContentsDigest(response, identity.catalogVersion);
10046
+ const payload = encodeASD(CatalogContentsResultSchema, response);
10047
+ let rawSize = 0, storedSize = 0;
10048
+ const bounded = { upload: async (data, encoding) => {
10049
+ if (encoding)
10050
+ throw new Error("catalog publication uploader requires identity encoding");
10051
+ rawSize = data.byteLength;
10052
+ if (rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX))
10053
+ throw new Error("catalog publication exceeds byte limit");
10054
+ let body = data;
10055
+ const compression = this.policy.compression ?? "identity";
10056
+ if (compression !== "identity" && compression !== "gzip" && compression !== "zstd")
10057
+ throw new Error("catalog publication compression must be identity, gzip or zstd");
10058
+ if (compression === "gzip") {
10059
+ body = new Uint8Array(await new Response(new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer());
10060
+ } else if (compression === "zstd") {
10061
+ const runtime = globalThis.Bun;
10062
+ if (typeof runtime?.zstdCompress === "function") {
10063
+ body = new Uint8Array(await runtime.zstdCompress(data));
10064
+ } else if (typeof process !== "undefined" && process.versions?.node) {
10065
+ const nodeZlib = "node:zlib";
10066
+ const zlib = await import(nodeZlib);
10067
+ if (typeof zlib.zstdCompressSync !== "function")
10068
+ throw new Error("zstd catalog publication requires Node >=22.15, Bun, or an encoder-capable runtime");
10069
+ body = new Uint8Array(zlib.zstdCompressSync(data));
10070
+ } else {
10071
+ throw new Error("zstd catalog publication requires an encoder-capable runtime; use gzip or identity here");
10072
+ }
10073
+ }
10074
+ storedSize = body.byteLength;
10075
+ if (storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX))
10076
+ throw new Error("catalog publication exceeds byte limit");
10077
+ return repository.storage.upload(body, compression === "identity" ? "" : compression);
10078
+ } };
10079
+ const ref = await publishExternalResult(OUTER_SCHEMA, { result: payload }, bounded, { includeSha256: true });
10080
+ const m = {
10081
+ formatVersion: 1,
10082
+ manifestId: crypto.randomUUID(),
10083
+ key,
10084
+ protocolName: VGI_PROTOCOL_NAME,
10085
+ protocolVersion: VGI_PROTOCOL_VERSION,
10086
+ contractHash: VGI_CATALOG_CONTRACT_HASH,
10087
+ codecRevision: 1,
10088
+ catalogVersion: identity.catalogVersion,
10089
+ etag: response.etag,
10090
+ sha256: ref.sha256,
10091
+ rawSize,
10092
+ storedSize,
10093
+ url: ref.url,
10094
+ validated: true,
10095
+ ...await repository.describe(ref.url)
10096
+ };
10097
+ await this.validate(m, key, identity, response);
10098
+ const winner = await repository.commitIfAbsent(m);
10099
+ if (!manifestSame(m, winner))
10100
+ await this.validate(winner, key, identity);
10101
+ return winner;
10102
+ }
10103
+ }
10104
+
9488
10105
  // src/protocol/handlers/catalog/contents.ts
10106
+ var schemaPathKey3 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
10107
+ var PUBLICATIONS = new WeakMap;
9489
10108
  var CACHE = new WeakMap;
9490
10109
  async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
9491
10110
  const result = await cat.catalogContents(attach, ifNoneMatch);
@@ -9500,39 +10119,74 @@ async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
9500
10119
  return buildCatalogContentsResponse({ catalog_version: version, etag: etag0, not_modified: true });
9501
10120
  }
9502
10121
  const infos = [...result.schemas ?? []];
9503
- const keys = infos.map((c) => schemaPathKey(c.schema.path));
10122
+ const keys = infos.map((c) => schemaPathKey3(c.schema.path));
9504
10123
  const keySet = new Set(keys);
9505
10124
  if (keySet.size !== keys.length)
9506
10125
  throw new Error("catalog_contents returned duplicate schema paths");
9507
10126
  for (const c of infos) {
9508
- if (c.schema.path.length > 1 && !keySet.has(schemaPathKey(c.schema.path.slice(0, -1)))) {
10127
+ if (c.schema.path.length > 1 && !keySet.has(schemaPathKey3(c.schema.path.slice(0, -1)))) {
9509
10128
  throw new Error(`catalog_contents returned schema path ${JSON.stringify(c.schema.path)} without its parent`);
9510
10129
  }
9511
10130
  }
9512
- const schemas = infos.sort((a, b) => a.schema.path.length - b.schema.path.length).map((c) => buildSchemaContents({
9513
- path: [...c.schema.path],
9514
- schema: encodeSchemaInfo(c.schema),
9515
- tables: c.tables.map((t) => encodeTableInfo(t)),
9516
- views: c.views.map((v) => encodeViewInfo(v)),
9517
- scalar_functions: c.scalar_functions.map((f) => encodeFunctionInfoOnce(f)),
9518
- aggregate_functions: c.aggregate_functions.map((f) => encodeFunctionInfoOnce(f)),
9519
- table_functions: c.table_functions.map((f) => encodeFunctionInfoOnce(f)),
9520
- scalar_macros: c.scalar_macros.map((m) => encodeMacroInfo(m)),
9521
- table_macros: c.table_macros.map((m) => encodeMacroInfo(m)),
9522
- indexes: c.indexes.map((i) => encodeIndexInfo(i))
9523
- }));
10131
+ const streams = encodeCatalogStreams(infos.sort((a, b) => a.schema.path.length - b.schema.path.length));
9524
10132
  let etag = etag0;
9525
10133
  if (etag === null && owner.catalogContentsEtag === "content-hash") {
9526
- etag = await catalogContentsDigest(schemas);
10134
+ etag = await catalogContentsDigest(streams, version);
9527
10135
  }
9528
10136
  if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) {
9529
10137
  return buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true });
9530
10138
  }
9531
- return buildCatalogContentsResponse({ catalog_version: version, etag, schemas });
10139
+ const response = buildCatalogContentsResponse({ catalog_version: version, etag, ...streams });
10140
+ decodeCatalogStreams(response);
10141
+ return response;
9532
10142
  }
9533
- async function serveCatalogContents(cat, attach, ifNoneMatch) {
10143
+ async function serveCatalogContents(cat, attach, ifNoneMatch, callContext, sealedAttach = attach) {
9534
10144
  const owner = cat.catalogContentsOwner(attach);
9535
10145
  const version = Number(await cat.version(attach));
10146
+ const policy = owner.catalogSnapshotPolicy;
10147
+ if (policy?.delivery === "published") {
10148
+ const request = { catalog: cat, attachOpaqueData: attach, callContext, catalogVersion: version };
10149
+ const inline = (etag) => wrapResult(buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true }), CatalogContentsResultSchema);
10150
+ const cheapEtag = await policy.etag?.(request);
10151
+ if (cheapEtag != null && cheapEtag === ifNoneMatch)
10152
+ return inline(cheapEtag);
10153
+ let manager = PUBLICATIONS.get(policy);
10154
+ if (!manager) {
10155
+ manager = new CatalogSnapshotManager(policy);
10156
+ PUBLICATIONS.set(policy, manager);
10157
+ }
10158
+ const scopeBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", sealedAttach));
10159
+ const attachmentScope = "attachment:" + Array.from(scopeBytes, (b) => b.toString(16).padStart(2, "0")).join("");
10160
+ const identify = async (input) => {
10161
+ const id = await policy.identity(input);
10162
+ return { ...id, visibilityScope: id.visibilityScope ?? attachmentScope };
10163
+ };
10164
+ const identity = await identify(request);
10165
+ if (identity.catalogVersion !== version)
10166
+ throw new Error("snapshot identity version differs from the attached catalog");
10167
+ const assertCurrentIdentity = async () => {
10168
+ const currentVersion = Number(await cat.version(attach));
10169
+ const current = await identify({ ...request, catalogVersion: currentVersion });
10170
+ if (currentVersion !== version || await manager.key(identity) !== await manager.key(current))
10171
+ throw new Error("catalog changed while resolving its publication");
10172
+ };
10173
+ const buildSnapshot = async (validator) => {
10174
+ const response = await buildCatalogContents(cat, owner, attach, version, validator);
10175
+ await assertCurrentIdentity();
10176
+ return response;
10177
+ };
10178
+ try {
10179
+ const manifest = await manager.warm(identity, () => buildSnapshot(null));
10180
+ await assertCurrentIdentity();
10181
+ if (manifest.etag === ifNoneMatch)
10182
+ return inline(manifest.etag);
10183
+ return new ExternalRef2(manifest.url, manifest.sha256);
10184
+ } catch (error) {
10185
+ if (policy.onPublicationFailure !== "ordinary")
10186
+ throw error;
10187
+ return wrapResult(await buildSnapshot(ifNoneMatch), CatalogContentsResultSchema);
10188
+ }
10189
+ }
9536
10190
  if (owner.catalogContentsCacheable()) {
9537
10191
  let pending = CACHE.get(owner);
9538
10192
  let snapshot = pending ? await pending.catch(() => null) : null;
@@ -9561,6 +10215,33 @@ async function serveCatalogContents(cat, attach, ifNoneMatch) {
9561
10215
  }
9562
10216
  return wrapResult(await buildCatalogContents(cat, owner, attach, version, ifNoneMatch), CatalogContentsResultSchema);
9563
10217
  }
10218
+
10219
+ // src/catalog/item-encoding.ts
10220
+ var ENCODED = new WeakMap;
10221
+ function freezeCatalogItem(item) {
10222
+ deepFreeze(item);
10223
+ return item;
10224
+ }
10225
+ function deepFreeze(value) {
10226
+ if (value === null || typeof value !== "object" || Object.isFrozen(value) || ArrayBuffer.isView(value))
10227
+ return;
10228
+ const proto = Object.getPrototypeOf(value);
10229
+ if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)
10230
+ return;
10231
+ for (const child of Object.values(value))
10232
+ deepFreeze(child);
10233
+ Object.freeze(value);
10234
+ }
10235
+ function encodeFunctionInfoOnce(info) {
10236
+ if (!Object.isFrozen(info))
10237
+ return encodeFunctionInfo(info);
10238
+ let encoded = ENCODED.get(info);
10239
+ if (encoded === undefined) {
10240
+ encoded = encodeFunctionInfo(info);
10241
+ ENCODED.set(info, encoded);
10242
+ }
10243
+ return encoded;
10244
+ }
9564
10245
  // src/catalog/interface.ts
9565
10246
  var encodeCopyFromFormatInfo = (v) => encodeASD(CopyFromFormatInfoSchema, {
9566
10247
  comment: v.comment ?? null,
@@ -9621,6 +10302,7 @@ function isPromise(v) {
9621
10302
  }
9622
10303
 
9623
10304
  class CatalogInterface {
10305
+ catalogSnapshotPolicy = null;
9624
10306
  catalogContentsEtag = null;
9625
10307
  catalogContentsAttachIndependent = false;
9626
10308
  catalogVersionFrozen = false;
@@ -10394,10 +11076,13 @@ function catalogAdminHandlers(getCatalog, signingKey) {
10394
11076
  items: schemas.map((s) => encodeSchemaInfo(s))
10395
11077
  }, CatalogSchemasResultSchema);
10396
11078
  });
10397
- const catalogContents = catalogHandler(signingKey, async (params) => {
10398
- const ifNoneMatch = params.if_none_match == null ? null : String(params.if_none_match);
10399
- return serveCatalogContents(getCatalog(), toUint8Array(params.attach_opaque_data), ifNoneMatch);
10400
- });
11079
+ const catalogContents = async (params, ctx) => {
11080
+ const sealedAttach = toUint8Array(params.attach_opaque_data).slice();
11081
+ return catalogHandler(signingKey, async (opened, context) => {
11082
+ const ifNoneMatch = opened.if_none_match == null ? null : String(opened.if_none_match);
11083
+ return serveCatalogContents(getCatalog(), toUint8Array(opened.attach_opaque_data), ifNoneMatch, context, sealedAttach);
11084
+ })(params, ctx);
11085
+ };
10401
11086
  const catalogCopyFromFormats = catalogHandler(signingKey, async (params) => {
10402
11087
  const cat = getCatalog();
10403
11088
  const formats = await cat.copyFromFormats(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -11519,6 +12204,8 @@ init_storage();
11519
12204
  var STREAMING_FINALIZE_KEY = new Uint8Array(0);
11520
12205
  function defineTableInOutFunction(config) {
11521
12206
  assertArrowTypes(config.args, `defineTableInOutFunction("${config.name}"): args`);
12207
+ checkResumeContract(config.name, config);
12208
+ checkInputRowsPerCall(config.name, config.inputRowsPerCall, false);
11522
12209
  const specs = [];
11523
12210
  let posIdx = 0;
11524
12211
  if (config.args) {
@@ -11700,20 +12387,27 @@ function defineTableInOutFunction(config) {
11700
12387
  return {
11701
12388
  outputSchema,
11702
12389
  inputSchema: request.bind_call.input_schema,
11703
- exchangeInit: () => ({ state, processParams, filterHistory: carriedFilterHistory }),
12390
+ continuesOutput: true,
12391
+ exchangeInit: () => ({ state, processParams, filterHistory: carriedFilterHistory, morePending: false }),
11704
12392
  exchangeFn: async (eState, input, out) => {
11705
- applyRevalidationValidators(eState.processParams, input);
11706
- applyDynamicFilterUpdate(eState, input);
11707
- let wrappedOut = makeMetadataBakingCollector(out);
11708
- if (projIds) {
11709
- wrappedOut = makeSchemaReconcilingCollector(wrappedOut, outputSchema);
11710
- }
11711
- const currentFilters = eState.processParams.pushdownFilters;
11712
- if (config.autoApplyFilters && currentFilters) {
11713
- wrappedOut = new FilteringOutputCollector(wrappedOut, currentFilters);
11714
- }
11715
- await processFn(eState.processParams, eState.state, input, wrappedOut);
11716
- if (eState.state != null) {
12393
+ await continuationTurn(config.name, eState, input, out, config.resume != null, async (tick) => {
12394
+ applyRevalidationValidators(eState.processParams, input);
12395
+ applyDynamicFilterUpdate(eState, input);
12396
+ let wrappedOut = makeMetadataBakingCollector(out);
12397
+ if (projIds) {
12398
+ wrappedOut = makeSchemaReconcilingCollector(wrappedOut, outputSchema);
12399
+ }
12400
+ const currentFilters = eState.processParams.pushdownFilters;
12401
+ if (config.autoApplyFilters && currentFilters) {
12402
+ wrappedOut = new FilteringOutputCollector(wrappedOut, currentFilters);
12403
+ }
12404
+ if (tick) {
12405
+ await config.resume(eState.processParams, eState.state, wrappedOut);
12406
+ } else {
12407
+ await processFn(eState.processParams, eState.state, input, wrappedOut);
12408
+ }
12409
+ });
12410
+ if (config.finalize && eState.state != null) {
11717
12411
  const serialized = serializeUserState(eState.state);
11718
12412
  if (serialized != null) {
11719
12413
  await boundStorage.put(serialized);
@@ -11791,7 +12485,6 @@ function makeSchemaReconcilingCollector(inner, targetSchema) {
11791
12485
  }
11792
12486
  });
11793
12487
  }
11794
- var PARENT_ROW_METADATA_KEY = "vgi_rpc.parent_row#b64";
11795
12488
  function parentRowsMetadata(parentRows, outputRows, extra) {
11796
12489
  if (parentRows.length !== outputRows) {
11797
12490
  throw new Error(`parentRowsMetadata: length ${parentRows.length} != output rows ${outputRows}; ` + `parentRows must carry exactly one input-row index per emitted output row`);
@@ -11800,28 +12493,16 @@ function parentRowsMetadata(parentRows, outputRows, extra) {
11800
12493
  if (outputRows === 0) {
11801
12494
  return md;
11802
12495
  }
11803
- const raw = new Uint8Array(parentRows.length * 4);
11804
- const dv = new DataView(raw.buffer);
11805
- for (let i = 0;i < parentRows.length; i++) {
11806
- dv.setInt32(i * 4, parentRows[i], true);
11807
- }
11808
- md.set(PARENT_ROW_METADATA_KEY, base64Encode(raw));
12496
+ md.set(PARENT_ROW_METADATA_KEY, encodeParentRows(parentRows));
11809
12497
  return md;
11810
12498
  }
11811
- function base64Encode(bytes) {
11812
- if (typeof globalThis.Buffer !== "undefined") {
11813
- return globalThis.Buffer.from(bytes).toString("base64");
11814
- }
11815
- let bin = "";
11816
- for (let i = 0;i < bytes.length; i++)
11817
- bin += String.fromCharCode(bytes[i]);
11818
- return globalThis.btoa(bin);
11819
- }
11820
12499
  function defineRowTransformFunction(config) {
11821
12500
  const numPositional = Object.keys(config.args ?? {}).length + (config.varargs ? 1 : 0);
11822
12501
  if (numPositional === 0) {
11823
12502
  throw new Error(`${config.name}: a blended row-transform function needs at least one ` + `positional arg (its per-row input column); found none.`);
11824
12503
  }
12504
+ checkResumeContract(config.name, config);
12505
+ const inputRowsPerCall = checkInputRowsPerCall(config.name, config.inputRowsPerCall, true);
11825
12506
  const specs = [];
11826
12507
  let posIdx = 0;
11827
12508
  if (config.args) {
@@ -11875,7 +12556,8 @@ function defineRowTransformFunction(config) {
11875
12556
  requiredSettings: config.requiredSettings,
11876
12557
  requiredSecrets: config.requiredSecrets,
11877
12558
  hasFinalize: false,
11878
- inputFromArgs: true
12559
+ inputFromArgs: true,
12560
+ inputRowsPerCall
11879
12561
  };
11880
12562
  function extractArgs(request) {
11881
12563
  const args = {};
@@ -11960,22 +12642,30 @@ function defineRowTransformFunction(config) {
11960
12642
  if (request.bind_call.input_schema == null) {
11961
12643
  throw new Error(`${config.name}: is a table-in-out function (its positional args are ` + `per-row input columns) but no input schema was supplied -- call it ` + `via table_in_out_function(input=...), not table_function().`);
11962
12644
  }
12645
+ const state = config.initialState ? config.initialState(processParams) : null;
11963
12646
  return {
11964
12647
  outputSchema,
11965
12648
  inputSchema: request.bind_call.input_schema,
11966
- exchangeInit: () => ({ state: null, processParams, filterHistory: carriedFilterHistory }),
12649
+ continuesOutput: true,
12650
+ exchangeInit: () => ({ state, processParams, filterHistory: carriedFilterHistory, morePending: false }),
11967
12651
  exchangeFn: async (eState, input, out) => {
11968
- applyRevalidationValidators(eState.processParams, input);
11969
- applyDynamicFilterUpdate(eState, input);
11970
- let wrappedOut = makeMetadataBakingCollector(out);
11971
- if (projIds) {
11972
- wrappedOut = makeSchemaReconcilingCollector(wrappedOut, outputSchema);
11973
- }
11974
- const currentFilters = eState.processParams.pushdownFilters;
11975
- if (config.autoApplyFilters && currentFilters) {
11976
- wrappedOut = new FilteringOutputCollector(wrappedOut, currentFilters);
11977
- }
11978
- await config.process(eState.processParams, input, wrappedOut);
12652
+ await continuationTurn(config.name, eState, input, out, config.resume != null, async (tick) => {
12653
+ applyRevalidationValidators(eState.processParams, input);
12654
+ applyDynamicFilterUpdate(eState, input);
12655
+ let wrappedOut = makeMetadataBakingCollector(out);
12656
+ if (projIds) {
12657
+ wrappedOut = makeSchemaReconcilingCollector(wrappedOut, outputSchema);
12658
+ }
12659
+ const currentFilters = eState.processParams.pushdownFilters;
12660
+ if (config.autoApplyFilters && currentFilters) {
12661
+ wrappedOut = new FilteringOutputCollector(wrappedOut, currentFilters);
12662
+ }
12663
+ if (tick) {
12664
+ await config.resume(eState.processParams, eState.state, wrappedOut);
12665
+ } else {
12666
+ await config.process(eState.processParams, input, wrappedOut, eState.state);
12667
+ }
12668
+ });
11979
12669
  }
11980
12670
  };
11981
12671
  }
@@ -12221,7 +12911,6 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
12221
12911
  }
12222
12912
  schemas(attachOpaqueData, transactionOpaqueData) {
12223
12913
  return this._descriptor.schemas.map((s) => ({
12224
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
12225
12914
  path: schemaDescriptorPath(s),
12226
12915
  comment: s.comment ?? null,
12227
12916
  tags: s.tags ?? {},
@@ -12253,7 +12942,6 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
12253
12942
  if (!desc)
12254
12943
  return null;
12255
12944
  return {
12256
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
12257
12945
  path: schemaDescriptorPath(desc),
12258
12946
  comment: desc.comment ?? null,
12259
12947
  tags: desc.tags ?? {},
@@ -12491,6 +13179,7 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
12491
13179
  sink_order_dependent: f.kind === "table_buffering" && f.meta.sinkOrderDependent === true,
12492
13180
  requires_input_batch_index: f.kind === "table_buffering" && f.meta.requiresInputBatchIndex === true,
12493
13181
  input_from_args: f.kind === "table_in_out" && f.meta.inputFromArgs === true,
13182
+ input_rows_per_call: f.kind === "table_in_out" && f.meta.inputFromArgs === true ? f.meta.inputRowsPerCall ?? null : null,
12494
13183
  required_settings: meta.requiredSettings,
12495
13184
  required_secrets: requiredSecrets.map((s) => ({
12496
13185
  secret_type: s.secret_type,
@@ -13421,6 +14110,7 @@ export {
13421
14110
  iterRows,
13422
14111
  list2 as list,
13423
14112
  map2 as map,
14113
+ moreOutputMetadata,
13424
14114
  nullType2 as nullType,
13425
14115
  parentRowsMetadata,
13426
14116
  projectBatch,
@@ -13448,4 +14138,4 @@ export {
13448
14138
  utf82 as utf8
13449
14139
  };
13450
14140
 
13451
- //# debugId=FC599621AC5B851964756E2164756E21
14141
+ //# debugId=DF2D9EC97DFECF8764756E2164756E21