You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "peterxcli (via GitHub)" <gi...@apache.org> on 2026/09/07 08:28:43 UTC
[PR] feat: expose struct field access for custom scalar functions [datafusion]
peterxcli opened a new pull request, #25013:
URL: https://github.com/apache/datafusion/pull/25013
## Which issue does this PR close?
Closes #21306.
## Rationale for this change
Custom scalar functions that extract struct fields currently miss Parquet leaf pruning and decoder-filter pushdown because these paths recognize `GetFieldFunc` directly. `placement()` describes where a function can execute, but does not identify the field it reads.
This draft proposes an explicit field-access capability for review.
## What changes are included in this PR?
- Add optional `ScalarUDFImpl::struct_field_access()` describing the source argument and literal field path; forward it through `ScalarUDF` and aliases and implement it for `GetFieldFunc`.
- Use the capability in Parquet projection/filter planning and physical schema adaptation, retaining the original function and argument layout.
- Preserve conservative fallback for Map/repeated-value traversal, functions without the capability, and explicit casts whose sibling conversions can fail.
The capability promises exact struct-field extraction, including ancestor null semantics. It does not cover arbitrary Variant decoding or add row-group statistics pruning. FFI forwarding is deferred; wrapped UDFs retain the default fallback.
A separate prerequisite commit fixes two existing needless-borrow lint failures with Rust 1.97.
## What is the testing strategy for this PR?
Regression tests use distinct custom UDFs, including reversed arguments and aliases. They cover chained paths, literal dots, null parents/children, reordered and narrowed schemas, missing fields, integer widening, explicit-cast errors, and Map fallback. A baseline red test reads all three leaves; the capability selects only the requested leaf. Decoder metrics verify three rows pruned when enabled and zero when the capability or pushdown is disabled.
Before rebasing from `ca5d10b75` onto `cc29ea12a`:
- Extended workspace tests: 11,233 Rust tests passed, eight ignored; all 511 SQL logic files passed.
- `cargo fmt --all`, `cargo clippy --all-targets --all-features -- -D warnings`, and `./dev/rust_lint.sh` passed.
Post-rebase Clippy and affected tests are running; results will be added here.
Existing `parquet_struct_query` benchmark, same 524,288-row file, ten samples, two execution orders (main / patch, milliseconds):
| Query | Main then patch | Patch then main |
| --- | ---: | ---: |
| Nested equality | 20.074 / 18.283 | 17.084 / 16.725 |
| Top-level filter control | 8.672 / 6.809 | 7.484 / 7.114 |
| Nested range | 18.004 / 20.202 | 18.792 / 18.003 |
These used the unoptimized CI profile on pre-rebase main and patch. They do not establish a repeatable speedup or regression; deterministic leaf masks and decoder metrics establish that the optimization occurred.
## Are there any user-facing changes?
An additive Rust UDF API lets custom exact struct-field accessors opt into existing Parquet optimizations. Existing implementations default to no capability. No SQL syntax or configuration changes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: expose UDF field access and input requirements for Parquet pruning [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #25013:
URL: https://github.com/apache/datafusion/pull/25013#discussion_r3978882438
##########
datafusion/datasource-parquet/src/projection_read_plan.rs:
##########
@@ -394,90 +385,99 @@ impl TreeNodeVisitor<'_> for PushdownChecker<'_> {
type Node = Arc<dyn PhysicalExpr>;
fn f_down(&mut self, node: &Self::Node) -> Result<TreeNodeRecursion> {
- // Handle struct field access like `s['foo']['bar'] > 10`.
- //
- // DataFusion represents nested field access as `get_field(Column("s"), "foo")`
- // (or chained: `get_field(get_field(Column("s"), "foo"), "bar")`).
- //
- // We intercept the outermost `get_field` on the way *down* the tree so
- // the visitor never reaches the raw `Column("s")` node. Without this,
- // `check_single_column` would see that `s` is a Struct and reject it.
- //
- // The strategy:
- // 1. Match `get_field` whose first arg is a `Column` (the struct root).
- // 2. Check that the *resolved* return type is primitive — meaning we've
- // drilled all the way to a leaf (e.g. `s['foo']` → Utf8).
- // 3. Record the root column index via `check_struct_field_column` and
- // return `Jump` to skip visiting the children (the Column and the
- // literal field-name args), since we've already handled them.
- //
- // If the return type is still nested (e.g. `s['nested_struct']` → Struct),
- // we fall through and let normal traversal continue, which will
- // eventually reject the expression when it hits the struct Column.
- if let Some(func) =
- ScalarFunctionExpr::try_downcast_func::<GetFieldFunc>(node.as_ref())
- {
- if let Some(recursion) = self.check_cast_struct_field_access(func) {
+ // Resolve capability-declaring accessors, including chains with
+ // different UDFs and argument layouts. Do not look through casts.
+ let mut source = node;
+ let mut paths = Vec::new();
+ while let Some(function) = source.downcast_ref::<ScalarFunctionExpr>() {
+ let Some(access) = function.struct_field_access() else {
+ break;
+ };
+ paths.push(access.field_path);
+ source = &function.args()[access.source_arg];
+ }
+ let field_path = paths.into_iter().rev().flatten().collect::<Vec<_>>();
+ if !field_path.is_empty() {
+ let return_type = node.data_type(self.file_schema)?;
+ if let Some(recursion) =
+ self.check_cast_struct_field_access(source, &field_path, &return_type)
+ {
return Ok(recursion);
}
- let args = func.args();
-
- if let Some(column) = args.first().and_then(|a| a.downcast_ref::<Column>()) {
- // for Map columns, get_field performs a runtime key lookup rather than a
- // schema-level field access so the entire Map column must be read,
- // we skip the struct field optimization and defer to normal Column traversal
- let is_map_column = self
+ if let Some(column) = source.downcast_ref::<Column>() {
+ // Resolve by name: physical column indices may still refer to
+ // an unprojected schema. Map/List paths must remain opaque.
+ let leaf_type = self
.file_schema
- .index_of(column.name())
+ .field_with_name(column.name())
.ok()
- .map(|idx| {
- matches!(
- self.file_schema.field(idx).data_type(),
- DataType::Map(_, _)
- )
- })
- .unwrap_or(false);
-
- let return_type = func.return_type();
+ .and_then(|root| {
+ field_path.iter().try_fold(root.data_type(), |ty, name| {
+ let DataType::Struct(fields) = ty else {
+ return None;
+ };
+ let mut matches =
+ fields.iter().filter(|field| field.name() == name);
+ let field = matches.next()?;
+ if matches.next().is_some() {
+ return None;
+ }
+ Some(field.data_type())
+ })
+ });
+ if leaf_type.is_some()
+ && (!return_type.is_nested()
+ || self.is_nested_type_supported(&return_type))
+ {
+ if let Some(recursion) =
+ self.check_struct_field_column(column.name(), field_path)
+ {
+ return Ok(recursion);
+ }
+ return Ok(TreeNodeRecursion::Jump);
+ }
+ }
+ }
- if !is_map_column
- && (!DataType::is_nested(return_type)
- || self.is_nested_type_supported(return_type))
+ if let Some(function) = node.downcast_ref::<ScalarFunctionExpr>()
+ && let Some(requirements) = function.required_input_fields(self.file_schema)
+ && !requirements.is_empty()
+ {
+ for (index, argument) in function.args().iter().enumerate() {
Review Comment:
Thanks @peterxcli , here is a suggestion:
**`required_input_fields` turns off the nested-column pushdown gate**
`projection_read_plan.rs:443-480`. The requirements branch returns `TreeNodeRecursion::Jump`
for every argument it claims, which skips `check_single_column` → `handle_nested_type`. That's
the check that sets `non_primitive_columns` for List/Map columns unless `allow_list_columns`
(i.e. `supports_list_predicates`, the verified `array_has*` / `IS NULL` allow-list) is true.
The accessor branch immediately above is guarded — `!return_type.is_nested() ||
self.is_nested_type_supported(&return_type)` — but this one has no type check at all, so
`prevents_pushdown()` stays `false`.
Confirmed with a scratch probe against `PushdownChecker::new(&schema, /*allow_list_columns=*/ false, false)`:
```rust
// schema: s: List<Int32>
fn required_input_fields(&self, _: ReturnFieldArgs) -> Option<Vec<InputFieldRequirement>> {
Some(vec![InputFieldRequirement { arg_index: 0, field_paths: vec![vec![]] }])
}
// => prevents_pushdown() == false (expected: true)
```
Same result for `schema: s: Struct<events: List<Int32>>` with `field_paths: vec![vec!["events".into()]]`,
and the same hole applies to `Map`. So any downstream UDF can opt itself past the gate by
declaring a requirement that prunes nothing — which contradicts this PR's own contract text:
"does not ... authorize moving the function across arbitrary operators".
Suggested fix — resolve each declared path's leaf type and apply the existing policy before
taking the shortcut, falling back to normal traversal otherwise:
```diff
if let Some(function) = node.downcast_ref::<ScalarFunctionExpr>()
&& let Some(requirements) = function.required_input_fields(self.file_schema)
&& !requirements.is_empty()
+ && requirements.iter().all(|requirement| {
+ // Reading a nested column into the row filter follows the same policy
+ // as an accessor: Struct subtrees are fine, other nested types only
+ // when the predicate set supports them. A declaration must not widen it.
+ function.args()[requirement.arg_index]
+ .return_field(self.file_schema)
+ .is_ok_and(|field| {
+ requirement.field_paths.iter().all(|path| {
+ resolve_leaf_type(field.data_type(), path).is_some_and(|leaf| {
+ matches!(leaf, DataType::Struct(_))
+ || !DataType::is_nested(leaf)
+ || self.is_nested_type_supported(leaf)
+ })
+ })
+ })
+ })
{
```
(`resolve_leaf_type` being the same name-resolving `Struct`-only walk already inlined in the
accessor branch — worth factoring out, since it now has three copies.)
A regression test in the same style as `custom_struct_accessor_does_not_prune_map_entries`
asserting `prevents_pushdown()` for a List-bearing requirement would lock this down.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: expose UDF field access and input requirements for Parquet pruning [datafusion]
Posted by "sdf-jkl (via GitHub) via github" <gi...@datafusion.apache.org>.
sdf-jkl commented on PR #25013:
URL: https://github.com/apache/datafusion/pull/25013#issuecomment-7388222978
I propose we continue in https://github.com/apache/datafusion/pull/26282 by @cetra3
@peterxcli seems to be more focused on https://github.com/apache/ozone right now
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: expose UDF field access and input requirements for Parquet pruning [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #25013:
URL: https://github.com/apache/datafusion/pull/25013#issuecomment-5642410403
@peterxcli , a suggestion:
**`try_narrow_struct_cast` can now fail the query instead of skipping the rewrite**
`schema_rewriter.rs:565` rebuilds the accessor against the physical file schema:
```rust
let extracted = Arc::new(ScalarFunctionExpr::try_new(
Arc::new(get_field_expr.fun().clone()),
args,
&self.physical_file_schema,
Arc::new(get_field_expr.config_options().clone()),
)?) as Arc<dyn PhysicalExpr>;
```
`try_new` runs `fields_with_udf` and `return_field_from_args` on the **physical** types — which differ from the logical ones by construction, since that difference is why the adapter inserted the cast you're about to drop. With the old `try_downcast_func::<GetFieldFunc>` gate the `?` was safe (`Signature::user_defined`, permissive). It isn't safe for arbitrary UDFs: a function that declares `struct_field_access` but doesn't accept the physical types now aborts the whole query, where every other path in this rewriter degrades to `Ok(None)`.
Reproduced on this branch using your own `FieldAt` helper with an `Exact` signature pinned to the logical struct type. File `s: Struct<value: Int32>`, registered schema `s: Struct<value: Int64>`, query `SELECT id FROM t WHERE field_at('value', s) > 5`:
```
declare_access=false: Ok([...]) // 1 row, as expected
declare_access=true: Err(Plan("Failed to coerce arguments to satisfy a call to
'field_at' function: coercion from Utf8, Struct(\"value\": Int32) to the
signature Exact(Utf8, Struct(\"value\": Int64)) failed"))
```
Declaring the capability should never make a working query fail. Make the rebuild best-effort:
```diff
- let extracted = Arc::new(ScalarFunctionExpr::try_new(
- Arc::new(get_field_expr.fun().clone()),
- args,
- &self.physical_file_schema,
- Arc::new(get_field_expr.config_options().clone()),
- )?) as Arc<dyn PhysicalExpr>;
+ // A third-party accessor may not accept the physical field types. That
+ // is a missed rewrite, not a query error: keep the cast and bail out.
+ let Ok(extracted) = ScalarFunctionExpr::try_new(
+ Arc::new(get_field_expr.fun().clone()),
+ args,
+ &self.physical_file_schema,
+ Arc::new(get_field_expr.config_options().clone()),
+ ) else {
+ return Ok(None);
+ };
+ let extracted = Arc::new(extracted) as Arc<dyn PhysicalExpr>;
```
Two follow-ups worth folding in:
1. `FieldAt::signature` is currently `Signature::any(2, Volatility::Immutable)` at all three construction sites, i.e. the one shape that can't hit this. Point one of them at an `Exact` signature over the logical struct type and assert the evolved query returns the right rows (unpruned) rather than erroring.
2. The `struct_field_access` doc promises implementors only "reordered or narrowed source structs". This rewrite does more — it drops the type-adapting cast and re-applies the conversion to the output, so the UDF sees the file's physical field types. Please say so in the contract, since that is the assumption this code actually relies on.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: expose UDF field access and input requirements for Parquet pruning [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #25013:
URL: https://github.com/apache/datafusion/pull/25013#issuecomment-6407291081
Convert to draft since this PR is waiting on author
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: expose struct field access for custom scalar functions [datafusion]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #25013:
URL: https://github.com/apache/datafusion/pull/25013#issuecomment-5568246205
## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/25013?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `88.83929%` with `25 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 81.71%. Comparing base ([`cc29ea1`](https://app.codecov.io/gh/apache/datafusion/commit/cc29ea12ae9c19640d98e43f5d3676aa3b334431?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`de7d5a3`](https://app.codecov.io/gh/apache/datafusion/commit/de7d5a3bf2bb02a4a5de21d8f8ebd0e929368dca?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/25013?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...ion/datasource-parquet/src/projection\_read\_plan.rs](https://app.codecov.io/gh/apache/datafusion/pull/25013?src=pr&el=tree&filepath=datafusion%2Fdatasource-parquet%2Fsrc%2Fprojection_read_plan.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9kYXRhc291cmNlLXBhcnF1ZXQvc3JjL3Byb2plY3Rpb25fcmVhZF9wbGFuLnJz) | 84.68% | [15 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/25013?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...usion/physical-expr-adapter/src/schema\_rewriter.rs](https://app.codecov.io/gh/apache/datafusion/pull/25013?src=pr&el=tree&filepath=datafusion%2Fphysical-expr-adapter%2Fsrc%2Fschema_rewriter.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1leHByLWFkYXB0ZXIvc3JjL3NjaGVtYV9yZXdyaXRlci5ycw==) | 83.33% | [5 Missing :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/25013?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [datafusion/functions/src/core/getfield.rs](https://app.codecov.io/gh/apache/datafusion/pull/25013?src=pr&el=tree&filepath=datafusion%2Ffunctions%2Fsrc%2Fcore%2Fgetfield.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9mdW5jdGlvbnMvc3JjL2NvcmUvZ2V0ZmllbGQucnM=) | 88.23% | [0 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/25013?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [datafusion/physical-expr/src/scalar\_function.rs](https://app.codecov.io/gh/apache/datafusion/pull/25013?src=pr&el=tree&filepath=datafusion%2Fphysical-expr%2Fsrc%2Fscalar_function.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1leHByL3NyYy9zY2FsYXJfZnVuY3Rpb24ucnM=) | 97.91% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/25013?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #25013 +/- ##
========================================
Coverage 81.70% 81.71%
========================================
Files 1127 1127
Lines 415654 415798 +144
Branches 415654 415798 +144
========================================
+ Hits 339614 339755 +141
+ Misses 56101 56100 -1
- Partials 19939 19943 +4
```
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/25013?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: expose UDF field access and input requirements for Parquet pruning [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #25013:
URL: https://github.com/apache/datafusion/pull/25013#issuecomment-5636482935
@peterxcli , here is a suggestion:
**requirement paths ending at a `Struct` bypass the List/Map pushdown policy**
`projection_read_plan.rs:440-446` short-circuits on `Struct` before looking at what the struct
contains, so the policy guard doesn't hold for anything nested below a selected sub-struct:
```rust
resolve_struct_field_type(&data_type, path).is_some_and(|leaf| {
matches!(leaf, DataType::Struct(_)) // <-- accepts the whole subtree unseen
|| !leaf.is_nested()
|| self.is_nested_type_supported(leaf)
})
```
Repro (dropped into `projection_read_plan::test`, UDF requires `["selected"]` on
`s: Struct<selected: Struct<arr: List<Int32>>>`, `allow_list_columns = false`):
```
PROBE prevents_pushdown (list nested in selected struct, allow_lists=false) = false
PROBE baseline whole-struct prevents_pushdown = true
```
The same list data reached via `get_field(s,'selected')` or a whole-column reference to `s` is
blocked. `allow_list_columns` comes from `supports_list_predicates`, i.e. the allowlist of
verified predicates (`array_has`/`array_has_all`/`array_has_any`, `IS [NOT] NULL`) — a UDF
requirement isn't on it, so declaring `required_input_fields` becomes a general escape hatch for
getting list/map columns into the row filter. That's precisely what the comment two lines above
says must not happen:
```rust
// Declaring dependencies cannot bypass the List/Map pushdown policy.
```
Map is affected identically, since the subtree is never inspected.
Suggested fix — check every leaf of the selected subtree instead of accepting `Struct` wholesale:
```diff
+ /// Whether every leaf below `data_type` is acceptable under the current
+ /// nested-pushdown policy. A selected sub-struct must not smuggle a List
+ /// or Map past the policy that a direct reference to it would hit.
+ fn subtree_is_pushable(&self, data_type: &DataType) -> bool {
+ match data_type {
+ DataType::Struct(fields) => fields
+ .iter()
+ .all(|field| self.subtree_is_pushable(field.data_type())),
+ other => !other.is_nested() || self.is_nested_type_supported(other),
+ }
+ }
```
```diff
data_type.is_some_and(|data_type| {
requirement.field_paths.iter().all(|path| {
- resolve_struct_field_type(&data_type, path).is_some_and(|leaf| {
- matches!(leaf, DataType::Struct(_))
- || !leaf.is_nested()
- || self.is_nested_type_supported(leaf)
- })
+ resolve_struct_field_type(&data_type, path)
+ .is_some_and(|leaf| self.subtree_is_pushable(leaf))
})
})
```
Existing `udf_input_requirements_respect_nested_pushdown_policy` cases still pass under this
(`Struct<value: Int32>` is all-primitive). Worth extending that test's type matrix with a
`Struct` wrapping each of the List/Map variants so the nested shape is pinned too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: expose UDF field access and input requirements for Parquet pruning [datafusion]
Posted by "cetra3 (via GitHub)" <gi...@apache.org>.
cetra3 commented on PR #25013:
URL: https://github.com/apache/datafusion/pull/25013#issuecomment-6157852949
Thanks for this, and for the downstream validation in datafusion-variant. At Pydantic we're moving our attribute storage to shredded Variant, so this is directly on our path. I've been exploring the same problem, and opened #26282 as a draft. It builds on the ideas here, and I'd like to converge rather than run two competing designs.
The main differences:
1. **One capability behind an accessor, instead of two hooks on `ScalarUDFImpl`.** `ScalarUDFImpl::as_nested_input_access()` returns `Option<&dyn NestedInputAccess>` and defaults to `None`. In this PR, `ScalarFunctionExpr::required_input_fields` resolves every argument's field (schema lookups, plus `reassign_expr_columns` and `return_field` for non-column arguments) before asking the UDF. It does that for every function node, at planning and again per file, even though almost every function returns `None`. With the accessor, functions without the capability cost one virtual call. It also keeps the scan-oriented contract off the main trait.
2. **`get_field` uses the same capability.** The Parquet read planner has a single code path for it and for any other function, with the same `get_field` behaviour as on `main`. That makes a separate `struct_field_access` unnecessary: a pure accessor implements `required_fields` the way `get_field` does.
3. **A second method, `output_statistics`, for row group and page pruning.** Given the statistics of the fields a call reads within a row group or page, the function returns statistics for its output. `get_field` passes the leaf's statistics through, so `WHERE s['a'] > 5` can now skip row groups and pages, which `main` can't do. A Variant accessor returns the typed leaf's statistics only where every fallback `value` on the path is null in that container (or the typed leaf has no nulls). That's the soundness guard Spark uses (SPARK-55817), and it keeps all Variant knowledge in the UDF.
Inputs are still `ReturnFieldArgs` against the per-file physical schema, and requirements are still struct field paths, so the core idea is the same as yours.
**Downstream validation.** I ported your datafusion-variant branch to it. `required_variant_input_fields` carried over almost unchanged. The one difference is that it lists leaves rather than ending a path at the typed subtree, because the draft only narrows to leaf paths so far. Your `parquet_input_fields` test passes unchanged against the new trait. I also added a test on real `shred_variant` data, with `k` shredded as Int32 and one value falling back. `variant_get(v, 'k', 'Int64') > 350` skips 2 of 4 row groups, and the row group holding the fallback value is always read and its row returned.
**Benchmark.** The draft adds `benchmarks/src/bin/nested_access.rs`: 1M rows, 50 shredded keys, and a few fallback values in some row groups. Reading one key drops from 479 MB to 9.6 MB. A selective filter on a sorted key then drops from 19.6 MB to 6.4 MB with `output_statistics`, skipping 5 of 8 row groups. The two row groups with fallback values are correctly kept.
How would you like to proceed? One option is reshaping this PR along those lines. Another is splitting #26282 into reviewable pieces with you as co-author: the trait plus read narrowing first, then statistics pruning. I'm happy either way, and I don't want to duplicate the work you've already done here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: expose UDF field access and input requirements for Parquet pruning [datafusion]
Posted by "peterxcli (via GitHub)" <gi...@apache.org>.
peterxcli commented on PR #25013:
URL: https://github.com/apache/datafusion/pull/25013#issuecomment-5582978854
I benchmarked a downstream implementation of this capability in [peterxcli/datafusion-variant#1](https://github.com/peterxcli/datafusion-variant/pull/1), using DataFusion commit `1180ae33d9903de607cd8dd5cd04c3efbbfa10b4` from this PR.
The partially shredded workload shows a substantial benefit even though the encoded root `value` column must still be read.
### Partially shredded Variant results
Median execution time with a warm filesystem cache:
| Query | Before | PR head, capability disabled | PR head, capability enabled | Before / enabled |
|---|---:|---:|---:|---:|
| Direct `variant_get` projection | 768.94 ms | 755.45 ms | 179.32 ms | **4.29x** |
| Selective `variant_get` filter | 827.26 ms | 818.26 ms | 183.94 ms | **4.50x** |
| `SUM(variant_get(...))` | 778.68 ms | 817.34 ms | 782.58 ms | Approximately unchanged |
Parquet bytes requested fall from **1,350 MB to 265 MB** for projection and **1,357 MB to 271 MB** for filtering—about **80% fewer bytes**. The capability-disabled control uses the same new dependencies and extraction implementation, isolating the effect of the input-field declaration from the DataFusion/Arrow upgrade.
Cold-cache advisory trials gave **4.57x** and **4.20x** speedups for projection and filtering. Linux storage-read counters fell from approximately **1,356 MB to 294 MB / 300 MB**, respectively. These counters include read-ahead; eviction used `POSIX_FADV_DONTNEED` on the benchmark file, without controlling the VM host's storage cache. Warm trials recorded zero storage-read bytes, so their gains reflect reduced processing of cached Parquet data.
### Setup and correctness
- One deterministic dataset: **1,048,576 rows**, 16 row groups, Snappy compression, eight unrelated 128-byte typed string fields, and a 256-byte field left encoded in root `value` on every row. The file is approximately 1.36 GB, including 265 MB in that encoded column.
- Every tenth `age` exceeds 4 billion and requires encoded fallback from its Int32 shredded field. The filter matches these rows; all row groups contain matches.
- Before: downstream `9e1c84698150eaef7b640f50f907dd8e585174f5` with DataFusion 54 / Arrow 58.3.0. After: downstream `fc1ef311d1270f9016dce07a48f893155fb06c8e` with this DataFusion commit / Arrow 59.2.0. Dependency versions match each revision's lockfile.
- Optimized release builds, Rust 1.98.0, a 16-vCPU AMD EPYC 7282 VM with 31 GiB RAM, four query workers/target partitions, and affinity to CPUs 0–7. Compilation finished before timing.
- Twelve warm trials per case; six cold advisory trials for partially shredded data. Variant execution order was balanced. Times exclude planning and table registration.
- **All 405 executions passed result-count/checksum checks**, including warmups and raw/all-object-fields-shredded controls. Enabled filters report **943,718 decoder-pruned rows**, with **104,858 matching rows**; before and capability-disabled runs report zero decoder-pruned rows.
### Remaining limitation
`SUM(variant_get(...))` did **not** receive input pruning in the observed plan: the function remains inside `AggregateExec`, and the scan has `projection=[v]`. Direct projection reaches `DataSourceExec` as a function expression and benefits from the declaration. Raw Variant data showed essentially unchanged performance and read volume.
These are results for a wide synthetic dataset with a literal path and typed Int64 extraction. They demonstrate input pruning and decoder-filter benefits, rather than a general speedup for every Variant query or row-group statistics pruning.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: expose UDF field access and input requirements for Parquet pruning [datafusion]
Posted by "alamb (via GitHub) via github" <gi...@datafusion.apache.org>.
alamb commented on PR #25013:
URL: https://github.com/apache/datafusion/pull/25013#issuecomment-7015071830
I tried to explain the main usecase for this change on
- https://github.com/apache/datafusion/issues/27588#top
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org