riclib opened a new issue, #27813:
URL: https://github.com/apache/datafusion/issues/27813

   ### Describe the bug
   
   On 55.2.0, a `SELECT DISTINCT` (or a `GROUP BY` with no aggregates) under a 
`LIMIT`, over a subquery that keeps the newest row per key with `row_number()`, 
fails at execution with an internal error:
   
   ```
   Internal error: Ordering direction required for DISTINCT with limit.
   This issue was likely caused by a bug in DataFusion's code.
   ```
   
   The window's sort leaves the partial `AggregateExec` in 
`ordering_mode=Sorted`, so it has an output ordering. But it still carries 
`lim=[n]` from `LimitedDistinctAggregation`. At execution, 
`AggregateExec::execute_typed` sees `limit_options` set, and 
`is_unordered_unfiltered_group_by_distinct()` returns false because of that 
output ordering. So it builds a `GroupedTopKAggregateStream`, which requires 
`limit_options.descending`, and that is `None` (no ORDER BY set it).
   
   ### To Reproduce
   
   ```sql
   CREATE TABLE t AS VALUES ('a', 1), ('a', 2), ('b', 1), ('c', 1);
   SELECT DISTINCT column1 FROM (
     SELECT column1, row_number() OVER (PARTITION BY column1, column2 ORDER BY 
column2 DESC) AS rn
     FROM t) WHERE rn = 1 LIMIT 1;
   ```
   
   Plan, from a real case:
   
   ```
   AggregateExec: mode=FinalPartitioned, gby=[deployment@0 as deployment], 
aggr=[], lim=[5]
     RepartitionExec: partitioning=Hash([deployment@0], 32), input_partitions=32
       AggregateExec: mode=Partial, gby=[deployment@0 as deployment], aggr=[], 
lim=[5], ordering_mode=Sorted
         FilterExec: _rn@1 = 1, projection=[deployment@0]
           ...
             BoundedWindowAggExec: ... mode=[Sorted]
               SortExec: expr=[deployment@0 ASC NULLS LAST, process@1 ASC NULLS 
LAST, ...]
   ```
   
   The same query over the base table, or with an `ORDER BY`, answers. A table 
that only declares `WITH ORDER (x ASC)` also answers.
   
   ### Expected behavior
   
   The query returns one row, as it does with 
`datafusion.optimizer.enable_distinct_aggregation_soft_limit = false`, which is 
our workaround.
   
   ### Additional context
   
   Either the soft limit should not be pushed into an aggregate that will run 
in sorted mode, or an ordered aggregate with a soft limit but no direction 
should fall back to the plain grouped stream.
   


-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to