Fix TopK aggregation for UTF-8/Utf8View group keys and add safe fallback for unsupported string aggregates (#19285)

## Which issue does this PR close?

* Closes #19219.

## Rationale for this change

A `GROUP BY ... ORDER BY <aggregate> ... LIMIT` query can trigger
DataFusion’s TopK aggregation optimization. In affected releases,
queries grouping by text columns—especially `Utf8View` produced via SQL
`varchar` mappings / `arrow_cast`—could fail at execution time with an
error such as `Can't group type: Utf8View`.

This happens because the optimizer may select the TopK aggregation path
even when the underlying TopK data structures (heap/hash table) do not
fully support the specific key/value Arrow types involved. Disabling
`datafusion.optimizer.enable_topk_aggregation` is a workaround, but it
forces users to trade correctness for performance.

This PR makes TopK type support explicit and consistent across the
optimizer and execution, adds support for UTF-8 string value heaps, and
ensures unsupported key/value combinations fall back to the standard
aggregation implementation rather than panicking.

## What changes are included in this PR?

* **Centralized TopK type validation**

* Introduced `topk_types_supported(key_type, value_type)` (in
`physical-plan/src/aggregates/mod.rs`) to validate both grouping key and
min/max value types.
* Optimizer now uses this shared check rather than duplicating partial
type logic.

* **Safer AggregateExec cloning for limit pushdown**

* Added `AggregateExec::with_new_limit` to clone an aggregate exec while
overriding only the TopK `limit` hint, avoiding manual reconstruction
and ensuring plan properties/fields remain consistent.

* **TopK hash table improvements + helper functions**

* Added `is_supported_hash_key_type` helper for grouping key
compatibility checks.
  * Refactored string key extraction to a single helper function.
* Added `find_or_insert` entry API to avoid double lookups and unify
insertion behavior.

* **TopK heap support for string aggregate values**

* Added `StringHeap` implementation supporting `Utf8`, `LargeUtf8`, and
`Utf8View` aggregate values using lexicographic ordering.
* Added `is_supported_heap_type` helper for aggregate value
compatibility.
* Updated `new_heap` to create `StringHeap` for supported string types
and return a clearer error message for unsupported types.

* **Debug contract in TopK stream**

* Added a debug assertion in `GroupedTopKAggregateStream` documenting
that type validation should have already happened (optimizer +
can_use_topk), without affecting release builds.

## Are these changes tested?

Yes.

* Added a new physical optimizer test covering UTF-8 grouping with:

1. **Supported** numeric `max/min` value (TopK should be used and
results correct)
2. **Unsupported** string `max/min` value (must fall back to standard
aggregation and not use `GroupedTopKAggregateStream`)

* Added unit tests in `PriorityMap` to validate lexicographic `min/max`
tracking for:

  * `Utf8`
  * `LargeUtf8`
  * `Utf8View`

* Added SQLLogicTest coverage (`aggregates_topk.slt`) for:

  * `varchar` tables
  * `Utf8View` via `arrow_cast`
* `EXPLAIN` verification that TopK limit propagation is applied and
plans remain stable
  * Regression case for `max(trace_id)` with `ORDER BY ... LIMIT`

## Are there any user-facing changes?

Yes (bug fix).

* Queries that group by text columns (including `Utf8View`) and use
`ORDER BY <aggregate> ... LIMIT` should no longer error.
* TopK aggregation now supports UTF-8 string aggregate values for
min/max (lexicographic ordering) where applicable.
* For unsupported type combinations, DataFusion will fall back
gracefully to the standard aggregation path instead of panicking.

No breaking public API changes are intended. The only new public helper
APIs are internal to the physical plan modules.

## LLM-generated code disclosure

This PR includes LLM-generated code and comments. All LLM-generated
content has been manually reviewed and tested.
9 files changed
tree: cde9d3d85a9346bbe826e6320f3247297dcee246
  1. .devcontainer/
  2. .github/
  3. benchmarks/
  4. ci/
  5. datafusion/
  6. datafusion-cli/
  7. datafusion-examples/
  8. dev/
  9. docs/
  10. python/
  11. test-utils/
  12. .asf.yaml
  13. .dockerignore
  14. .editorconfig
  15. .gitattributes
  16. .gitignore
  17. .gitmodules
  18. Cargo.lock
  19. Cargo.toml
  20. CHANGELOG.md
  21. clippy.toml
  22. CODE_OF_CONDUCT.md
  23. CONTRIBUTING.md
  24. doap.rdf
  25. header
  26. LICENSE.txt
  27. licenserc.toml
  28. NOTICE.txt
  29. pre-commit.sh
  30. README.md
  31. rust-toolchain.toml
  32. rustfmt.toml
  33. taplo.toml
  34. typos.toml
README.md

Apache DataFusion

Crates.io Apache licensed Build Status Commit Activity Open Issues Pending PRs Discord chat Linkedin Crates.io MSRV

Website | API Docs | Chat

DataFusion is an extensible query engine written in Rust that uses Apache Arrow as its in-memory format.

This crate provides libraries and binaries for developers building fast and feature rich database and analytic systems, customized to particular workloads. See use cases for examples. The following related subprojects target end users:

“Out of the box,” DataFusion offers SQL and Dataframe APIs, excellent performance, built-in support for CSV, Parquet, JSON, and Avro, extensive customization, and a great community.

DataFusion features a full query planner, a columnar, streaming, multi-threaded, vectorized execution engine, and partitioned data sources. You can customize DataFusion at almost all points including additional data sources, query languages, functions, custom operators and more. See the Architecture section for more details.

Here are links to some important information

What can you do with this crate?

DataFusion is great for building projects such as domain specific query engines, new database platforms and data pipelines, query languages and more. It lets you start quickly from a fully working engine, and then customize those features specific to your use. Click Here to see a list known users.

Contributing to DataFusion

Please see the contributor guide and communication pages for more information.

Crate features

This crate has several features which can be specified in your Cargo.toml.

Default features:

  • nested_expressions: functions for working with nested type function such as array_to_string
  • compression: reading files compressed with xz2, bzip2, flate2, and zstd
  • crypto_expressions: cryptographic functions such as md5 and sha256
  • datetime_expressions: date and time functions such as to_timestamp
  • encoding_expressions: encode and decode functions
  • parquet: support for reading the Apache Parquet format
  • sql: Support for sql parsing / planning
  • regex_expressions: regular expression functions, such as regexp_match
  • unicode_expressions: Include unicode aware functions such as character_length
  • unparser: enables support to reverse LogicalPlans back into SQL
  • recursive_protection: uses recursive for stack overflow protection.

Optional features:

  • avro: support for reading the Apache Avro format
  • backtrace: include backtrace information in error messages
  • parquet_encryption: support for using Parquet Modular Encryption
  • serde: enable arrow-schema's serde feature

DataFusion API Evolution and Deprecation Guidelines

Public methods in Apache DataFusion evolve over time: while we try to maintain a stable API, we also improve the API over time. As a result, we typically deprecate methods before removing them, according to the deprecation guidelines.

Dependencies and Cargo.lock

Following the guidance on committing Cargo.lock files, this project commits its Cargo.lock file.

CI uses the committed Cargo.lock file, and dependencies are updated regularly using Dependabot PRs.