Skip to content

feat: expression-keyed statistics pruning (struct fields, pluggable resolvers) - #27736

Draft
adriangb wants to merge 26 commits into
apache:mainfrom
adriangb:expr-stats-pruning
Draft

adriangb wants to merge 26 commits into
apache:mainfrom
adriangb:expr-stats-pruning

Conversation

@adriangb

@adriangb adriangb commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

Parquet stores min/max, null counts, page indexes and bloom filters for every struct field leaf. DataFusion ignores all of them for s['a'], because PruningPredicate only knows top-level columns.

Example

A file with 4 row groups of 3 rows each, s: {a: int, b: int}:

Row group s['a']
0 1..3
1 10..12
2 NULL struct, 20, NULL field
3 30..32
EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] > 15;
- pruning_predicate=<none>
- row_groups_pruned_statistics=4 total → 4 matched
+ pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 > 15
+ row_groups_pruned_statistics=4 total → 2 matched

The same thing, for other access paths:

Query main This PR
s['a'] > 15 (row groups) 4 → 4 4 → 2
s['a'] < 10 over 2 files 2 → 2 row groups 2 → 1, and that 1 is fully matched (filter skipped)
ORDER BY s['a'] DESC LIMIT 3 (TopK dynamic filter) 0 pruned 4 of 5 pruned, same as a plain column
s['a'] = 50 with bloom filters 2 → 2 0 row groups read
hash join on s['a'], build keys 0, 5000, 9999 10 → 10 10 → 3, same as a plain column
fake_variant_get(v, 'a') > 5 with a custom resolver (test) nothing pruned shredded row groups pruned

What changes are included in this PR?

API overview

Two layers. The pruning crate learns that an expression can have statistics. The Parquet crate decides which leaf column holds them.

flowchart LR
    P["predicate<br/>s['a'] > 15"] --> B["PruningPredicateBuilder<br/>.with_statistics_expr_matcher(m)"]
    B -->|"m.matches(s['a'])?"| K["stats key = s['a']"]
    K --> S["PruningStatistics<br/>max_values_for_expr(s['a'])"]
    S --> R["ParquetStatisticsResolvers"]
    R --> G["GetFieldStatisticsResolver<br/>(built in)"]
    R --> X["your resolver<br/>(e.g. variant_get)"]
    G --> L["ParquetLeafStatistics<br/>row groups / pages / bloom"]
    X --> L
Loading

datafusion-pruning

// "This expression has its own statistics."
pub trait StatisticsExprMatcher {
    fn matches(&self, expr: &Arc<dyn PhysicalExpr>) -> bool;
}

PruningPredicateBuilder::new().with_statistics_expr_matcher(matcher)

A matched expression must read exactly one column and have a non-nested type. It is then a stats key, like a column. Every rewrite that works on a column also works on a key: comparisons, IS [NOT] NULL, CAST/TRY_CAST/NOT, booleans, compact IN, literal guarantees (bloom filters) and the hash join bitmap.

PruningStatistics (moved to datafusion-physical-expr-common)

fn min_values_for_expr(&self, expr: &Arc<dyn PhysicalExpr>) -> Option<ArrayRef> { None }
fn max_values_for_expr(..)  -> Option<ArrayRef> { None }
fn null_counts_for_expr(..) -> Option<ArrayRef> { None }
fn contained_for_expr(.., values: &HashSet<ScalarValue>) -> Option<BooleanArray> { None }

All default to None, so existing implementations keep compiling. A null entry means "unknown", never a guess.

datafusion-datasource-parquet

pub trait ParquetStatisticsResolver {
    fn matches(&self, expr: &Arc<dyn PhysicalExpr>) -> bool;
    // Row group and page stats, read from the leaves this resolver picks.
    fn statistics(&self, expr, kind: ExprStatisticsKind, stats: &dyn ParquetLeafStatistics)
        -> Option<ArrayRef>;
    // Opt-in: one leaf for the page index or the bloom filter.
    fn page_index_leaf(..) -> Option<usize> { None }
    fn bloom_filter_leaf(..) -> Option<usize> { None }
}

ParquetSource::with_statistics_resolver(Arc::new(MyVariantResolver))

ParquetStatisticsResolvers holds the list. It starts with GetFieldStatisticsResolver, and it is also the matcher for every pruning predicate the scan builds (static, page, bloom, TopK, hash join).

How to review

Review commit by commit. Each test: commit records the output on main, and the next commit's slt diff shows what changes.

# Commit
1 test: slt for struct field pruning
2 refactor: move PruningStatistics to datafusion-physical-expr-common (mechanical)
3 feat: *_for_expr methods on PruningStatistics
4 refactor: PredicateBuildContext
5 refactor: key statistics by a column or an expression
6 feat: StatisticsExprMatcher
7 feat: Parquet resolvers, row groups
8 feat: Parquet resolvers, page index
9 test: a resolver from outside DataFusion (fake variant_get)
10-11 test: / feat: dynamic TopK pruner gets the resolvers
12 feat: IS [NOT] NULL on keys
13-14 test: / feat: CAST, TRY_CAST, NOT over keys (struct type drift)
15 feat: boolean keys
16-17 test: / feat: compact IN on keys
18 feat: literal guarantees on keys
19-20 test: / feat: bloom filters on struct fields
21-22 test: / feat: hash join HashTableLookupExpr bitmap on keys
23 test: slt for a NULL struct field in a fully matched row group and a placeholder-named column
24 fix: add IS NULL for matched expressions in the full-match inverse
25 fix: skip expression guarantees when a real column uses the placeholder prefix
26 test: dynamic filter with a custom resolver, missing struct field null counts

What is the testing strategy for this PR?

  • parquet_struct_field_pruning.slt: EXPLAIN ANALYZE metrics for every case in the table above, plus null structs vs null fields, type drift (INT file, DOUBLE table) and != on Int8/Date/Decimal.
  • expr_statistics_resolver.rs: a fake variant_get with its own resolver, static and dynamic filters, and a file with no null counts.
  • Unit tests in pruning_predicate.rs for key rewrites and literal guarantees.
  • Fuzzing and mutation testing found two bugs (fixed in commits 23-25) and two untested paths (covered in 26).

Are there any user-facing changes?

Yes, and one is breaking:

Change Breaking?
PruningStatistics moves from datafusion-common to datafusion-physical-expr-common Yes: an import path changes
New *_for_expr methods with default None No
New StatisticsExprMatcher, ParquetStatisticsResolver, ParquetSource::with_statistics_resolver No
A ParquetSource with a custom resolver does not serialize to proto New limitation

🤖 Generated with Claude Code

@github-actions github-actions Bot added physical-expr Changes to the physical-expr crates core Core DataFusion crate sqllogictest SQL Logic Tests (.slt) catalog Related to the catalog crate common Related to common crate datasource Changes to the datasource crate labels Nov 25, 2026
adriangb and others added 22 commits November 25, 2026 10:07
Records the current behavior: predicates on `get_field(s, 'a')` get no
pruning predicate, so every row group and page is read. Later commits
update the expected output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`PruningStatistics` lives in `datafusion-common`, which cannot name
`PhysicalExpr`. Asking a statistics source for the statistics of an
expression (such as `get_field(s, 'a')` or `variant_get(v, 'a')`)
needs the trait to live next to `PhysicalExpr`.

This is a mechanical move of `datafusion_common::pruning` to
`datafusion_physical_expr_common::pruning` and an update of the
imports. `datafusion_common` cannot re-export it, because
`physical-expr-common` depends on it, so the old path is removed.
`datafusion_pruning::PruningStatistics` keeps working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`PruningStatistics` only returns statistics for whole columns. Add
`min_values_for_expr`, `max_values_for_expr`, `null_counts_for_expr`
and `contained_for_expr`, so a source can answer for an expression such
as `get_field(s, 'a')` or `variant_get(v, 'a')`.

The defaults return `None`, so existing implementations keep working
and prune nothing for such expressions. `CompositePruningStatistics`
forwards the new methods to its members.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`build_predicate_expression` takes the schema, the unhandled-predicate
hook and the IN-list limit as separate arguments and passes all three
to each recursive call. Struct field pruning adds one more read-only
setting (which expressions have their own statistics).

Bundle them in `PredicateBuildContext`. No behavior change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`RequiredColumns` and `PruningExpressionBuilder` identify the statistics
they read by a bare column. Pruning on `get_field(s, 'a')` or
`variant_get(v, 'a')` needs statistics for an expression that is not a
column.

This adds an optional expression next to each required column and a
`StatsKey` that `ColumnReferenceCount` returns. The statistics record
batch reads expression statistics through `*_for_expr`. Every key is
still a plain column, so behavior does not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`PruningPredicate` only reads statistics for columns, so a predicate on
`get_field(s, 'a')` or `variant_get(v, 'a')` cannot be pruned. The
pruning crate cannot know which such expressions a statistics source
can answer: Parquet knows struct fields, and a variant extension knows
shredded variant paths.

Add `StatisticsExprMatcher`, set with
`PruningPredicateBuilder::with_statistics_expr_matcher`. A matched
expression that reads one column and has a non-nested type becomes one
statistics key: the predicate replaces it with its statistics columns
and reads them through `PruningStatistics::*_for_expr`.

`RequiredColumns::single_column` returns `None` when a key is an
expression. The new `single_key` returns the column or expression.

No caller sets a matcher yet, so plans do not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Parquet stores statistics for every leaf column, including struct
fields and shredded variant columns, but predicates on `get_field` or
`variant_get` cannot use them.

Add `ParquetStatisticsResolver`. A resolver says which expressions it
may answer and reads their statistics from `ParquetLeafStatistics`, a
view of the leaf column statistics of a file's row groups. Resolvers
can come from outside DataFusion through
`ParquetSource::with_statistics_resolver`. The resolvers of a scan are
also the `StatisticsExprMatcher` for its pruning predicates.

`GetFieldStatisticsResolver` is always present. It maps
`get_field(s, 'a', ...)` to the leaf of that struct field and rejects
paths through maps or lists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The page index only accepts predicates whose statistics come from one
column, so `s['a'] >= 85` read every page of a row group.

A resolver can now name the one Parquet leaf whose pages hold an
expression, through `ParquetStatisticsResolver::page_index_leaf`. The
page filter prunes that leaf's pages, and `PagesPruningStatistics`
answers the resolvers through `ParquetLeafStatistics`, for that leaf
only, because the pages of other leaves do not line up. The page index
load check uses the same leaf.

The default returns `None`, so a resolver that needs several leaves
(such as a shredded variant) prunes row groups only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Show that a crate outside DataFusion can register a
`ParquetStatisticsResolver` for its own function. A stand-in for a
shredded `variant_get` reads bounds from the shredded `typed_value` leaf,
and only uses them for row groups where the binary fallback `value`
leaf is null in every row. Without the resolver, nothing is pruned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Records the current behavior: `ORDER BY s['a'] DESC LIMIT 3` gets no
pruning predicate for its dynamic filter, while the same query on a plain
column does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`RowGroupPruner` re-checks row groups as a dynamic filter (such as a TopK
bound) tightens. It built its pruning predicate without a statistics
matcher and read statistics with the default resolvers only, so it could
never prune on a struct field or a custom resolver's expression.

Pass it the scan's `ParquetStatisticsResolvers` for both. The TopK slt
does not change yet: its filter `s['a'] IS NULL OR ...` still becomes
`true`, because `IS NULL` only accepts a column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`IS NULL` and `IS NOT NULL` only accepted a bare column, so
`get_field(s, 'a') IS NULL` became `true`. A dynamic TopK filter on a
nullable key always has the shape `key IS NULL OR key > x`, so the
`true` arm made the whole filter unprunable.

Accept any statistics key and read its null count through
`null_counts_for_expr`. For a struct field the Parquet leaf null count
also counts rows where an ancestor is null, which matches `get_field`.
`ORDER BY s['a'] DESC LIMIT 3` now skips 4 of 5 row groups, as the same
query on a plain column does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Records the current behavior: when a file stores a struct field as INT
and the table declares DOUBLE, `s['a'] > 6.5` is checked as
`CAST(get_field(s, 'a') AS DOUBLE) > 6.5` and prunes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The schema adapter reads a struct field whose file type differs from the
table type as `CAST(get_field(s, 'a') AS T)`. The comparison rewrite only
looked through casts down to a bare column, so such predicates could not
be pruned when the cast stays (for example INT to DOUBLE against 6.5).

`rewrite_expr_to_prunable` now takes the statistics key and stops at it,
so CAST, TRY_CAST, negation and NOT over a key are handled like over a
column. Order preservation is still checked for each cast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A boolean column used directly as a predicate (`WHERE flag`, `WHERE NOT
flag`) is pruned with its min and max. A boolean struct field
(`WHERE s['flag']`) was not, because the check only accepted a bare
column and looked at the column's own type.

Accept any statistics key and check the type of the key expression,
since the root of a boolean struct field is a struct.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With a raised `max_in_list_size`, a 21-value IN list on `s['a']` is
pruned through the per-value rewrite (one equality per value). The next
commit gives it the compact form without changing the pruning result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An IN list longer than 20 values (when `max_in_list_size` allows it) is
checked with one compact set-intersection test against min and max. For
a struct field it fell back to one equality check per value, because the
compact form only accepted a bare column.

Accept any statistics key, taking the value type from the key expression.
The pruning result does not change, only the size of the predicate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A predicate such as `s['a'] = 5` or `s['a'] IN (1, 2)` gives a literal
guarantee that a bloom filter can check, but `LiteralGuarantee` only
describes columns, so struct fields got none.

Before `LiteralGuarantee::analyze` runs, each distinct matched
expression is replaced with a placeholder column of a reserved name. The
guarantees on placeholders are mapped back to their expressions as
`ExprLiteralGuarantee`s, and `prune` checks them with
`PruningStatistics::contained_for_expr`. `LiteralGuarantee` and the
existing column guarantees do not change.

`always_true` counts expression guarantees, so a predicate whose only
pruning power is such a guarantee is kept. `literal_exprs` lists the
expressions, so a source can load only the bloom filters it needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Records the current behavior: the file has bloom filters for its struct
field leaves, but `s['a'] = 50` does not use them, so both row groups
are read although neither holds 50. The test also checks that `!=` and
values present in Int8, Date and Decimal fields keep their rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Parquet writes a bloom filter per leaf column, so struct fields have
their own. DataFusion only loaded bloom filters for top-level columns,
so `s['a'] = 50` could not use them.

A `ParquetStatisticsResolver` can now name the leaf whose bloom filter
holds the values of an expression, through `bloom_filter_leaf`.
`GetFieldStatisticsResolver` names the struct field leaf. The opener
loads those filters for the predicate's `literal_exprs`, and
`BloomFilterStatistics` answers `contained_for_expr` from them, with the
same rules as for a column: it never reports that a value is present.

The default returns `None`. A shredded variant cannot use it, because
some of its values may live in the binary `value` column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Records the current behavior: with a sparse build side, the hash-lookup
dynamic filter prunes the probe scan to 3 of 10 row groups for a join on
a plain column, but to none for the same join on `s['a']`. Only the
min/max bounds of the filter apply to the struct field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A hash join pushes a `HashTableLookupExpr` into the probe-side scan. It
carries a bitmap of the build-side key range, which prunes containers
whose key range falls in a gap between build keys. The bitmap term only
accepted a bare column (optionally under a widening cast), so a join on
`s['a']` was pruned by the filter's min/max bounds alone.

Accept any statistics key under the optional cast, taking the statistics
type from the key expression. The cast must still widen that type. With
build keys 0, 5000 and 9999, a join on `s['a']` now reads 3 of 10 row
groups, as the same join on a plain column does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
adriangb and others added 4 commits November 25, 2026 13:08
These cases show two wrong results: a NULL struct field in a fully
matched row group, and a real column named like a statistics
placeholder that takes a struct field's bloom filter guarantee.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A struct field such as s['a'] can be NULL when s is not nullable.
build_inverted_predicate only added IS NULL for nullable columns, so a
row group with a NULL field was marked fully matched and its rows
skipped the filter. The inverse now adds IS NULL for every expression
that the statistics matcher accepts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…efix

analyze_literal_guarantees maps placeholder columns back to matched
expressions by name. A real column with a placeholder name was mapped
to an expression, and its bloom filter guarantee pruned row groups
that match. The function now skips expression guarantees when the
predicate references such a column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…unts

These tests catch two gaps that mutation testing found. The dynamic
TopK pruner must use custom resolvers. A missing null count on a struct
field must not count as zero nulls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@adriangb

Copy link
Copy Markdown
Contributor Author

FWIW this is +400 LOC. The rest is refactored code and a lot of tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

catalog Related to the catalog crate common Related to common crate core Core DataFusion crate datasource Changes to the datasource crate physical-expr Changes to the physical-expr crates sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support row group pruning for struct field predicates

1 participant