Skip to content

Further refactoring of type coercion function code - #19603

Merged
Jefffrey merged 5 commits into
apache:mainfrom
Jefffrey:further-refactoring-type-coercion
Jan 28, 2026
Merged

Further refactoring of type coercion function code#19603
Jefffrey merged 5 commits into
apache:mainfrom
Jefffrey:further-refactoring-type-coercion

Conversation

@Jefffrey

@Jefffrey Jefffrey commented Jan 2, 2026

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

Found lots of code duplicated here, so unifying them.

What changes are included in this PR?

  • Reduce code duplication around handling scalar/aggregate/window UDFs in type coercion related code, via usage of new UDFCoercionExt trait which unifies some of their behaviours (introduced by Refactor duplicate code in type_coercion/functions.rs #19518)
  • Deprecate functions can_coerce_from() and generate_signature_error_msg() to work towards minimizing our public API surface
  • Fix some UDF signatures which nested UserDefined within OneOf
  • Fix bug where type coercion rewrites weren't being applied to arguments of non-aggregate window UDFs

Are these changes tested?

Existing tests.

Are there any user-facing changes?

Deprecated some functions.

@github-actions github-actions Bot added logical-expr Logical plan and expressions optimizer Optimizer rules core Core DataFusion crate functions Changes to functions implementation spark labels Jan 2, 2026
}
}

/// Performs type coercion for scalar function arguments.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reorganizing these so the only public function of this file is near the top (fields_with_udf())

Comment thread datafusion/expr/src/type_coercion/functions.rs Outdated
Comment on lines +155 to +158
Expr::ScalarFunction(_)
| Expr::WindowFunction(_)
| Expr::AggregateFunction(_) => {
Ok(self.to_field(schema)?.1.data_type().clone())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reusing existing logic from to_field() implementation


/// Verify that function is invoked with correct number and type of arguments as
/// defined in `TypeSignature`.
fn verify_function_arguments<F: UDFCoercionExt>(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the new UDFCoercionExt trait we can now more easily share common code between scalar, aggregate and window UDFs

Comment thread datafusion/expr/src/expr_schema.rs Outdated
Comment thread datafusion/expr/src/utils.rs Outdated
pub fn new() -> Self {
Self {
signature: Signature::one_of(
vec![TypeSignature::Nullary, TypeSignature::UserDefined],

@Jefffrey Jefffrey Jan 2, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really like the idea of having UserDefined nested within a OneOf signature, so amending some functions which are doing this. Ideally a function declaring UserDefined should handle all of its coercion logic itself, instead of mixing this custom logic with the other signature API.

Comment on lines +691 to +692
expr::WindowFunctionDefinition::WindowUDF(udf) => {
coerce_arguments_for_signature(args, self.schema, udf.as_ref())?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This arm for coercing non-aggregate window UDFs actually was missing; adding this back in lead to discovering some UDF window tests were incorrect (see next comment)

fn new(test_state: Arc<TestState>) -> Self {
let signature =
Signature::exact(vec![DataType::Float64], Volatility::Immutable);
Signature::exact(vec![DataType::Int64], Volatility::Immutable);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sample UDF declared it accepted f64's but internally it acted as if input was i64; this was never caught because apparently type coercion wasn't being run on non-aggregate window functions, and the input data was already i64. Nice little fix.

@Jefffrey
Jefffrey marked this pull request as ready for review January 2, 2026 09:41

@martin-g martin-g left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

TypeSignature::Variadic(valid_types) => valid_types
.iter()
.map(|valid_type| current_types.iter().map(|_| valid_type.clone()).collect())
.map(|valid_type| vec![valid_type.clone(); current_types.len()])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏻

///
/// Otherwise, returns an error if there's a type mismatch between
/// the window function's signature and the provided arguments.
fn window_function_field(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has been inlined to to_field()

/// (losslessly converted) into a value of `type_to`
///
/// See the module level documentation for more detail on coercion.
#[deprecated(since = "53.0.0", note = "Unused internal function")]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was only ever used in a test; trying to minimize our API surface area for simplicity so deprecating this

/// round(Float32)
/// ```
#[expect(clippy::needless_pass_by_value)]
#[deprecated(since = "53.0.0", note = "Internal function")]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly removing this from our public API since I see no need for it to be public

@alamb alamb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like a nice cleanup to me -- thank you @Jefffrey and @martin-g

@Jefffrey
Jefffrey added this pull request to the merge queue Jan 28, 2026
Merged via the queue into apache:main with commit a77e5a5 Jan 28, 2026
32 checks passed
@Jefffrey
Jefffrey deleted the further-refactoring-type-coercion branch January 28, 2026 13:54
de-bgunter pushed a commit to de-bgunter/datafusion that referenced this pull request Mar 24, 2026
## Which issue does this PR close?

<!--
We generally require a GitHub issue to be filed for all bug fixes and
enhancements and this helps us generate change logs for our releases.
You can link an issue to this PR using the GitHub syntax. For example
`Closes apache#123` indicates that this PR will close issue apache#123.
-->

- Follow up to apache#19518
- Initial work before tackling apache#19004

## Rationale for this change

<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->

Found lots of code duplicated here, so unifying them.

## What changes are included in this PR?

<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->

- Reduce code duplication around handling scalar/aggregate/window UDFs
in type coercion related code, via usage of new `UDFCoercionExt` trait
which unifies some of their behaviours (introduced by apache#19518)
- Deprecate functions `can_coerce_from()` and
`generate_signature_error_msg()` to work towards minimizing our public
API surface
- Fix some UDF signatures which nested `UserDefined` within `OneOf`
- Fix bug where type coercion rewrites weren't being applied to
arguments of non-aggregate window UDFs

## Are these changes tested?

<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code

If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
-->

Existing tests.

## Are there any user-facing changes?

<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
-->

Deprecated some functions.

<!--
If there are any breaking changes to public APIs, please add the `api
change` label.
-->

---------

Co-authored-by: Andrew Lamb <andrew@nerdnetworks.org>
Stazer added a commit to Stazer/datafusion that referenced this pull request Aug 23, 2026
…ls, matching pre-UDWF and documented early-validation behavior

Prior to converting these to User Defined Window Functions (apache#13201,
2024-11-13), the built-in signatures were exact: first_value/last_value
took exactly 1 argument, nth_value exactly 2 - there was never a
zero-argument form. The UDWF conversion introduced `TypeSignature::Any(0)`
(later renamed to `Nullary` in apache#19603) into the shared OneOf signature,
which let a zero-argument call (e.g. `first_value()`) pass type checking.
`NthValueEvaluator::evaluate` unconditionally indexes into `values[0]`,
so this caused a process-killing panic (index out of bounds) instead of
a query error.

Two fixes, matching two separate safety nets that already exist in this
codebase for exactly this class of bug:

1. Remove the zero-argument form from the signature. None of these
   functions have a meaningful 0-arg form - first_value/last_value need
   1, nth_value needs 2, matching lead()/lag()'s analogous Any(1..N)
   signature, which never included it. This lets DataFusion's generic
   argument-count check (datafusion_expr::type_coercion::functions::data_types)
   reject `first_value()` cleanly during logical planning.

2. Validate the argument count in `partition_evaluator()` itself. Per
   the review discussion on apache#13201 (comment 2454209975) and the resulting
   `create_udwf_window_expr` code in
   datafusion/physical-plan/src/windows/mod.rs, UDWF signatures are
   deliberately permissive and argument validation is expected to happen
   inside the evaluator - `create_evaluator()` is called during physical
   planning specifically to surface such errors early rather than during
   execution. That validation was simply never implemented for the
   zero-argument case here.

Together these give defense in depth: the signature fix rejects the
common case even before physical planning, and the evaluator-level
check protects any caller that reaches partition_evaluator() through
a path other than SQL-level type coercion (e.g. the DataFrame API).

Verified both `select first_value() over ()` and
`select first_value() over (order by x)` - the latter used to return
an unrelated Arrow schema-mismatch error by coincidence rather than
because it was ever a valid call - now fail identically and cleanly
during planning.

Adds sqllogictest coverage for all three functions and unit tests for
both the signature and the evaluator-level guard.
Stazer added a commit to Stazer/datafusion that referenced this pull request Aug 23, 2026
…ls, matching pre-UDWF and documented early-validation behavior

Prior to converting these to User Defined Window Functions (apache#13201,
2024-11-13), the built-in signatures were exact: first_value/last_value
took exactly 1 argument, nth_value exactly 2 - there was never a
zero-argument form. The UDWF conversion introduced `TypeSignature::Any(0)`
(later renamed to `Nullary` in apache#19603) into the shared OneOf signature,
which let a zero-argument call (e.g. `first_value()`) pass type checking.
`NthValueEvaluator::evaluate` unconditionally indexes into `values[0]`,
so this caused a process-killing panic (index out of bounds) instead of
a query error.

Two fixes, matching two separate safety nets that already exist in this
codebase for exactly this class of bug:

1. Remove the zero-argument form from the signature. None of these
   functions have a meaningful 0-arg form - first_value/last_value need
   1, nth_value needs 2, matching lead()/lag()'s analogous Any(1..N)
   signature, which never included it. This lets DataFusion's generic
   argument-count check (datafusion_expr::type_coercion::functions::data_types)
   reject `first_value()` cleanly during logical planning.

2. Validate the argument count in `partition_evaluator()` itself. Per
   the review discussion on apache#13201 (comment 2454209975) and the resulting
   `create_udwf_window_expr` code in
   datafusion/physical-plan/src/windows/mod.rs, UDWF signatures are
   deliberately permissive and argument validation is expected to happen
   inside the evaluator - `create_evaluator()` is called during physical
   planning specifically to surface such errors early rather than during
   execution. That validation was simply never implemented for the
   zero-argument case here.

Together these give defense in depth: the signature fix rejects the
common case even before physical planning, and the evaluator-level
check protects any caller that reaches partition_evaluator() through
a path other than SQL-level type coercion (e.g. the DataFrame API).

Verified both `select first_value() over ()` and
`select first_value() over (order by x)` - the latter used to return
an unrelated Arrow schema-mismatch error by coincidence rather than
because it was ever a valid call - now fail identically and cleanly
during planning.

Adds sqllogictest coverage for all three functions and unit tests for
both the signature and the evaluator-level guard.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate functions Changes to functions implementation logical-expr Logical plan and expressions optimizer Optimizer rules spark

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants