@query-farm/vgi 0.49.1 → 0.50.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 (38) hide show
  1. package/README.md +1 -1
  2. package/dist/catalog/composite.d.ts +1 -1
  3. package/dist/catalog/descriptors.d.ts +34 -2
  4. package/dist/catalog/interface.d.ts +47 -8
  5. package/dist/catalog/read-only.d.ts +48 -1
  6. package/dist/client/client.d.ts +13 -7
  7. package/dist/client-entry.d.ts +1 -1
  8. package/dist/client-entry.js +40 -16
  9. package/dist/client-entry.js.map +6 -6
  10. package/dist/functions/storage.d.ts +7 -0
  11. package/dist/generated/vgi-client.d.ts +4 -0
  12. package/dist/generated/vgi-protocol-schemas.d.ts +2 -2
  13. package/dist/generated/vgi-service.d.ts +7 -26
  14. package/dist/index.core.d.ts +4 -3
  15. package/dist/index.js +285 -186
  16. package/dist/index.js.map +17 -17
  17. package/dist/protocol/dispatch.d.ts +5 -3
  18. package/dist/serve-entry.js +63 -61
  19. package/dist/serve-entry.js.map +10 -10
  20. package/dist/worker-cf-entry.js +241 -170
  21. package/dist/worker-cf-entry.js.map +16 -16
  22. package/dist/write-results.d.ts +8 -1
  23. package/package.json +1 -1
  24. package/src/catalog/composite.ts +2 -2
  25. package/src/catalog/descriptors.ts +35 -2
  26. package/src/catalog/interface.ts +78 -10
  27. package/src/catalog/read-only.ts +297 -175
  28. package/src/client/client.ts +22 -13
  29. package/src/client-entry.ts +4 -0
  30. package/src/filter-pushdown/evaluate.ts +30 -14
  31. package/src/functions/storage.ts +44 -3
  32. package/src/generated/vgi-client.ts +6 -1
  33. package/src/generated/vgi-protocol-schemas.ts +8 -12
  34. package/src/generated/vgi-service.ts +9 -48
  35. package/src/index.core.ts +4 -3
  36. package/src/protocol/dispatch.ts +5 -3
  37. package/src/protocol/handlers/catalog/table.ts +14 -21
  38. package/src/write-results.ts +8 -3
@@ -22,7 +22,7 @@ import {
22
22
  encodeScanFunctionResult,
23
23
  buildCatalogAttachResult,
24
24
  } from "./interface.js";
25
- import { schemaDescriptorPath, type CatalogDescriptor, type SchemaDescriptor, type TableDescriptor, type ViewDescriptor, type MacroDescriptor, type SettingDescriptor, type SecretTypeDescriptor, type ForeignKeyDef, type DefaultValue } from "./descriptors.js";
25
+ import { schemaDescriptorPath, FUNCTION_VISIBILITY_PUBLIC, FUNCTION_VISIBILITY_TABLE_ONLY, type FunctionVisibility, type CatalogDescriptor, type SchemaDescriptor, type TableDescriptor, type ViewDescriptor, type MacroDescriptor, type SettingDescriptor, type SecretTypeDescriptor, type ForeignKeyDef, type DefaultValue } from "./descriptors.js";
26
26
  import { serializeColumnStatistics } from "../util/statistics.js";
27
27
  import { SCAN_PLANNING_BIND, SCAN_PLANNING_FILTERED, validateScanPlanning } from "./scan-planning.js";
28
28
  import type { VgiFunction } from "../functions/types.js";
@@ -108,6 +108,13 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
108
108
  private _functionListings = new Map<SchemaDescriptor, Map<FunctionListingKind, readonly FunctionInfo[]>>();
109
109
  /** One frozen FunctionInfo per (declaring schema, function), shared by listings and `global_functions`. */
110
110
  private _functionInfos = new Map<SchemaDescriptor, Map<VgiFunction, FunctionInfo>>();
111
+ /**
112
+ * Protocol 3.3: every function each schema's listing carries, in order, with
113
+ * its visibility -- the schema's own `functions`, then each of its tables'
114
+ * scan and write functions that no schema declares (see
115
+ * `buildFunctionListings`).
116
+ */
117
+ private _builtListings?: ReturnType<typeof buildFunctionListings>;
111
118
 
112
119
  constructor(
113
120
  descriptor: CatalogDescriptor,
@@ -145,6 +152,24 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
145
152
  }
146
153
  }
147
154
 
155
+ /** Per-schema listings, built on first use (the descriptor is immutable from then on). */
156
+ private get _listings(): Map<SchemaDescriptor, Map<VgiFunction, FunctionVisibility>> {
157
+ return (this._builtListings ??= buildFunctionListings(this._descriptor)).listings;
158
+ }
159
+
160
+ /** The schema whose listing carries each function (first one wins). */
161
+ private get _listedIn(): Map<VgiFunction, SchemaDescriptor> {
162
+ return (this._builtListings ??= buildFunctionListings(this._descriptor)).listedIn;
163
+ }
164
+
165
+ /**
166
+ * The visibility `fn` is listed with in `schema` (protocol 3.3), or null
167
+ * when that schema's listing does not carry it.
168
+ */
169
+ functionVisibility(schema: SchemaDescriptor, fn: VgiFunction): FunctionVisibility | null {
170
+ return this._listings.get(schema)?.get(fn) ?? null;
171
+ }
172
+
148
173
  /**
149
174
  * Which schema declares `fn`, by object identity, or null if no schema does.
150
175
  *
@@ -162,10 +187,11 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
162
187
  * Mirrors vgi-python's `ReadOnlyCatalogInterface._schema_for_function`.
163
188
  */
164
189
  private _schemaForFunction(fn: VgiFunction): string[] | null {
165
- for (const sch of this._descriptor.schemas ?? []) {
166
- if ((sch.functions ?? []).includes(fn)) return schemaDescriptorPath(sch);
167
- }
168
- return null;
190
+ // Protocol 3.3: a table's scan/write function is always listed -- in the
191
+ // schema that declares it, else in its table's schema as table_only -- so
192
+ // this is null only for a function no listing carries.
193
+ const sch = this._listedIn.get(fn);
194
+ return sch ? schemaDescriptorPath(sch) : null;
169
195
  }
170
196
 
171
197
  catalogs(): string[] {
@@ -350,7 +376,9 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
350
376
  // partitioned by kind to match python's behavior.
351
377
  private _estimatedObjectCount(s: SchemaDescriptor): Record<string, number> {
352
378
  let scalar = 0, aggregate = 0, table = 0;
353
- for (const f of s.functions ?? []) {
379
+ // Count what the listing carries: a table's auto-included scan/write
380
+ // functions too, or a zero count would make the client skip the listing.
381
+ for (const f of this._listings.get(s)?.keys() ?? []) {
354
382
  if (f.kind === "scalar") scalar++;
355
383
  else if ((f.kind as string) === "aggregate") aggregate++;
356
384
  else table++; // "table" and "table_in_out"
@@ -501,8 +529,8 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
501
529
  write_result_modes: writeResultModesFor(t),
502
530
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
503
531
  // Inline scan_function only for purely function-backed tables.
504
- // When explicit `columns` are also declared, the table is on the
505
- // legacy catalog_table_scan_function_get path; inlining would
532
+ // When explicit `columns` are also declared, the scan is resolved per
533
+ // call through catalog_table_scan_branches_get; inlining would
506
534
  // shadow the per-call dispatch and prevent workers from varying
507
535
  // the scan function (e.g. version-resolved time-travel).
508
536
  scan_function: t.function && !t.columns
@@ -576,7 +604,9 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
576
604
  transactionOpaqueData?: TransactionOpaqueData
577
605
  ): FunctionInfo[] {
578
606
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
579
- if (!schema || !schema.functions) return [];
607
+ const entries = schema ? this._listings.get(schema) : undefined;
608
+ if (!schema || !entries || entries.size === 0) return [];
609
+ const listed = [...entries.keys()];
580
610
 
581
611
  // Filter by SchemaObjectType (lowercase on the wire: scalar_function,
582
612
  // table_function, aggregate_function). Unknown filter values pass
@@ -587,7 +617,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
587
617
  // Schema names match case-insensitively, and an item's schema_path keeps
588
618
  // the caller's spelling, so a differently-spelled request is built fresh,
589
619
  // exactly as before, rather than growing the cache per spelling.
590
- return schema.functions.filter((f) => inListing(f, kind)).map((f) => this._functionToInfo(f, path));
620
+ return listed.filter((f) => inListing(f, kind)).map((f) => this._functionToInfo(f, path, entries.get(f)!));
591
621
  }
592
622
  let listings = this._functionListings.get(schema);
593
623
  if (!listings) {
@@ -597,7 +627,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
597
627
  let listing = listings.get(kind);
598
628
  if (!listing) {
599
629
  listing = Object.freeze(
600
- schema.functions.filter((f) => inListing(f, kind)).map((f) => this._sharedFunctionInfo(schema, f)),
630
+ listed.filter((f) => inListing(f, kind)).map((f) => this._sharedFunctionInfo(schema, f)),
601
631
  );
602
632
  listings.set(kind, listing);
603
633
  }
@@ -621,7 +651,8 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
621
651
  // Cloned before freezing: the built item shares arrays with the function's
622
652
  // own metadata (categories, monotonicity, ...), which must stay the
623
653
  // author's to do with as they like.
624
- info = freezeCatalogItem(structuredClone(this._functionToInfo(f, schemaDescriptorPath(schema))));
654
+ const visibility = this.functionVisibility(schema, f) ?? FUNCTION_VISIBILITY_PUBLIC;
655
+ info = freezeCatalogItem(structuredClone(this._functionToInfo(f, schemaDescriptorPath(schema), visibility)));
625
656
  infos.set(f, info);
626
657
  }
627
658
  return info;
@@ -635,167 +666,8 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
635
666
  * (schema contents *and* `global_functions`) must carry the same value in
636
667
  * both. Shared by `schemaContentsFunctions` and `_globalFunctionInfos`.
637
668
  */
638
- private _functionToInfo(f: VgiFunction, path: string[]): FunctionInfo {
639
- const meta = resolveMetadata(f);
640
- const argSchema = argumentSpecsToSchema(f.argumentSpecs);
641
- const argBytes = serializeSchema(argSchema);
642
- const defaults = f.meta.parameterDefaultValues ?? null;
643
- if (defaults) {
644
- if (defaults.numRows !== 1) {
645
- throw new Error(`parameterDefaultValues must contain exactly one row, got ${defaults.numRows}`);
646
- }
647
- let argumentIndex = 0;
648
- for (const defaultField of defaults.schema.fields) {
649
- while (argumentIndex < argSchema.fields.length && argSchema.fields[argumentIndex]!.name !== defaultField.name) {
650
- argumentIndex++;
651
- }
652
- if (argumentIndex === argSchema.fields.length) {
653
- throw new Error(`parameterDefaultValues field '${defaultField.name}' is not in argument signature order`);
654
- }
655
- const argumentField = argSchema.fields[argumentIndex]!;
656
- if (typeSignature(argumentField.type) !== typeSignature(defaultField.type)) {
657
- throw new Error(
658
- `parameterDefaultValues field '${defaultField.name}' has type ${typeSignature(defaultField.type)}, ` +
659
- `expected ${typeSignature(argumentField.type)}`,
660
- );
661
- }
662
- argumentIndex++;
663
- }
664
- }
665
-
666
- // Use the function's default output schema if available,
667
- // otherwise empty schema (table functions determine output at bind time)
668
- const outputSchemaBytes = serializeSchema(
669
- f.defaultOutputSchema ?? schema_([])
670
- );
671
-
672
- // Every validated requirement reaches the wire: type, scope and name.
673
- const requiredSecrets = meta.requiredSecrets.map((s) => ({
674
- secret_type: s.secretType,
675
- scope: s.scope,
676
- secret_name: s.secretName,
677
- }));
678
-
679
- // Function-level tags surfaced into duckdb_functions().tags. The wire
680
- // map is string→string, so the metadata linter (vgi-lint-check) and any
681
- // worker-side conventions (e.g. VGI307's `vgi.columns_md` on a dynamic
682
- // table function) can read them. Worker-provided tags are MERGED OVER
683
- // any SDK-derived tags rather than replacing them — and derived tags
684
- // never clobber worker-set keys. There are no SDK-derived function tags
685
- // today (examples flow into FunctionInfo.examples, not a tag), so the
686
- // derived base is empty; the merge keeps that invariant if one is ever
687
- // added.
688
- const derivedTags: Record<string, string> = {};
689
- const tags: Record<string, string> = { ...derivedTags, ...(meta.tags ?? {}) };
690
-
691
- return {
692
- comment: null,
693
- tags,
694
- name: f.meta.name,
695
- schema_path: normalizeSchemaPath(path),
696
- function_type: meta.functionType.toUpperCase() as "SCALAR" | "TABLE" | "TABLE_BUFFERING" | "AGGREGATE",
697
- arguments: argBytes,
698
- output_schema: outputSchemaBytes,
699
- parameter_default_values: defaults
700
- ? serializeBatch(defaults)
701
- : null,
702
- stability: meta.stability as any,
703
- null_handling: meta.nullHandling as any,
704
- argument_monotonicity: meta.argumentMonotonicity,
705
- description: meta.description,
706
- examples: meta.examples.map((e) => ({
707
- sql: e.sql,
708
- description: e.description,
709
- expected_output: null,
710
- })),
711
- categories: meta.categories,
712
- projection_pushdown: meta.projectionPushdown,
713
- filter_pushdown: meta.filterPushdown,
714
- sampling_pushdown: meta.samplingPushdown,
715
- // Mirror Python: None for scalars, the meta flag for table functions.
716
- // The C++ extension only honours this for rowid-bearing tables.
717
- late_materialization:
718
- (f.kind as string) === "table" && f.meta.lateMaterialization === true ? true : null,
719
- filter_semantic_profiles: meta.filterSemanticProfiles,
720
- additional_filter_functions: meta.additionalFilterFunctions.map((value) => ({
721
- namespace: value.namespace, name: value.name, version: BigInt(value.version) as any,
722
- })),
723
- runtime_filter_algorithms: meta.runtimeFilterAlgorithms.map((value) => ({
724
- namespace: value.namespace, name: value.name, version: BigInt(value.version) as any,
725
- })),
726
- filter_evaluation_contexts: meta.filterEvaluationContexts.map((value) => ({
727
- profile: value.profile, provider_fingerprint: value.providerFingerprint,
728
- })),
729
- order_preservation: meta.preservesOrder as any,
730
- max_workers: meta.maxWorkers ?? DEFAULT_MAX_WORKERS,
731
- // Opt-in features the read-only catalog's functions do not use; the
732
- // regenerated FunctionInfo schema requires these non-nullable
733
- // fields, so default them explicitly. table_buffering functions
734
- // thread their batch_index requirement through supports_batch_index
735
- // so the C++ operator declares RequiredPartitionInfo=BatchIndex.
736
- supports_batch_index:
737
- ((f.kind as string) === "table_buffering" && f.meta.requiresInputBatchIndex === true) ||
738
- ((f.kind as string) === "table" && f.meta.supportsBatchIndex === true),
739
- // Split-based scan planning (protocol 1.4.0). A function opts in by
740
- // declaring `supportsSplits` AND implementing plan()/onSplit(): the
741
- // declaration is what a distributed engine reads to decide it can
742
- // retry a task, because a split NAMES its work and re-running one
743
- // reads exactly the same rows.
744
- supports_splits: (f.kind as string) === "table" && f.meta.supportsSplits === true,
745
- // The worker applies pushed filters EXACTLY, so the engine may drop
746
- // its own copy. Wrong answers if declared falsely.
747
- filters_exactly_applied:
748
- (f.kind as string) === "table" && f.meta.filtersExactlyApplied === true,
749
- // Addressable positions in the data, for incremental/streaming reads.
750
- supports_positions: (f.kind as string) === "table" && f.meta.supportsPositions === true,
751
- // null means UNBOUNDED, not "expires immediately" — a client must not
752
- // assume a TTL exists, or long-running streams are foreclosed.
753
- split_token_ttl_seconds:
754
- (f.kind as string) === "table" ? (f.meta.splitTokenTtlSeconds ?? null) : null,
755
- partition_kind:
756
- (f.kind as string) === "table" && f.meta.partitionKind
757
- ? f.meta.partitionKind
758
- : "NOT_PARTITIONED",
759
- order_dependent: meta.orderDependent as any,
760
- distinct_dependent: meta.distinctDependent as any,
761
- supports_window: false,
762
- streaming_partitioned: false,
763
- // table_in_out functions with a finalize callback, AND every
764
- // table_buffering function (the Source phase always runs), get the
765
- // FINALIZE init() phase. Advertising has_finalize=true on a function
766
- // without it makes DuckDB call FinalExecute and crash with
767
- // 'FinalExecute not supported for project_input'.
768
- has_finalize:
769
- (f.kind === "table_in_out" && f.meta.hasFinalize === true) ||
770
- (f.kind as string) === "table_buffering",
771
- source_order_dependent:
772
- (f.kind as string) === "table_buffering" && f.meta.sourceOrderDependent === true,
773
- sink_order_dependent:
774
- (f.kind as string) === "table_buffering" && f.meta.sinkOrderDependent === true,
775
- requires_input_batch_index:
776
- (f.kind as string) === "table_buffering" && f.meta.requiresInputBatchIndex === true,
777
- // Blended ("UNNEST-style") table-in-out: positional args ARE the
778
- // per-row input columns (real typed args, no TABLE placeholder), so
779
- // one registration serves literal / column / LATERAL call shapes.
780
- // Set by defineRowTransformFunction; the C++ extension reads it to
781
- // enter the in-out registration branch with real-typed args and
782
- // drive the literal single-row scan-mode. False for scalars —
783
- // mirrors Python's `input_from_args=False if is_scalar else ...`.
784
- input_from_args:
785
- f.kind === "table_in_out" && f.meta.inputFromArgs === true,
786
- // Blended only: the most input rows per worker call (null = a whole
787
- // chunk). Mirrors Python's `None if is_scalar else ...`.
788
- input_rows_per_call:
789
- f.kind === "table_in_out" && f.meta.inputFromArgs === true
790
- ? (f.meta.inputRowsPerCall ?? null)
791
- : null,
792
- required_settings: meta.requiredSettings,
793
- required_secrets: requiredSecrets.map((s) => ({
794
- secret_type: s.secret_type,
795
- scope: s.scope,
796
- secret_name: s.secret_name,
797
- })),
798
- };
669
+ private _functionToInfo(f: VgiFunction, path: string[], visibility: FunctionVisibility): FunctionInfo {
670
+ return functionInfoFor(f, path, visibility);
799
671
  }
800
672
 
801
673
  /**
@@ -1335,8 +1207,8 @@ function inferScalarType(val: any): VgiDataType {
1335
1207
  // Mirrors python's _inline_function_result: a serialized one-row batch of
1336
1208
  // ScanFunctionResultSchema (function_name, arguments, required_extensions,
1337
1209
  // schema_path). The C++ extension uses these bytes verbatim and skips the
1338
- // catalog_table_scan_function_get RPC, so the schema this inlines has to agree
1339
- // with what that RPC would have answered.
1210
+ // catalog_table_scan_branches_get RPC, so what this inlines has to agree with
1211
+ // the one branch that RPC would have answered.
1340
1212
  function inlineScanFunction(
1341
1213
  func: VgiFunction,
1342
1214
  args: Arguments | undefined,
@@ -1369,6 +1241,189 @@ function sameSpelling(left: Iterable<unknown> | string, right: Iterable<unknown>
1369
1241
  return a.length === b.length && a.every((part, i) => part === b[i]);
1370
1242
  }
1371
1243
 
1244
+ /**
1245
+ * Build the wire `FunctionInfo` a schema listing carries for `f`.
1246
+ *
1247
+ * `schemaPath` is the schema the function is listed in (the bind-dispatch
1248
+ * key). `visibility` is protocol 3.3's `FunctionInfo.visibility`: pass
1249
+ * `FUNCTION_VISIBILITY_TABLE_ONLY` for a table's scan or write function that
1250
+ * must not be callable from SQL. A hand-written `CatalogInterface` uses this
1251
+ * from `schemaContentsFunctions` to list the functions its tables name (the
1252
+ * client takes their capabilities only from the listing and refuses a table
1253
+ * whose function no listing carries). `ReadOnlyCatalogInterface` builds its
1254
+ * listings with it.
1255
+ */
1256
+ export function functionInfoFor(
1257
+ f: VgiFunction,
1258
+ schemaPath: string[],
1259
+ visibility: FunctionVisibility = FUNCTION_VISIBILITY_PUBLIC,
1260
+ ): FunctionInfo {
1261
+ const path = schemaPath;
1262
+ const meta = resolveMetadata(f);
1263
+ const argSchema = argumentSpecsToSchema(f.argumentSpecs);
1264
+ const argBytes = serializeSchema(argSchema);
1265
+ const defaults = f.meta.parameterDefaultValues ?? null;
1266
+ if (defaults) {
1267
+ if (defaults.numRows !== 1) {
1268
+ throw new Error(`parameterDefaultValues must contain exactly one row, got ${defaults.numRows}`);
1269
+ }
1270
+ let argumentIndex = 0;
1271
+ for (const defaultField of defaults.schema.fields) {
1272
+ while (argumentIndex < argSchema.fields.length && argSchema.fields[argumentIndex]!.name !== defaultField.name) {
1273
+ argumentIndex++;
1274
+ }
1275
+ if (argumentIndex === argSchema.fields.length) {
1276
+ throw new Error(`parameterDefaultValues field '${defaultField.name}' is not in argument signature order`);
1277
+ }
1278
+ const argumentField = argSchema.fields[argumentIndex]!;
1279
+ if (typeSignature(argumentField.type) !== typeSignature(defaultField.type)) {
1280
+ throw new Error(
1281
+ `parameterDefaultValues field '${defaultField.name}' has type ${typeSignature(defaultField.type)}, ` +
1282
+ `expected ${typeSignature(argumentField.type)}`,
1283
+ );
1284
+ }
1285
+ argumentIndex++;
1286
+ }
1287
+ }
1288
+
1289
+ // Use the function's default output schema if available,
1290
+ // otherwise empty schema (table functions determine output at bind time)
1291
+ const outputSchemaBytes = serializeSchema(
1292
+ f.defaultOutputSchema ?? schema_([])
1293
+ );
1294
+
1295
+ // Every validated requirement reaches the wire: type, scope and name.
1296
+ const requiredSecrets = meta.requiredSecrets.map((s) => ({
1297
+ secret_type: s.secretType,
1298
+ scope: s.scope,
1299
+ secret_name: s.secretName,
1300
+ }));
1301
+
1302
+ // Function-level tags surfaced into duckdb_functions().tags. The wire
1303
+ // map is string→string, so the metadata linter (vgi-lint-check) and any
1304
+ // worker-side conventions (e.g. VGI307's `vgi.columns_md` on a dynamic
1305
+ // table function) can read them. Worker-provided tags are MERGED OVER
1306
+ // any SDK-derived tags rather than replacing them — and derived tags
1307
+ // never clobber worker-set keys. There are no SDK-derived function tags
1308
+ // today (examples flow into FunctionInfo.examples, not a tag), so the
1309
+ // derived base is empty; the merge keeps that invariant if one is ever
1310
+ // added.
1311
+ const derivedTags: Record<string, string> = {};
1312
+ const tags: Record<string, string> = { ...derivedTags, ...(meta.tags ?? {}) };
1313
+
1314
+ return {
1315
+ comment: null,
1316
+ tags,
1317
+ name: f.meta.name,
1318
+ schema_path: normalizeSchemaPath(path),
1319
+ function_type: meta.functionType.toUpperCase() as "SCALAR" | "TABLE" | "TABLE_BUFFERING" | "AGGREGATE",
1320
+ arguments: argBytes,
1321
+ output_schema: outputSchemaBytes,
1322
+ parameter_default_values: defaults
1323
+ ? serializeBatch(defaults)
1324
+ : null,
1325
+ stability: meta.stability as any,
1326
+ null_handling: meta.nullHandling as any,
1327
+ argument_monotonicity: meta.argumentMonotonicity,
1328
+ description: meta.description,
1329
+ examples: meta.examples.map((e) => ({
1330
+ sql: e.sql,
1331
+ description: e.description,
1332
+ expected_output: null,
1333
+ })),
1334
+ categories: meta.categories,
1335
+ projection_pushdown: meta.projectionPushdown,
1336
+ filter_pushdown: meta.filterPushdown,
1337
+ sampling_pushdown: meta.samplingPushdown,
1338
+ // Mirror Python: None for scalars, the meta flag for table functions.
1339
+ // The C++ extension only honours this for rowid-bearing tables.
1340
+ late_materialization:
1341
+ (f.kind as string) === "table" && f.meta.lateMaterialization === true ? true : null,
1342
+ filter_semantic_profiles: meta.filterSemanticProfiles,
1343
+ additional_filter_functions: meta.additionalFilterFunctions.map((value) => ({
1344
+ namespace: value.namespace, name: value.name, version: BigInt(value.version) as any,
1345
+ })),
1346
+ runtime_filter_algorithms: meta.runtimeFilterAlgorithms.map((value) => ({
1347
+ namespace: value.namespace, name: value.name, version: BigInt(value.version) as any,
1348
+ })),
1349
+ filter_evaluation_contexts: meta.filterEvaluationContexts.map((value) => ({
1350
+ profile: value.profile, provider_fingerprint: value.providerFingerprint,
1351
+ })),
1352
+ order_preservation: meta.preservesOrder as any,
1353
+ max_workers: meta.maxWorkers ?? DEFAULT_MAX_WORKERS,
1354
+ // Opt-in features the read-only catalog's functions do not use; the
1355
+ // regenerated FunctionInfo schema requires these non-nullable
1356
+ // fields, so default them explicitly. table_buffering functions
1357
+ // thread their batch_index requirement through supports_batch_index
1358
+ // so the C++ operator declares RequiredPartitionInfo=BatchIndex.
1359
+ supports_batch_index:
1360
+ ((f.kind as string) === "table_buffering" && f.meta.requiresInputBatchIndex === true) ||
1361
+ ((f.kind as string) === "table" && f.meta.supportsBatchIndex === true),
1362
+ // Split-based scan planning (protocol 1.4.0). A function opts in by
1363
+ // declaring `supportsSplits` AND implementing plan()/onSplit(): the
1364
+ // declaration is what a distributed engine reads to decide it can
1365
+ // retry a task, because a split NAMES its work and re-running one
1366
+ // reads exactly the same rows.
1367
+ supports_splits: (f.kind as string) === "table" && f.meta.supportsSplits === true,
1368
+ // The worker applies pushed filters EXACTLY, so the engine may drop
1369
+ // its own copy. Wrong answers if declared falsely.
1370
+ filters_exactly_applied:
1371
+ (f.kind as string) === "table" && f.meta.filtersExactlyApplied === true,
1372
+ // Addressable positions in the data, for incremental/streaming reads.
1373
+ supports_positions: (f.kind as string) === "table" && f.meta.supportsPositions === true,
1374
+ // null means UNBOUNDED, not "expires immediately" — a client must not
1375
+ // assume a TTL exists, or long-running streams are foreclosed.
1376
+ split_token_ttl_seconds:
1377
+ (f.kind as string) === "table" ? (f.meta.splitTokenTtlSeconds ?? null) : null,
1378
+ partition_kind:
1379
+ (f.kind as string) === "table" && f.meta.partitionKind
1380
+ ? f.meta.partitionKind
1381
+ : "NOT_PARTITIONED",
1382
+ order_dependent: meta.orderDependent as any,
1383
+ distinct_dependent: meta.distinctDependent as any,
1384
+ supports_window: false,
1385
+ streaming_partitioned: false,
1386
+ // table_in_out functions with a finalize callback, AND every
1387
+ // table_buffering function (the Source phase always runs), get the
1388
+ // FINALIZE init() phase. Advertising has_finalize=true on a function
1389
+ // without it makes DuckDB call FinalExecute and crash with
1390
+ // 'FinalExecute not supported for project_input'.
1391
+ has_finalize:
1392
+ (f.kind === "table_in_out" && f.meta.hasFinalize === true) ||
1393
+ (f.kind as string) === "table_buffering",
1394
+ source_order_dependent:
1395
+ (f.kind as string) === "table_buffering" && f.meta.sourceOrderDependent === true,
1396
+ sink_order_dependent:
1397
+ (f.kind as string) === "table_buffering" && f.meta.sinkOrderDependent === true,
1398
+ requires_input_batch_index:
1399
+ (f.kind as string) === "table_buffering" && f.meta.requiresInputBatchIndex === true,
1400
+ // Blended ("UNNEST-style") table-in-out: positional args ARE the
1401
+ // per-row input columns (real typed args, no TABLE placeholder), so
1402
+ // one registration serves literal / column / LATERAL call shapes.
1403
+ // Set by defineRowTransformFunction; the C++ extension reads it to
1404
+ // enter the in-out registration branch with real-typed args and
1405
+ // drive the literal single-row scan-mode. False for scalars —
1406
+ // mirrors Python's `input_from_args=False if is_scalar else ...`.
1407
+ input_from_args:
1408
+ f.kind === "table_in_out" && f.meta.inputFromArgs === true,
1409
+ // Blended only: the most input rows per worker call (null = a whole
1410
+ // chunk). Mirrors Python's `None if is_scalar else ...`.
1411
+ input_rows_per_call:
1412
+ f.kind === "table_in_out" && f.meta.inputFromArgs === true
1413
+ ? (f.meta.inputRowsPerCall ?? null)
1414
+ : null,
1415
+ required_settings: meta.requiredSettings,
1416
+ required_secrets: requiredSecrets.map((s) => ({
1417
+ secret_type: s.secret_type,
1418
+ scope: s.scope,
1419
+ secret_name: s.secret_name,
1420
+ })),
1421
+ // Protocol 3.3: table_only for a table's hidden scan and every
1422
+ // write function; public otherwise.
1423
+ visibility,
1424
+ };
1425
+ }
1426
+
1372
1427
  // ---------------------------------------------------------------- writable tables
1373
1428
 
1374
1429
  function writeFunctionOf(table: TableDescriptor, operation: WriteOperation): VgiFunction | undefined {
@@ -1391,7 +1446,74 @@ function validateTableScanPlanning(table: TableDescriptor): void {
1391
1446
  }
1392
1447
  }
1393
1448
 
1449
+ /**
1450
+ * Protocol 3.3 function listings for a descriptor: per schema, every function
1451
+ * its listing carries and the visibility each is sent with.
1452
+ *
1453
+ * The rules (enforced here, so authors need do nothing):
1454
+ * - Every function a table names (scan, insert, update, delete) is sent: a
1455
+ * function a schema declares in `functions` is listed there; any other is
1456
+ * listed in its table's schema, after the declared functions.
1457
+ * - Write functions are always `table_only`, wherever they are listed.
1458
+ * - A scan is `table_only` unless a schema declares it in `functions` or a
1459
+ * table naming it sets `exposeScan`; then it is `public`.
1460
+ * - Every other declared function is `public`.
1461
+ */
1462
+ export function buildFunctionListings(descriptor: CatalogDescriptor): {
1463
+ listings: Map<SchemaDescriptor, Map<VgiFunction, FunctionVisibility>>;
1464
+ listedIn: Map<VgiFunction, SchemaDescriptor>;
1465
+ } {
1466
+ const listings = new Map<SchemaDescriptor, Map<VgiFunction, FunctionVisibility>>();
1467
+ const listedIn = new Map<VgiFunction, SchemaDescriptor>();
1468
+ const writeFunctions = new Set<VgiFunction>();
1469
+ for (const sch of descriptor.schemas ?? []) {
1470
+ for (const tbl of sch.tables ?? []) {
1471
+ for (const op of WRITE_OPERATIONS) {
1472
+ const fn = writeFunctionOf(tbl, op);
1473
+ if (fn) writeFunctions.add(fn);
1474
+ }
1475
+ }
1476
+ }
1477
+ const listingOf = (sch: SchemaDescriptor): Map<VgiFunction, FunctionVisibility> => {
1478
+ let listing = listings.get(sch);
1479
+ if (!listing) listings.set(sch, (listing = new Map()));
1480
+ return listing;
1481
+ };
1482
+ for (const sch of descriptor.schemas ?? []) {
1483
+ const listing = listingOf(sch);
1484
+ for (const fn of sch.functions ?? []) {
1485
+ if (!listedIn.has(fn)) listedIn.set(fn, sch);
1486
+ listing.set(fn, writeFunctions.has(fn) ? FUNCTION_VISIBILITY_TABLE_ONLY : FUNCTION_VISIBILITY_PUBLIC);
1487
+ }
1488
+ }
1489
+ const declared = new Set(listedIn.keys());
1490
+ for (const sch of descriptor.schemas ?? []) {
1491
+ for (const tbl of sch.tables ?? []) {
1492
+ const named: Array<[VgiFunction | undefined, boolean]> = [
1493
+ [tbl.function, false],
1494
+ ...WRITE_OPERATIONS.map((op): [VgiFunction | undefined, boolean] => [writeFunctionOf(tbl, op), true]),
1495
+ ];
1496
+ for (const [fn, isWrite] of named) {
1497
+ if (!fn || declared.has(fn)) continue;
1498
+ const owner = listedIn.get(fn) ?? sch;
1499
+ if (!listedIn.has(fn)) listedIn.set(fn, owner);
1500
+ const listing = listingOf(owner);
1501
+ const visibility: FunctionVisibility =
1502
+ !isWrite && !writeFunctions.has(fn) && tbl.exposeScan === true
1503
+ ? FUNCTION_VISIBILITY_PUBLIC
1504
+ : FUNCTION_VISIBILITY_TABLE_ONLY;
1505
+ // Exposure wins: a scan shared by tables is public if any exposes it.
1506
+ if (listing.get(fn) !== FUNCTION_VISIBILITY_PUBLIC) listing.set(fn, visibility);
1507
+ }
1508
+ }
1509
+ }
1510
+ return { listings, listedIn };
1511
+ }
1512
+
1394
1513
  function validateWritableTable(table: TableDescriptor): void {
1514
+ if (table.exposeScan && !table.function) {
1515
+ throw new Error(`Table '${table.name}': exposeScan requires a scan function (set 'function')`);
1516
+ }
1395
1517
  const modes = validateWriteResultModes((table.writeResultModes ?? {}) as Record<string, string>);
1396
1518
  for (const operation of Object.keys(modes) as WriteOperation[]) {
1397
1519
  if (!writeFunctionOf(table, operation)) {
@@ -50,8 +50,8 @@ import {
50
50
  type TransactionOpaqueData,
51
51
  decodeCatalogInfo,
52
52
  type CatalogInfo,
53
- type ScanFunctionResult,
54
- decodeScanFunctionResult,
53
+ type ScanBranchesInfo,
54
+ decodeScanBranchesResult,
55
55
  } from "../catalog/interface.js";
56
56
  import { wrapRequest, unwrapResult } from "./protocol.js";
57
57
  import { toUint8Array } from "../util/bytes.js";
@@ -1222,7 +1222,11 @@ export class VgiClient {
1222
1222
  return items[0] ?? null;
1223
1223
  }
1224
1224
 
1225
- /** Create a new table. */
1225
+ /**
1226
+ * Create a new table. Resolves to whether this call created it: `false`
1227
+ * when `onConflict` is IGNORE (`IF NOT EXISTS`) and the table already
1228
+ * existed (protocol 3.3 `created`).
1229
+ */
1226
1230
  async tableCreate(
1227
1231
  attachOpaqueData: AttachOpaqueData,
1228
1232
  schemaPath: string[] | string,
@@ -1231,8 +1235,8 @@ export class VgiClient {
1231
1235
  onConflict: OnCreateConflict,
1232
1236
  constraintDefinitions: Uint8Array[] = [],
1233
1237
  transactionOpaqueData?: TransactionOpaqueData,
1234
- ): Promise<void> {
1235
- await this.rpc.call("catalog_table_create", {
1238
+ ): Promise<boolean> {
1239
+ const result = await this.rpc.call("catalog_table_create", {
1236
1240
  request: encodeASD(TableCreateRequestSchema, {
1237
1241
  attach_opaque_data: attachOpaqueData,
1238
1242
  schema_path: normalizeSchemaPath(schemaPath),
@@ -1243,6 +1247,8 @@ export class VgiClient {
1243
1247
  transaction_opaque_data: transactionOpaqueData ?? null,
1244
1248
  }),
1245
1249
  });
1250
+ if (!result) throw new VgiClientError("table_create returned null");
1251
+ return unwrapResult(result).created === true;
1246
1252
  }
1247
1253
 
1248
1254
  /** Drop a table by name. */
@@ -1265,28 +1271,31 @@ export class VgiClient {
1265
1271
  }
1266
1272
 
1267
1273
  /**
1268
- * Get the scan function for a table — tells DuckDB which function to call
1269
- * to read the table data (e.g. `read_parquet` with a path argument). Used
1270
- * by the VGI extension during query planning.
1274
+ * Get a table's scan branches -- tells DuckDB which function (or file
1275
+ * format) reads each physical source of the table. A single-source table
1276
+ * has one branch. Protocol 3.3 removed the single-function
1277
+ * `catalog_table_scan_function_get` RPC (and this client's
1278
+ * `tableScanFunctionGet`); this is the only scan-discovery call.
1271
1279
  */
1272
- async tableScanFunctionGet(
1280
+ async tableScanBranchesGet(
1273
1281
  attachOpaqueData: AttachOpaqueData,
1274
1282
  schemaPath: string[] | string,
1275
1283
  name: string,
1276
1284
  atUnit?: string | null,
1277
1285
  atValue?: string | null,
1278
1286
  transactionOpaqueData?: TransactionOpaqueData,
1279
- ): Promise<ScanFunctionResult> {
1280
- const result = await this.rpc.call("catalog_table_scan_function_get", {
1287
+ ): Promise<ScanBranchesInfo> {
1288
+ const result = await this.rpc.call("catalog_table_scan_branches_get", {
1281
1289
  attach_opaque_data: attachOpaqueData,
1282
1290
  schema_path: normalizeSchemaPath(schemaPath),
1283
1291
  name,
1284
1292
  at_unit: atUnit ?? null,
1285
1293
  at_value: atValue ?? null,
1286
1294
  transaction_opaque_data: transactionOpaqueData ?? null,
1295
+ pushdown_filters: null,
1287
1296
  });
1288
- if (!result) throw new VgiClientError("table_scan_function_get returned null");
1289
- return decodeScanFunctionResult(unwrapResult(result));
1297
+ if (!result) throw new VgiClientError("table_scan_branches_get returned null");
1298
+ return decodeScanBranchesResult(unwrapResult(result));
1290
1299
  }
1291
1300
 
1292
1301
  /** Set or clear the comment on a table. */
@@ -75,6 +75,10 @@ export {
75
75
  type CatalogAttachResult,
76
76
  type AttachOpaqueData,
77
77
  type TransactionOpaqueData,
78
+ type ScanFunctionResult,
79
+ type ScanBranchInfo,
80
+ type ScanBranchesInfo,
81
+ decodeScanBranchesResult,
78
82
  } from "./catalog/interface.js";
79
83
 
80
84
  // vgi.v3 records: decode constraint records (readConstraintRecord), negotiate