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.
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
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.
Please see the contributor guide and communication pages for more information.
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_stringcompression: reading files compressed with xz2, bzip2, flate2, and zstdcrypto_expressions: cryptographic functions such as md5 and sha256datetime_expressions: date and time functions such as to_timestampencoding_expressions: encode and decode functionsparquet: support for reading the Apache Parquet formatsql: Support for sql parsing / planningregex_expressions: regular expression functions, such as regexp_matchunicode_expressions: Include unicode aware functions such as character_lengthunparser: enables support to reverse LogicalPlans back into SQLrecursive_protection: uses recursive for stack overflow protection.Optional features:
avro: support for reading the Apache Avro formatbacktrace: include backtrace information in error messagesparquet_encryption: support for using Parquet Modular Encryptionserde: enable arrow-schema's serde featurePublic 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.
Cargo.lockFollowing 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.