@query-farm/vgi 0.48.4 → 0.49.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 (60) hide show
  1. package/README.md +52 -1
  2. package/dist/attach-secret-keyfile.d.ts +11 -0
  3. package/dist/attach-secret-options.d.ts +96 -0
  4. package/dist/catalog/attach-option.d.ts +6 -0
  5. package/dist/catalog/composite.d.ts +2 -0
  6. package/dist/catalog/descriptors.d.ts +11 -0
  7. package/dist/catalog/interface.d.ts +54 -2
  8. package/dist/catalog/scan-planning.d.ts +76 -0
  9. package/dist/client-entry.js +32 -4
  10. package/dist/client-entry.js.map +9 -8
  11. package/dist/generated/vgi-client.d.ts +1 -0
  12. package/dist/generated/vgi-protocol-schemas.d.ts +1 -1
  13. package/dist/generated/vgi-service.d.ts +5 -1
  14. package/dist/index.core.d.ts +3 -0
  15. package/dist/index.js +3245 -2538
  16. package/dist/index.js.map +32 -29
  17. package/dist/protocol/dispatch.d.ts +13 -2
  18. package/dist/protocol/handlers/catalog/admin.d.ts +1 -1
  19. package/dist/protocol/handlers/catalog/index.d.ts +1 -1
  20. package/dist/protocol/handlers/catalog/index_methods.d.ts +1 -1
  21. package/dist/protocol/handlers/catalog/macro.d.ts +1 -1
  22. package/dist/protocol/handlers/catalog/shared.d.ts +28 -3
  23. package/dist/protocol/handlers/catalog/table.d.ts +1 -1
  24. package/dist/protocol/handlers/catalog/view.d.ts +1 -1
  25. package/dist/protocol/handlers/function.d.ts +2 -0
  26. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  27. package/dist/serve-entry.d.ts +5 -0
  28. package/dist/serve-entry.js +2026 -101
  29. package/dist/serve-entry.js.map +27 -20
  30. package/dist/worker-cf-entry.d.ts +2 -2
  31. package/dist/worker-cf-entry.js +823 -103
  32. package/dist/worker-cf-entry.js.map +27 -24
  33. package/dist/worker.d.ts +10 -0
  34. package/package.json +1 -1
  35. package/src/attach-secret-keyfile.ts +185 -0
  36. package/src/attach-secret-options.ts +418 -0
  37. package/src/catalog/attach-option.ts +6 -0
  38. package/src/catalog/column-metadata.ts +7 -0
  39. package/src/catalog/composite.ts +5 -0
  40. package/src/catalog/descriptors.ts +11 -0
  41. package/src/catalog/interface.ts +97 -2
  42. package/src/catalog/read-only.ts +14 -1
  43. package/src/catalog/scan-planning.ts +314 -0
  44. package/src/generated/vgi-client.ts +2 -1
  45. package/src/generated/vgi-protocol-schemas.ts +6 -2
  46. package/src/generated/vgi-service.ts +7 -2
  47. package/src/index.core.ts +21 -0
  48. package/src/protocol/dispatch.ts +16 -4
  49. package/src/protocol/handlers/catalog/admin.ts +33 -18
  50. package/src/protocol/handlers/catalog/index.ts +6 -5
  51. package/src/protocol/handlers/catalog/index_methods.ts +5 -3
  52. package/src/protocol/handlers/catalog/macro.ts +7 -5
  53. package/src/protocol/handlers/catalog/shared.ts +52 -6
  54. package/src/protocol/handlers/catalog/table.ts +43 -30
  55. package/src/protocol/handlers/catalog/view.ts +9 -7
  56. package/src/protocol/handlers/function.ts +11 -5
  57. package/src/protocol/handlers/table-buffering.ts +2 -1
  58. package/src/serve-entry.ts +6 -1
  59. package/src/worker-cf-entry.ts +9 -0
  60. package/src/worker.ts +12 -0
@@ -4923,7 +4923,7 @@ import {
4923
4923
  Protocol
4924
4924
  } from "@query-farm/vgi-rpc";
4925
4925
  var VGI_PROTOCOL_NAME = "vgi.v3";
4926
- var VGI_PROTOCOL_VERSION = "3.1.0";
4926
+ var VGI_PROTOCOL_VERSION = "3.2.0";
4927
4927
  function exchangeStream(callbacks) {
4928
4928
  return { kind: "exchange", ...callbacks };
4929
4929
  }
@@ -5793,7 +5793,8 @@ var VGI_V3_METHODS = [
5793
5793
  field2("name", utf82(), false),
5794
5794
  field2("at_unit", utf82(), true),
5795
5795
  field2("at_value", utf82(), true),
5796
- field2("transaction_opaque_data", binary2(), true)
5796
+ field2("transaction_opaque_data", binary2(), true),
5797
+ field2("pushdown_filters", binary2(), true)
5797
5798
  ]),
5798
5799
  result: schema2([
5799
5800
  field2("result", binary2(), false)
@@ -6405,7 +6406,7 @@ init_arrow();
6405
6406
 
6406
6407
  // src/generated/vgi-protocol-schemas.ts
6407
6408
  init_arrow();
6408
- var VGI_CATALOG_CONTRACT_HASH = "1d12ce672b43ca1510721f89637bb374d27693b100d357ac2ead99fcddc27e9f";
6409
+ var VGI_CATALOG_CONTRACT_HASH = "d9304d52d78b0ceb90319d9a83759781df4a711b72443790654335c8cfcad9bf";
6409
6410
  var CatalogInfoSchema = schema2([
6410
6411
  field2("name", utf82(), false),
6411
6412
  field2("implementation_version", utf82(), true),
@@ -6441,7 +6442,8 @@ var TableInfoSchema = schema2([
6441
6442
  field2("bind_result", binary2(), true),
6442
6443
  field2("required_filters", list2(field2("item", list2(field2("item", list2(field2("item", utf82(), true)), true)), true)), false),
6443
6444
  field2("options", binary2(), true),
6444
- field2("layout", binary2(), true)
6445
+ field2("layout", binary2(), true),
6446
+ field2("scan_planning", utf82(), false)
6445
6447
  ]);
6446
6448
  var ViewInfoSchema = schema2([
6447
6449
  field2("comment", utf82(), true),
@@ -6765,7 +6767,9 @@ var ScanBranchSchema = schema2([
6765
6767
  field2("format_name", utf82(), true),
6766
6768
  field2("format_locations", list2(field2("item", utf82(), true)), true),
6767
6769
  field2("format_options", binary2(), true),
6768
- field2("schema_path", list2(field2("item", utf82(), true)), true)
6770
+ field2("schema_path", list2(field2("item", utf82(), true)), true),
6771
+ field2("row_count", int642(), true),
6772
+ field2("column_statistics", binary2(), true)
6769
6773
  ]);
6770
6774
  var ScanSplitSchema = schema2([
6771
6775
  field2("payload", binary2(), false),
@@ -7608,7 +7612,8 @@ var CatalogTableScanBranchesGetParamsSchema = schema2([
7608
7612
  field2("name", utf82(), false),
7609
7613
  field2("at_unit", utf82(), true),
7610
7614
  field2("at_value", utf82(), true),
7611
- field2("transaction_opaque_data", binary2(), true)
7615
+ field2("transaction_opaque_data", binary2(), true),
7616
+ field2("pushdown_filters", binary2(), true)
7612
7617
  ]);
7613
7618
  var CatalogTableScanFunctionGetParamsSchema = schema2([
7614
7619
  field2("attach_opaque_data", binary2(), false),
@@ -9965,13 +9970,402 @@ async function openBytes(token, key, aad, version, field = "opaque data") {
9965
9970
  }
9966
9971
  }
9967
9972
 
9973
+ // src/attach-secret-options.ts
9974
+ init_arrow();
9975
+
9976
+ // src/attach-secret-keyfile.ts
9977
+ function builtins() {
9978
+ const proc = globalThis.process;
9979
+ const get = proc?.getBuiltinModule?.bind(proc);
9980
+ const fs = get?.("node:fs");
9981
+ const os = get?.("node:os");
9982
+ const path = get?.("node:path");
9983
+ if (!fs || !os || !path)
9984
+ throw new Error("this runtime has no filesystem for the host-local attach secret key file.");
9985
+ return { fs, os, path };
9986
+ }
9987
+ var ATTACH_SECRET_KEY_FILE_ENV = "VGI_ATTACH_SECRET_KEY_FILE";
9988
+ var KEY_LEN = 32;
9989
+ var FILE_NAME = "attach-secret-options.key";
9990
+ var REMEDY = "Set VGI_SIGNING_KEY (or configure attachSecretKey), or point VGI_ATTACH_SECRET_KEY_FILE at a valid key file.";
9991
+ function username() {
9992
+ try {
9993
+ const name = builtins().os.userInfo().username;
9994
+ if (name)
9995
+ return name;
9996
+ } catch {}
9997
+ return process.env.USER || process.env.USERNAME || String(process.getuid?.() ?? "user");
9998
+ }
9999
+ function isDirectory(path) {
10000
+ try {
10001
+ return builtins().fs.statSync(path).isDirectory();
10002
+ } catch {
10003
+ return false;
10004
+ }
10005
+ }
10006
+ function hostLocalAttachSecretKeyPath(env = globalThis.process?.env ?? {}) {
10007
+ const { os, path: { join } } = builtins();
10008
+ const explicit = env[ATTACH_SECRET_KEY_FILE_ENV];
10009
+ if (explicit)
10010
+ return explicit;
10011
+ const xdg = env.XDG_RUNTIME_DIR;
10012
+ if (xdg && isDirectory(xdg))
10013
+ return join(xdg, "vgi", FILE_NAME);
10014
+ return join(os.tmpdir(), `vgi-${username()}`, FILE_NAME);
10015
+ }
10016
+ var POSIX = typeof process === "undefined" || process.platform !== "win32";
10017
+ function checkOwnedPrivate(path, mode, uid, what) {
10018
+ if (!POSIX)
10019
+ return;
10020
+ const me = process.getuid?.();
10021
+ if (me !== undefined && uid !== me) {
10022
+ throw new Error(`attach secret key ${what} ${path} is not owned by the current user. ${REMEDY}`);
10023
+ }
10024
+ if ((mode & 63) !== 0) {
10025
+ throw new Error(`attach secret key ${what} ${path} is accessible by group/other (mode ${(mode & 511).toString(8)}); ` + `it must be ${what === "directory" ? "0700" : "0600"}. ${REMEDY}`);
10026
+ }
10027
+ }
10028
+ function ensureDir(dir) {
10029
+ const { mkdirSync, lstatSync } = builtins().fs;
10030
+ try {
10031
+ mkdirSync(dir, { recursive: true, mode: 448 });
10032
+ } catch (e) {
10033
+ if (e.code !== "EEXIST")
10034
+ throw e;
10035
+ }
10036
+ const st = lstatSync(dir);
10037
+ if (!st.isDirectory())
10038
+ throw new Error(`attach secret key directory ${dir} is not a directory. ${REMEDY}`);
10039
+ checkOwnedPrivate(dir, st.mode, st.uid, "directory");
10040
+ }
10041
+ function readKey(path) {
10042
+ const { openSync, fstatSync, readSync, closeSync, constants } = builtins().fs;
10043
+ let fd;
10044
+ try {
10045
+ fd = openSync(path, constants.O_RDONLY | (POSIX ? constants.O_NOFOLLOW : 0));
10046
+ } catch (e) {
10047
+ if (e.code === "ENOENT")
10048
+ return null;
10049
+ throw new Error(`attach secret key file ${path} cannot be opened (${e.code}). ${REMEDY}`);
10050
+ }
10051
+ try {
10052
+ const st = fstatSync(fd);
10053
+ if (!st.isFile())
10054
+ throw new Error(`attach secret key file ${path} is not a regular file. ${REMEDY}`);
10055
+ checkOwnedPrivate(path, st.mode, st.uid, "file");
10056
+ const buf = new Uint8Array(KEY_LEN + 1);
10057
+ let n = 0;
10058
+ for (;; ) {
10059
+ const got = readSync(fd, buf, n, buf.length - n, null);
10060
+ if (got <= 0)
10061
+ break;
10062
+ n += got;
10063
+ if (n === buf.length)
10064
+ break;
10065
+ }
10066
+ if (n !== KEY_LEN || st.size !== KEY_LEN) {
10067
+ throw new Error(`attach secret key file ${path} must contain exactly ${KEY_LEN} raw bytes (found ${st.size}). ${REMEDY}`);
10068
+ }
10069
+ return buf.subarray(0, KEY_LEN);
10070
+ } finally {
10071
+ closeSync(fd);
10072
+ }
10073
+ }
10074
+ function createKey(path) {
10075
+ const { openSync, writeSync, fsyncSync, closeSync, linkSync, unlinkSync, constants } = builtins().fs;
10076
+ const { dirname, join } = builtins().path;
10077
+ const tmp = join(dirname(path), `.${FILE_NAME}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
10078
+ const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);
10079
+ try {
10080
+ const key = crypto.getRandomValues(new Uint8Array(KEY_LEN));
10081
+ let off = 0;
10082
+ while (off < KEY_LEN)
10083
+ off += writeSync(fd, key, off, KEY_LEN - off);
10084
+ fsyncSync(fd);
10085
+ } finally {
10086
+ closeSync(fd);
10087
+ }
10088
+ try {
10089
+ linkSync(tmp, path);
10090
+ } catch (e) {
10091
+ if (e.code !== "EEXIST") {
10092
+ unlinkSync(tmp);
10093
+ throw e;
10094
+ }
10095
+ }
10096
+ unlinkSync(tmp);
10097
+ }
10098
+ function loadHostLocalAttachSecretKey(path = hostLocalAttachSecretKeyPath()) {
10099
+ ensureDir(builtins().path.dirname(path));
10100
+ const existing = readKey(path);
10101
+ if (existing)
10102
+ return existing;
10103
+ createKey(path);
10104
+ const created = readKey(path);
10105
+ if (!created)
10106
+ throw new Error(`attach secret key file ${path} vanished after creation. ${REMEDY}`);
10107
+ return created;
10108
+ }
10109
+ var cached;
10110
+ async function hostLocalAttachSecretKey() {
10111
+ const path = hostLocalAttachSecretKeyPath();
10112
+ if (cached?.path === path)
10113
+ return cached.key;
10114
+ const key = loadHostLocalAttachSecretKey(path);
10115
+ cached = { path, key };
10116
+ return key;
10117
+ }
10118
+
10119
+ // src/attach-secret-options.ts
10120
+ var UTF82 = new TextEncoder;
10121
+ var ATTACH_SECRET_OPTIONS_INFO = "vgi.attach_secret_options.v1";
10122
+ var ATTACH_SECRET_OPTIONS_VERSION = 1;
10123
+ var TRAILER_MAGIC = Uint8Array.of(0, 86, 71, 73, 65, 79, 1, 255);
10124
+ var TRAILER_FIXED = 4 + TRAILER_MAGIC.length;
10125
+ var NONCE_LEN2 = 24;
10126
+ var TAG_LEN2 = 16;
10127
+ var AAD_PREFIX = UTF82.encode(`${ATTACH_SECRET_OPTIONS_INFO}\x00`);
10128
+ var UUID_LEN = 16;
10129
+ var FIELD = "attach_opaque_data";
10130
+
10131
+ class AttachSecretKeyUnavailableError extends Error {
10132
+ constructor(message) {
10133
+ super(message);
10134
+ this.name = "AttachSecretKeyUnavailableError";
10135
+ }
10136
+ }
10137
+
10138
+ class AttachOptionsUnavailableError extends Error {
10139
+ constructor() {
10140
+ super("attachOptions(): these bytes are not an attach_opaque_data value the framework handed to this call. " + "Pass the attach value exactly as received (bindCall.attach_opaque_data, a TableBuffering attachId, or a " + "catalog method's attachOpaqueData argument, or a subarray of it), not a copy.");
10141
+ this.name = "AttachOptionsUnavailableError";
10142
+ }
10143
+ }
10144
+ var subkeys = new Map;
10145
+ function hexOf(b) {
10146
+ let s = "";
10147
+ for (let i = 0;i < b.length; i++)
10148
+ s += b[i].toString(16).padStart(2, "0");
10149
+ return s;
10150
+ }
10151
+ function deriveAttachSecretKey(root) {
10152
+ const id = hexOf(root);
10153
+ let derived = subkeys.get(id);
10154
+ if (!derived) {
10155
+ derived = (async () => {
10156
+ const ikm = await crypto.subtle.importKey("raw", root, "HKDF", false, ["deriveBits"]);
10157
+ const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: UTF82.encode(ATTACH_SECRET_OPTIONS_INFO) }, ikm, 256);
10158
+ return new Uint8Array(bits);
10159
+ })();
10160
+ subkeys.set(id, derived);
10161
+ derived.catch(() => subkeys.delete(id));
10162
+ }
10163
+ return derived;
10164
+ }
10165
+ function defaultHostLocal() {
10166
+ return hostLocalAttachSecretKey();
10167
+ }
10168
+ function noKeyMessage() {
10169
+ return "A secret ATTACH option has a value but this worker has no key to encrypt it with: configure " + "`attachSecretKey`, run with a signing key (VGI_SIGNING_KEY), or run where the host-local key file " + "(VGI_ATTACH_SECRET_KEY_FILE) can be used.";
10170
+ }
10171
+ async function rootKey(source) {
10172
+ if (source.explicit && source.explicit.length > 0)
10173
+ return source.explicit;
10174
+ if (source.signingKey && source.signingKey.length > 0)
10175
+ return source.signingKey;
10176
+ return (source.hostLocal ?? defaultHostLocal)();
10177
+ }
10178
+ function aadFor(uuid) {
10179
+ const out = new Uint8Array(AAD_PREFIX.length + uuid.length);
10180
+ out.set(AAD_PREFIX, 0);
10181
+ out.set(uuid, AAD_PREFIX.length);
10182
+ return out;
10183
+ }
10184
+ function u32le(n) {
10185
+ const b = new Uint8Array(4);
10186
+ new DataView(b.buffer).setUint32(0, n, true);
10187
+ return b;
10188
+ }
10189
+ function readU32le(b, off) {
10190
+ return new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off, true);
10191
+ }
10192
+ function concat2(...parts) {
10193
+ let total = 0;
10194
+ for (const p of parts)
10195
+ total += p.length;
10196
+ const out = new Uint8Array(total);
10197
+ let off = 0;
10198
+ for (const p of parts) {
10199
+ out.set(p, off);
10200
+ off += p.length;
10201
+ }
10202
+ return out;
10203
+ }
10204
+ function splitOptions(optionsIpc, secretNames) {
10205
+ if (!optionsIpc || optionsIpc.length === 0)
10206
+ return null;
10207
+ const batch = deserializeBatch(optionsIpc);
10208
+ if (batch.numRows === 0 || batch.schema.fields.length === 0)
10209
+ return null;
10210
+ const row = iterRows(batch).next().value ?? {};
10211
+ const plainFields = [];
10212
+ const secretFields = [];
10213
+ const plainCols = {};
10214
+ const secretCols = {};
10215
+ for (const f of batch.schema.fields) {
10216
+ const value = row[f.name];
10217
+ if (secretNames.has(f.name.toLowerCase()) && value !== null && value !== undefined) {
10218
+ secretFields.push(f);
10219
+ secretCols[f.name] = [value];
10220
+ } else {
10221
+ plainFields.push(f);
10222
+ plainCols[f.name] = [value ?? null];
10223
+ }
10224
+ }
10225
+ return {
10226
+ plain: plainFields.length ? serializeBatch(batchFromColumns(plainCols, schema2(plainFields))) : null,
10227
+ secret: secretFields.length ? serializeBatch(batchFromColumns(secretCols, schema2(secretFields))) : null
10228
+ };
10229
+ }
10230
+ async function packAttachOptionsTrailer(uuid, optionsIpc, secretNames, keys, fixedNonce) {
10231
+ const split = splitOptions(optionsIpc, secretNames);
10232
+ if (split === null)
10233
+ return new Uint8Array(0);
10234
+ const plain = split.plain ?? new Uint8Array(0);
10235
+ let secret = new Uint8Array(0);
10236
+ if (split.secret) {
10237
+ let root;
10238
+ try {
10239
+ root = await rootKey(keys);
10240
+ } catch (e) {
10241
+ if (e instanceof AttachSecretKeyUnavailableError)
10242
+ throw e;
10243
+ throw new AttachSecretKeyUnavailableError(`${noKeyMessage()} ${e.message}`);
10244
+ }
10245
+ const key = await deriveAttachSecretKey(root);
10246
+ const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN2));
10247
+ const ct = xchacha20poly1305(key, nonce, aadFor(uuid)).encrypt(split.secret);
10248
+ secret = concat2(Uint8Array.of(ATTACH_SECRET_OPTIONS_VERSION), nonce, ct);
10249
+ }
10250
+ const body = concat2(u32le(plain.length), plain, secret);
10251
+ return concat2(body, u32le(body.length), TRAILER_MAGIC);
10252
+ }
10253
+ function endsWithMagic(b) {
10254
+ if (b.length < TRAILER_MAGIC.length)
10255
+ return false;
10256
+ const off = b.length - TRAILER_MAGIC.length;
10257
+ for (let i = 0;i < TRAILER_MAGIC.length; i++)
10258
+ if (b[off + i] !== TRAILER_MAGIC[i])
10259
+ return false;
10260
+ return true;
10261
+ }
10262
+ function decodeOptions(ipc) {
10263
+ const batch = deserializeBatch(ipc);
10264
+ if (batch.numRows === 0)
10265
+ return {};
10266
+ return { ...iterRows(batch).next().value ?? {} };
10267
+ }
10268
+ var registry = new WeakMap;
10269
+ var EMPTY = Object.freeze({});
10270
+ async function openFrameworkAttach(full, keys) {
10271
+ if (full.length < UUID_LEN)
10272
+ return full;
10273
+ const copy = full.slice();
10274
+ let end = copy.length;
10275
+ let options = EMPTY;
10276
+ if (copy.length >= UUID_LEN + TRAILER_FIXED && endsWithMagic(copy)) {
10277
+ const bodyLen = readU32le(copy, copy.length - TRAILER_FIXED);
10278
+ const bodyStart = copy.length - TRAILER_FIXED - bodyLen;
10279
+ if (bodyLen < 4 || bodyStart < UUID_LEN)
10280
+ throw new OpaqueDataRejectedError(FIELD);
10281
+ const body = copy.subarray(bodyStart, copy.length - TRAILER_FIXED);
10282
+ const plainLen = readU32le(body, 0);
10283
+ if (4 + plainLen > body.length)
10284
+ throw new OpaqueDataRejectedError(FIELD);
10285
+ const plain = body.subarray(4, 4 + plainLen);
10286
+ const secret = body.subarray(4 + plainLen);
10287
+ const values = {};
10288
+ try {
10289
+ if (plain.length)
10290
+ Object.assign(values, decodeOptions(plain));
10291
+ } catch {
10292
+ throw new OpaqueDataRejectedError(FIELD);
10293
+ }
10294
+ if (secret.length) {
10295
+ if (secret.length < 1 + NONCE_LEN2 + TAG_LEN2 || secret[0] !== ATTACH_SECRET_OPTIONS_VERSION) {
10296
+ throw new OpaqueDataRejectedError(FIELD);
10297
+ }
10298
+ let opened;
10299
+ try {
10300
+ const key = await deriveAttachSecretKey(await rootKey(keys));
10301
+ const nonce = secret.subarray(1, 1 + NONCE_LEN2);
10302
+ opened = xchacha20poly1305(key, nonce, aadFor(copy.subarray(0, UUID_LEN))).decrypt(secret.subarray(1 + NONCE_LEN2));
10303
+ } catch {
10304
+ throw new OpaqueDataRejectedError(FIELD);
10305
+ }
10306
+ try {
10307
+ Object.assign(values, decodeOptions(opened));
10308
+ } catch {
10309
+ throw new OpaqueDataRejectedError(FIELD);
10310
+ }
10311
+ }
10312
+ options = Object.freeze(values);
10313
+ end = bodyStart;
10314
+ }
10315
+ registry.set(copy.buffer, options);
10316
+ return copy.subarray(UUID_LEN, end);
10317
+ }
10318
+ function attachOptions(attachOpaqueData) {
10319
+ if (attachOpaqueData == null)
10320
+ return EMPTY;
10321
+ const found = registry.get(attachOpaqueData.buffer);
10322
+ if (found !== undefined)
10323
+ return found;
10324
+ if (attachOpaqueData.length === 0)
10325
+ return EMPTY;
10326
+ throw new AttachOptionsUnavailableError;
10327
+ }
10328
+ async function secretAttachOptionNames(catalog, name, deserialize) {
10329
+ const names = new Set;
10330
+ if (typeof catalog.attachOptionSpecs === "function") {
10331
+ for (const spec of catalog.attachOptionSpecs(name) ?? [])
10332
+ if (spec.secret)
10333
+ names.add(spec.name.toLowerCase());
10334
+ }
10335
+ if (typeof catalog.catalogsInfo === "function") {
10336
+ let infos;
10337
+ try {
10338
+ infos = await catalog.catalogsInfo();
10339
+ } catch {
10340
+ infos = [];
10341
+ }
10342
+ for (const info of infos ?? []) {
10343
+ if (info.name !== name)
10344
+ continue;
10345
+ for (const raw of info.attach_option_specs ?? []) {
10346
+ try {
10347
+ const spec = deserialize(raw);
10348
+ if (spec.secret)
10349
+ names.add(spec.name.toLowerCase());
10350
+ } catch {}
10351
+ }
10352
+ }
10353
+ }
10354
+ return names;
10355
+ }
10356
+
9968
10357
  // src/protocol/handlers/catalog/shared.ts
9969
- async function sealAttach(plaintext, auth, signingKey) {
10358
+ async function sealAttach(plaintext, auth, signingKey, options) {
9970
10359
  const uuid = new Uint8Array(ATTACH_UUID_LEN);
9971
10360
  crypto.getRandomValues(uuid);
9972
- const minted = new Uint8Array(ATTACH_UUID_LEN + plaintext.length);
10361
+ const trailer = options ? await packAttachOptionsTrailer(uuid, options.optionsIpc, options.secretNames, {
10362
+ explicit: options.attachSecretKey,
10363
+ signingKey
10364
+ }) : new Uint8Array(0);
10365
+ const minted = new Uint8Array(ATTACH_UUID_LEN + plaintext.length + trailer.length);
9973
10366
  minted.set(uuid, 0);
9974
10367
  minted.set(plaintext, ATTACH_UUID_LEN);
10368
+ minted.set(trailer, ATTACH_UUID_LEN + plaintext.length);
9975
10369
  if (!signingKey)
9976
10370
  return minted;
9977
10371
  return sealBytes(minted, signingKey, attachAad(auth), ATTACH_ENVELOPE_VERSION);
@@ -9981,9 +10375,9 @@ async function openAttachFull(envelope, auth, signingKey) {
9981
10375
  return envelope;
9982
10376
  return openBytes(envelope, signingKey, attachAad(auth), ATTACH_ENVELOPE_VERSION, "attach_opaque_data");
9983
10377
  }
9984
- async function openAttach(envelope, auth, signingKey) {
10378
+ async function openAttach(envelope, auth, signingKey, attachSecretKey) {
9985
10379
  const full = await openAttachFull(envelope, auth, signingKey);
9986
- return full.length < ATTACH_UUID_LEN ? full : full.subarray(ATTACH_UUID_LEN);
10380
+ return openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
9987
10381
  }
9988
10382
  async function sealTransaction(plaintext, attachEnvelope, auth, signingKey) {
9989
10383
  if (!signingKey)
@@ -9995,7 +10389,8 @@ async function openTransaction(envelope, attachEnvelope, auth, signingKey) {
9995
10389
  return envelope;
9996
10390
  return openBytes(envelope, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION, "transaction_opaque_data");
9997
10391
  }
9998
- async function unwrapParamsOpaque(params, ctx, signingKey) {
10392
+ async function unwrapParamsOpaque(params, ctx, keys) {
10393
+ const { signingKey, attachSecretKey } = keys;
9999
10394
  const auth = ctx?.auth;
10000
10395
  let sealedAttach = new Uint8Array(0);
10001
10396
  if (params.attach_opaque_data != null) {
@@ -10003,7 +10398,7 @@ async function unwrapParamsOpaque(params, ctx, signingKey) {
10003
10398
  if (env.length > 0) {
10004
10399
  sealedAttach = env;
10005
10400
  const full = signingKey ? await openBytes(env, signingKey, attachAad(auth), ATTACH_ENVELOPE_VERSION, "attach_opaque_data") : env;
10006
- params.attach_opaque_data = full.length < ATTACH_UUID_LEN ? full : full.subarray(ATTACH_UUID_LEN);
10401
+ params.attach_opaque_data = await openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
10007
10402
  }
10008
10403
  }
10009
10404
  if (signingKey && params.transaction_opaque_data != null) {
@@ -10013,14 +10408,15 @@ async function unwrapParamsOpaque(params, ctx, signingKey) {
10013
10408
  }
10014
10409
  }
10015
10410
  }
10016
- function catalogHandler(signingKey, handler) {
10411
+ function catalogHandler(keysOrSigningKey, handler) {
10412
+ const keys = keysOrSigningKey instanceof Uint8Array || keysOrSigningKey === undefined ? { signingKey: keysOrSigningKey } : keysOrSigningKey;
10017
10413
  return async (wire, ctx) => {
10018
10414
  let params = wire;
10019
10415
  if (params.request != null && params.attach_opaque_data === undefined && params.name === undefined) {
10020
10416
  params = unwrapRequest(params.request);
10021
10417
  }
10022
10418
  normalizeRequestSchemaPaths(params);
10023
- await unwrapParamsOpaque(params, ctx, signingKey);
10419
+ await unwrapParamsOpaque(params, ctx, keys);
10024
10420
  return handler(params, ctx);
10025
10421
  };
10026
10422
  }
@@ -10162,7 +10558,7 @@ var RESERVED_FLAGS_MASK = 254;
10162
10558
  var FINGERPRINT_LEN = 16;
10163
10559
  var HEADER_LEN = 4 + FINGERPRINT_LEN;
10164
10560
  var SEAL_VERSION = 1;
10165
- var AAD_PREFIX = new TextEncoder().encode("vgi.split_token.v1\x00");
10561
+ var AAD_PREFIX2 = new TextEncoder().encode("vgi.split_token.v1\x00");
10166
10562
  var SPLIT_TOKEN_INVALID = "SPLIT_TOKEN_INVALID";
10167
10563
  var SPLIT_SNAPSHOT_EXPIRED = "SPLIT_SNAPSHOT_EXPIRED";
10168
10564
  class SplitTokenError extends Error {
@@ -10173,7 +10569,7 @@ class SplitTokenError extends Error {
10173
10569
  this.kind = kind;
10174
10570
  }
10175
10571
  }
10176
- function concat2(...parts) {
10572
+ function concat3(...parts) {
10177
10573
  const total = parts.reduce((n, p) => n + p.length, 0);
10178
10574
  const out = new Uint8Array(total);
10179
10575
  let at = 0;
@@ -10194,13 +10590,13 @@ function equalBytes2(a, b) {
10194
10590
  async function bindFingerprint(schemaPath, functionName, args, settings, projection) {
10195
10591
  const enc = new TextEncoder;
10196
10592
  const zero = Uint8Array.of(0);
10197
- const field = (label, value) => concat2(enc.encode(label), zero, value, zero);
10198
- const message = concat2(AAD_PREFIX, field("schema_path", enc.encode(JSON.stringify(schemaPath))), field("function_name", enc.encode(functionName)), field("arguments", args), field("settings", settings), field("projection_ids", projection));
10593
+ const field = (label, value) => concat3(enc.encode(label), zero, value, zero);
10594
+ const message = concat3(AAD_PREFIX2, field("schema_path", enc.encode(JSON.stringify(schemaPath))), field("function_name", enc.encode(functionName)), field("arguments", args), field("settings", settings), field("projection_ids", projection));
10199
10595
  const digest = await crypto.subtle.digest("SHA-256", message);
10200
10596
  return new Uint8Array(digest).slice(0, FINGERPRINT_LEN);
10201
10597
  }
10202
10598
  function splitTokenAad(header, auth) {
10203
- return concat2(header, identityTail(auth));
10599
+ return concat3(header, identityTail(auth));
10204
10600
  }
10205
10601
  function splitAnchor(catalogVersion) {
10206
10602
  const out = new Uint8Array(8);
@@ -10219,11 +10615,11 @@ async function buildSplitToken(opts) {
10219
10615
  head[0] = SPLIT_TOKEN_FORMAT_VERSION;
10220
10616
  head[1] = signingKey ? FLAG_PAYLOAD_SEALED : 0;
10221
10617
  new DataView(head.buffer).setUint16(2, anchor.length, true);
10222
- const body = concat2(head, fingerprint, anchor);
10618
+ const body = concat3(head, fingerprint, anchor);
10223
10619
  if (!signingKey)
10224
- return concat2(body, payload);
10620
+ return concat3(body, payload);
10225
10621
  const sealed = await sealBytes(payload, signingKey, splitTokenAad(body, auth), SEAL_VERSION);
10226
- return concat2(body, sealed);
10622
+ return concat3(body, sealed);
10227
10623
  }
10228
10624
  async function openSplitToken(token, opts = {}) {
10229
10625
  const { signingKey, auth, expectedFingerprint, currentAnchor } = opts;
@@ -10271,7 +10667,7 @@ async function openSplitToken(token, opts = {}) {
10271
10667
  }
10272
10668
 
10273
10669
  // src/protocol/handlers/function.ts
10274
- async function liveSplitAnchor(catalogInterface, bindCall, auth, signingKey) {
10670
+ async function liveSplitAnchor(catalogInterface, bindCall, auth, signingKey, attachSecretKey) {
10275
10671
  if (!catalogInterface?.version || bindCall.attach_opaque_data == null)
10276
10672
  return;
10277
10673
  const raw = toUint8Array(bindCall.attach_opaque_data);
@@ -10283,7 +10679,7 @@ async function liveSplitAnchor(catalogInterface, bindCall, auth, signingKey) {
10283
10679
  }
10284
10680
  const forms = [
10285
10681
  async () => raw,
10286
- async () => openAttach(raw, auth, signingKey)
10682
+ async () => openAttach(raw, auth, signingKey, attachSecretKey)
10287
10683
  ];
10288
10684
  for (const form of forms) {
10289
10685
  try {
@@ -10297,7 +10693,7 @@ async function resolveSplitPayloads(request, innerParams, opts) {
10297
10693
  return;
10298
10694
  const fp = fingerprintInputs(toUint8Array(innerParams.bind_call));
10299
10695
  const expected = await bindFingerprint(fp.schemaPath, fp.functionName, fp.args, fp.settings, new Uint8Array(0));
10300
- const currentAnchor = opts.checkAnchor ? await liveSplitAnchor(opts.catalogInterface, request.bind_call, opts.auth, opts.signingKey) : undefined;
10696
+ const currentAnchor = opts.checkAnchor ? await liveSplitAnchor(opts.catalogInterface, request.bind_call, opts.auth, opts.signingKey, opts.attachSecretKey) : undefined;
10301
10697
  request.split_payloads = [];
10302
10698
  for (const token of request.split_tokens) {
10303
10699
  request.split_payloads.push(await openSplitToken(token, {
@@ -10309,14 +10705,14 @@ async function resolveSplitPayloads(request, innerParams, opts) {
10309
10705
  }
10310
10706
  }
10311
10707
  function functionHandlers(config) {
10312
- const { registry, signingKey, catalogInterface } = config;
10708
+ const { registry, signingKey, catalogInterface, attachSecretKey } = config;
10313
10709
  async function stripAttach(attach, ctx) {
10314
10710
  if (attach == null)
10315
10711
  return null;
10316
10712
  const env = toUint8Array(attach);
10317
10713
  if (env.length === 0)
10318
10714
  return env;
10319
- return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey);
10715
+ return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
10320
10716
  }
10321
10717
  async function openOpaque(bindCall, ctx) {
10322
10718
  const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
@@ -10361,6 +10757,7 @@ function functionHandlers(config) {
10361
10757
  await resolveSplitPayloads(request, innerParams, {
10362
10758
  auth,
10363
10759
  signingKey,
10760
+ attachSecretKey,
10364
10761
  catalogInterface,
10365
10762
  checkAnchor: true
10366
10763
  });
@@ -10406,6 +10803,7 @@ function functionHandlers(config) {
10406
10803
  await resolveSplitPayloads(request, { bind_call: carried.bindCallIpc }, {
10407
10804
  auth: currentRequestAuth(),
10408
10805
  signingKey,
10806
+ attachSecretKey,
10409
10807
  catalogInterface,
10410
10808
  checkAnchor: false
10411
10809
  });
@@ -10477,7 +10875,7 @@ function functionHandlers(config) {
10477
10875
  const plan = func.plan ? await func.plan(request) : { splits: [{ payload: new Uint8Array(0) }] };
10478
10876
  const fp = fingerprintInputs(toUint8Array(innerParams.bind_call));
10479
10877
  const fingerprint = await bindFingerprint(fp.schemaPath, fp.functionName, fp.args, fp.settings, new Uint8Array(0));
10480
- const anchor = plan.catalogVersion != null ? splitAnchor(plan.catalogVersion) : await liveSplitAnchor(catalogInterface, request.bind_call, ctx?.auth, signingKey) ?? splitAnchor(0);
10878
+ const anchor = plan.catalogVersion != null ? splitAnchor(plan.catalogVersion) : await liveSplitAnchor(catalogInterface, request.bind_call, ctx?.auth, signingKey, attachSecretKey) ?? splitAnchor(0);
10481
10879
  const blobs = [];
10482
10880
  for (const split of plan.splits) {
10483
10881
  const token = await buildSplitToken({
@@ -11338,7 +11736,7 @@ function splitLenPrefixed(buf, count) {
11338
11736
  }
11339
11737
 
11340
11738
  // src/protocol/handlers/table-buffering.ts
11341
- function tableBufferingHandlers(registry, signingKey) {
11739
+ function tableBufferingHandlers(registry, signingKey, attachSecretKey) {
11342
11740
  function resolveBuffering(name, schemaPath) {
11343
11741
  const func = registry.get(name, {
11344
11742
  arguments: new Arguments,
@@ -11355,7 +11753,7 @@ function tableBufferingHandlers(registry, signingKey) {
11355
11753
  const functionName = inner.function_name;
11356
11754
  const executionId = toUint8Array(inner.execution_id);
11357
11755
  const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
11358
- const attach = rawAttach && rawAttach.length > 0 ? await openAttach(rawAttach, ctx?.auth, signingKey) : rawAttach;
11756
+ const attach = rawAttach && rawAttach.length > 0 ? await openAttach(rawAttach, ctx?.auth, signingKey, attachSecretKey) : rawAttach;
11359
11757
  const transactionId = inner.transaction_id ? toUint8Array(inner.transaction_id) : null;
11360
11758
  const func = resolveBuffering(functionName, inner.schema_path ?? null);
11361
11759
  const bound = new BoundStorage(storage, executionId);
@@ -11904,6 +12302,220 @@ function servedTableInfo(info) {
11904
12302
  return served === schema ? info : { ...info, columns: serializeSchema(served) };
11905
12303
  }
11906
12304
 
12305
+ // src/catalog/scan-planning.ts
12306
+ init_arrow();
12307
+ var SCAN_PLANNING_BIND = "bind";
12308
+ var SCAN_PLANNING_FILTERED = "filtered";
12309
+ var SCAN_PLANNING_MODES = Object.freeze([SCAN_PLANNING_BIND, SCAN_PLANNING_FILTERED]);
12310
+ function validateScanPlanning(tableName, scanPlanning, hasInlineScanFunction) {
12311
+ const mode = scanPlanning ?? SCAN_PLANNING_BIND;
12312
+ if (mode !== SCAN_PLANNING_BIND && mode !== SCAN_PLANNING_FILTERED) {
12313
+ throw new Error(`Table '${tableName}': scan_planning must be one of ${JSON.stringify(SCAN_PLANNING_MODES)}, got ${JSON.stringify(mode)}`);
12314
+ }
12315
+ if (mode === SCAN_PLANNING_FILTERED && hasInlineScanFunction) {
12316
+ throw new Error(`Table '${tableName}': scan_planning='filtered' cannot be combined with an inlined scan_function; ` + "the scan redirect must be resolved per query with the query's filters");
12317
+ }
12318
+ return mode;
12319
+ }
12320
+
12321
+ class ScanPlanningFilters {
12322
+ raw;
12323
+ tableColumns;
12324
+ _decoded = null;
12325
+ constructor(raw, tableColumns) {
12326
+ this.raw = raw;
12327
+ this.tableColumns = tableColumns;
12328
+ }
12329
+ decode() {
12330
+ if (this._decoded == null) {
12331
+ this._decoded = (async () => {
12332
+ const columns = await this.tableColumns();
12333
+ if (columns == null) {
12334
+ throw new Error("pushdown_filters: the table's declared columns could not be resolved");
12335
+ }
12336
+ return deserializeFilters(deserializeBatch(this.raw), { outputSchema: columns });
12337
+ })();
12338
+ this._decoded.catch(() => {
12339
+ this._decoded = null;
12340
+ });
12341
+ }
12342
+ return this._decoded;
12343
+ }
12344
+ async mayMatch(statistics) {
12345
+ return filtersMayMatch(await this.decode(), statistics);
12346
+ }
12347
+ }
12348
+ function filtersMayMatch(filters, statistics) {
12349
+ const list = Symbol.iterator in statistics ? statistics : Object.values(statistics);
12350
+ const byName = new Map;
12351
+ for (const stat of list)
12352
+ byName.set(stat.columnName, stat);
12353
+ if (byName.size === 0)
12354
+ return true;
12355
+ for (const predicate of filters.predicates) {
12356
+ if (provablyFalse(predicate.expression, byName))
12357
+ return false;
12358
+ }
12359
+ return true;
12360
+ }
12361
+ var FLIPPED = {
12362
+ ["eq" /* EQ */]: "eq" /* EQ */,
12363
+ ["ne" /* NE */]: "ne" /* NE */,
12364
+ ["lt" /* LT */]: "gt" /* GT */,
12365
+ ["le" /* LE */]: "ge" /* GE */,
12366
+ ["gt" /* GT */]: "lt" /* LT */,
12367
+ ["ge" /* GE */]: "le" /* LE */
12368
+ };
12369
+ function columnStat(expr, stats) {
12370
+ if (expr.node !== "column_ref")
12371
+ return null;
12372
+ const stat = stats.get(expr.columnName);
12373
+ return stat == null ? null : { stat, type: stat.arrowType ?? expr.dataType };
12374
+ }
12375
+ function outside(ref, value, valueType) {
12376
+ const lo = ref.stat.min ?? null;
12377
+ const hi = ref.stat.max ?? null;
12378
+ const cmpLo = lo == null ? null : compare2(lo, ref.type, value, valueType);
12379
+ const cmpHi = hi == null ? null : compare2(hi, ref.type, value, valueType);
12380
+ return cmpLo != null && cmpLo > 0 || cmpHi != null && cmpHi < 0;
12381
+ }
12382
+ function provablyFalse(expr, stats) {
12383
+ switch (expr.node) {
12384
+ case "and":
12385
+ return expr.children.some((child) => provablyFalse(child, stats));
12386
+ case "or":
12387
+ return expr.children.length > 0 && expr.children.every((child) => provablyFalse(child, stats));
12388
+ case "comparison": {
12389
+ let op = expr.op;
12390
+ let ref = columnStat(expr.left, stats);
12391
+ let literal = expr.right;
12392
+ if (ref == null) {
12393
+ ref = columnStat(expr.right, stats);
12394
+ literal = expr.left;
12395
+ op = FLIPPED[expr.op];
12396
+ }
12397
+ if (ref == null || op == null || !(op in FLIPPED) || literal.node !== "literal")
12398
+ return false;
12399
+ if (ref.stat.hasNotNull === false)
12400
+ return true;
12401
+ const c = literal.value;
12402
+ if (c == null)
12403
+ return true;
12404
+ const litType = literal.field?.type;
12405
+ const lo = ref.stat.min ?? null;
12406
+ const hi = ref.stat.max ?? null;
12407
+ const cmpLo = lo == null ? null : compare2(lo, ref.type, c, litType);
12408
+ const cmpHi = hi == null ? null : compare2(hi, ref.type, c, litType);
12409
+ switch (op) {
12410
+ case "eq" /* EQ */:
12411
+ return cmpLo != null && cmpLo > 0 || cmpHi != null && cmpHi < 0;
12412
+ case "ne" /* NE */:
12413
+ return cmpLo === 0 && cmpHi === 0;
12414
+ case "lt" /* LT */:
12415
+ return cmpLo != null && cmpLo >= 0;
12416
+ case "le" /* LE */:
12417
+ return cmpLo != null && cmpLo > 0;
12418
+ case "gt" /* GT */:
12419
+ return cmpHi != null && cmpHi <= 0;
12420
+ case "ge" /* GE */:
12421
+ return cmpHi != null && cmpHi < 0;
12422
+ default:
12423
+ return false;
12424
+ }
12425
+ }
12426
+ case "in": {
12427
+ if (expr.negated || expr.set.kind !== "literal")
12428
+ return false;
12429
+ const ref = columnStat(expr.expression, stats);
12430
+ if (ref == null)
12431
+ return false;
12432
+ if (ref.stat.hasNotNull === false)
12433
+ return true;
12434
+ if (ref.stat.min == null && ref.stat.max == null)
12435
+ return false;
12436
+ const setType = expr.set.field?.type;
12437
+ const values = expr.set.values.filter((v) => v != null);
12438
+ if (values.length === 0)
12439
+ return true;
12440
+ return values.every((v) => outside(ref, v, setType));
12441
+ }
12442
+ case "is_null": {
12443
+ const ref = columnStat(expr.expression, stats);
12444
+ if (ref == null)
12445
+ return false;
12446
+ return expr.negated ? ref.stat.hasNotNull === false : ref.stat.hasNull === false;
12447
+ }
12448
+ default:
12449
+ return false;
12450
+ }
12451
+ }
12452
+ function compare2(a, aType, b, bType) {
12453
+ const x = comparable(a, aType);
12454
+ const y = comparable(b, bType);
12455
+ if (x == null || y == null || x.kind !== y.kind)
12456
+ return null;
12457
+ const u = x.value;
12458
+ const v = y.value;
12459
+ if (typeof u === "number" && Number.isNaN(u))
12460
+ return null;
12461
+ if (typeof v === "number" && Number.isNaN(v))
12462
+ return null;
12463
+ if (typeof u === "string" && typeof v === "string")
12464
+ return compareCodePoints2(u, v);
12465
+ return u < v ? -1 : u > v ? 1 : 0;
12466
+ }
12467
+ function compareCodePoints2(a, b) {
12468
+ const ia = a[Symbol.iterator]();
12469
+ const ib = b[Symbol.iterator]();
12470
+ for (;; ) {
12471
+ const x = ia.next();
12472
+ const y = ib.next();
12473
+ if (x.done || y.done)
12474
+ return x.done && y.done ? 0 : x.done ? -1 : 1;
12475
+ const cx = x.value.codePointAt(0);
12476
+ const cy = y.value.codePointAt(0);
12477
+ if (cx !== cy)
12478
+ return cx < cy ? -1 : 1;
12479
+ }
12480
+ }
12481
+ var MS_PER_DAY2 = 86400000;
12482
+ var NS_PER_UNIT = [1000000000n, 1000000n, 1000n, 1n];
12483
+ function comparable(v, type) {
12484
+ if (type != null) {
12485
+ if (isDate(type)) {
12486
+ if (v instanceof Date)
12487
+ return { kind: "date", value: v.getTime() };
12488
+ if (typeof v === "number" || typeof v === "bigint") {
12489
+ return { kind: "date", value: type.unit === 0 ? Number(v) * MS_PER_DAY2 : Number(v) };
12490
+ }
12491
+ return null;
12492
+ }
12493
+ if (isTimestamp(type)) {
12494
+ const scale = NS_PER_UNIT[type.unit ?? -1];
12495
+ if (scale == null)
12496
+ return null;
12497
+ if (v instanceof Date)
12498
+ return { kind: "timestamp", value: BigInt(v.getTime()) * 1000000n };
12499
+ if (typeof v === "bigint")
12500
+ return { kind: "timestamp", value: v * scale };
12501
+ if (typeof v === "number" && Number.isSafeInteger(v))
12502
+ return { kind: "timestamp", value: BigInt(v) * scale };
12503
+ return null;
12504
+ }
12505
+ if (isDecimal(type) || isTime(type) || isInterval(type) || isDuration(type))
12506
+ return null;
12507
+ }
12508
+ if (v instanceof Date)
12509
+ return null;
12510
+ if (typeof v === "number" || typeof v === "bigint")
12511
+ return { kind: "numeric", value: v };
12512
+ if (typeof v === "string")
12513
+ return { kind: "string", value: v };
12514
+ if (typeof v === "boolean")
12515
+ return { kind: "boolean", value: v ? 1 : 0 };
12516
+ return null;
12517
+ }
12518
+
11907
12519
  // src/catalog/column-metadata.ts
11908
12520
  function scalarText(value) {
11909
12521
  for (let i = 0;i < value.length; i++) {
@@ -12050,12 +12662,16 @@ function validateColumnMetadataIpc(bytes) {
12050
12662
  vector(schema, 1, (f) => field(f, 0));
12051
12663
  }
12052
12664
  function validateTableInfoColumns(info) {
12665
+ validateScanPlanning(info.name, info.scan_planning, info.scan_function != null);
12053
12666
  if (info.columns.length) {
12054
12667
  validateColumnMetadataIpc(info.columns);
12055
12668
  validateColumnExpressionsIpc(info.columns, info.schema_path);
12056
12669
  }
12057
12670
  }
12058
12671
  function servedValidatedTableInfo(info) {
12672
+ const scanPlanning = validateScanPlanning(info.name, info.scan_planning, info.scan_function != null);
12673
+ if (info.scan_planning !== scanPlanning)
12674
+ info = { ...info, scan_planning: scanPlanning };
12059
12675
  if (info.columns.length)
12060
12676
  validateColumnMetadataIpc(info.columns);
12061
12677
  const served = servedTableInfo(info);
@@ -12665,6 +13281,7 @@ function encodeFunctionInfoOnce(info) {
12665
13281
  return encoded;
12666
13282
  }
12667
13283
  // src/catalog/interface.ts
13284
+ init_arrow();
12668
13285
  var encodeCopyFromFormatInfo = (v) => encodeASD(CopyFromFormatInfoSchema, {
12669
13286
  comment: v.comment ?? null,
12670
13287
  tags: v.tags ?? {},
@@ -12716,9 +13333,70 @@ function encodeScanBranch(cols) {
12716
13333
  format_name: [cols.format_name ?? null],
12717
13334
  format_locations: [cols.format_locations ?? null],
12718
13335
  format_options: [cols.format_options ?? null],
12719
- schema_path: [cols.schema_path ?? null]
13336
+ schema_path: [cols.schema_path ?? null],
13337
+ row_count: [cols.row_count ?? null],
13338
+ column_statistics: [cols.column_statistics ?? null]
12720
13339
  }), ScanBranchSchema));
12721
13340
  }
13341
+ function branchStatistics(branch) {
13342
+ let rowCount = null;
13343
+ if (branch.rowCount != null) {
13344
+ if (typeof branch.rowCount === "number" && !Number.isSafeInteger(branch.rowCount)) {
13345
+ throw new Error(`ScanBranch.rowCount must be an integer, got ${branch.rowCount}`);
13346
+ }
13347
+ rowCount = BigInt(branch.rowCount);
13348
+ if (rowCount < 0n)
13349
+ throw new Error(`ScanBranch.rowCount must be >= 0, got ${rowCount}`);
13350
+ }
13351
+ let columnStatistics = null;
13352
+ const stats = branch.columnStatistics;
13353
+ if (stats instanceof Uint8Array) {
13354
+ columnStatistics = stats;
13355
+ } else if (stats != null) {
13356
+ const names = stats.map((s) => s.columnName);
13357
+ if (new Set(names).size !== names.length) {
13358
+ throw new Error("ScanBranch.columnStatistics names a column more than once");
13359
+ }
13360
+ columnStatistics = serializeColumnStatistics(stats);
13361
+ }
13362
+ return { row_count: rowCount, column_statistics: columnStatistics };
13363
+ }
13364
+ function serializeBranchArguments(branch) {
13365
+ const fields = [];
13366
+ const values = {};
13367
+ const positional = branch.positionalArguments ?? [];
13368
+ positional.forEach((arg, index) => {
13369
+ const name = `arg_${index}`;
13370
+ fields.push(field2(name, arg.type, true));
13371
+ values[name] = [arg.value];
13372
+ });
13373
+ for (const [name, arg] of Object.entries(branch.namedArguments ?? {})) {
13374
+ fields.push(field2(name, arg.type, true));
13375
+ values[name] = [arg.value];
13376
+ }
13377
+ const batchSchema = schema2(fields);
13378
+ return serializeBatch(batchFromColumns(values, batchSchema));
13379
+ }
13380
+ function buildScanBranchesResult(branches, requiredExtensions = []) {
13381
+ const serializedBranches = branches.map((branch) => encodeScanBranch({
13382
+ function_name: branch.functionName,
13383
+ arguments: serializeBranchArguments(branch),
13384
+ branch_filter: branch.branchFilter,
13385
+ writable: branch.writable,
13386
+ source_catalog: branch.sourceCatalog,
13387
+ source_schema_path: branch.sourceSchemaPath,
13388
+ source_table: branch.sourceTable,
13389
+ format_name: branch.formatName,
13390
+ format_locations: branch.formatLocations,
13391
+ format_options: branch.formatOptions,
13392
+ schema_path: branch.schemaPath,
13393
+ ...branchStatistics(branch)
13394
+ }));
13395
+ return {
13396
+ branches: serializedBranches,
13397
+ required_extensions: requiredExtensions
13398
+ };
13399
+ }
12722
13400
  function isPromise(v) {
12723
13401
  return v != null && typeof v.then === "function";
12724
13402
  }
@@ -12835,6 +13513,9 @@ class CatalogInterface {
12835
13513
  const legacy = this.tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
12836
13514
  return isPromise(legacy) ? legacy.then((r) => singleBranchResult(r)) : singleBranchResult(legacy);
12837
13515
  }
13516
+ tableScanBranchesPlan(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData, pushdownFilters) {
13517
+ return this.tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
13518
+ }
12838
13519
  tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
12839
13520
  return null;
12840
13521
  }
@@ -12946,6 +13627,9 @@ class CatalogInterface {
12946
13627
  catalogContentsOwner(_attachOpaqueData) {
12947
13628
  return this;
12948
13629
  }
13630
+ attachOptions(attachOpaqueData) {
13631
+ return attachOptions(attachOpaqueData);
13632
+ }
12949
13633
  transactionBegin(attachOpaqueData) {
12950
13634
  return null;
12951
13635
  }
@@ -13107,9 +13791,9 @@ var TICKET_ENVELOPE_VERSION = 1;
13107
13791
  var MAX_OPTIONS_BYTES = 16 * 1024;
13108
13792
  var MAX_TICKET_CHARS = 32 * 1024;
13109
13793
  var CLOCK_SKEW_SECONDS = 60;
13110
- var UTF82 = new TextEncoder;
13794
+ var UTF83 = new TextEncoder;
13111
13795
  var STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
13112
- var TICKET_AAD_DOMAIN = UTF82.encode("vgi.attach_ticket.v1\x00");
13796
+ var TICKET_AAD_DOMAIN = UTF83.encode("vgi.attach_ticket.v1\x00");
13113
13797
  var TICKET_ID = /^[0-9a-f]{32}$/;
13114
13798
  var B64URL = /^[A-Za-z0-9_-]+$/;
13115
13799
  var MAX_TEXT = 65535;
@@ -13163,14 +13847,14 @@ class SealAttachDeniedError extends Error {
13163
13847
  }
13164
13848
  }
13165
13849
  function attachTicketAad(principal) {
13166
- const p = UTF82.encode(principal);
13850
+ const p = UTF83.encode(principal);
13167
13851
  const out = new Uint8Array(TICKET_AAD_DOMAIN.length + p.length);
13168
13852
  out.set(TICKET_AAD_DOMAIN, 0);
13169
13853
  out.set(p, TICKET_AAD_DOMAIN.length);
13170
13854
  return out;
13171
13855
  }
13172
13856
  function packText(value, name) {
13173
- const raw = UTF82.encode(value);
13857
+ const raw = UTF83.encode(value);
13174
13858
  if (raw.length > MAX_TEXT)
13175
13859
  throw new Error(`${name} is longer than 65535 bytes`);
13176
13860
  const out = new Uint8Array(2 + raw.length);
@@ -13494,8 +14178,9 @@ function buildAttachTicketsProtocol(config) {
13494
14178
  }
13495
14179
 
13496
14180
  // src/protocol/handlers/catalog/admin.ts
13497
- function catalogAdminHandlers(getCatalog, signingKey) {
13498
- const catalogCatalogs = catalogHandler(signingKey, async () => {
14181
+ function catalogAdminHandlers(getCatalog, signingKey, attachSecretKey) {
14182
+ const keys = { signingKey, attachSecretKey };
14183
+ const catalogCatalogs = catalogHandler(keys, async () => {
13499
14184
  const cat = getCatalog();
13500
14185
  const infos = cat.catalogsInfo ? await cat.catalogsInfo() : cat.catalogs().map((name) => ({
13501
14186
  name,
@@ -13526,29 +14211,31 @@ function catalogAdminHandlers(getCatalog, signingKey) {
13526
14211
  result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised));
13527
14212
  result.selected_capabilities = encodeCatalogCapabilities(selectCatalogCapabilities(advertised, clientCapabilities, result.supports_transactions ?? false));
13528
14213
  }
13529
- const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
14214
+ const optionsIpc = innerParams.options == null ? null : toUint8Array(innerParams.options);
14215
+ const secretNames = optionsIpc && optionsIpc.length > 0 ? await secretAttachOptionNames(cat, innerParams.name, deserializeAttachOptionSpec) : new Set;
14216
+ const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey, { optionsIpc, secretNames, attachSecretKey });
13530
14217
  return wrapResult(buildCatalogAttachResult({
13531
14218
  ...result,
13532
14219
  attach_opaque_data: sealedAttach,
13533
14220
  supports_column_statistics: result.supports_column_statistics ?? true
13534
14221
  }), CatalogAttachResultSchema);
13535
14222
  };
13536
- const catalogDetach = catalogHandler(signingKey, async (params) => {
14223
+ const catalogDetach = catalogHandler(keys, async (params) => {
13537
14224
  const cat = getCatalog();
13538
14225
  await cat.detach(toUint8Array(params.attach_opaque_data));
13539
14226
  return {};
13540
14227
  });
13541
- const catalogCreate = catalogHandler(signingKey, async (params) => {
14228
+ const catalogCreate = catalogHandler(keys, async (params) => {
13542
14229
  const cat = getCatalog();
13543
14230
  await cat.create(params.name, params.on_conflict, params.options);
13544
14231
  return {};
13545
14232
  });
13546
- const catalogDrop = catalogHandler(signingKey, async (params) => {
14233
+ const catalogDrop = catalogHandler(keys, async (params) => {
13547
14234
  const cat = getCatalog();
13548
14235
  await cat.drop(params.name);
13549
14236
  return {};
13550
14237
  });
13551
- const catalogVersion = catalogHandler(signingKey, async (params) => {
14238
+ const catalogVersion = catalogHandler(keys, async (params) => {
13552
14239
  const cat = getCatalog();
13553
14240
  const version = await cat.version(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13554
14241
  return wrapResult({ version }, CatalogVersionResultSchema);
@@ -13556,23 +14243,23 @@ function catalogAdminHandlers(getCatalog, signingKey) {
13556
14243
  const catalogTransactionBegin = async (params, ctx) => {
13557
14244
  const auth = ctx?.auth;
13558
14245
  const sealedAttach = params.attach_opaque_data != null ? toUint8Array(params.attach_opaque_data) : new Uint8Array(0);
13559
- const attachPlain = await openAttach(sealedAttach, auth, signingKey);
14246
+ const attachPlain = await openAttach(sealedAttach, auth, signingKey, attachSecretKey);
13560
14247
  const cat = getCatalog();
13561
14248
  const txPlain = await cat.transactionBegin(attachPlain);
13562
14249
  const transaction_opaque_data = txPlain != null ? await sealTransaction(toUint8Array(txPlain), sealedAttach, auth, signingKey) : null;
13563
14250
  return wrapResult({ transaction_opaque_data }, CatalogTransactionBeginResultSchema);
13564
14251
  };
13565
- const catalogTransactionCommit = catalogHandler(signingKey, async (params) => {
14252
+ const catalogTransactionCommit = catalogHandler(keys, async (params) => {
13566
14253
  const cat = getCatalog();
13567
14254
  await cat.transactionCommit(toUint8Array(params.attach_opaque_data), toUint8Array(params.transaction_opaque_data));
13568
14255
  return {};
13569
14256
  });
13570
- const catalogTransactionRollback = catalogHandler(signingKey, async (params) => {
14257
+ const catalogTransactionRollback = catalogHandler(keys, async (params) => {
13571
14258
  const cat = getCatalog();
13572
14259
  await cat.transactionRollback(toUint8Array(params.attach_opaque_data), toUint8Array(params.transaction_opaque_data));
13573
14260
  return {};
13574
14261
  });
13575
- const catalogSchemas = catalogHandler(signingKey, async (params) => {
14262
+ const catalogSchemas = catalogHandler(keys, async (params) => {
13576
14263
  const cat = getCatalog();
13577
14264
  const schemas = await cat.schemas(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13578
14265
  return wrapResult({
@@ -13581,52 +14268,52 @@ function catalogAdminHandlers(getCatalog, signingKey) {
13581
14268
  });
13582
14269
  const catalogContents = async (params, ctx) => {
13583
14270
  const sealedAttach = toUint8Array(params.attach_opaque_data).slice();
13584
- return catalogHandler(signingKey, async (opened, context) => {
14271
+ return catalogHandler(keys, async (opened, context) => {
13585
14272
  const ifNoneMatch = opened.if_none_match == null ? null : String(opened.if_none_match);
13586
14273
  return serveCatalogContents(getCatalog(), toUint8Array(opened.attach_opaque_data), ifNoneMatch, context, sealedAttach);
13587
14274
  })(params, ctx);
13588
14275
  };
13589
- const catalogCopyFromFormats = catalogHandler(signingKey, async (params) => {
14276
+ const catalogCopyFromFormats = catalogHandler(keys, async (params) => {
13590
14277
  const cat = getCatalog();
13591
14278
  const formats = await cat.copyFromFormats(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13592
14279
  return wrapResult({
13593
14280
  items: formats.map((f) => encodeCopyFromFormatInfo(f))
13594
14281
  }, CatalogCopyFromFormatsResultSchema);
13595
14282
  });
13596
- const catalogSchemaGet = catalogHandler(signingKey, async (params) => {
14283
+ const catalogSchemaGet = catalogHandler(keys, async (params) => {
13597
14284
  const cat = getCatalog();
13598
14285
  const info = await cat.schemaGet(toUint8Array(params.attach_opaque_data), params.path, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13599
14286
  return wrapResult({
13600
14287
  items: info ? [encodeSchemaInfo(info)] : []
13601
14288
  }, CatalogSchemaGetResultSchema);
13602
14289
  });
13603
- const catalogSchemaCreate = catalogHandler(signingKey, async (params) => {
14290
+ const catalogSchemaCreate = catalogHandler(keys, async (params) => {
13604
14291
  if (params.options != null)
13605
14292
  throw new MethodNotImplementedError2("catalog_schema_create requires negotiated vgi.schema.options.create.v1");
13606
14293
  const cat = getCatalog();
13607
14294
  await cat.schemaCreate(toUint8Array(params.attach_opaque_data), Array.from(params.path), params.comment, catalogStringMap(params.tags), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined, decodeDictValue(params.on_conflict));
13608
14295
  return {};
13609
14296
  });
13610
- const catalogSchemaDrop = catalogHandler(signingKey, async (params) => {
14297
+ const catalogSchemaDrop = catalogHandler(keys, async (params) => {
13611
14298
  const cat = getCatalog();
13612
14299
  await cat.schemaDrop(toUint8Array(params.attach_opaque_data), params.path, params.ignore_not_found, params.cascade, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13613
14300
  return {};
13614
14301
  });
13615
- const catalogSchemaContentsTables = catalogHandler(signingKey, async (params) => {
14302
+ const catalogSchemaContentsTables = catalogHandler(keys, async (params) => {
13616
14303
  const cat = getCatalog();
13617
14304
  const tables = await cat.schemaContentsTables(toUint8Array(params.attach_opaque_data), params.path, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13618
14305
  return wrapResult({
13619
14306
  items: tables.map((t) => encodeValidatedTableInfo(t))
13620
14307
  }, CatalogSchemaContentsTablesResultSchema);
13621
14308
  });
13622
- const catalogSchemaContentsViews = catalogHandler(signingKey, async (params) => {
14309
+ const catalogSchemaContentsViews = catalogHandler(keys, async (params) => {
13623
14310
  const cat = getCatalog();
13624
14311
  const views = await cat.schemaContentsViews(toUint8Array(params.attach_opaque_data), params.path, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13625
14312
  return wrapResult({
13626
14313
  items: views.map((v) => encodeViewInfo(v))
13627
14314
  }, CatalogSchemaContentsViewsResultSchema);
13628
14315
  });
13629
- const catalogSchemaContentsFunctions = catalogHandler(signingKey, async (params) => {
14316
+ const catalogSchemaContentsFunctions = catalogHandler(keys, async (params) => {
13630
14317
  const cat = getCatalog();
13631
14318
  const funcs = await cat.schemaContentsFunctions(toUint8Array(params.attach_opaque_data), params.path, decodeDictValue(params.type), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13632
14319
  return wrapResult({
@@ -13657,6 +14344,7 @@ function catalogAdminHandlers(getCatalog, signingKey) {
13657
14344
 
13658
14345
  // src/protocol/handlers/catalog/table.ts
13659
14346
  import { MethodNotImplementedError as MethodNotImplementedError4 } from "@query-farm/vgi-rpc";
14347
+ init_arrow();
13660
14348
 
13661
14349
  // src/catalog/unconstrained-columns.ts
13662
14350
  init_arrow();
@@ -13704,15 +14392,16 @@ function requireFlatColumnPath(value, operation) {
13704
14392
  }
13705
14393
  return path;
13706
14394
  }
13707
- function catalogTableHandlers(getCatalog, signingKey) {
13708
- const catalogTableGet = catalogHandler(signingKey, async (params) => {
14395
+ function catalogTableHandlers(getCatalog, signingKey, attachSecretKey) {
14396
+ const keys = { signingKey, attachSecretKey };
14397
+ const catalogTableGet = catalogHandler(keys, async (params) => {
13709
14398
  const cat = getCatalog();
13710
14399
  const info = await cat.tableGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.at_unit, params.at_value, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13711
14400
  return wrapResult({
13712
14401
  items: info ? [encodeValidatedTableInfo(info)] : []
13713
14402
  }, CatalogTableGetResultSchema);
13714
14403
  });
13715
- const catalogTableCreate = catalogHandler(signingKey, async (params) => {
14404
+ const catalogTableCreate = catalogHandler(keys, async (params) => {
13716
14405
  if (params.constraint_definitions == null)
13717
14406
  throw new Error("constraint_definitions is required");
13718
14407
  const definitions = Array.from(params.constraint_definitions, (d) => toUint8Array(d));
@@ -13733,7 +14422,7 @@ function catalogTableHandlers(getCatalog, signingKey) {
13733
14422
  await cat.tableCreate(attach, params.schema_path, params.name, toUint8Array(params.columns), params.on_conflict, definitions, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13734
14423
  return {};
13735
14424
  });
13736
- const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
14425
+ const catalogTableConstraintsApply = catalogHandler(keys, async (params) => {
13737
14426
  const attach = toUint8Array(params.attach_opaque_data);
13738
14427
  const cat = getCatalog();
13739
14428
  const caps = await cat.catalogCapabilities(attach);
@@ -13766,50 +14455,60 @@ function catalogTableHandlers(getCatalog, signingKey) {
13766
14455
  }
13767
14456
  return wrapResult({ table, definition_revision: revision, constraints: snapshot.constraints.map((c) => toUint8Array(c)) }, CatalogTableConstraintsApplyResultSchema);
13768
14457
  });
13769
- const catalogTableDrop = catalogHandler(signingKey, async (params) => {
14458
+ const catalogTableDrop = catalogHandler(keys, async (params) => {
13770
14459
  const cat = getCatalog();
13771
14460
  await cat.tableDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13772
14461
  return {};
13773
14462
  });
13774
- const catalogTableColumnStatisticsGet = catalogHandler(signingKey, async (params) => {
14463
+ const catalogTableColumnStatisticsGet = catalogHandler(keys, async (params) => {
13775
14464
  const cat = getCatalog();
13776
14465
  const stats = await cat.tableColumnStatisticsGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13777
14466
  return { result: stats?.bytes ?? null };
13778
14467
  });
13779
- const catalogTableScanFunctionGet = catalogHandler(signingKey, async (params) => {
14468
+ const catalogTableScanFunctionGet = catalogHandler(keys, async (params) => {
13780
14469
  const cat = getCatalog();
13781
14470
  const scanResult = await cat.tableScanFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.at_unit, params.at_value, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13782
14471
  return wrapResult(scanResult, ScanFunctionResultSchema);
13783
14472
  });
13784
14473
  const optionalTx = (params) => params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined;
13785
- const catalogTableInsertFunctionGet = catalogHandler(signingKey, async (params) => {
14474
+ const catalogTableInsertFunctionGet = catalogHandler(keys, async (params) => {
13786
14475
  const result = await getCatalog().tableInsertFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params), params.writable_branch_function_name ?? null);
13787
14476
  return wrapResult(result, ScanFunctionResultSchema);
13788
14477
  });
13789
- const catalogTableUpdateFunctionGet = catalogHandler(signingKey, async (params) => {
14478
+ const catalogTableUpdateFunctionGet = catalogHandler(keys, async (params) => {
13790
14479
  const result = await getCatalog().tableUpdateFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params));
13791
14480
  return wrapResult(result, ScanFunctionResultSchema);
13792
14481
  });
13793
- const catalogTableDeleteFunctionGet = catalogHandler(signingKey, async (params) => {
14482
+ const catalogTableDeleteFunctionGet = catalogHandler(keys, async (params) => {
13794
14483
  const result = await getCatalog().tableDeleteFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params));
13795
14484
  return wrapResult(result, ScanFunctionResultSchema);
13796
14485
  });
13797
- const catalogTableScanBranchesGet = catalogHandler(signingKey, async (params) => {
14486
+ const catalogTableScanBranchesGet = catalogHandler(keys, async (params) => {
13798
14487
  const cat = getCatalog();
13799
- const branchesResult = await cat.tableScanBranchesGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.at_unit, params.at_value, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
14488
+ const attach = toUint8Array(params.attach_opaque_data);
14489
+ const tx = params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined;
14490
+ const schemaPath = params.schema_path;
14491
+ const name = params.name;
14492
+ const atUnit = params.at_unit;
14493
+ const atValue = params.at_value;
14494
+ const filters = params.pushdown_filters != null ? new ScanPlanningFilters(toUint8Array(params.pushdown_filters), async () => {
14495
+ const info = await cat.tableGet(attach, schemaPath, name, atUnit, atValue, tx);
14496
+ return info && info.columns.length ? deserializeSchema(toUint8Array(info.columns)) : null;
14497
+ }) : null;
14498
+ const branchesResult = await cat.tableScanBranchesPlan(attach, schemaPath, name, atUnit, atValue, tx, filters);
13800
14499
  return wrapResult(branchesResult, ScanBranchesResultSchema);
13801
14500
  });
13802
- const catalogTableCommentSet = catalogHandler(signingKey, async (params) => {
14501
+ const catalogTableCommentSet = catalogHandler(keys, async (params) => {
13803
14502
  const cat = getCatalog();
13804
14503
  await cat.tableCommentSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.comment, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13805
14504
  return {};
13806
14505
  });
13807
- const catalogTableRename = catalogHandler(signingKey, async (params) => {
14506
+ const catalogTableRename = catalogHandler(keys, async (params) => {
13808
14507
  const cat = getCatalog();
13809
14508
  await cat.tableRename(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.new_name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13810
14509
  return {};
13811
14510
  });
13812
- const catalogTableColumnAdd = catalogHandler(signingKey, async (params) => {
14511
+ const catalogTableColumnAdd = catalogHandler(keys, async (params) => {
13813
14512
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_add");
13814
14513
  validateColumnMetadataIpc(toUint8Array(params.column_definition));
13815
14514
  validateColumnExpressionsIpc(toUint8Array(params.column_definition), params.schema_path);
@@ -13817,49 +14516,49 @@ function catalogTableHandlers(getCatalog, signingKey) {
13817
14516
  await cat.tableColumnAdd(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, toUint8Array(params.column_definition), params.ignore_not_found, params.if_column_not_exists, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13818
14517
  return {};
13819
14518
  });
13820
- const catalogTableColumnDrop = catalogHandler(signingKey, async (params) => {
14519
+ const catalogTableColumnDrop = catalogHandler(keys, async (params) => {
13821
14520
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_drop");
13822
14521
  const cat = getCatalog();
13823
14522
  await cat.tableColumnDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.ignore_not_found, params.if_column_exists, params.cascade, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13824
14523
  return {};
13825
14524
  });
13826
- const catalogTableColumnRename = catalogHandler(signingKey, async (params) => {
14525
+ const catalogTableColumnRename = catalogHandler(keys, async (params) => {
13827
14526
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_rename");
13828
14527
  const cat = getCatalog();
13829
14528
  await cat.tableColumnRename(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.new_column_name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13830
14529
  return {};
13831
14530
  });
13832
- const catalogTableColumnCommentSet = catalogHandler(signingKey, async (params) => {
14531
+ const catalogTableColumnCommentSet = catalogHandler(keys, async (params) => {
13833
14532
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_comment_set");
13834
14533
  const cat = getCatalog();
13835
14534
  await cat.tableColumnCommentSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.comment, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13836
14535
  return {};
13837
14536
  });
13838
- const catalogTableColumnDefaultSet = catalogHandler(signingKey, async (params) => {
14537
+ const catalogTableColumnDefaultSet = catalogHandler(keys, async (params) => {
13839
14538
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_default_set");
13840
14539
  const cat = getCatalog();
13841
14540
  await cat.tableColumnDefaultSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, toUint8Array(params.expression), params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13842
14541
  return {};
13843
14542
  });
13844
- const catalogTableColumnDefaultDrop = catalogHandler(signingKey, async (params) => {
14543
+ const catalogTableColumnDefaultDrop = catalogHandler(keys, async (params) => {
13845
14544
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_default_drop");
13846
14545
  const cat = getCatalog();
13847
14546
  await cat.tableColumnDefaultDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13848
14547
  return {};
13849
14548
  });
13850
- const catalogTableColumnTypeChange = catalogHandler(signingKey, async (params) => {
14549
+ const catalogTableColumnTypeChange = catalogHandler(keys, async (params) => {
13851
14550
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_type_change");
13852
14551
  const cat = getCatalog();
13853
14552
  await cat.tableColumnTypeChange(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, toUint8Array(params.column_definition), params.expression == null ? null : toUint8Array(params.expression), params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13854
14553
  return {};
13855
14554
  });
13856
- const catalogTableNotNullSet = catalogHandler(signingKey, async (params) => {
14555
+ const catalogTableNotNullSet = catalogHandler(keys, async (params) => {
13857
14556
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_not_null_set");
13858
14557
  const cat = getCatalog();
13859
14558
  await cat.tableNotNullSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13860
14559
  return {};
13861
14560
  });
13862
- const catalogTableNotNullDrop = catalogHandler(signingKey, async (params) => {
14561
+ const catalogTableNotNullDrop = catalogHandler(keys, async (params) => {
13863
14562
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_not_null_drop");
13864
14563
  const cat = getCatalog();
13865
14564
  await cat.tableNotNullDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.column_path, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -13891,15 +14590,16 @@ function catalogTableHandlers(getCatalog, signingKey) {
13891
14590
  }
13892
14591
 
13893
14592
  // src/protocol/handlers/catalog/view.ts
13894
- function catalogViewHandlers(getCatalog, signingKey) {
13895
- const catalogViewGet = catalogHandler(signingKey, async (params) => {
14593
+ function catalogViewHandlers(getCatalog, signingKey, attachSecretKey) {
14594
+ const keys = { signingKey, attachSecretKey };
14595
+ const catalogViewGet = catalogHandler(keys, async (params) => {
13896
14596
  const cat = getCatalog();
13897
14597
  const info = await cat.viewGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13898
14598
  return wrapResult({
13899
14599
  items: info ? [encodeViewInfo(info)] : []
13900
14600
  }, CatalogViewGetResultSchema);
13901
14601
  });
13902
- const catalogViewCreate = catalogHandler(signingKey, async (params) => {
14602
+ const catalogViewCreate = catalogHandler(keys, async (params) => {
13903
14603
  if (params.security !== "regular")
13904
14604
  throw new Error(`view security mode ${params.security} is unsupported`);
13905
14605
  const tags = catalogStringMap(params.tags);
@@ -13910,22 +14610,22 @@ function catalogViewHandlers(getCatalog, signingKey) {
13910
14610
  await cat.viewCreate(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.definition, decodeDictValue(params.on_conflict), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined, params.aliases ?? [], params.comment, tags, columnComments);
13911
14611
  return {};
13912
14612
  });
13913
- const catalogViewDrop = catalogHandler(signingKey, async (params) => {
14613
+ const catalogViewDrop = catalogHandler(keys, async (params) => {
13914
14614
  const cat = getCatalog();
13915
14615
  await cat.viewDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13916
14616
  return {};
13917
14617
  });
13918
- const catalogViewRename = catalogHandler(signingKey, async (params) => {
14618
+ const catalogViewRename = catalogHandler(keys, async (params) => {
13919
14619
  const cat = getCatalog();
13920
14620
  await cat.viewRename(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.new_name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13921
14621
  return {};
13922
14622
  });
13923
- const catalogViewCommentSet = catalogHandler(signingKey, async (params) => {
14623
+ const catalogViewCommentSet = catalogHandler(keys, async (params) => {
13924
14624
  const cat = getCatalog();
13925
14625
  await cat.viewCommentSet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.comment, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13926
14626
  return {};
13927
14627
  });
13928
- const catalogViewColumnCommentSet = catalogHandler(signingKey, async (params) => {
14628
+ const catalogViewColumnCommentSet = catalogHandler(keys, async (params) => {
13929
14629
  const path = Array.from(params.column_path);
13930
14630
  if (path.length !== 1 || !path[0] || path[0].includes("\x00"))
13931
14631
  throw new Error("view column comments require one raw output identifier");
@@ -13936,15 +14636,16 @@ function catalogViewHandlers(getCatalog, signingKey) {
13936
14636
  }
13937
14637
 
13938
14638
  // src/protocol/handlers/catalog/macro.ts
13939
- function catalogMacroHandlers(getCatalog, signingKey) {
13940
- const catalogMacroGet = catalogHandler(signingKey, async (params) => {
14639
+ function catalogMacroHandlers(getCatalog, signingKey, attachSecretKey) {
14640
+ const keys = { signingKey, attachSecretKey };
14641
+ const catalogMacroGet = catalogHandler(keys, async (params) => {
13941
14642
  const cat = getCatalog();
13942
14643
  const info = await cat.macroGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13943
14644
  return wrapResult({
13944
14645
  items: info ? [encodeMacroInfo(info)] : []
13945
14646
  }, CatalogMacroGetResultSchema);
13946
14647
  });
13947
- const catalogMacroCreate = catalogHandler(signingKey, async (params) => {
14648
+ const catalogMacroCreate = catalogHandler(keys, async (params) => {
13948
14649
  const cat = getCatalog();
13949
14650
  const innerParams = decodeASD(MacroCreateRequestSchema, encodeASD(MacroCreateRequestSchema, params));
13950
14651
  if (!innerParams.overloads?.length)
@@ -13952,12 +14653,12 @@ function catalogMacroHandlers(getCatalog, signingKey) {
13952
14653
  await cat.macroCreate(toUint8Array(innerParams.attach_opaque_data), innerParams.schema_path, innerParams.name, innerParams.macro_type, innerParams.overloads, innerParams.on_conflict, innerParams.transaction_opaque_data ? toUint8Array(innerParams.transaction_opaque_data) : undefined);
13953
14654
  return {};
13954
14655
  });
13955
- const catalogMacroDrop = catalogHandler(signingKey, async (params) => {
14656
+ const catalogMacroDrop = catalogHandler(keys, async (params) => {
13956
14657
  const cat = getCatalog();
13957
14658
  await cat.macroDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13958
14659
  return {};
13959
14660
  });
13960
- const catalogSchemaContentsMacros = catalogHandler(signingKey, async (params) => {
14661
+ const catalogSchemaContentsMacros = catalogHandler(keys, async (params) => {
13961
14662
  const cat = getCatalog();
13962
14663
  const macros = await cat.schemaContentsMacros(toUint8Array(params.attach_opaque_data), params.path, decodeDictValue(params.type), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13963
14664
  return wrapResult({
@@ -13968,15 +14669,16 @@ function catalogMacroHandlers(getCatalog, signingKey) {
13968
14669
  }
13969
14670
 
13970
14671
  // src/protocol/handlers/catalog/index_methods.ts
13971
- function catalogIndexHandlers(getCatalog, signingKey) {
13972
- const catalogSchemaContentsIndexes = catalogHandler(signingKey, async (params) => {
14672
+ function catalogIndexHandlers(getCatalog, signingKey, attachSecretKey) {
14673
+ const keys = { signingKey, attachSecretKey };
14674
+ const catalogSchemaContentsIndexes = catalogHandler(keys, async (params) => {
13973
14675
  const cat = getCatalog();
13974
14676
  const indexes = await cat.schemaContentsIndexes(toUint8Array(params.attach_opaque_data), params.path, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13975
14677
  return wrapResult({
13976
14678
  items: indexes.map((i) => encodeIndexInfo(i))
13977
14679
  }, CatalogSchemaContentsIndexesResultSchema);
13978
14680
  });
13979
- const catalogIndexGet = catalogHandler(signingKey, async (params) => {
14681
+ const catalogIndexGet = catalogHandler(keys, async (params) => {
13980
14682
  const cat = getCatalog();
13981
14683
  const info = await cat.indexGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13982
14684
  return wrapResult({
@@ -13987,14 +14689,14 @@ function catalogIndexHandlers(getCatalog, signingKey) {
13987
14689
  }
13988
14690
 
13989
14691
  // src/protocol/handlers/catalog/index.ts
13990
- function catalogHandlers(catalog, signingKey) {
14692
+ function catalogHandlers(catalog, signingKey, attachSecretKey) {
13991
14693
  const getCatalog = makeGetCatalog(catalog);
13992
14694
  return {
13993
- ...catalogAdminHandlers(getCatalog, signingKey),
13994
- ...catalogTableHandlers(getCatalog, signingKey),
13995
- ...catalogViewHandlers(getCatalog, signingKey),
13996
- ...catalogMacroHandlers(getCatalog, signingKey),
13997
- ...catalogIndexHandlers(getCatalog, signingKey)
14695
+ ...catalogAdminHandlers(getCatalog, signingKey, attachSecretKey),
14696
+ ...catalogTableHandlers(getCatalog, signingKey, attachSecretKey),
14697
+ ...catalogViewHandlers(getCatalog, signingKey, attachSecretKey),
14698
+ ...catalogMacroHandlers(getCatalog, signingKey, attachSecretKey),
14699
+ ...catalogIndexHandlers(getCatalog, signingKey, attachSecretKey)
13998
14700
  };
13999
14701
  }
14000
14702
 
@@ -14005,11 +14707,12 @@ function buildVgiService(config) {
14005
14707
  ...functionHandlers({
14006
14708
  registry: config.registry,
14007
14709
  signingKey: config.signingKey,
14710
+ attachSecretKey: config.attachSecretKey,
14008
14711
  catalogInterface: config.catalogInterface
14009
14712
  }),
14010
14713
  ...aggregateHandlers(config.registry),
14011
- ...tableBufferingHandlers(config.registry, config.signingKey),
14012
- ...catalogHandlers(config.catalogInterface, config.signingKey)
14714
+ ...tableBufferingHandlers(config.registry, config.signingKey, config.attachSecretKey),
14715
+ ...catalogHandlers(config.catalogInterface, config.signingKey, config.attachSecretKey)
14013
14716
  };
14014
14717
  }
14015
14718
  function buildVgiProtocol(config) {
@@ -15588,8 +16291,10 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
15588
16291
  if (options.perAttachItemIds)
15589
16292
  this.perAttachItemIds = true;
15590
16293
  for (const sch of descriptor.schemas ?? [])
15591
- for (const tbl of sch.tables ?? [])
16294
+ for (const tbl of sch.tables ?? []) {
15592
16295
  validateWritableTable(tbl);
16296
+ validateTableScanPlanning(tbl);
16297
+ }
15593
16298
  for (const sch of descriptor.schemas ?? []) {
15594
16299
  for (const fn of sch.functions ?? [])
15595
16300
  registry.registerInSchema(fn, schemaDescriptorPath(sch), descriptor.name);
@@ -15834,7 +16539,8 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
15834
16539
  delete_function: t.deleteFunction ? inlineScanFunction(t.deleteFunction, undefined, this._schemaForFunction(t.deleteFunction)) : null,
15835
16540
  cardinality_estimate: t.inlinedCardinality ? Number(t.inlinedCardinality.estimate) : null,
15836
16541
  cardinality_max: t.inlinedCardinality ? Number(t.inlinedCardinality.max) : null,
15837
- required_filters: requiredFilters
16542
+ required_filters: requiredFilters,
16543
+ scan_planning: t.scanPlanning ?? SCAN_PLANNING_BIND
15838
16544
  };
15839
16545
  }));
15840
16546
  validateForeignKeyTargets(infos.map((info) => ({ schemaPath: info.schema_path, name: info.name, constraints: info.constraints })));
@@ -16367,6 +17073,12 @@ function sameSpelling(left, right) {
16367
17073
  function writeFunctionOf(table, operation) {
16368
17074
  return operation === "insert" ? table.insertFunction : operation === "update" ? table.updateFunction : table.deleteFunction;
16369
17075
  }
17076
+ function validateTableScanPlanning(table) {
17077
+ validateScanPlanning(table.name, table.scanPlanning, false);
17078
+ if (table.scanPlanning === SCAN_PLANNING_FILTERED && (table.function || !table.columns)) {
17079
+ throw new Error(`Table '${table.name}': scanPlanning 'filtered' requires columns and no function; the catalog's ` + "tableScanBranchesPlan supplies the scan per query");
17080
+ }
17081
+ }
16370
17082
  function validateWritableTable(table) {
16371
17083
  const modes = validateWriteResultModes(table.writeResultModes ?? {});
16372
17084
  for (const operation of Object.keys(modes)) {
@@ -16507,6 +17219,9 @@ class CompositeCatalogInterface extends CatalogInterface {
16507
17219
  async tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
16508
17220
  return await this._route(attachOpaqueData).tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
16509
17221
  }
17222
+ async tableScanBranchesPlan(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData, pushdownFilters) {
17223
+ return await this._route(attachOpaqueData).tableScanBranchesPlan(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData, pushdownFilters);
17224
+ }
16510
17225
  async tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
16511
17226
  return await this._route(attachOpaqueData).tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
16512
17227
  }
@@ -17004,7 +17719,10 @@ export {
17004
17719
  PARENT_ROW_METADATA_KEY,
17005
17720
  ROW_SCALAR_EXPRESSION,
17006
17721
  ReadOnlyCatalogInterface,
17722
+ SCAN_PLANNING_BIND,
17723
+ SCAN_PLANNING_FILTERED,
17007
17724
  ScanFunctionResultSchema,
17725
+ ScanPlanningFilters,
17008
17726
  StatusError2 as StatusError,
17009
17727
  TRANSACTION_DDL,
17010
17728
  TimeUnit2 as TimeUnit,
@@ -17022,6 +17740,7 @@ export {
17022
17740
  buildConstraintChange,
17023
17741
  buildConstraintDefinition,
17024
17742
  buildMacroOverload,
17743
+ buildScanBranchesResult,
17025
17744
  buildStatisticsBatch,
17026
17745
  cacheControlMetadata,
17027
17746
  canonicalIndex,
@@ -17077,6 +17796,7 @@ export {
17077
17796
  encodeSqlExpression,
17078
17797
  field2 as field,
17079
17798
  filterBatch,
17799
+ filtersMayMatch,
17080
17800
  fixedSizeBinary2 as fixedSizeBinary,
17081
17801
  fixedSizeList2 as fixedSizeList,
17082
17802
  float162 as float16,
@@ -17160,4 +17880,4 @@ export {
17160
17880
  validateTableConstraints
17161
17881
  };
17162
17882
 
17163
- //# debugId=FAC9CCEE4111237264756E2164756E21
17883
+ //# debugId=A2EDD9D8BB9FFE7F64756E2164756E21