Inf1mum commented on code in PR #219:
URL: https://github.com/apache/datafusion-site/pull/219#discussion_r4698599457
##########
content/blog/2026-11-13-topk-per-partition.md:
##########
@@ -0,0 +1,377 @@
+---
+layout: post
+title: Top N Per Group with PartitionedTopKExec in Apache DataFusion
+date: 2026-11-13
+author: Vadim Lazuk
+categories: [performance]
+---
+
+<!--
+{% comment %}
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to you under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+{% endcomment %}
+-->
+
+[TOC]
+
+*[Vadim Lazuk](https://github.com/Inf1mum)*
+
+"Find the top N rows within each group" is one of the most common shapes in
+analytics: the five best-selling products in each category, the three most
+recent events per device, the two highest-revenue rows per store. In SQL this
+is usually written with a ranking window function and an outer filter:
+
+```sql
+SELECT * FROM (
+ SELECT ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS
rn, *
+ FROM sales
+) WHERE rn <= 5;
+```
+
+Until recently, DataFusion evaluated this query by sorting the *entire* input
+to compute the window function, and then throwing almost all of the sorted
+output away. DataFusion 55 recognizes the pattern: with
+[datafusion.optimizer.enable_window_topn] enabled, the full sort is replaced
+by a new `PartitionedTopKExec` operator that keeps only the top N rows per
+partition in a bounded heap.
+
+The rest of this post shows how to enable the feature, what changes in the
+plan, how the operator works, and where it helps and where it does not.
+
+[@alamb]: https://github.com/alamb
+[@SubhamSinghal]: https://github.com/SubhamSinghal
+[datafusion.optimizer.enable_window_topn]:
https://datafusion.apache.org/user-guide/configs.html
+[#6899]: https://github.com/apache/datafusion/issues/6899
+
+## The "Top N Per Group" Pattern
+
+The query above computes the top five rows per `category`. The same shape
+covers the latest events per device, the highest-paid employees per
+department, and many other screens and reports. It is also query 8 of the
+[h2o group-by benchmark] ("top 2 rows by value per group"), which DataFusion
+tracks as part of its effort to stay competitive on [db-benchmark][#13586].
+
+[h2o group-by benchmark]: https://github.com/h2oai/db-benchmark
+[#13586]: https://github.com/apache/datafusion/issues/13586
+
+What matters for the optimizer is the ratio: the filter keeps a *small, fixed
+number of rows per group* (`rn <= K`), while the input per group is large.
+When that holds, almost all the work of a sort-based plan is discarded.
+
+## The Default Plan Sorts Everything
+
+A ranking window function must see each partition's rows as one contiguous,
+ordered run. The straightforward way to guarantee that is to sort the whole
+input by `(partition keys, order keys)` and evaluate the window over the
+sorted stream. With the optimization disabled, the physical plan for the
+query above is (abridged):
+
+```text
+ProjectionExec
+ FilterExec: rn <= 5
+ BoundedWindowAggExec: ROW_NUMBER() PARTITION BY [category] ORDER BY
[revenue DESC]
+ SortExec: expr=[category ASC, revenue DESC]
+ DataSourceExec
+```
+
+The plan is correct, but every stage does work on rows the filter later
+throws away:
+
+1. **`SortExec` sorts the entire dataset by `(category, revenue)`.** The
+ window function needs each partition's rows contiguous and in `ORDER BY`
+ order, and a full sort is the only way to guarantee that here. It is a
+ blocking, spill-capable sort of all N rows: O(N log N) time, O(N) memory,
+ with excess rows written to disk and merged back once the memory pool
+ runs out.
+
+2. **`BoundedWindowAggExec` computes `ROW_NUMBER` for every row.** It walks
+ the sorted stream and numbers each partition's rows 1, 2, 3, ... It holds
+ state only for the partition currently open, hence "bounded", but it
+ still touches all N rows, including the ones about to be discarded.
+
+3. **`FilterExec` keeps only the rows with `rn <= 5`.** Everything the sort
+ and the window did for the other rows is wasted here.
+
+With 10 million rows, 1,000 partitions, and `K = 3`, the plan sorts all 10
+million rows to keep 3,000 — 0.03% of the input. The surviving fraction is
+roughly `K × P / N`, and it shrinks toward zero as the partition key's
+cardinality grows.
+
+## How It Works
+
+`PartitionedTopKExec` reads *unsorted* input and keeps one bounded top-K heap
+per distinct partition key, instead of sorting the dataset. Rows are
+converted to Arrow's row format with a single shared `RowConverter` and
+grouped by their partition key. Each group's rows flow into that group's
+heap, which holds the best K rows according to the `ORDER BY` and evicts the
+rest as new rows arrive. All heaps share a single `MemoryReservation`, so the
+operator reports its memory usage to DataFusion's memory pool as one unit
+[#21479], [#23096].
+
+The overall cost changes from O(N log N) time and O(N) memory to:
+
+- **O(N log K)** time — each row is compared against a heap of size K.
+- **O(K × P × row_size)** memory — K retained rows for each of the P
+ distinct partitions.
+
+For example, with `fetch=3` and input:
+
+```text
+store | revenue
+------|--------
Review Comment:
Done -- both examples use category and revenue now.
##########
content/blog/2026-11-13-topk-per-partition.md:
##########
@@ -0,0 +1,377 @@
+---
+layout: post
+title: Top N Per Group with PartitionedTopKExec in Apache DataFusion
+date: 2026-11-13
+author: Vadim Lazuk
+categories: [performance]
+---
+
+<!--
+{% comment %}
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to you under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+{% endcomment %}
+-->
+
+[TOC]
+
+*[Vadim Lazuk](https://github.com/Inf1mum)*
+
+"Find the top N rows within each group" is one of the most common shapes in
+analytics: the five best-selling products in each category, the three most
+recent events per device, the two highest-revenue rows per store. In SQL this
+is usually written with a ranking window function and an outer filter:
+
+```sql
+SELECT * FROM (
+ SELECT ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS
rn, *
+ FROM sales
+) WHERE rn <= 5;
+```
+
+Until recently, DataFusion evaluated this query by sorting the *entire* input
+to compute the window function, and then throwing almost all of the sorted
+output away. DataFusion 55 recognizes the pattern: with
+[datafusion.optimizer.enable_window_topn] enabled, the full sort is replaced
+by a new `PartitionedTopKExec` operator that keeps only the top N rows per
+partition in a bounded heap.
+
+The rest of this post shows how to enable the feature, what changes in the
+plan, how the operator works, and where it helps and where it does not.
+
+[@alamb]: https://github.com/alamb
+[@SubhamSinghal]: https://github.com/SubhamSinghal
+[datafusion.optimizer.enable_window_topn]:
https://datafusion.apache.org/user-guide/configs.html
+[#6899]: https://github.com/apache/datafusion/issues/6899
+
+## The "Top N Per Group" Pattern
+
+The query above computes the top five rows per `category`. The same shape
+covers the latest events per device, the highest-paid employees per
+department, and many other screens and reports. It is also query 8 of the
+[h2o group-by benchmark] ("top 2 rows by value per group"), which DataFusion
+tracks as part of its effort to stay competitive on [db-benchmark][#13586].
+
+[h2o group-by benchmark]: https://github.com/h2oai/db-benchmark
+[#13586]: https://github.com/apache/datafusion/issues/13586
+
+What matters for the optimizer is the ratio: the filter keeps a *small, fixed
+number of rows per group* (`rn <= K`), while the input per group is large.
+When that holds, almost all the work of a sort-based plan is discarded.
+
+## The Default Plan Sorts Everything
+
+A ranking window function must see each partition's rows as one contiguous,
+ordered run. The straightforward way to guarantee that is to sort the whole
+input by `(partition keys, order keys)` and evaluate the window over the
+sorted stream. With the optimization disabled, the physical plan for the
+query above is (abridged):
+
+```text
+ProjectionExec
+ FilterExec: rn <= 5
+ BoundedWindowAggExec: ROW_NUMBER() PARTITION BY [category] ORDER BY
[revenue DESC]
+ SortExec: expr=[category ASC, revenue DESC]
+ DataSourceExec
+```
+
+The plan is correct, but every stage does work on rows the filter later
+throws away:
+
+1. **`SortExec` sorts the entire dataset by `(category, revenue)`.** The
+ window function needs each partition's rows contiguous and in `ORDER BY`
+ order, and a full sort is the only way to guarantee that here. It is a
+ blocking, spill-capable sort of all N rows: O(N log N) time, O(N) memory,
+ with excess rows written to disk and merged back once the memory pool
+ runs out.
+
+2. **`BoundedWindowAggExec` computes `ROW_NUMBER` for every row.** It walks
+ the sorted stream and numbers each partition's rows 1, 2, 3, ... It holds
+ state only for the partition currently open, hence "bounded", but it
+ still touches all N rows, including the ones about to be discarded.
+
+3. **`FilterExec` keeps only the rows with `rn <= 5`.** Everything the sort
+ and the window did for the other rows is wasted here.
+
+With 10 million rows, 1,000 partitions, and `K = 3`, the plan sorts all 10
+million rows to keep 3,000 — 0.03% of the input. The surviving fraction is
+roughly `K × P / N`, and it shrinks toward zero as the partition key's
+cardinality grows.
+
+## How It Works
+
+`PartitionedTopKExec` reads *unsorted* input and keeps one bounded top-K heap
+per distinct partition key, instead of sorting the dataset. Rows are
+converted to Arrow's row format with a single shared `RowConverter` and
+grouped by their partition key. Each group's rows flow into that group's
+heap, which holds the best K rows according to the `ORDER BY` and evicts the
+rest as new rows arrive. All heaps share a single `MemoryReservation`, so the
+operator reports its memory usage to DataFusion's memory pool as one unit
+[#21479], [#23096].
+
+The overall cost changes from O(N log N) time and O(N) memory to:
+
+- **O(N log K)** time — each row is compared against a heap of size K.
+- **O(K × P × row_size)** memory — K retained rows for each of the P
+ distinct partitions.
+
+For example, with `fetch=3` and input:
+
+```text
+store | revenue
+------|--------
+ A | 100
+ B | 50
+ A | 200
+ B | 150
+ A | 300
+ A | 400
+```
+
+the operator keeps two heaps: `store=A` retains `{400, 300, 200}` and evicts
Review Comment:
Agreed -- both diagram requests are now one marked TODO covering the two
plans; see the diagram thread above for how I suggest we do it.
##########
content/blog/2026-11-13-topk-per-partition.md:
##########
@@ -0,0 +1,377 @@
+---
+layout: post
+title: Top N Per Group with PartitionedTopKExec in Apache DataFusion
+date: 2026-11-13
+author: Vadim Lazuk
+categories: [performance]
+---
+
+<!--
+{% comment %}
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to you under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+{% endcomment %}
+-->
+
+[TOC]
+
+*[Vadim Lazuk](https://github.com/Inf1mum)*
+
+"Find the top N rows within each group" is one of the most common shapes in
+analytics: the five best-selling products in each category, the three most
+recent events per device, the two highest-revenue rows per store. In SQL this
+is usually written with a ranking window function and an outer filter:
+
+```sql
+SELECT * FROM (
+ SELECT ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS
rn, *
+ FROM sales
+) WHERE rn <= 5;
+```
+
+Until recently, DataFusion evaluated this query by sorting the *entire* input
+to compute the window function, and then throwing almost all of the sorted
+output away. DataFusion 55 recognizes the pattern: with
+[datafusion.optimizer.enable_window_topn] enabled, the full sort is replaced
+by a new `PartitionedTopKExec` operator that keeps only the top N rows per
+partition in a bounded heap.
+
+The rest of this post shows how to enable the feature, what changes in the
+plan, how the operator works, and where it helps and where it does not.
+
+[@alamb]: https://github.com/alamb
+[@SubhamSinghal]: https://github.com/SubhamSinghal
+[datafusion.optimizer.enable_window_topn]:
https://datafusion.apache.org/user-guide/configs.html
+[#6899]: https://github.com/apache/datafusion/issues/6899
+
+## The "Top N Per Group" Pattern
+
+The query above computes the top five rows per `category`. The same shape
+covers the latest events per device, the highest-paid employees per
+department, and many other screens and reports. It is also query 8 of the
+[h2o group-by benchmark] ("top 2 rows by value per group"), which DataFusion
+tracks as part of its effort to stay competitive on [db-benchmark][#13586].
+
+[h2o group-by benchmark]: https://github.com/h2oai/db-benchmark
+[#13586]: https://github.com/apache/datafusion/issues/13586
+
+What matters for the optimizer is the ratio: the filter keeps a *small, fixed
+number of rows per group* (`rn <= K`), while the input per group is large.
+When that holds, almost all the work of a sort-based plan is discarded.
+
+## The Default Plan Sorts Everything
+
+A ranking window function must see each partition's rows as one contiguous,
+ordered run. The straightforward way to guarantee that is to sort the whole
+input by `(partition keys, order keys)` and evaluate the window over the
+sorted stream. With the optimization disabled, the physical plan for the
+query above is (abridged):
+
+```text
+ProjectionExec
+ FilterExec: rn <= 5
+ BoundedWindowAggExec: ROW_NUMBER() PARTITION BY [category] ORDER BY
[revenue DESC]
+ SortExec: expr=[category ASC, revenue DESC]
+ DataSourceExec
+```
+
+The plan is correct, but every stage does work on rows the filter later
+throws away:
+
+1. **`SortExec` sorts the entire dataset by `(category, revenue)`.** The
+ window function needs each partition's rows contiguous and in `ORDER BY`
+ order, and a full sort is the only way to guarantee that here. It is a
+ blocking, spill-capable sort of all N rows: O(N log N) time, O(N) memory,
+ with excess rows written to disk and merged back once the memory pool
+ runs out.
+
+2. **`BoundedWindowAggExec` computes `ROW_NUMBER` for every row.** It walks
+ the sorted stream and numbers each partition's rows 1, 2, 3, ... It holds
+ state only for the partition currently open, hence "bounded", but it
+ still touches all N rows, including the ones about to be discarded.
+
+3. **`FilterExec` keeps only the rows with `rn <= 5`.** Everything the sort
+ and the window did for the other rows is wasted here.
+
+With 10 million rows, 1,000 partitions, and `K = 3`, the plan sorts all 10
+million rows to keep 3,000 — 0.03% of the input. The surviving fraction is
+roughly `K × P / N`, and it shrinks toward zero as the partition key's
+cardinality grows.
+
+## How It Works
+
+`PartitionedTopKExec` reads *unsorted* input and keeps one bounded top-K heap
+per distinct partition key, instead of sorting the dataset. Rows are
+converted to Arrow's row format with a single shared `RowConverter` and
+grouped by their partition key. Each group's rows flow into that group's
+heap, which holds the best K rows according to the `ORDER BY` and evicts the
+rest as new rows arrive. All heaps share a single `MemoryReservation`, so the
+operator reports its memory usage to DataFusion's memory pool as one unit
+[#21479], [#23096].
+
+The overall cost changes from O(N log N) time and O(N) memory to:
+
+- **O(N log K)** time — each row is compared against a heap of size K.
+- **O(K × P × row_size)** memory — K retained rows for each of the P
+ distinct partitions.
+
+For example, with `fetch=3` and input:
+
+```text
+store | revenue
+------|--------
+ A | 100
+ B | 50
+ A | 200
+ B | 150
+ A | 300
+ A | 400
+```
+
+the operator keeps two heaps: `store=A` retains `{400, 300, 200}` and evicts
+`100`; `store=B` retains `{150, 50}`. It emits the retained rows in
+`(partition_keys, order_keys)` order — `A/400, A/300, A/200, B/150, B/50` —
+which is exactly the contiguous ordered run the window operator needs to
+assign `ROW_NUMBER` values 1..3 per partition.
+
+### What Each Ranking Function Has to Retain
+
+The three ranking functions differ in what a correct implementation must keep
+per partition:
+
+- `ROW_NUMBER` numbers rows 1, 2, 3, ... with no ties, so exactly K rows
+ per partition suffice.
+- `RANK` gives tied rows the same rank and skips subsequent ranks, so
Review Comment:
Trimmed -- the three ranking functions are one short paragraph now, and RANK
gets a single sentence: it must also retain rows tied with the row at the
boundary, so a query can legitimately return more than K rows per group.
--
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]