Repository navigation
Conversation
4793006 to
68509e0
Compare
`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. The 57.0.0 upgrade guide describes the new import path. 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>
`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>
`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. Add an optional expression next to each required column, and a `StatsKey` that `ColumnReferenceCount` returns. Every helper that reads statistics takes a `StatsKey`, and `RequiredColumns::stat_key_expr` replaces the per-statistic `*_column_expr` wrappers. 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`. A key works in every place a column does: - comparisons, `IS [NOT] NULL`, and a bare or negated boolean key - `CAST`, `TRY_CAST` and `NOT` over a key - the compact form of a long `IN` list - the key range bitmap of a hash join lookup The helpers take the `PredicateBuildContext`, which holds the matcher. `RequiredColumns::single_column` returns `None` when a key is an expression. The new `single_key` returns the column or expression, and `PruningPredicate::stats_key_exprs` lists the expression keys of the predicate. 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 each struct field, but a predicate on a struct field such as `s['a'] > 15` cannot prune row groups or pages yet. Add `parquet_struct_field_pruning.slt` with the current output, so the next commits show what changes. It covers row groups, two files, the page index, a dynamic TopK filter, struct type drift, a long `IN` list, a hash join dynamic filter, and a struct field that is NULL in a non-nullable struct. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Parquet stores statistics for each struct field, but the scan only gives column statistics to the row group pruning predicate. A predicate such as `s['a'] > 15` therefore reads every row group. Add the `statistics_resolver` module: - `ParquetStatisticsResolver::bind` binds an expression to the leaves of one file and returns a `BoundExprStatistics`, or `None` when the file has no statistics for it. - `GetFieldStatisticsResolver` binds `get_field` paths through structs. - `FileStatisticsResolvers` binds the scan's resolvers to one file and caches each binding. It is the `StatisticsExprMatcher` of the file's pruning predicates, so an expression is a key only when it binds. An expression that does not bind is not a key, and the predicate uses keys in its children. - `ParquetSource::with_statistics_resolver` adds a resolver from outside DataFusion. A source with a custom resolver does not serialize without a custom codec. `RowGroupPruningStatistics` reads expression statistics from the binding. The dynamic `RowGroupPruner` uses the same resolvers, so a TopK or hash join filter on a struct field prunes row groups too. A full match must also prove that the expression has no nulls. A struct field can be NULL when its struct column is not nullable, so the inverted predicate adds `IS NULL` for each expression key. The slt shows the row groups that are now pruned. `EXPLAIN` does not bind resolvers yet, so its pruning predicate is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The `EXPLAIN` output of a Parquet scan shows a pruning predicate that is built without a file, so it has no statistics resolvers. Its predicate for `s['a'] > 15` does not show the struct field statistics that the scan uses. Bind the resolvers for the display to the Parquet schema that a file written with the logical file schema would have. The display then builds the predicate with `TableSchema::file_schema` instead of `TableSchema::table_schema`, because the Parquet schema has no partition columns. The `EXPLAIN` plans of `parquet_struct_field_pruning.slt` and `projection_pushdown.slt` now show the struct field keys. 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` reads every page of a row group. A binding can now name the one Parquet leaf whose pages hold an expression, through `BoundExprStatistics::page_index_leaf`. The page filter builds its predicates with the file's resolvers as the matcher and prunes the pages of that leaf. `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 binding that needs several leaves (such as a shredded variant) prunes row groups only. The slt shows the pages that are now pruned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`ParquetSource::with_statistics_resolver` lets another crate prune on its own expressions, such as a variant extension with shredded columns. Only the built-in struct field resolver has tests so far. Add integration tests with resolvers defined outside DataFusion: - a fake shredded variant resolver prunes row groups, with a static and with a dynamic filter, and nothing is pruned without it - a missing struct field null count keeps the row group - an outer expression that does not bind falls back to the statistics of its inner struct field, one that binds uses its own statistics, and each of two files binds on its own Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Parquet writes a bloom filter for each struct field leaf, but the scan only reads the bloom filters of top-level columns. Row groups that span a wide range of `s['a']` cannot be pruned by `s['a'] = 50`. Add cases with the current output, so the next commits show what changes. They cover struct fields of several types, `!=`, values that are present, and a real column whose name looks like the placeholder that the literal guarantee analysis uses for statistics keys. 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 get none. Before `LiteralGuarantee::analyze` runs, each distinct expression key is replaced with a placeholder column of a reserved name. The guarantees on placeholders are mapped back to their expressions, and `prune` checks them with `PruningStatistics::contained_for_expr`. `LiteralGuarantee` and the existing column guarantees do not change. A real column whose name starts with the placeholder prefix would be mistaken for a key, so a predicate with such a column gets no expression guarantees. `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>
Parquet writes a bloom filter per leaf column, so struct fields have their own. DataFusion only loads bloom filters for top-level columns, so `s['a'] = 50` cannot use them. A binding can now name the leaf whose bloom filter holds the values of an expression, through `BoundExprStatistics::bloom_filter_leaf`. The struct field binding names its leaf. The opener loads those filters for the predicate's `literal_exprs` in the same loop as the column filters, 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. The slt shows the two row groups that the bloom filters now prune. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
68509e0 to
866bb35
Compare
…-stats-pruning # Conflicts: # docs/source/library-user-guide/upgrading/57.0.0.md
| /// Only struct paths are supported. A path through a map is a runtime key | ||
| /// lookup, and a field below a list has statistics per element, not per row. | ||
| #[derive(Debug, Default)] | ||
| pub(crate) struct GetFieldStatisticsResolver; |
There was a problem hiding this comment.
The fake Variant resolver has to match its function by name and restate which leaves it reads. With #26282, a single built-in resolver could cover any function with the NestedInputAccess capability: bind gets the leaves from required_fields (which is called with each file's physical schema, so per-file shredding works), and statistics calls output_statistics. get_field would go through the same path with no GetFieldFunc downcast, and a function author would get pruning and narrowed reads from one implementation. The resolver trait would stay for the format-specific cases, like binding a cast to a sidecar leaf. It feels like this PR and #26282 fit together well: this one gives output_statistics a general place to be called from, and that one would no longer need its placeholder-column rewrite.
There was a problem hiding this comment.
I'm not convinced there can be an implementaiton that is shared by struct field access and variant. Variant has all of the quirks of needing stats to determine if the shredded field can be trusted, etc. But if there can be then I agree something like #26282 could be used to implement it with this PR as the API that backs it.
| /// The built-in resolver for struct fields is always present. | ||
| /// | ||
| /// [`ParquetStatisticsResolver`]: crate::statistics_resolver::ParquetStatisticsResolver | ||
| pub fn with_statistics_resolver( |
There was a problem hiding this comment.
This only reaches scans where the caller builds the ParquetSource by hand. Is there a route for ListingTable or CREATE EXTERNAL TABLE, where the user registers a UDF but never sees the source?
There was a problem hiding this comment.
We can add that API later and wire it just like the other similar options.
| &self, | ||
| expr: &Arc<dyn PhysicalExpr>, | ||
| ) -> Option<Arc<dyn BoundExprStatistics>> { | ||
| if let Some(bound) = self.lock_bindings().get(expr) { |
There was a problem hiding this comment.
matches is called for every non-column node the rewrite visits, and bind starts with a HashMap lookup keyed by the expression, which hashes that node's whole subtree under the mutex. Once one key is bound the map is non-empty, so a long OR chain or a large dynamic filter hashes quadratically, per file, and again each time a dynamic filter updates. Could the resolvers get a cheap reject before the lookup?
There was a problem hiding this comment.
Agreed the quadratic behavior is not ideal. I will look into what we can do.
The matcher answered `matches(expr) -> bool`, and the statistics later looked the same expression up again. Parquet joined the two with a per-file `HashMap` keyed by expression. Every lookup hashed the whole subtree of the node, so building a predicate cost the sum of all subtree sizes per file and per dynamic filter update: O(n^2) for a left-deep `OR` chain, and a large `IN` list was hashed again at every ancestor. `StatisticsExprMatcher::bind` now returns an opaque binding. The predicate keeps it in a new `StatsExpr` key and passes that key to the `*_for_expr` methods of `PruningStatistics`. Parquet reads the statistics, page index leaf and bloom filter leaf from the binding. The cache, its mutex and the resolver plumbing in the row group and page statistics are gone. Bloom filters of expressions are keyed by leaf, and two keys on the same leaf load its bloom filter once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Which issue does this PR close?
GetFieldFunc#21306.variant_get) can plug in.get_field, through aScalarUDFImplcapability. This PR puts the knowledge in the data source instead, because which leaf holds the statistics depends on the file format and the file (for example, Variant shredding differs per file).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'], becausePruningPredicateonly knows top-level columns.Example
A file with 4 row groups of 3 rows each,
s: {a: int, b: int}:s['a']The same thing, for other access paths:
mains['a'] > 15(row groups)s['a'] < 10over 2 filesORDER BY s['a'] DESC LIMIT 3(TopK dynamic filter)s['a'] = 50with bloom filterss['a'], build keys 0, 5000, 9999fake_variant_get(v, 'a') > 5with a custom resolver (test)What changes are included in this PR?
API overview
Three layers. Each one knows only what it needs:
PruningPredicatedatafusion-pruningPruningStatisticsdatafusion-physical-expr-commonParquetStatisticsResolverdatafusion-datasource-parquetHow they fit together, for one file:
sequenceDiagram participant O as Parquet opener participant F as FileStatisticsResolvers participant R as resolver (get_field, variant_get, ...) participant P as PruningPredicate participant S as RowGroupPruningStatistics O->>F: per-file setup (resolvers, file schemas) O->>P: build(predicate, matcher = F) P->>F: bind(s['a']) F->>R: bind(s['a'], schemas) R-->>F: Some(bound), leaf 3 F-->>P: Some(binding) → s['a'] is a key Note over P: key = StatsExpr(s['a'], binding)<br/>rewrite: s['a'] > 15 → s['a']_max > 15 O->>P: prune(S) P->>S: max_values_for_expr(key) S->>R: key.binding().statistics(Max, leaf stats) R-->>P: [3, 12, 20, 32] (one per row group)The binding is the only link between a key and its statistics. Nothing looks the expression up again, so there is no cache, and a key cannot be read with another file's statistics. The same per-file
Fdrives page, bloom filter, full-match, TopK and hash join pruning.datafusion-pruningThe rewrite walks each side of a comparison top down. The first matched sub-expression becomes the key, the same as a column:
A key must read exactly one column and have a non-nested type. Every rewrite that handles a column handles a key: comparisons,
IS [NOT] NULL,CAST/TRY_CAST/NOT/negation, booleans, compactIN, literal guarantees (bloom filters) and the hash join bitmap.PruningStatistics(moved todatafusion-physical-expr-common)All default to
None, so existing implementations keep compiling. A null entry means "unknown", never a guess. A source finds its own binding by type, so it must bind a private type. The Parquet implementations only forward to the binding:datafusion-datasource-parquetBuilt in:
get_field. One leaf, so every kind of pruning works:Outside DataFusion: shredded
variant_get(v, 'a')(sketch of the test resolver). The value lives in two leaves, so bounds are only valid where no row fell back to the binary column:The key can differ by file, because
bindruns per file:EXPLAIN binds against a Parquet schema built from the Arrow file schema, so keys whose leaves exist only in real files (shredded variant) do not show in the EXPLAIN
pruning_predicate. The scan still uses them.How to review
Review commit by commit. Refactors come first and change no behavior. Each
test:slt commit records the output before the change, and eachfeat:commit's slt diff shows its effect.refactor:movePruningStatisticstodatafusion-physical-expr-common(mechanical, plus upgrade guide entry)refactor:pass read-only predicate settings asPredicateBuildContextfeat:*_for_exprmethods onPruningStatisticsrefactor:key statistics by a column or an expression (StatsKey), no behavior changefeat:StatisticsExprMatcher: keys in comparisons,IS [NOT] NULL, casts,NOT, booleans, compactIN, hash lookuptest:slt for struct field pruning (output onmain)feat:Parquet row groups with resolvers (bind,BoundExprStatistics, TopK, full match)feat:show statistics keys in the EXPLAINpruning_predicatefeat:Parquet pages with resolverstest:resolver from outside DataFusion (fakevariant_get)test:slt for bloom filters on struct fields (output before the change)feat:literal guarantees for statistics keysfeat:bloom filters on struct fieldsperf:carry the resolver binding in the statistics key (replaces a per-file cache, see the timings below)What is the testing strategy for this PR?
parquet_struct_field_pruning.slt:EXPLAIN ANALYZEmetrics for every case in the table above, plus null structs vs null fields, type drift (INTfile,DOUBLEtable) and!=on Int8/Date/Decimal.expr_statistics_resolver.rs: a fakevariant_getwith its own resolver, static and dynamic filters, a file with no null counts, and per-file binding with fallback to an inner key.Unit tests in
pruning_predicate.rsfor key rewrites and literal guarantees.Fuzzing (random struct data,
target_partitions,pushdown_filters) and mutation testing against the slt and Rust tests.Building one file's pruning predicate for a left-deep
ORofs['a'] = iterms (release build, local timing test, mean of 3 runs):The cache hashed the whole subtree of each node on every lookup, so its cost grew faster than quadratic. With the binding the cost is linear.
Not in this PR
Statistics/ColumnStatistics#20707).s['a'](Read only required Parquet leaf columns for UDFs on nested fields (e.g. shredded Variant access withvariant_get) #27588).variant_getresolver. It belongs withvariant_getin its own crate. The test resolver shows the shape it needs: two leaves per key, and unknown bounds where a row falls back to the binary column.Are there any user-facing changes?
Yes, and one is breaking:
PruningStatisticsmoves fromdatafusion-commontodatafusion-physical-expr-common*_for_exprmethods with defaultNoneRequiredColumns::single_column()returnsNonefor an expression keypruning_predicateforget_fieldfiltersStatisticsExprMatcher,StatsExpr,ParquetStatisticsResolver,BoundExprStatistics,ParquetLeafStatistics,ExprStatisticsKind,leaf_index_by_path,ParquetSource::with_statistics_resolverParquetSourcewith a custom resolver does not serialize to proto🤖 Generated with Claude Code