You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "geoffreyclaude (via GitHub)" <gi...@apache.org> on 2025/04/01 14:02:19 UTC

[I] Extend TopK early termination to partially sorted inputs [datafusion]

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

   ### Is your feature request related to a problem or challenge?
   
   DataFusion currently has a "TopK early termination" optimization, which speeds up queries that involve `ORDER BY` and `LIMIT` if the input data is already sorted by the full ordering requested in the query.
   
   However, many real-world scenarios involve datasets that are only partially sorted.
   
   For example, consider a time-series dataset that's pre-sorted by `day` but not sorted within each day. Queries requesting data sorted by `day, timestamp` should still benefit significantly from optimization because once DataFusion has collected the required number of rows from the most recent day(s), it could safely ignore data from earlier days.
   
   Today, DataFusion does not take advantage of such partial ordering, resulting in unnecessary scans and sorts.
   
   Example query affected by this:
   
   ```sql
   SELECT day, sensor_id, reading, timestamp
   FROM sensor_readings
   WHERE sensor_id = 1002
   ORDER BY day DESC, timestamp DESC
   LIMIT 10;
   ```
   
   If the data source providing `sensor_readings` can guarantee a `day DESC` ordering, this query should quickly finish after scanning enough rows from the most recent days, but currently DataFusion will continue scanning unnecessarily the full `sensor_readings`.
   
   
   
   ### Describe the solution you'd like
   
   I propose extending DataFusion's existing "TopK early termination" optimization to handle cases where the input data is partially sorted by a prefix of the requested ordering.
   
   Specifically, DataFusion should detect:
   
   - When the input ordering has a non-empty common prefix with the query's requested ordering.
   - When the top-K buffer is full.
   - If all still pending rows are guaranteed to be strictly worse than the top-K's max value, comparing only on the common prefix.
   
   Under these conditions, DataFusion can safely terminate scanning early, significantly improving query performance and reducing resource consumption.
   
   ### Describe alternatives you've considered
   
   _No response_
   
   ### Additional context
   
   I wasn't able to find benchmarks on already sorted data.
   
   However, a simple reproducer from the TPCH dataset could be:
   ```sql
   CREATE EXTERNAL TABLE lineitem_ship (
       l_shipdate     DATE,
       l_commitdate   DATE,
       l_shipmode     VARCHAR,
       l_quantity     INT
   )
   STORED AS PARQUET
   LOCATION 'scratch/topk'
   WITH ORDER (l_shipdate);
   
   INSERT INTO lineitem_ship
   SELECT
       l_shipdate,
       l_commitdate,
       l_shipmode,
       l_quantity
   FROM lineitem
   ORDER BY l_shipdate;
   
   SELECT
       l_shipdate,
       l_commitdate,
       l_quantity
   FROM lineitem_ship
   WHERE l_shipmode IN ('MAIL', 'AIR')
   ORDER BY l_shipdate, l_commitdate, l_quantity
   LIMIT 10;
   ```
   
   This query today scans the full `lineitem_ship` table. I'd expect it to be orders of magnitude faster with the sort prefix enhancement.


-- 
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.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: [I] Extend TopK early termination to partially sorted inputs [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on issue #15529:
URL: https://github.com/apache/datafusion/issues/15529#issuecomment-2773087938

   > FWIW my view is that https://github.com/apache/datafusion/pull/15301 tries to implement data skipping for partially sorted / globally roughly clustered inputs where there is an ORDER BY LIMIT on the sortedish dimension. It does not try to avoid sorting the remaining data or anything like that.
   
   Thanks for confirming! The rebase on top of your PR was simple enough, so I'll work on getting my issue's PR properly cleaned up and hopefully you'll have merged yours by then :) 


-- 
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: [I] Extend TopK early termination to partially sorted inputs [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on issue #15529:
URL: https://github.com/apache/datafusion/issues/15529#issuecomment-2781385443

   @NGA-TRAN  and @gabotechs  can you please help review this PR?


-- 
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: [I] Extend TopK early termination to partially sorted inputs [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on issue #15529:
URL: https://github.com/apache/datafusion/issues/15529#issuecomment-2769593513

   I ran some quick [experiments on my fork](https://github.com/geoffreyclaude/datafusion/pull/3) by checking for early termination after each batch processed in the "topK" on the example TPCH query above:
   - Elapsed dropped from `16s` to `800ms`: 20x speedup
   - The Parquet DataSource `output_rows` metric dropped from `17135217` to `81920` (81920 because it read 1 batch of 8192 rows in parallel on 10 partitions): 200x reduction
   - The Parquet DataSource `bytes_scanned` metric dropped from `130MB` to `23MB`: 5x reduction (which doesn't align at all with the `output_rows` reduction for some reason...)


-- 
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: [I] Extend TopK early termination to partially sorted inputs [datafusion]

Posted by "NGA-TRAN (via GitHub)" <gi...@apache.org>.
NGA-TRAN commented on issue #15529:
URL: https://github.com/apache/datafusion/issues/15529#issuecomment-2780700162

   Thanks for a nice real life use case and benchmarking numbers, @geoffreyclaude 


-- 
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: [I] Extend TopK early termination to partially sorted inputs [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on issue #15529:
URL: https://github.com/apache/datafusion/issues/15529#issuecomment-2779122390

   PR should be ready for review. I've included some pretty nice benchmark results from https://github.com/apache/datafusion/pull/15560:
   
   ```
   > ./bench.sh compare main partitioned_topk
   Comparing main and partitioned_topk
   --------------------                                                                          
   Benchmark top10_sorted_tpch.json                                                              
   --------------------                                                                          
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
   ┃ Query        ┃     main ┃ partitioned_topk ┃         Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
   │ Q1           │  24.73ms │          24.86ms │      no change │
   │ Q2           │   5.42ms │           5.27ms │      no change │
   │ Q3           │  77.20ms │          76.83ms │      no change │
   │ Q4           │  28.43ms │           5.41ms │  +5.26x faster │
   │ Q5           │  18.44ms │          18.34ms │      no change │
   │ Q6           │  32.91ms │          32.52ms │      no change │
   │ Q7           │  74.63ms │          75.11ms │      no change │
   │ Q8           │  77.22ms │           6.78ms │ +11.39x faster │
   │ Q9           │  90.10ms │          10.04ms │  +8.97x faster │
   │ Q10          │ 135.39ms │          14.04ms │  +9.64x faster │
   │ Q11          │  72.33ms │          71.06ms │      no change │
   └──────────────┴──────────┴──────────────────┴────────────────┘
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┓ 
   ┃ Benchmark Summary               ┃          ┃ 
   ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━┩ 
   │ Total Time (main)               │ 636.81ms │
   │ Total Time (partitioned_topk)   │ 340.26ms │
   │ Average Time (main)             │  57.89ms │
   │ Average Time (partitioned_topk) │  30.93ms │                                                
   │ Queries Faster                  │        4 │                                                
   │ Queries Slower                  │        0 │                                                
   │ Queries with No Change          │        7 │                                                
   └─────────────────────────────────┴──────────┘
   ```


-- 
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: [I] Extend TopK early termination to partially sorted inputs [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on issue #15529:
URL: https://github.com/apache/datafusion/issues/15529#issuecomment-2772802775

   FWIW my view is that #15301 tries to implement data skipping for partially sorted / globally roughly clustered inputs where there is an ORDER BY LIMIT on the sortedish dimension. It does not try to avoid sorting the remaining data or anything like that.


-- 
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: [I] Extend TopK early termination to partially sorted inputs [datafusion]

Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada closed issue #15529: Extend TopK early termination to partially sorted inputs
URL: https://github.com/apache/datafusion/issues/15529


-- 
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: [I] Extend TopK early termination to partially sorted inputs [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on issue #15529:
URL: https://github.com/apache/datafusion/issues/15529#issuecomment-2772276984

   @alamb:
   > This may be some overlap with this work from @adriangb (though I realize you are talking about a different optimization)
   
   The two are complimentary. @adriangb's PR is super cool and paves the way for more general dynamic filters, but from what I tested out doesn't fully cover the case of partially sorted inputs. Although that might be me incorrectly testing!


-- 
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: [I] Extend TopK early termination to partially sorted inputs [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on issue #15529:
URL: https://github.com/apache/datafusion/issues/15529#issuecomment-2770458720

   This may be some overlap with this work from @adriangb (though I realize you are talking about a different optimization)
   - https://github.com/apache/datafusion/issues/15037
    
   
   


-- 
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