@query-farm/vgi 0.48.5 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.48.5",
3
+ "version": "0.49.0",
4
4
  "description": "TypeScript framework for extending DuckDB with user-defined functions via the Vector Gateway Interface (VGI) over Arrow IPC.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Query Farm LLC (https://query.farm)",
@@ -3,6 +3,7 @@ import { validateColumnExpressionsIpc } from "./column-expressions.js";
3
3
  import type { VgiSchema } from "../arrow/index.js";
4
4
  import { encodeTableInfo, type TableInfo } from "../generated/vgi-client.js";
5
5
  import { servedTableInfo } from "./constraints.js";
6
+ import { validateScanPlanning } from "./scan-planning.js";
6
7
 
7
8
  function scalarText(value: string): void {
8
9
  for (let i = 0; i < value.length; i++) {
@@ -144,6 +145,7 @@ export function validateColumnMetadataIpc(bytes: Uint8Array): void {
144
145
  vector(schema, 1, (f) => field(f, 0));
145
146
  }
146
147
  export function validateTableInfoColumns(info: TableInfo): void {
148
+ validateScanPlanning(info.name, info.scan_planning, info.scan_function != null);
147
149
  if (info.columns.length) { validateColumnMetadataIpc(info.columns); validateColumnExpressionsIpc(info.columns, info.schema_path); }
148
150
  }
149
151
  /**
@@ -153,6 +155,11 @@ export function validateTableInfoColumns(info: TableInfo): void {
153
155
  * generated metadata translated), whose column expressions are checked last.
154
156
  */
155
157
  export function servedValidatedTableInfo(info: TableInfo): TableInfo {
158
+ // Protocol 3.2: default an absent `scan_planning` (a catalog written for
159
+ // 3.1) to "bind", and refuse unknown values or a "filtered" table that
160
+ // inlines its scan.
161
+ const scanPlanning = validateScanPlanning(info.name, info.scan_planning, info.scan_function != null);
162
+ if (info.scan_planning !== scanPlanning) info = { ...info, scan_planning: scanPlanning };
156
163
  if (info.columns.length) validateColumnMetadataIpc(info.columns);
157
164
  const served = servedTableInfo(info);
158
165
  if (served.columns.length) {
@@ -24,6 +24,7 @@ import type {
24
24
  ViewInfo,
25
25
  } from "./interface.js";
26
26
  import { CatalogInterface } from "./interface.js";
27
+ import type { ScanPlanningFilters } from "./scan-planning.js";
27
28
  import { OpaqueDataRejectedError } from "../crypto.js";
28
29
  import { VgiError } from "../errors.js";
29
30
 
@@ -166,6 +167,10 @@ export class CompositeCatalogInterface extends CatalogInterface {
166
167
  return await this._route(attachOpaqueData).tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
167
168
  }
168
169
 
170
+ override async tableScanBranchesPlan(attachOpaqueData: AttachOpaqueData, schemaPath: string[], name: string, atUnit: string | undefined, atValue: string | undefined, transactionOpaqueData: TransactionOpaqueData | undefined, pushdownFilters: ScanPlanningFilters | null): Promise<any> {
171
+ return await this._route(attachOpaqueData).tableScanBranchesPlan(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData, pushdownFilters);
172
+ }
173
+
169
174
  override async tableColumnStatisticsGet(attachOpaqueData: AttachOpaqueData, schemaPath: string[], name: string, transactionOpaqueData?: TransactionOpaqueData): Promise<{ bytes: Uint8Array; cacheMaxAgeSeconds: number | null } | null> {
170
175
  return await this._route(attachOpaqueData).tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
171
176
  }
@@ -116,6 +116,17 @@ export interface TableDescriptor {
116
116
  * a child does not satisfy its parent. Empty/undefined means no requirements. */
117
117
  requiredFilters?: string[][][];
118
118
  supportsTimeTravel?: boolean;
119
+ /**
120
+ * Protocol 3.2 — when the client resolves this table's scan redirect.
121
+ * `"bind"` (default) keeps 3.1 behaviour. `"filtered"` makes the client call
122
+ * `catalog_table_scan_branches_get` once per scan, after collecting the
123
+ * query's predicates on the table, and pass them as `pushdown_filters` to
124
+ * the catalog's `tableScanBranchesPlan` (override it on a
125
+ * `ReadOnlyCatalogInterface` subclass); zero branches then means "no rows".
126
+ * Requires `columns` and no `function`: a `function` table inlines a fixed
127
+ * scan redirect.
128
+ */
129
+ scanPlanning?: "bind" | "filtered";
119
130
  /**
120
131
  * Inline cardinality estimate/max surfaced through TableInfo. When set,
121
132
  * the C++ extension uses these directly and skips the per-bind
@@ -177,6 +177,8 @@ import { conformColumns } from "../codec/conform.js";
177
177
  import { schema as schema_, field as field_, type VgiDataType, type VgiField } from "../arrow/index.js";
178
178
  import { toUint8Array } from "../util/bytes.js";
179
179
  import { ScanBranchSchema, ScanFunctionResultSchema } from "../generated/vgi-protocol-schemas.js";
180
+ import { serializeColumnStatistics, type ColumnStatistics } from "../util/statistics.js";
181
+ import type { ScanPlanningFilters } from "./scan-planning.js";
180
182
 
181
183
  /**
182
184
  * Result from `tableScanFunctionGet` — tells the VGI DuckDB extension which
@@ -361,6 +363,8 @@ function encodeScanBranch(cols: {
361
363
  format_locations?: string[] | null | undefined;
362
364
  format_options?: Uint8Array | null | undefined;
363
365
  schema_path?: string[] | null | undefined;
366
+ row_count?: bigint | null | undefined;
367
+ column_statistics?: Uint8Array | null | undefined;
364
368
  }): Uint8Array {
365
369
  return serializeBatch(
366
370
  batchFromColumns(
@@ -376,6 +380,8 @@ function encodeScanBranch(cols: {
376
380
  format_locations: [cols.format_locations ?? null],
377
381
  format_options: [cols.format_options ?? null],
378
382
  schema_path: [cols.schema_path ?? null],
383
+ row_count: [cols.row_count ?? null],
384
+ column_statistics: [cols.column_statistics ?? null],
379
385
  }),
380
386
  ScanBranchSchema as any,
381
387
  ),
@@ -434,6 +440,44 @@ export interface ScanBranchInput {
434
440
  * names a catalog-table branch's *source table's* schema.
435
441
  */
436
442
  schemaPath?: string[] | null;
443
+ /**
444
+ * Protocol 3.2 — estimated rows this branch produces before any predicate.
445
+ * Cardinality estimation only; a client never trusts it as exact.
446
+ */
447
+ rowCount?: number | bigint | null;
448
+ /**
449
+ * Protocol 3.2 — conservative per-column statistics for every row this
450
+ * branch produces, keyed by the table's declared column names (columns may
451
+ * be omitted). A client drops the branch when a query predicate is provably
452
+ * false against them, so wrong statistics silently lose rows: leave a column
453
+ * out rather than guess. Either the statistics themselves or an
454
+ * already-serialized `serializeColumnStatistics` payload.
455
+ */
456
+ columnStatistics?: ColumnStatistics[] | Uint8Array | null;
457
+ }
458
+
459
+ /** Validate and encode a branch's protocol 3.2 statistics fields. */
460
+ function branchStatistics(branch: ScanBranchInput): { row_count: bigint | null; column_statistics: Uint8Array | null } {
461
+ let rowCount: bigint | null = null;
462
+ if (branch.rowCount != null) {
463
+ if (typeof branch.rowCount === "number" && !Number.isSafeInteger(branch.rowCount)) {
464
+ throw new Error(`ScanBranch.rowCount must be an integer, got ${branch.rowCount}`);
465
+ }
466
+ rowCount = BigInt(branch.rowCount);
467
+ if (rowCount < 0n) throw new Error(`ScanBranch.rowCount must be >= 0, got ${rowCount}`);
468
+ }
469
+ let columnStatistics: Uint8Array | null = null;
470
+ const stats = branch.columnStatistics;
471
+ if (stats instanceof Uint8Array) {
472
+ columnStatistics = stats;
473
+ } else if (stats != null) {
474
+ const names = stats.map((s) => s.columnName);
475
+ if (new Set(names).size !== names.length) {
476
+ throw new Error("ScanBranch.columnStatistics names a column more than once");
477
+ }
478
+ columnStatistics = serializeColumnStatistics(stats);
479
+ }
480
+ return { row_count: rowCount, column_statistics: columnStatistics };
437
481
  }
438
482
 
439
483
  /**
@@ -491,8 +535,10 @@ function serializeBranchArguments(branch: ScanBranchInput): Uint8Array {
491
535
  * `ScanBranchesResult` construction in the test fixture's
492
536
  * `table_scan_branches_get`.
493
537
  *
494
- * An empty `branches` list is serialized verbatim — the C++ side loud-fails
495
- * on it (that asymmetry is exercised by multi_branch_empty_branches.test).
538
+ * An empty `branches` list is serialized verbatim. For a table declaring
539
+ * `scan_planning: "filtered"` (protocol 3.2) it means the scan produces no
540
+ * rows; for a `"bind"` table the client still rejects it (exercised by
541
+ * multi_branch_empty_branches.test).
496
542
  */
497
543
  export function buildScanBranchesResult(
498
544
  branches: ScanBranchInput[],
@@ -511,6 +557,7 @@ export function buildScanBranchesResult(
511
557
  format_locations: branch.formatLocations,
512
558
  format_options: branch.formatOptions,
513
559
  schema_path: branch.schemaPath,
560
+ ...branchStatistics(branch),
514
561
  }),
515
562
  );
516
563
  return {
@@ -912,6 +959,35 @@ export abstract class CatalogInterface {
912
959
  ? legacy.then((r) => singleBranchResult(r))
913
960
  : singleBranchResult(legacy);
914
961
  }
962
+ /**
963
+ * Plan a table's scan branches with the query's predicates (protocol 3.2).
964
+ *
965
+ * The worker calls this for every `catalog_table_scan_branches_get`. The
966
+ * default ignores `pushdownFilters` and returns `tableScanBranchesGet`, so
967
+ * catalogs written for 3.1 keep working unchanged. Override it for tables
968
+ * declaring `scan_planning: "filtered"` to return fewer branches or files.
969
+ *
970
+ * Every predicate is advisory: the client re-applies all of them, so return
971
+ * any superset of the branches and files that could hold matching rows, and
972
+ * never drop one that could. `ScanPlanningFilters.mayMatch` prunes
973
+ * candidates by min/max statistics. A `"filtered"` table may return zero
974
+ * branches, meaning the scan produces no rows.
975
+ *
976
+ * `pushdownFilters` is null when none were collected (bind-time planning, or
977
+ * no usable predicate); otherwise its predicates are decoded lazily against
978
+ * the table's declared columns (`tableGet(...).columns`).
979
+ */
980
+ tableScanBranchesPlan(
981
+ attachOpaqueData: AttachOpaqueData,
982
+ schemaPath: string[],
983
+ name: string,
984
+ atUnit: string | undefined,
985
+ atValue: string | undefined,
986
+ transactionOpaqueData: TransactionOpaqueData | undefined,
987
+ pushdownFilters: ScanPlanningFilters | null,
988
+ ): Awaitable<any> {
989
+ return this.tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
990
+ }
915
991
  /**
916
992
  * Return serialized column statistics for a table, or null if none are
917
993
  * available. The result is the IPC bytes of a ColumnStatistics RecordBatch
@@ -24,6 +24,7 @@ import {
24
24
  } from "./interface.js";
25
25
  import { schemaDescriptorPath, 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
+ import { SCAN_PLANNING_BIND, SCAN_PLANNING_FILTERED, validateScanPlanning } from "./scan-planning.js";
27
28
  import type { VgiFunction } from "../functions/types.js";
28
29
  import type { FunctionRegistry } from "../functions/registry.js";
29
30
  import { argumentSpecsToSchema } from "../arguments/argument-spec.js";
@@ -116,7 +117,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
116
117
  this._descriptor = descriptor;
117
118
  this._registry = registry;
118
119
  if (options.perAttachItemIds) this.perAttachItemIds = true;
119
- for (const sch of descriptor.schemas ?? []) for (const tbl of sch.tables ?? []) validateWritableTable(tbl);
120
+ for (const sch of descriptor.schemas ?? []) for (const tbl of sch.tables ?? []) { validateWritableTable(tbl); validateTableScanPlanning(tbl); }
120
121
  // Index every function this catalog declares by its owning schema, so a
121
122
  // schema-qualified bind resolves to the right implementation when one name
122
123
  // is declared in more than one schema. Table-backing functions are indexed
@@ -516,6 +517,7 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
516
517
  ? Number(t.inlinedCardinality.max)
517
518
  : null,
518
519
  required_filters: requiredFilters,
520
+ scan_planning: t.scanPlanning ?? SCAN_PLANNING_BIND,
519
521
  };
520
522
  }));
521
523
  // DuckDB resolves a foreign key against its target when the referencing
@@ -1373,6 +1375,17 @@ function writeFunctionOf(table: TableDescriptor, operation: WriteOperation): Vgi
1373
1375
  * an unknown operation or mode, a mode for an operation with no function, or
1374
1376
  * UPDATE/DELETE without a scan function to supply row ids.
1375
1377
  */
1378
+ /** Protocol 3.2: a `"filtered"` table supplies its scan per query, so it declares `columns`, not `function`. */
1379
+ function validateTableScanPlanning(table: TableDescriptor): void {
1380
+ validateScanPlanning(table.name, table.scanPlanning, false);
1381
+ if (table.scanPlanning === SCAN_PLANNING_FILTERED && (table.function || !table.columns)) {
1382
+ throw new Error(
1383
+ `Table '${table.name}': scanPlanning 'filtered' requires columns and no function; the catalog's ` +
1384
+ "tableScanBranchesPlan supplies the scan per query",
1385
+ );
1386
+ }
1387
+ }
1388
+
1376
1389
  function validateWritableTable(table: TableDescriptor): void {
1377
1390
  const modes = validateWriteResultModes((table.writeResultModes ?? {}) as Record<string, string>);
1378
1391
  for (const operation of Object.keys(modes) as WriteOperation[]) {
@@ -0,0 +1,314 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Protocol 3.2 filtered scan planning (docs/protocol/scan-planning.md in
3
+ // vgi-python). Mirrors vgi-python's vgi/scan_planning.py and the
4
+ // `scan_planning` validation in vgi/catalog/catalog_interface.py.
5
+ //
6
+ // A table declaring `TableInfo.scan_planning = "filtered"` receives the
7
+ // query's predicates in `catalog_table_scan_branches_get`. The catalog's
8
+ // `tableScanBranchesPlan` hook gets them as a `ScanPlanningFilters` and may
9
+ // use them to return fewer branches or fewer files. Every predicate is
10
+ // advisory: the client re-applies all of them, so a worker may ignore any
11
+ // predicate it does not understand, but must never drop a branch or file that
12
+ // could hold a matching row.
13
+
14
+ import {
15
+ deserializeBatch, isDate, isDecimal, isDuration, isInterval, isTime, isTimestamp,
16
+ type VgiDataType, type VgiSchema,
17
+ } from "../arrow/index.js";
18
+ import { deserializeFilters } from "../filter-pushdown/deserialize.js";
19
+ import type { PushdownFilters } from "../filter-pushdown/evaluate.js";
20
+ import { ComparisonOp, type FilterExpression } from "../filter-pushdown/types.js";
21
+
22
+ /** Protocol 3.2 `TableInfo.scan_planning`: resolve the scan redirect at bind time (3.1 behaviour). */
23
+ export const SCAN_PLANNING_BIND = "bind";
24
+ /** Protocol 3.2 `TableInfo.scan_planning`: resolve it per scan with the query's filters. */
25
+ export const SCAN_PLANNING_FILTERED = "filtered";
26
+ /** When the client resolves a table's scan redirect. */
27
+ export type ScanPlanningMode = typeof SCAN_PLANNING_BIND | typeof SCAN_PLANNING_FILTERED;
28
+ /** Every legal `TableInfo.scan_planning` value. */
29
+ export const SCAN_PLANNING_MODES: readonly ScanPlanningMode[] = Object.freeze([SCAN_PLANNING_BIND, SCAN_PLANNING_FILTERED]);
30
+
31
+ /**
32
+ * Validate a table's `scan_planning` value and return it (`"bind"` when
33
+ * absent). Unknown values are a protocol error, and a `"filtered"` table must
34
+ * not inline `scan_function`: its scan redirect is resolved per query with
35
+ * the query's filters.
36
+ */
37
+ export function validateScanPlanning(
38
+ tableName: string,
39
+ scanPlanning: unknown,
40
+ hasInlineScanFunction: boolean,
41
+ ): ScanPlanningMode {
42
+ const mode = scanPlanning ?? SCAN_PLANNING_BIND;
43
+ if (mode !== SCAN_PLANNING_BIND && mode !== SCAN_PLANNING_FILTERED) {
44
+ throw new Error(
45
+ `Table '${tableName}': scan_planning must be one of ${JSON.stringify(SCAN_PLANNING_MODES)}, got ${JSON.stringify(mode)}`,
46
+ );
47
+ }
48
+ if (mode === SCAN_PLANNING_FILTERED && hasInlineScanFunction) {
49
+ throw new Error(
50
+ `Table '${tableName}': scan_planning='filtered' cannot be combined with an inlined scan_function; ` +
51
+ "the scan redirect must be resolved per query with the query's filters",
52
+ );
53
+ }
54
+ return mode;
55
+ }
56
+
57
+ /**
58
+ * Per-column statistics describing a scan candidate (a file, a partition, a
59
+ * branch) — the same claims `ScanBranch.column_statistics` makes: every
60
+ * non-null value of the column lies within `[min, max]`; `hasNull: false`
61
+ * means the column has no NULLs; `hasNotNull: false` means it is entirely
62
+ * NULL. A missing `min`/`max`/flag claims nothing. `ColumnStatistics` (the
63
+ * type `serializeColumnStatistics` takes) satisfies this shape.
64
+ */
65
+ export interface ScanCandidateStatistics {
66
+ columnName: string;
67
+ /** Arrow type of `min`/`max`; defaults to the column's declared type. */
68
+ arrowType?: VgiDataType | null;
69
+ min?: unknown;
70
+ max?: unknown;
71
+ hasNull?: boolean | null;
72
+ hasNotNull?: boolean | null;
73
+ }
74
+
75
+ type Awaitable<T> = T | Promise<T>;
76
+
77
+ /**
78
+ * The query predicates sent with a filtered `catalog_table_scan_branches_get`.
79
+ *
80
+ * `raw` is the wire bytes: an Arrow IPC stream holding one VGI Filter
81
+ * Encoding v2 snapshot batch whose column indexes refer to the table's
82
+ * declared columns (`TableInfo.columns`). `decode()` resolves those columns
83
+ * (at most once) and decodes the predicates; nothing is decoded until a hook
84
+ * asks.
85
+ */
86
+ export class ScanPlanningFilters {
87
+ private _decoded: Promise<PushdownFilters> | null = null;
88
+
89
+ constructor(
90
+ /** The wire bytes of the filter v2 snapshot. */
91
+ readonly raw: Uint8Array,
92
+ /** Resolves the table's declared columns, the schema the column indexes refer to. */
93
+ private readonly tableColumns: () => Awaitable<VgiSchema | null>,
94
+ ) {}
95
+
96
+ /** Decode the predicates against the table's declared columns (cached). */
97
+ decode(): Promise<PushdownFilters> {
98
+ if (this._decoded == null) {
99
+ this._decoded = (async () => {
100
+ const columns = await this.tableColumns();
101
+ if (columns == null) {
102
+ throw new Error("pushdown_filters: the table's declared columns could not be resolved");
103
+ }
104
+ return deserializeFilters(deserializeBatch(this.raw), { outputSchema: columns });
105
+ })();
106
+ // A failed decode is not cached: the next call retries.
107
+ this._decoded.catch(() => { this._decoded = null; });
108
+ }
109
+ return this._decoded;
110
+ }
111
+
112
+ /**
113
+ * False only when the predicates provably exclude every row `statistics`
114
+ * describes. See `filtersMayMatch`.
115
+ */
116
+ async mayMatch(
117
+ statistics: Iterable<ScanCandidateStatistics> | Readonly<Record<string, ScanCandidateStatistics>>,
118
+ ): Promise<boolean> {
119
+ return filtersMayMatch(await this.decode(), statistics);
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Return false only when `filters` provably exclude every row described by
125
+ * `statistics`; use it to prune a manifest (files, partitions) before
126
+ * returning branches.
127
+ *
128
+ * Reasons over top-level conjuncts built from `AND`/`OR`, comparisons between
129
+ * a column and a literal (`=`, `!=`, `<`, `<=`, `>`, `>=`), `IN` lists and
130
+ * `IS [NOT] NULL`. Columns, predicates or values it cannot reason about —
131
+ * casts, function calls, incomparable literal types, columns without
132
+ * statistics — count as "may match", so the answer errs towards keeping data.
133
+ */
134
+ export function filtersMayMatch(
135
+ filters: PushdownFilters,
136
+ statistics: Iterable<ScanCandidateStatistics> | Readonly<Record<string, ScanCandidateStatistics>>,
137
+ ): boolean {
138
+ const list: Iterable<ScanCandidateStatistics> = Symbol.iterator in (statistics as object)
139
+ ? (statistics as Iterable<ScanCandidateStatistics>)
140
+ : Object.values(statistics as Record<string, ScanCandidateStatistics>);
141
+ const byName = new Map<string, ScanCandidateStatistics>();
142
+ for (const stat of list) byName.set(stat.columnName, stat);
143
+ if (byName.size === 0) return true;
144
+ for (const predicate of filters.predicates) {
145
+ if (provablyFalse(predicate.expression, byName)) return false;
146
+ }
147
+ return true;
148
+ }
149
+
150
+ const FLIPPED: Partial<Record<ComparisonOp, ComparisonOp>> = {
151
+ [ComparisonOp.EQ]: ComparisonOp.EQ,
152
+ [ComparisonOp.NE]: ComparisonOp.NE,
153
+ [ComparisonOp.LT]: ComparisonOp.GT,
154
+ [ComparisonOp.LE]: ComparisonOp.GE,
155
+ [ComparisonOp.GT]: ComparisonOp.LT,
156
+ [ComparisonOp.GE]: ComparisonOp.LE,
157
+ };
158
+
159
+ /** A column reference with statistics, and the Arrow type its statistic values are in. */
160
+ interface StatRef {
161
+ stat: ScanCandidateStatistics;
162
+ type: VgiDataType | undefined;
163
+ }
164
+
165
+ function columnStat(expr: FilterExpression, stats: Map<string, ScanCandidateStatistics>): StatRef | null {
166
+ if (expr.node !== "column_ref") return null;
167
+ const stat = stats.get(expr.columnName);
168
+ // Statistic values are in the statistic's own Arrow type when it names one
169
+ // (that is how they serialize), else in the column's declared type.
170
+ return stat == null ? null : { stat, type: stat.arrowType ?? expr.dataType };
171
+ }
172
+
173
+ /** Whether every non-null value in `[lo, hi]` differs from `value` (`value` lies outside the range). */
174
+ function outside(ref: StatRef, value: unknown, valueType: VgiDataType | undefined): boolean {
175
+ const lo = ref.stat.min ?? null;
176
+ const hi = ref.stat.max ?? null;
177
+ const cmpLo = lo == null ? null : compare(lo, ref.type, value, valueType);
178
+ const cmpHi = hi == null ? null : compare(hi, ref.type, value, valueType);
179
+ return (cmpLo != null && cmpLo > 0) || (cmpHi != null && cmpHi < 0);
180
+ }
181
+
182
+ /** True only when `expr` is false or NULL for every row `stats` describe. */
183
+ function provablyFalse(expr: FilterExpression, stats: Map<string, ScanCandidateStatistics>): boolean {
184
+ switch (expr.node) {
185
+ case "and":
186
+ return expr.children.some((child) => provablyFalse(child, stats));
187
+ case "or":
188
+ return expr.children.length > 0 && expr.children.every((child) => provablyFalse(child, stats));
189
+ case "comparison": {
190
+ let op: ComparisonOp | undefined = expr.op;
191
+ let ref = columnStat(expr.left, stats);
192
+ let literal = expr.right;
193
+ if (ref == null) {
194
+ ref = columnStat(expr.right, stats);
195
+ literal = expr.left;
196
+ op = FLIPPED[expr.op];
197
+ }
198
+ // IS [NOT] DISTINCT FROM is never NULL, so it is not in FLIPPED.
199
+ if (ref == null || op == null || !(op in FLIPPED) || literal.node !== "literal") return false;
200
+ if (ref.stat.hasNotNull === false) return true; // all NULL: the comparison is NULL
201
+ const c = literal.value;
202
+ if (c == null) return true; // a comparison with NULL is NULL
203
+ const litType = literal.field?.type;
204
+ const lo = ref.stat.min ?? null;
205
+ const hi = ref.stat.max ?? null;
206
+ const cmpLo = lo == null ? null : compare(lo, ref.type, c, litType);
207
+ const cmpHi = hi == null ? null : compare(hi, ref.type, c, litType);
208
+ switch (op) {
209
+ case ComparisonOp.EQ:
210
+ return (cmpLo != null && cmpLo > 0) || (cmpHi != null && cmpHi < 0);
211
+ case ComparisonOp.NE:
212
+ return cmpLo === 0 && cmpHi === 0;
213
+ case ComparisonOp.LT:
214
+ return cmpLo != null && cmpLo >= 0;
215
+ case ComparisonOp.LE:
216
+ return cmpLo != null && cmpLo > 0;
217
+ case ComparisonOp.GT:
218
+ return cmpHi != null && cmpHi <= 0;
219
+ case ComparisonOp.GE:
220
+ return cmpHi != null && cmpHi < 0;
221
+ default:
222
+ return false;
223
+ }
224
+ }
225
+ case "in": {
226
+ if (expr.negated || expr.set.kind !== "literal") return false;
227
+ const ref = columnStat(expr.expression, stats);
228
+ if (ref == null) return false;
229
+ if (ref.stat.hasNotNull === false) return true;
230
+ if (ref.stat.min == null && ref.stat.max == null) return false;
231
+ const setType = expr.set.field?.type;
232
+ const values = expr.set.values.filter((v) => v != null);
233
+ if (values.length === 0) return true; // x IN (NULL, ...) is never true
234
+ return values.every((v) => outside(ref, v, setType));
235
+ }
236
+ case "is_null": {
237
+ const ref = columnStat(expr.expression, stats);
238
+ if (ref == null) return false;
239
+ return expr.negated ? ref.stat.hasNotNull === false : ref.stat.hasNull === false;
240
+ }
241
+ default:
242
+ return false;
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Sign of `a - b`, or null when the two values are not comparable. Each value
248
+ * is first normalized by its Arrow type (a date32 literal arrives as a day
249
+ * count, a date statistic is usually a `Date`, a timestamp is a bigint in its
250
+ * unit), then values compare only within one kind (numeric, string, boolean,
251
+ * date, timestamp), so a representation it does not understand reads as
252
+ * "unknown", never as a wrong answer.
253
+ */
254
+ function compare(a: unknown, aType: VgiDataType | undefined, b: unknown, bType: VgiDataType | undefined): number | null {
255
+ const x = comparable(a, aType);
256
+ const y = comparable(b, bType);
257
+ if (x == null || y == null || x.kind !== y.kind) return null;
258
+ const u = x.value;
259
+ const v = y.value;
260
+ if (typeof u === "number" && Number.isNaN(u)) return null;
261
+ if (typeof v === "number" && Number.isNaN(v)) return null;
262
+ if (typeof u === "string" && typeof v === "string") return compareCodePoints(u, v);
263
+ // Mixed number/bigint compare exactly with the relational operators.
264
+ return u < v ? -1 : u > v ? 1 : 0;
265
+ }
266
+
267
+ /** Code-point (= UTF-8 byte) order, which is how DuckDB orders VARCHAR; `<` on JS strings is UTF-16 order. */
268
+ function compareCodePoints(a: string, b: string): number {
269
+ const ia = a[Symbol.iterator]();
270
+ const ib = b[Symbol.iterator]();
271
+ for (;;) {
272
+ const x = ia.next();
273
+ const y = ib.next();
274
+ if (x.done || y.done) return x.done && y.done ? 0 : x.done ? -1 : 1;
275
+ const cx = x.value.codePointAt(0)!;
276
+ const cy = y.value.codePointAt(0)!;
277
+ if (cx !== cy) return cx < cy ? -1 : 1;
278
+ }
279
+ }
280
+
281
+ const MS_PER_DAY = 86_400_000;
282
+ // Arrow TimeUnit SECOND=0, MILLISECOND=1, MICROSECOND=2, NANOSECOND=3 -> nanoseconds per unit.
283
+ const NS_PER_UNIT = [1_000_000_000n, 1_000_000n, 1_000n, 1n] as const;
284
+
285
+ type Comparable = { kind: string; value: number | bigint | string };
286
+
287
+ function comparable(v: unknown, type: VgiDataType | undefined): Comparable | null {
288
+ if (type != null) {
289
+ if (isDate(type)) {
290
+ // Milliseconds since the epoch; a raw value is days (date32) or ms (date64).
291
+ if (v instanceof Date) return { kind: "date", value: v.getTime() };
292
+ if (typeof v === "number" || typeof v === "bigint") {
293
+ return { kind: "date", value: (type as { unit?: number }).unit === 0 ? Number(v) * MS_PER_DAY : Number(v) };
294
+ }
295
+ return null;
296
+ }
297
+ if (isTimestamp(type)) {
298
+ // Nanoseconds since the epoch; a raw value is in the type's unit.
299
+ const scale = NS_PER_UNIT[(type as { unit?: number }).unit ?? -1];
300
+ if (scale == null) return null;
301
+ if (v instanceof Date) return { kind: "timestamp", value: BigInt(v.getTime()) * 1_000_000n };
302
+ if (typeof v === "bigint") return { kind: "timestamp", value: v * scale };
303
+ if (typeof v === "number" && Number.isSafeInteger(v)) return { kind: "timestamp", value: BigInt(v) * scale };
304
+ return null;
305
+ }
306
+ // Decimals, times, intervals, nested types: representation-dependent; never prune.
307
+ if (isDecimal(type) || isTime(type) || isInterval(type) || isDuration(type)) return null;
308
+ }
309
+ if (v instanceof Date) return null; // a Date without a date/timestamp type is ambiguous
310
+ if (typeof v === "number" || typeof v === "bigint") return { kind: "numeric", value: v };
311
+ if (typeof v === "string") return { kind: "string", value: v };
312
+ if (typeof v === "boolean") return { kind: "boolean", value: v ? 1 : 0 };
313
+ return null;
314
+ }
@@ -2,7 +2,7 @@
2
2
  // GENERATED by vgi.codegen.ts_client. DO NOT EDIT BY HAND.
3
3
  //
4
4
  // Generator: vgi-gen-ts-client v1
5
- // Content hash: 0fab849ec28b
5
+ // Content hash: ea9cbf1729ea
6
6
  //
7
7
  // To regenerate:
8
8
  // uv run --project ~/Development/vgi-python vgi-gen-ts-client \
@@ -99,6 +99,7 @@ export interface TableInfo {
99
99
  required_filters: string[][][];
100
100
  options?: /** @ipc-record OptionState */ Uint8Array | null;
101
101
  layout?: /** @ipc-record TableLayout */ Uint8Array | null;
102
+ scan_planning: string;
102
103
  }
103
104
 
104
105
  export interface ViewInfo {
@@ -2,7 +2,7 @@
2
2
  // GENERATED by vgi.codegen.ts_schemas. DO NOT EDIT BY HAND.
3
3
  //
4
4
  // Generator: vgi-gen-ts-schemas v2
5
- // Content hash: 4b57381f6bef
5
+ // Content hash: b46c5420bb5d
6
6
  //
7
7
  // To regenerate:
8
8
  // uv run --project ~/Development/vgi-python vgi-gen-ts-schemas \
@@ -30,7 +30,7 @@ import {
30
30
  } from "../arrow/index.js";
31
31
 
32
32
  /** Canonical fingerprint of the nested catalog wire schemas. */
33
- export const VGI_CATALOG_CONTRACT_HASH = "1d12ce672b43ca1510721f89637bb374d27693b100d357ac2ead99fcddc27e9f";
33
+ export const VGI_CATALOG_CONTRACT_HASH = "d9304d52d78b0ceb90319d9a83759781df4a711b72443790654335c8cfcad9bf";
34
34
 
35
35
  // Origin: CatalogInfo
36
36
  export const CatalogInfoSchema = schema([
@@ -73,6 +73,7 @@ export const TableInfoSchema = schema([
73
73
  field("required_filters", list(field("item", list(field("item", list(field("item", utf8(), true)), true)), true)), false),
74
74
  field("options", binary(), true),
75
75
  field("layout", binary(), true),
76
+ field("scan_planning", utf8(), false),
76
77
  ]);
77
78
 
78
79
  // Origin: ViewInfo
@@ -483,6 +484,8 @@ export const ScanBranchSchema = schema([
483
484
  field("format_locations", list(field("item", utf8(), true)), true),
484
485
  field("format_options", binary(), true),
485
486
  field("schema_path", list(field("item", utf8(), true)), true),
487
+ field("row_count", int64(), true),
488
+ field("column_statistics", binary(), true),
486
489
  ]);
487
490
 
488
491
  // Origin: ScanSplit
@@ -1608,6 +1611,7 @@ export const CatalogTableScanBranchesGetParamsSchema = schema([
1608
1611
  field("at_unit", utf8(), true),
1609
1612
  field("at_value", utf8(), true),
1610
1613
  field("transaction_opaque_data", binary(), true),
1614
+ field("pushdown_filters", binary(), true),
1611
1615
  ]);
1612
1616
 
1613
1617
  // Origin: method 'catalog_table_scan_function_get' params
@@ -2,7 +2,7 @@
2
2
  // GENERATED by vgi.codegen.ts_registry. DO NOT EDIT BY HAND.
3
3
  //
4
4
  // Generator: python -m vgi.codegen.ts_registry v1
5
- // Content hash: d92d651266e2
5
+ // Content hash: 2ebfceb69d3f
6
6
  //
7
7
  // To regenerate:
8
8
  // uv run --project ~/Development/vgi-python python scripts/regen_generated.py
@@ -38,7 +38,7 @@ import {
38
38
  export const VGI_PROTOCOL_NAME = "vgi.v3";
39
39
 
40
40
  /** The protocol's semver, stamped on every request by a client of this protocol. */
41
- export const VGI_PROTOCOL_VERSION = "3.1.0";
41
+ export const VGI_PROTOCOL_VERSION = "3.2.0";
42
42
 
43
43
  /** What a unary handler returns: the result row, now or later. */
44
44
  export type VgiReply<T> = T | ExternalRef | Promise<T | ExternalRef>;
@@ -789,6 +789,8 @@ export interface CatalogTableScanBranchesGetParams {
789
789
  at_value: string | null;
790
790
  /** The `transaction_opaque_data` column (`binary`, nullable). */
791
791
  transaction_opaque_data: Uint8Array | null;
792
+ /** The `pushdown_filters` column (`binary`, nullable). */
793
+ pushdown_filters: Uint8Array | null;
792
794
  }
793
795
 
794
796
  /** The params of `catalog_table_scan_function_get`, one property per params-schema column. */
@@ -1477,6 +1479,8 @@ export interface VgiService {
1477
1479
  /**
1478
1480
  * Get the list of scan branches for a multi-branch table. Returns `ScanBranchesResult` as IPC bytes.
1479
1481
  *
1482
+ * Protocol 3.2: ``pushdown_filters`` carries the query's predicates on the table (an Arrow IPC stream holding one VGI Filter Encoding v2 snapshot batch; column indexes refer to ``TableInfo.columns``) when the table declares ``scan_planning = "filtered"``. Every predicate is advisory. ``None`` means none were collected. See ``docs/protocol/scan-planning.md``.
1483
+ *
1480
1484
  * Additive successor to ``catalog_table_scan_function_get``. Workers that only implement the legacy method continue to work — the VGI extension's C++ side catches ``MethodNotImplementedError`` and falls back to the legacy RPC, wrapping the single-function result as a one-branch list. Workers that implement BOTH the legacy and the branches method guarantee single-process compatibility with both old and new extensions.
1481
1485
  *
1482
1486
  * Multi-branch tables compose a logical scan from N physical sources (canonical case: Kafka hot tier + Iceberg cold tier). The extension's optimizer rewrite stitches the branches together via ``LogicalSetOperation(UNION_ALL, ...)``, one arm per branch.
@@ -2534,6 +2538,7 @@ export const VGI_V3_METHODS: readonly VgiMethodSpec[] = [
2534
2538
  field("at_unit", utf8(), true),
2535
2539
  field("at_value", utf8(), true),
2536
2540
  field("transaction_opaque_data", binary(), true),
2541
+ field("pushdown_filters", binary(), true),
2537
2542
  ]),
2538
2543
  result: schema([
2539
2544
  field("result", binary(), false),