You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "SubhamSinghal (via GitHub)" <gi...@apache.org> on 2026/10/02 10:54:05 UTC
[PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
SubhamSinghal opened a new pull request, #25968:
URL: https://github.com/apache/datafusion/pull/25968
## Which issue does this PR close?
Related to #6899 (WindowTopN). Follows #25730 (merged), which applied this design to `ROW_NUMBER`. This PR brings `RANK` to the same design.
## Rationale for this change
With `enable_window_topn`, `RANK() ... WHERE rk <= K` on high-cardinality `PARTITION BY` is **slower than the sort plan it replaces**: at 100K partitions the rewrite costs 2.76× the sort plan's CPU. `PartitionedTopKRank::insert_batch`:
- gathers one `take_record_batch` sub-batch per (input batch, partition) pair, roughly one small `RecordBatch` per input row at 100K partitions;
- does a 1-row `take_record_batch` for every row evicted into the tie list;
- runs a full `TopKHeap`, with its own `RecordBatchStore`, per partition;
- sums `size()` over every partition on every batch.
Profiling main at 1M partitions put about 58% of samples in creating and destroying those small batches. Payload width made almost no difference, so the cost is the number of calls, not the bytes copied. #25730 removed exactly this for `ROW_NUMBER`. This PR does the same for `RANK`, plus boundary ties.
## What changes are included in this PR?
In `datafusion/physical-plan/src/topk/mod.rs`, plus a doc update in `sorts/partitioned_topk.rs`:
- **`PartitionedTopKRank` uses #25730's design.** It encodes the partition and ORDER BY columns once per batch, keeps or drops each row in its partition's `PartitionHeap` in one pass, then gathers **the admitted rows once per input batch** into an operator-wide `RecordBatchStore`. Output is interleaved out of that store in `batch_size` chunks by `EmitState`, so the `BatchCoalescer` goes away.
- **Ties are 8-byte `StoreRef`s** (`batch_id`, `row`) in a per-partition `ties` list. Every tie shares the heap root's key, so none is stored.
- Evicted but still tied: the row's reference and its store use move from the heap to the tie list. No 1-row `take_record_batch`.
- Cutoff improves: the evicted row and all ties are released, one `unuse` each, so amortised O(1) per admitted row.
- **Memory stays proportional to rows retained** (the property #24591 established). The store holds only admitted rows, and the same ratio-2 compaction as #25730 keeps `store.total_rows ≤ 2 × live_slots` after every batch, where `live_slots` counts heap rows and ties. Ties from every partition a batch touches share that batch's one store entry, so they are charged once, not once per partition (the over-count in #23326).
- **`size()` is O(1)**, from running totals plus `store.size()`.
- **Shared with `ROW_NUMBER`.** Compaction (`RecordBatchStore::compact`, replacing `PartitionedTopK::compact_store`), the in-flight batch's bookkeeping (`pending` / `release` / `insert_rows`) and stream construction (`EmitState::stream`) are now used by both operators. No behaviour change for `ROW_NUMBER`.
- **`EvictedRow` is removed.** `RANK` was its last reader. `TopKHeap::add` no longer looks up and clones the evicted row's batch.
## Are these changes tested?
Yes. All existing `PartitionedTopKRank` tests pass, including the three memory-bound tests from #24591. New tests:
- `test_partitioned_topk_rank_bookkeeping_tracks_recompute`: 256 randomized shapes, checking after every batch that each store entry's `uses` matches the rows pointing into it, `total_rows ≤ 2 × live_slots`, the running totals and reservation match a recompute, and the output matches brute force in `(pk, val)` order. It replaces `test_partitioned_topk_rank_matches_bruteforce`.
- `test_partitioned_topk_rank_store_bounded_when_ties_spread_thinly`, `test_partitioned_topk_rank_boundary_move_releases_ties_across_batches`, and `test_partitioned_topk_rank_ties_share_one_store_entry` (the #23326 shape).
## Benchmarks
`benchmarks/queries/h2o/window.sql` RANK queries Q18–Q23 (h2o J1 `large`, 10M rows, K=2). User CPU, median of 7 alternating runs, 14 cores. **base** = #25730's tip, whose `RANK` code is main's; **sort plan** = flag off.
| partitions | main, ON vs OFF | this branch, ON vs OFF |
|---|---|---|
| 100 (Q18) | 5.87× faster | 6.07× faster |
| 1,000 (Q19) | 5.31× faster | 6.00× faster |
| 1,000 (Q20) | 4.78× faster | 5.24× faster |
| 10,000 (Q21) | 2.02× faster | 5.44× faster |
| 10,000 (Q22) | 2.19× faster | 4.74× faster |
| 100,000 (Q23) | 2.76× slower | 1.83× faster |
## Are there any user-facing changes?
No. `enable_window_topn` stays default-false,
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal merged PR #25968:
URL: https://github.com/apache/datafusion/pull/25968
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#discussion_r4182855608
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
Review Comment:
Addressed in f9d7919e1fed26f901ab6b5a2730e0057b85d56d
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
Review Comment:
Addressed in f9d7919e1fed26f901ab6b5a2730e0057b85d56d
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#issuecomment-6019236908
run benchmark h2o_medium_window
```yaml
env:
DATAFUSION_OPTIMIZER_ENABLE_WINDOW_TOPN: true
```
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#discussion_r4182845485
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2179,217 +2233,192 @@ impl PartitionedTopKRank {
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
- // 4. Per-partition: classify each row and dispatch.
+ // 2. One pass over the rows in batch order, as in
+ // `PartitionedTopK::insert_batch`: a partition's heap and ties are
+ // only touched by its own rows, which still arrive in ascending row
+ // order, so interleaving partitions cannot change a decision. An
+ // admission, to the heap or to ties, records which row it kept;
+ // phase 3 gathers them all at once.
let k = self.k;
let mut replacements: usize = 0;
+ self.admitted_rows.clear();
+ // The gathered batch's id is known before the batch exists, so slots
+ // can point at it during the pass.
+ let mut pending = self.store.pending();
+ {
+ let pk_rows = &self.partition_scratch_rows;
+ let ob_rows = &self.scratch_rows;
+ let states = &mut self.states;
+ let admitted_rows = &mut self.admitted_rows;
+ let store = &mut self.store;
+ let evicted_key = &mut self.evicted_key;
+ // Accumulated locally and folded in once.
+ let mut interned_bytes = 0usize;
+ let mut admitted_bytes = 0usize;
+ let mut ties_grown = 0usize;
+ let mut new_slots = 0usize;
+ let mut released_slots = 0usize;
- for (pk, indices) in groups.drain() {
- let state = self.states.entry(pk).or_insert_with(|| RankPartitionState {
- heap: TopKHeap::new(k),
- ties: Vec::new(),
- });
-
- // Once the heap is full, a group whose rows are *all* strictly
- // worse than the boundary changes neither the heap nor the
- // ties. Bail before the gather below — at high partition
- // cardinality this is the common case.
- if let Some(max_row) = state.heap.max() {
- let boundary = max_row.row();
- if indices
- .iter()
- .all(|&i| self.scratch_rows.row(i as usize).as_ref() > boundary)
- {
- continue;
+ for row in 0..num_rows {
+ let pk = pk_rows.row(row);
+ let mut interned = false;
+ let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
+ interned = true;
+ RankPartitionState::default()
+ });
+ if interned {
+ interned_bytes += pk.as_ref().len();
}
- }
-
- // Gather this partition's rows into their own batch, as
- // `PartitionedTopK` does. Registering the whole input batch
- // instead would pin it — and charge for it — once per
- // partition key present in the batch, so a batch spanning P
- // partitions would be counted P times over.
- let indices_arr = UInt32Array::from(indices);
- let sub_batch = take_record_batch(batch, &indices_arr)?;
-
- // Indices *into `sub_batch`* of rows from this batch that tied
- // at the boundary. Coalesced into a single tie entry at the end
- // of the partition's loop. Discarded if the boundary moves up
- // mid-loop (those rows were tied to the old boundary, which is
- // now strictly worse than the new K-th).
- let mut equal_indices: Vec<u32> = Vec::new();
- // Lazy-registered: only attached if at least one row reaches
- // the heap from this batch in this partition.
- let mut heap_entry: Option<RecordBatchEntry> = None;
-
- for (sub_idx, &orig_idx) in indices_arr.values().iter().enumerate() {
- let row = self.scratch_rows.row(orig_idx as usize);
-
- // Classify against the current K-th-best (the heap top).
- // `heap.max()` returns `None` while the heap is filling,
- // so unclassified rows fall through to the heap path.
- let classification = state
- .heap
- .max()
- .map(|max_row| row.as_ref().cmp(max_row.row()));
-
- match classification {
+ let key = ob_rows.row(row);
+ let key = key.as_ref();
+ // An admission's row in the gathered batch is its position in
+ // `admitted_rows`, because the gather preserves that order.
+ let at = StoreRef {
+ batch_id: pending.id,
+ row: admitted_rows.len() as u32,
+ };
+ match state.heap.classify(k, key) {
+ // Strictly worse than the boundary: drop the row.
+ Some(Ordering::Greater) => continue,
Some(Ordering::Equal) => {
- equal_indices.push(sub_idx as u32);
+ ties_grown += state.push_tie(at);
+ new_slots += 1;
}
- // Strictly worse than the current boundary: drop the row.
- Some(Ordering::Greater) => {}
- Some(Ordering::Less) | None => {
- // Heap path: heap not yet full, or row strictly
- // better than the current boundary.
- let entry_ref = heap_entry.get_or_insert_with(|| {
- state.heap.register_batch(sub_batch.clone())
- });
- if let Some(EvictedRow {
- batch: evicted_batch,
- index: evicted_index,
- row_bytes: evicted_bytes,
- }) = state.heap.add(entry_ref, row, sub_idx)
- {
- // Compare the new boundary (post-eviction heap
- // top) against the evicted row's bytes — both
- // already in encoded form, no clones needed.
- let boundary_changed = state
- .heap
- .max()
- .expect("heap was full to evict; must still be full")
- .row()
- != evicted_bytes.as_slice();
- if boundary_changed {
- // Boundary moved up — prior ties (across
- // all prior batches) and equal_indices
- // accumulated earlier in THIS batch were
- // tied to the old boundary, now strictly
- // worse than the new K-th-best. Discard.
- state.ties.clear();
- equal_indices.clear();
- } else {
- // Boundary unchanged — the evicted row is
- // still tied at the boundary. Gather just
- // that row: holding `evicted_batch` would
- // keep a whole heap batch alive for one row,
- // and one such entry per input batch would
- // again make memory grow with the input.
- let one = UInt32Array::from(vec![evicted_index as u32]);
- state.push_ties(take_record_batch(&evicted_batch, &one)?);
+
+ None => {
+ let (evicted, grown) = state.heap.add(k, key, at);
+ debug_assert!(
+ evicted.is_none(),
+ "a heap that is not full evicts nothing"
+ );
+ admitted_bytes += grown;
+ new_slots += 1;
+ replacements += 1;
+ }
+ Some(Ordering::Less) => {
+ // Replacing the root overwrites its key in place, so
+ // keep a copy to tell whether the boundary moved.
+ evicted_key.clear();
+ evicted_key.extend_from_slice(
+ state.heap.worst_key().expect("classified, so full"),
+ );
+ let (evicted, grown) = state.heap.add(k, key, at);
+ let evicted = evicted.expect("a full heap evicts");
+ admitted_bytes += grown;
+ if state.heap.worst_key() == Some(evicted_key.as_slice()) {
+ // Boundary unchanged: the evicted row is still
+ // tied at it. Its slot moves to the tie list, and
+ // its store use with it — no gather, no release.
+ ties_grown += state.push_tie(evicted);
+ new_slots += 1;
+ } else {
+ // Boundary moved up: the evicted row and every tie
+ // (from this batch or earlier ones) now rank
+ // below K.
+ store.release(&mut pending, evicted.batch_id);
+ for tie in &state.ties {
+ store.release(&mut pending, tie.batch_id);
}
+ released_slots += state.ties.len();
+ state.ties.clear();
Review Comment:
Addressed in f9d7919e1fed26f901ab6b5a2730e0057b85d56d
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#discussion_r4183167738
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2140,8 +2213,8 @@ impl PartitionedTopKRank {
return Ok(());
}
- // 1. Evaluate + encode partition columns into the reusable
- // scratch (cleared then appended).
+ // 1. Evaluate the partition and ORDER BY columns and encode each once
Review Comment:
Addressed in 2901db21221f6bdc87a8bc80d565902f730ec186
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#issuecomment-6029879509
Thank you @SubhamSinghal and @jayzhan211
This is nice!
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#issuecomment-5978632137
@kosiew @jayzhan211 @kumarUjjawal can you help in reviewing 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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "adriangbot (via GitHub)" <gi...@apache.org>.
adriangbot commented on PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#issuecomment-6020526350
🤖 Benchmark completed (GKE) | [trigger](https://github.com/apache/datafusion/pull/25968#issuecomment-6019236908)
**Instance:** `c4a-highmem-16` (12 vCPU / 65 GiB)
Comparing partitioned-topk-rank-shared-store (a499fc31de6b724bfd8dd44a6a7b1af82b64e19c) to 4d167a1 (merge-base) [diff](https://github.com/apache/datafusion/compare/4d167a167228a424ef8cc29fd6bea5f17fc23c2a..a499fc31de6b724bfd8dd44a6a7b1af82b64e19c)
<details><summary>Run configuration</summary>
```yaml
run benchmark h2o_medium_window
env:
DATAFUSION_OPTIMIZER_ENABLE_WINDOW_TOPN: "true"
```
</details>
<details><summary>CPU Details (lscpu)</summary>
```
Architecture: aarch64
CPU op-mode(s): 64-bit
Byte Order: Little Endian
CPU(s): 16
On-line CPU(s) list: 0-15
Vendor ID: ARM
Model name: Neoverse-V2
Model: 1
Thread(s) per core: 1
Core(s) per cluster: 16
Socket(s): -
Cluster(s): 1
Stepping: r0p1
BogoMIPS: 2000.00
Flags: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache: 1 MiB (16 instances)
L1i cache: 1 MiB (16 instances)
L2 cache: 32 MiB (16 instances)
L3 cache: 80 MiB (1 instance)
NUMA node(s): 1
NUMA node0 CPU(s): 0-15
Vulnerability Gather data sampling: Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1: Mitigation; __user pointer sanitization
Vulnerability Spectre v2: Mitigation; CSV2, BHB
Vulnerability Srbds: Not affected
Vulnerability Tsa: Not affected
Vulnerability Tsx async abort: Not affected
Vulnerability Vmscape: Not affected
```
</details>
<details><summary>Details</summary>
<p>
```
Comparing HEAD and partitioned-topk-rank-shared-store
--------------------
Benchmark h2o_window.json
--------------------
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
┃ Query ┃ HEAD ┃ partitioned-topk-rank-shared-store ┃ Change ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
│ QQuery 1 │ 1487.16 ms │ 1486.60 ms │ no change │
│ QQuery 2 │ 19501.15 ms │ 19528.55 ms │ no change │
│ QQuery 3 │ 24186.51 ms │ 23761.94 ms │ no change │
│ QQuery 4 │ 5014.53 ms │ 4987.42 ms │ no change │
│ QQuery 5 │ 12777.86 ms │ 12610.12 ms │ no change │
│ QQuery 6 │ 30584.02 ms │ 30735.27 ms │ no change │
│ QQuery 7 │ 28120.62 ms │ 27177.10 ms │ no change │
│ QQuery 8 │ 141144.14 ms │ 142038.74 ms │ no change │
│ QQuery 9 │ 4564.76 ms │ 4457.14 ms │ no change │
│ QQuery 10 │ 5948.43 ms │ 5879.71 ms │ no change │
│ QQuery 11 │ 5758.39 ms │ 5868.85 ms │ no change │
│ QQuery 12 │ 11434.52 ms │ 11417.50 ms │ no change │
│ QQuery 13 │ 1478.96 ms │ 1467.47 ms │ no change │
│ QQuery 14 │ 1289.64 ms │ 1292.89 ms │ no change │
│ QQuery 15 │ 1299.35 ms │ 1288.02 ms │ no change │
│ QQuery 16 │ 1310.22 ms │ 1313.25 ms │ no change │
│ QQuery 17 │ 1563.49 ms │ 1582.24 ms │ no change │
│ QQuery 18 │ 1289.90 ms │ 1277.68 ms │ no change │
│ QQuery 19 │ 1309.37 ms │ 1315.52 ms │ no change │
│ QQuery 20 │ 1382.69 ms │ 1374.98 ms │ no change │
│ QQuery 21 │ 2362.86 ms │ 1534.03 ms │ +1.54x faster │
│ QQuery 22 │ 2423.09 ms │ 1627.23 ms │ +1.49x faster │
│ QQuery 23 │ 2404.42 ms │ 1600.53 ms │ +1.50x faster │
│ QQuery 24 │ 1290.33 ms │ 1302.89 ms │ no change │
│ QQuery 25 │ 1318.69 ms │ 1317.42 ms │ no change │
│ QQuery 26 │ 1402.56 ms │ 1404.30 ms │ no change │
│ QQuery 27 │ 2331.73 ms │ 2343.11 ms │ no change │
│ QQuery 28 │ 2442.06 ms │ 2472.31 ms │ no change │
│ QQuery 29 │ 2449.06 ms │ 2436.30 ms │ no change │
└───────────┴──────────────┴────────────────────────────────────┴───────────────┘
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ Benchmark Summary ┃ ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
│ Total Time (HEAD) │ 319870.51ms │
│ Total Time (partitioned-topk-rank-shared-store) │ 316899.11ms │
│ Average Time (HEAD) │ 11030.02ms │
│ Average Time (partitioned-topk-rank-shared-store) │ 10927.56ms │
│ Queries Faster │ 3 │
│ Queries Slower │ 0 │
│ Queries with No Change │ 26 │
│ Queries with Failure │ 0 │
└───────────────────────────────────────────────────┴─────────────┘
Distribution per query (min / mean ±stddev / max):
Comparing HEAD and partitioned-topk-rank-shared-store
--------------------
Benchmark h2o_window.json
--------------------
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
┃ Query ┃ HEAD ┃ partitioned-topk-rank-shared-store ┃ Change ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
│ QQuery 1 │ 1487.16 / 1499.47 ±13.57 / 1518.38 ms │ 1486.60 / 1487.85 ±1.21 / 1489.48 ms │ no change │
│ QQuery 2 │ 19501.15 / 19523.45 ±16.19 / 19539.12 ms │ 19528.55 / 19553.35 ±22.18 / 19582.39 ms │ no change │
│ QQuery 3 │ 24186.51 / 28745.50 ±3228.20 / 31233.89 ms │ 23761.94 / 27244.34 ±2771.44 / 30543.09 ms │ +1.06x faster │
│ QQuery 4 │ 5014.53 / 5205.64 ±157.03 / 5399.14 ms │ 4987.42 / 5187.89 ±229.77 / 5509.60 ms │ no change │
│ QQuery 5 │ 12777.86 / 12807.33 ±36.33 / 12858.52 ms │ 12610.12 / 12676.82 ±47.63 / 12718.32 ms │ no change │
│ QQuery 6 │ 30584.02 / 30644.25 ±50.99 / 30708.70 ms │ 30735.27 / 30753.41 ±14.65 / 30771.14 ms │ no change │
│ QQuery 7 │ 28120.62 / 28145.80 ±27.45 / 28183.98 ms │ 27177.10 / 27203.70 ±29.06 / 27244.13 ms │ no change │
│ QQuery 8 │ 141144.14 / 141658.82 ±599.88 / 142500.21 ms │ 142038.74 / 143034.15 ±788.07 / 143965.98 ms │ no change │
│ QQuery 9 │ 4564.76 / 4685.85 ±110.72 / 4832.37 ms │ 4457.14 / 4536.74 ±58.32 / 4595.24 ms │ no change │
│ QQuery 10 │ 5948.43 / 6084.41 ±96.34 / 6159.79 ms │ 5879.71 / 6000.03 ±89.88 / 6095.69 ms │ no change │
│ QQuery 11 │ 5758.39 / 5883.18 ±107.11 / 6019.94 ms │ 5868.85 / 5931.63 ±54.04 / 6000.77 ms │ no change │
│ QQuery 12 │ 11434.52 / 11601.53 ±199.74 / 11882.33 ms │ 11417.50 / 11520.29 ±118.72 / 11686.66 ms │ no change │
│ QQuery 13 │ 1478.96 / 1543.39 ±90.30 / 1671.08 ms │ 1467.47 / 1553.24 ±99.90 / 1693.35 ms │ no change │
│ QQuery 14 │ 1289.64 / 1305.77 ±12.51 / 1320.11 ms │ 1292.89 / 1300.84 ±6.33 / 1308.37 ms │ no change │
│ QQuery 15 │ 1299.35 / 1301.20 ±2.30 / 1304.45 ms │ 1288.02 / 1304.37 ±12.00 / 1316.50 ms │ no change │
│ QQuery 16 │ 1310.22 / 1317.79 ±7.86 / 1328.63 ms │ 1313.25 / 1329.13 ±13.73 / 1346.75 ms │ no change │
│ QQuery 17 │ 1563.49 / 1582.13 ±23.45 / 1615.20 ms │ 1582.24 / 1609.70 ±22.12 / 1636.42 ms │ no change │
│ QQuery 18 │ 1289.90 / 1296.10 ±5.36 / 1302.98 ms │ 1277.68 / 1306.32 ±23.25 / 1334.63 ms │ no change │
│ QQuery 19 │ 1309.37 / 1333.27 ±19.54 / 1357.23 ms │ 1315.52 / 1324.87 ±6.78 / 1331.35 ms │ no change │
│ QQuery 20 │ 1382.69 / 1393.87 ±8.17 / 1401.97 ms │ 1374.98 / 1382.94 ±8.11 / 1394.08 ms │ no change │
│ QQuery 21 │ 2362.86 / 2372.12 ±10.15 / 2386.24 ms │ 1534.03 / 1549.74 ±11.34 / 1560.42 ms │ +1.53x faster │
│ QQuery 22 │ 2423.09 / 2460.80 ±30.34 / 2497.37 ms │ 1627.23 / 1639.55 ±9.67 / 1650.86 ms │ +1.50x faster │
│ QQuery 23 │ 2404.42 / 2434.03 ±20.94 / 2449.43 ms │ 1600.53 / 1627.00 ±22.99 / 1656.59 ms │ +1.50x faster │
│ QQuery 24 │ 1290.33 / 1298.43 ±5.74 / 1302.94 ms │ 1302.89 / 1314.22 ±9.47 / 1326.08 ms │ no change │
│ QQuery 25 │ 1318.69 / 1327.67 ±8.89 / 1339.78 ms │ 1317.42 / 1319.55 ±2.85 / 1323.57 ms │ no change │
│ QQuery 26 │ 1402.56 / 1416.12 ±11.28 / 1430.18 ms │ 1404.30 / 1418.34 ±11.08 / 1431.38 ms │ no change │
│ QQuery 27 │ 2331.73 / 2360.61 ±20.56 / 2377.98 ms │ 2343.11 / 2372.81 ±25.57 / 2405.52 ms │ no change │
│ QQuery 28 │ 2442.06 / 2484.09 ±29.73 / 2505.83 ms │ 2472.31 / 2489.27 ±15.54 / 2509.86 ms │ no change │
│ QQuery 29 │ 2449.06 / 2454.41 ±4.47 / 2460.00 ms │ 2436.30 / 2452.80 ±17.58 / 2477.16 ms │ no change │
└───────────┴──────────────────────────────────────────────┴──────────────────────────────────────────────┴───────────────┘
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ Benchmark Summary ┃ ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
│ Total Time (HEAD) │ 326167.04ms │
│ Total Time (partitioned-topk-rank-shared-store) │ 322424.89ms │
│ Average Time (HEAD) │ 11247.14ms │
│ Average Time (partitioned-topk-rank-shared-store) │ 11118.10ms │
│ Queries Faster │ 4 │
│ Queries Slower │ 0 │
│ Queries with No Change │ 25 │
│ Queries with Failure │ 0 │
└───────────────────────────────────────────────────┴─────────────┘
```
</p>
</details>
<details><summary>Resource Usage</summary>
**h2o_medium_window — base (merge-base)**
| Metric | Value |
|--------|-------|
| Wall time | 980.2s |
| Peak memory | 38.2 GiB |
| Avg memory | 7.0 GiB |
| CPU user | 4075.8s |
| CPU sys | 203.3s |
| Peak spill | 0 B |
**h2o_medium_window — branch**
| Metric | Value |
|--------|-------|
| Wall time | 970.2s |
| Peak memory | 38.9 GiB |
| Avg memory | 6.9 GiB |
| CPU user | 3964.4s |
| CPU sys | 195.1s |
| Peak spill | 0 B |
</details>
---
[File an issue](https://github.com/adriangb/datafusion-benchmarking/issues) against this benchmark runner
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#issuecomment-5951297654
## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/25968?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `93.67089%` with `25 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 82.61%. Comparing base ([`4d167a1`](https://app.codecov.io/gh/apache/datafusion/commit/4d167a167228a424ef8cc29fd6bea5f17fc23c2a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`7a1b6f0`](https://app.codecov.io/gh/apache/datafusion/commit/7a1b6f0064a51afd388cd330b6cbfd44d0d05e02?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 3 commits behind head on main.
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/25968?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [datafusion/physical-plan/src/topk/mod.rs](https://app.codecov.io/gh/apache/datafusion/pull/25968?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Ftopk%2Fmod.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy90b3BrL21vZC5ycw==) | 93.67% | [4 Missing and 21 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/25968?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #25968 +/- ##
==========================================
+ Coverage 82.60% 82.61% +0.01%
==========================================
Files 1145 1145
Lines 444057 444440 +383
Branches 444057 444440 +383
==========================================
+ Hits 366796 367175 +379
+ Misses 54996 54970 -26
- Partials 22265 22295 +30
```
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/25968?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#discussion_r4182848096
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1313,6 +1314,145 @@ impl RecordBatchStore {
+ self.batches.capacity() * (size_of::<u32>() + size_of::<RecordBatchEntry>())
+ self.batches_size
}
+
+ /// Rewrite the store to hold only the rows `partitions` still reference,
+ /// once it holds [`STORE_COMPACTION_RATIO`]× more than the `live_slots` of
+ /// them, and repoint every partition at the rows' new places.
+ /// [`PartitionedTopK`] and [`PartitionedTopKRank`] call this at the end of
+ /// every `insert_batch`.
+ ///
+ /// An entry holds every row *admitted* from its input batch and is freed
+ /// only when the last of them is evicted, so when survivors spread thinly
+ /// one live row keeps a whole entry resident and residency tracks the
+ /// *input*, not `partitions × K`: 512 partitions of `K = 1` fed 512 batches
+ /// pin 131 K rows to retain 512. Nothing else bounds that. A single entry is
+ /// no exception — rows admitted then superseded within their own batch stay
+ /// in the gather unreferenced — so this does not skip a one-entry store.
+ /// `RANK` ties add a second way to leave rows unreferenced, since a
+ /// boundary move releases every tie of the partition at once.
+ ///
+ /// Amortized O(1) per admitted row: one pass over the live slots, and it
+ /// cannot recur until the store has taken on another `live_slots` rows.
+ ///
+ /// Rows are rewritten into `batch_size` chunks, not one batch: an entry is
+ /// released only when its last slot is evicted, so a single batch of every
+ /// live row would free nothing until every partition has churned.
+ ///
+ /// Peak residency is the old store plus the new one — chunks are built
+ /// before the old entries drop, and the reservation is not resized until
+ /// `insert_batch` returns — so a pool sized at the steady-state bound can be
+ /// exceeded transiently without erroring.
+ ///
+ /// All-or-nothing: plan the move and interleave, which is the only fallible
+ /// step, before rewriting the slots and the store. A failing interleave
+ /// leaves the operator as it was rather than holding slots pointing at ids
+ /// the store never got.
+ fn compact<P: StoreSlots>(
+ &mut self,
+ partitions: &mut HashMap<Vec<u8>, P>,
+ live_slots: usize,
+ batch_size: usize,
+ ) -> Result<()> {
+ if self.total_rows <= live_slots * STORE_COMPACTION_RATIO {
+ return Ok(());
+ }
+
+ // Scoped so these clones, which keep the old batches alive while the
+ // compacted ones are built, drop before the store is rewritten.
+ let first_id = self.next_batch_id();
+ let (moved, chunks) = {
+ let (old, array_pos) = self.positional();
+
+ // Keyed by the row's current place rather than by its position in
+ // this walk, so the partitions are free to repoint in any order —
+ // no two slots share a store row, so the key identifies exactly one
+ // slot.
+ let mut coords: Vec<(usize, usize)> = Vec::with_capacity(live_slots);
+ let mut moved: HashMap<StoreRef, StoreRef> =
Review Comment:
Addressed in f9d7919e1fed26f901ab6b5a2730e0057b85d56d
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#discussion_r4182849541
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1313,6 +1314,145 @@ impl RecordBatchStore {
+ self.batches.capacity() * (size_of::<u32>() + size_of::<RecordBatchEntry>())
+ self.batches_size
}
+
+ /// Rewrite the store to hold only the rows `partitions` still reference,
+ /// once it holds [`STORE_COMPACTION_RATIO`]× more than the `live_slots` of
+ /// them, and repoint every partition at the rows' new places.
+ /// [`PartitionedTopK`] and [`PartitionedTopKRank`] call this at the end of
+ /// every `insert_batch`.
+ ///
+ /// An entry holds every row *admitted* from its input batch and is freed
+ /// only when the last of them is evicted, so when survivors spread thinly
+ /// one live row keeps a whole entry resident and residency tracks the
+ /// *input*, not `partitions × K`: 512 partitions of `K = 1` fed 512 batches
+ /// pin 131 K rows to retain 512. Nothing else bounds that. A single entry is
+ /// no exception — rows admitted then superseded within their own batch stay
+ /// in the gather unreferenced — so this does not skip a one-entry store.
+ /// `RANK` ties add a second way to leave rows unreferenced, since a
+ /// boundary move releases every tie of the partition at once.
+ ///
+ /// Amortized O(1) per admitted row: one pass over the live slots, and it
+ /// cannot recur until the store has taken on another `live_slots` rows.
+ ///
+ /// Rows are rewritten into `batch_size` chunks, not one batch: an entry is
+ /// released only when its last slot is evicted, so a single batch of every
+ /// live row would free nothing until every partition has churned.
+ ///
+ /// Peak residency is the old store plus the new one — chunks are built
+ /// before the old entries drop, and the reservation is not resized until
+ /// `insert_batch` returns — so a pool sized at the steady-state bound can be
+ /// exceeded transiently without erroring.
+ ///
+ /// All-or-nothing: plan the move and interleave, which is the only fallible
+ /// step, before rewriting the slots and the store. A failing interleave
+ /// leaves the operator as it was rather than holding slots pointing at ids
+ /// the store never got.
+ fn compact<P: StoreSlots>(
+ &mut self,
+ partitions: &mut HashMap<Vec<u8>, P>,
+ live_slots: usize,
+ batch_size: usize,
+ ) -> Result<()> {
+ if self.total_rows <= live_slots * STORE_COMPACTION_RATIO {
+ return Ok(());
+ }
+
+ // Scoped so these clones, which keep the old batches alive while the
+ // compacted ones are built, drop before the store is rewritten.
+ let first_id = self.next_batch_id();
+ let (moved, chunks) = {
+ let (old, array_pos) = self.positional();
Review Comment:
Addressed in f9d7919e1fed26f901ab6b5a2730e0057b85d56d
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2179,217 +2233,192 @@ impl PartitionedTopKRank {
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
- // 4. Per-partition: classify each row and dispatch.
+ // 2. One pass over the rows in batch order, as in
+ // `PartitionedTopK::insert_batch`: a partition's heap and ties are
+ // only touched by its own rows, which still arrive in ascending row
+ // order, so interleaving partitions cannot change a decision. An
+ // admission, to the heap or to ties, records which row it kept;
+ // phase 3 gathers them all at once.
let k = self.k;
let mut replacements: usize = 0;
+ self.admitted_rows.clear();
+ // The gathered batch's id is known before the batch exists, so slots
+ // can point at it during the pass.
+ let mut pending = self.store.pending();
+ {
+ let pk_rows = &self.partition_scratch_rows;
+ let ob_rows = &self.scratch_rows;
+ let states = &mut self.states;
+ let admitted_rows = &mut self.admitted_rows;
+ let store = &mut self.store;
+ let evicted_key = &mut self.evicted_key;
+ // Accumulated locally and folded in once.
+ let mut interned_bytes = 0usize;
+ let mut admitted_bytes = 0usize;
+ let mut ties_grown = 0usize;
+ let mut new_slots = 0usize;
+ let mut released_slots = 0usize;
- for (pk, indices) in groups.drain() {
- let state = self.states.entry(pk).or_insert_with(|| RankPartitionState {
- heap: TopKHeap::new(k),
- ties: Vec::new(),
- });
-
- // Once the heap is full, a group whose rows are *all* strictly
- // worse than the boundary changes neither the heap nor the
- // ties. Bail before the gather below — at high partition
- // cardinality this is the common case.
- if let Some(max_row) = state.heap.max() {
- let boundary = max_row.row();
- if indices
- .iter()
- .all(|&i| self.scratch_rows.row(i as usize).as_ref() > boundary)
- {
- continue;
+ for row in 0..num_rows {
+ let pk = pk_rows.row(row);
+ let mut interned = false;
+ let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
+ interned = true;
+ RankPartitionState::default()
+ });
+ if interned {
+ interned_bytes += pk.as_ref().len();
}
- }
-
- // Gather this partition's rows into their own batch, as
- // `PartitionedTopK` does. Registering the whole input batch
- // instead would pin it — and charge for it — once per
- // partition key present in the batch, so a batch spanning P
- // partitions would be counted P times over.
- let indices_arr = UInt32Array::from(indices);
- let sub_batch = take_record_batch(batch, &indices_arr)?;
-
- // Indices *into `sub_batch`* of rows from this batch that tied
- // at the boundary. Coalesced into a single tie entry at the end
- // of the partition's loop. Discarded if the boundary moves up
- // mid-loop (those rows were tied to the old boundary, which is
- // now strictly worse than the new K-th).
- let mut equal_indices: Vec<u32> = Vec::new();
- // Lazy-registered: only attached if at least one row reaches
- // the heap from this batch in this partition.
- let mut heap_entry: Option<RecordBatchEntry> = None;
-
- for (sub_idx, &orig_idx) in indices_arr.values().iter().enumerate() {
- let row = self.scratch_rows.row(orig_idx as usize);
-
- // Classify against the current K-th-best (the heap top).
- // `heap.max()` returns `None` while the heap is filling,
- // so unclassified rows fall through to the heap path.
- let classification = state
- .heap
- .max()
- .map(|max_row| row.as_ref().cmp(max_row.row()));
-
- match classification {
+ let key = ob_rows.row(row);
+ let key = key.as_ref();
+ // An admission's row in the gathered batch is its position in
+ // `admitted_rows`, because the gather preserves that order.
+ let at = StoreRef {
+ batch_id: pending.id,
+ row: admitted_rows.len() as u32,
+ };
+ match state.heap.classify(k, key) {
+ // Strictly worse than the boundary: drop the row.
+ Some(Ordering::Greater) => continue,
Some(Ordering::Equal) => {
- equal_indices.push(sub_idx as u32);
+ ties_grown += state.push_tie(at);
+ new_slots += 1;
}
- // Strictly worse than the current boundary: drop the row.
- Some(Ordering::Greater) => {}
- Some(Ordering::Less) | None => {
- // Heap path: heap not yet full, or row strictly
- // better than the current boundary.
- let entry_ref = heap_entry.get_or_insert_with(|| {
- state.heap.register_batch(sub_batch.clone())
- });
- if let Some(EvictedRow {
- batch: evicted_batch,
- index: evicted_index,
- row_bytes: evicted_bytes,
- }) = state.heap.add(entry_ref, row, sub_idx)
- {
- // Compare the new boundary (post-eviction heap
- // top) against the evicted row's bytes — both
- // already in encoded form, no clones needed.
- let boundary_changed = state
- .heap
- .max()
- .expect("heap was full to evict; must still be full")
- .row()
- != evicted_bytes.as_slice();
- if boundary_changed {
- // Boundary moved up — prior ties (across
- // all prior batches) and equal_indices
- // accumulated earlier in THIS batch were
- // tied to the old boundary, now strictly
- // worse than the new K-th-best. Discard.
- state.ties.clear();
- equal_indices.clear();
- } else {
- // Boundary unchanged — the evicted row is
- // still tied at the boundary. Gather just
- // that row: holding `evicted_batch` would
- // keep a whole heap batch alive for one row,
- // and one such entry per input batch would
- // again make memory grow with the input.
- let one = UInt32Array::from(vec![evicted_index as u32]);
- state.push_ties(take_record_batch(&evicted_batch, &one)?);
+
+ None => {
+ let (evicted, grown) = state.heap.add(k, key, at);
+ debug_assert!(
+ evicted.is_none(),
+ "a heap that is not full evicts nothing"
+ );
+ admitted_bytes += grown;
+ new_slots += 1;
+ replacements += 1;
+ }
+ Some(Ordering::Less) => {
+ // Replacing the root overwrites its key in place, so
+ // keep a copy to tell whether the boundary moved.
+ evicted_key.clear();
Review Comment:
Addressed in f9d7919e1fed26f901ab6b5a2730e0057b85d56d
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on code in PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#discussion_r4181160814
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2179,217 +2233,192 @@ impl PartitionedTopKRank {
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
- // 4. Per-partition: classify each row and dispatch.
+ // 2. One pass over the rows in batch order, as in
+ // `PartitionedTopK::insert_batch`: a partition's heap and ties are
+ // only touched by its own rows, which still arrive in ascending row
+ // order, so interleaving partitions cannot change a decision. An
+ // admission, to the heap or to ties, records which row it kept;
+ // phase 3 gathers them all at once.
let k = self.k;
let mut replacements: usize = 0;
+ self.admitted_rows.clear();
+ // The gathered batch's id is known before the batch exists, so slots
+ // can point at it during the pass.
+ let mut pending = self.store.pending();
+ {
+ let pk_rows = &self.partition_scratch_rows;
+ let ob_rows = &self.scratch_rows;
+ let states = &mut self.states;
+ let admitted_rows = &mut self.admitted_rows;
+ let store = &mut self.store;
+ let evicted_key = &mut self.evicted_key;
+ // Accumulated locally and folded in once.
+ let mut interned_bytes = 0usize;
+ let mut admitted_bytes = 0usize;
+ let mut ties_grown = 0usize;
+ let mut new_slots = 0usize;
+ let mut released_slots = 0usize;
- for (pk, indices) in groups.drain() {
- let state = self.states.entry(pk).or_insert_with(|| RankPartitionState {
- heap: TopKHeap::new(k),
- ties: Vec::new(),
- });
-
- // Once the heap is full, a group whose rows are *all* strictly
- // worse than the boundary changes neither the heap nor the
- // ties. Bail before the gather below — at high partition
- // cardinality this is the common case.
- if let Some(max_row) = state.heap.max() {
- let boundary = max_row.row();
- if indices
- .iter()
- .all(|&i| self.scratch_rows.row(i as usize).as_ref() > boundary)
- {
- continue;
+ for row in 0..num_rows {
+ let pk = pk_rows.row(row);
+ let mut interned = false;
+ let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
+ interned = true;
+ RankPartitionState::default()
+ });
+ if interned {
+ interned_bytes += pk.as_ref().len();
}
- }
-
- // Gather this partition's rows into their own batch, as
- // `PartitionedTopK` does. Registering the whole input batch
- // instead would pin it — and charge for it — once per
- // partition key present in the batch, so a batch spanning P
- // partitions would be counted P times over.
- let indices_arr = UInt32Array::from(indices);
- let sub_batch = take_record_batch(batch, &indices_arr)?;
-
- // Indices *into `sub_batch`* of rows from this batch that tied
- // at the boundary. Coalesced into a single tie entry at the end
- // of the partition's loop. Discarded if the boundary moves up
- // mid-loop (those rows were tied to the old boundary, which is
- // now strictly worse than the new K-th).
- let mut equal_indices: Vec<u32> = Vec::new();
- // Lazy-registered: only attached if at least one row reaches
- // the heap from this batch in this partition.
- let mut heap_entry: Option<RecordBatchEntry> = None;
-
- for (sub_idx, &orig_idx) in indices_arr.values().iter().enumerate() {
- let row = self.scratch_rows.row(orig_idx as usize);
-
- // Classify against the current K-th-best (the heap top).
- // `heap.max()` returns `None` while the heap is filling,
- // so unclassified rows fall through to the heap path.
- let classification = state
- .heap
- .max()
- .map(|max_row| row.as_ref().cmp(max_row.row()));
-
- match classification {
+ let key = ob_rows.row(row);
+ let key = key.as_ref();
+ // An admission's row in the gathered batch is its position in
+ // `admitted_rows`, because the gather preserves that order.
+ let at = StoreRef {
+ batch_id: pending.id,
+ row: admitted_rows.len() as u32,
+ };
+ match state.heap.classify(k, key) {
+ // Strictly worse than the boundary: drop the row.
+ Some(Ordering::Greater) => continue,
Some(Ordering::Equal) => {
Review Comment:
In PartitionedTopKRank::insert_batch, rows admitted as ties (the `Equal` arm) do not increment `replacements`, but every other admission does, and every admission does in PartitionedTopK, so `row_replacements` undercounts rows the operator retained.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2179,217 +2233,192 @@ impl PartitionedTopKRank {
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
- // 4. Per-partition: classify each row and dispatch.
+ // 2. One pass over the rows in batch order, as in
+ // `PartitionedTopK::insert_batch`: a partition's heap and ties are
+ // only touched by its own rows, which still arrive in ascending row
+ // order, so interleaving partitions cannot change a decision. An
+ // admission, to the heap or to ties, records which row it kept;
+ // phase 3 gathers them all at once.
let k = self.k;
let mut replacements: usize = 0;
+ self.admitted_rows.clear();
+ // The gathered batch's id is known before the batch exists, so slots
+ // can point at it during the pass.
+ let mut pending = self.store.pending();
+ {
+ let pk_rows = &self.partition_scratch_rows;
+ let ob_rows = &self.scratch_rows;
+ let states = &mut self.states;
+ let admitted_rows = &mut self.admitted_rows;
+ let store = &mut self.store;
+ let evicted_key = &mut self.evicted_key;
+ // Accumulated locally and folded in once.
+ let mut interned_bytes = 0usize;
+ let mut admitted_bytes = 0usize;
+ let mut ties_grown = 0usize;
+ let mut new_slots = 0usize;
+ let mut released_slots = 0usize;
- for (pk, indices) in groups.drain() {
- let state = self.states.entry(pk).or_insert_with(|| RankPartitionState {
- heap: TopKHeap::new(k),
- ties: Vec::new(),
- });
-
- // Once the heap is full, a group whose rows are *all* strictly
- // worse than the boundary changes neither the heap nor the
- // ties. Bail before the gather below — at high partition
- // cardinality this is the common case.
- if let Some(max_row) = state.heap.max() {
- let boundary = max_row.row();
- if indices
- .iter()
- .all(|&i| self.scratch_rows.row(i as usize).as_ref() > boundary)
- {
- continue;
+ for row in 0..num_rows {
+ let pk = pk_rows.row(row);
+ let mut interned = false;
+ let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
+ interned = true;
+ RankPartitionState::default()
+ });
+ if interned {
+ interned_bytes += pk.as_ref().len();
}
- }
-
- // Gather this partition's rows into their own batch, as
- // `PartitionedTopK` does. Registering the whole input batch
- // instead would pin it — and charge for it — once per
- // partition key present in the batch, so a batch spanning P
- // partitions would be counted P times over.
- let indices_arr = UInt32Array::from(indices);
- let sub_batch = take_record_batch(batch, &indices_arr)?;
-
- // Indices *into `sub_batch`* of rows from this batch that tied
- // at the boundary. Coalesced into a single tie entry at the end
- // of the partition's loop. Discarded if the boundary moves up
- // mid-loop (those rows were tied to the old boundary, which is
- // now strictly worse than the new K-th).
- let mut equal_indices: Vec<u32> = Vec::new();
- // Lazy-registered: only attached if at least one row reaches
- // the heap from this batch in this partition.
- let mut heap_entry: Option<RecordBatchEntry> = None;
-
- for (sub_idx, &orig_idx) in indices_arr.values().iter().enumerate() {
- let row = self.scratch_rows.row(orig_idx as usize);
-
- // Classify against the current K-th-best (the heap top).
- // `heap.max()` returns `None` while the heap is filling,
- // so unclassified rows fall through to the heap path.
- let classification = state
- .heap
- .max()
- .map(|max_row| row.as_ref().cmp(max_row.row()));
-
- match classification {
+ let key = ob_rows.row(row);
+ let key = key.as_ref();
+ // An admission's row in the gathered batch is its position in
+ // `admitted_rows`, because the gather preserves that order.
+ let at = StoreRef {
+ batch_id: pending.id,
+ row: admitted_rows.len() as u32,
+ };
+ match state.heap.classify(k, key) {
+ // Strictly worse than the boundary: drop the row.
+ Some(Ordering::Greater) => continue,
Some(Ordering::Equal) => {
- equal_indices.push(sub_idx as u32);
+ ties_grown += state.push_tie(at);
+ new_slots += 1;
}
- // Strictly worse than the current boundary: drop the row.
- Some(Ordering::Greater) => {}
- Some(Ordering::Less) | None => {
- // Heap path: heap not yet full, or row strictly
- // better than the current boundary.
- let entry_ref = heap_entry.get_or_insert_with(|| {
- state.heap.register_batch(sub_batch.clone())
- });
- if let Some(EvictedRow {
- batch: evicted_batch,
- index: evicted_index,
- row_bytes: evicted_bytes,
- }) = state.heap.add(entry_ref, row, sub_idx)
- {
- // Compare the new boundary (post-eviction heap
- // top) against the evicted row's bytes — both
- // already in encoded form, no clones needed.
- let boundary_changed = state
- .heap
- .max()
- .expect("heap was full to evict; must still be full")
- .row()
- != evicted_bytes.as_slice();
- if boundary_changed {
- // Boundary moved up — prior ties (across
- // all prior batches) and equal_indices
- // accumulated earlier in THIS batch were
- // tied to the old boundary, now strictly
- // worse than the new K-th-best. Discard.
- state.ties.clear();
- equal_indices.clear();
- } else {
- // Boundary unchanged — the evicted row is
- // still tied at the boundary. Gather just
- // that row: holding `evicted_batch` would
- // keep a whole heap batch alive for one row,
- // and one such entry per input batch would
- // again make memory grow with the input.
- let one = UInt32Array::from(vec![evicted_index as u32]);
- state.push_ties(take_record_batch(&evicted_batch, &one)?);
+
+ None => {
+ let (evicted, grown) = state.heap.add(k, key, at);
+ debug_assert!(
+ evicted.is_none(),
+ "a heap that is not full evicts nothing"
+ );
+ admitted_bytes += grown;
+ new_slots += 1;
+ replacements += 1;
+ }
+ Some(Ordering::Less) => {
+ // Replacing the root overwrites its key in place, so
+ // keep a copy to tell whether the boundary moved.
+ evicted_key.clear();
+ evicted_key.extend_from_slice(
+ state.heap.worst_key().expect("classified, so full"),
+ );
+ let (evicted, grown) = state.heap.add(k, key, at);
+ let evicted = evicted.expect("a full heap evicts");
+ admitted_bytes += grown;
+ if state.heap.worst_key() == Some(evicted_key.as_slice()) {
+ // Boundary unchanged: the evicted row is still
+ // tied at it. Its slot moves to the tie list, and
+ // its store use with it — no gather, no release.
+ ties_grown += state.push_tie(evicted);
+ new_slots += 1;
+ } else {
+ // Boundary moved up: the evicted row and every tie
+ // (from this batch or earlier ones) now rank
+ // below K.
+ store.release(&mut pending, evicted.batch_id);
+ for tie in &state.ties {
+ store.release(&mut pending, tie.batch_id);
}
+ released_slots += state.ties.len();
+ state.ties.clear();
Review Comment:
Release tie-list capacity when the boundary improves
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1313,6 +1314,145 @@ impl RecordBatchStore {
+ self.batches.capacity() * (size_of::<u32>() + size_of::<RecordBatchEntry>())
+ self.batches_size
}
+
+ /// Rewrite the store to hold only the rows `partitions` still reference,
+ /// once it holds [`STORE_COMPACTION_RATIO`]× more than the `live_slots` of
+ /// them, and repoint every partition at the rows' new places.
+ /// [`PartitionedTopK`] and [`PartitionedTopKRank`] call this at the end of
+ /// every `insert_batch`.
+ ///
+ /// An entry holds every row *admitted* from its input batch and is freed
+ /// only when the last of them is evicted, so when survivors spread thinly
+ /// one live row keeps a whole entry resident and residency tracks the
+ /// *input*, not `partitions × K`: 512 partitions of `K = 1` fed 512 batches
+ /// pin 131 K rows to retain 512. Nothing else bounds that. A single entry is
+ /// no exception — rows admitted then superseded within their own batch stay
+ /// in the gather unreferenced — so this does not skip a one-entry store.
+ /// `RANK` ties add a second way to leave rows unreferenced, since a
+ /// boundary move releases every tie of the partition at once.
+ ///
+ /// Amortized O(1) per admitted row: one pass over the live slots, and it
+ /// cannot recur until the store has taken on another `live_slots` rows.
+ ///
+ /// Rows are rewritten into `batch_size` chunks, not one batch: an entry is
+ /// released only when its last slot is evicted, so a single batch of every
+ /// live row would free nothing until every partition has churned.
+ ///
+ /// Peak residency is the old store plus the new one — chunks are built
+ /// before the old entries drop, and the reservation is not resized until
+ /// `insert_batch` returns — so a pool sized at the steady-state bound can be
+ /// exceeded transiently without erroring.
+ ///
+ /// All-or-nothing: plan the move and interleave, which is the only fallible
+ /// step, before rewriting the slots and the store. A failing interleave
+ /// leaves the operator as it was rather than holding slots pointing at ids
+ /// the store never got.
+ fn compact<P: StoreSlots>(
+ &mut self,
+ partitions: &mut HashMap<Vec<u8>, P>,
+ live_slots: usize,
+ batch_size: usize,
+ ) -> Result<()> {
+ if self.total_rows <= live_slots * STORE_COMPACTION_RATIO {
+ return Ok(());
+ }
+
+ // Scoped so these clones, which keep the old batches alive while the
+ // compacted ones are built, drop before the store is rewritten.
+ let first_id = self.next_batch_id();
+ let (moved, chunks) = {
+ let (old, array_pos) = self.positional();
+
+ // Keyed by the row's current place rather than by its position in
+ // this walk, so the partitions are free to repoint in any order —
+ // no two slots share a store row, so the key identifies exactly one
+ // slot.
+ let mut coords: Vec<(usize, usize)> = Vec::with_capacity(live_slots);
+ let mut moved: HashMap<StoreRef, StoreRef> =
Review Comment:
RecordBatchStore::compact builds a HashMap<StoreRef, StoreRef> with live_slots entries just to repoint slots, although partitions.values()/values_mut() and store_rows()/repoint() walk the slots in the same order, so a running counter would give each slot its new place.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2179,217 +2233,192 @@ impl PartitionedTopKRank {
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
- // 4. Per-partition: classify each row and dispatch.
+ // 2. One pass over the rows in batch order, as in
+ // `PartitionedTopK::insert_batch`: a partition's heap and ties are
+ // only touched by its own rows, which still arrive in ascending row
+ // order, so interleaving partitions cannot change a decision. An
+ // admission, to the heap or to ties, records which row it kept;
+ // phase 3 gathers them all at once.
let k = self.k;
let mut replacements: usize = 0;
+ self.admitted_rows.clear();
+ // The gathered batch's id is known before the batch exists, so slots
+ // can point at it during the pass.
+ let mut pending = self.store.pending();
+ {
+ let pk_rows = &self.partition_scratch_rows;
+ let ob_rows = &self.scratch_rows;
+ let states = &mut self.states;
+ let admitted_rows = &mut self.admitted_rows;
+ let store = &mut self.store;
+ let evicted_key = &mut self.evicted_key;
+ // Accumulated locally and folded in once.
+ let mut interned_bytes = 0usize;
+ let mut admitted_bytes = 0usize;
+ let mut ties_grown = 0usize;
+ let mut new_slots = 0usize;
+ let mut released_slots = 0usize;
- for (pk, indices) in groups.drain() {
- let state = self.states.entry(pk).or_insert_with(|| RankPartitionState {
- heap: TopKHeap::new(k),
- ties: Vec::new(),
- });
-
- // Once the heap is full, a group whose rows are *all* strictly
- // worse than the boundary changes neither the heap nor the
- // ties. Bail before the gather below — at high partition
- // cardinality this is the common case.
- if let Some(max_row) = state.heap.max() {
- let boundary = max_row.row();
- if indices
- .iter()
- .all(|&i| self.scratch_rows.row(i as usize).as_ref() > boundary)
- {
- continue;
+ for row in 0..num_rows {
+ let pk = pk_rows.row(row);
+ let mut interned = false;
+ let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
+ interned = true;
+ RankPartitionState::default()
+ });
+ if interned {
+ interned_bytes += pk.as_ref().len();
}
- }
-
- // Gather this partition's rows into their own batch, as
- // `PartitionedTopK` does. Registering the whole input batch
- // instead would pin it — and charge for it — once per
- // partition key present in the batch, so a batch spanning P
- // partitions would be counted P times over.
- let indices_arr = UInt32Array::from(indices);
- let sub_batch = take_record_batch(batch, &indices_arr)?;
-
- // Indices *into `sub_batch`* of rows from this batch that tied
- // at the boundary. Coalesced into a single tie entry at the end
- // of the partition's loop. Discarded if the boundary moves up
- // mid-loop (those rows were tied to the old boundary, which is
- // now strictly worse than the new K-th).
- let mut equal_indices: Vec<u32> = Vec::new();
- // Lazy-registered: only attached if at least one row reaches
- // the heap from this batch in this partition.
- let mut heap_entry: Option<RecordBatchEntry> = None;
-
- for (sub_idx, &orig_idx) in indices_arr.values().iter().enumerate() {
- let row = self.scratch_rows.row(orig_idx as usize);
-
- // Classify against the current K-th-best (the heap top).
- // `heap.max()` returns `None` while the heap is filling,
- // so unclassified rows fall through to the heap path.
- let classification = state
- .heap
- .max()
- .map(|max_row| row.as_ref().cmp(max_row.row()));
-
- match classification {
+ let key = ob_rows.row(row);
+ let key = key.as_ref();
+ // An admission's row in the gathered batch is its position in
+ // `admitted_rows`, because the gather preserves that order.
+ let at = StoreRef {
+ batch_id: pending.id,
+ row: admitted_rows.len() as u32,
+ };
+ match state.heap.classify(k, key) {
+ // Strictly worse than the boundary: drop the row.
+ Some(Ordering::Greater) => continue,
Some(Ordering::Equal) => {
- equal_indices.push(sub_idx as u32);
+ ties_grown += state.push_tie(at);
+ new_slots += 1;
}
- // Strictly worse than the current boundary: drop the row.
- Some(Ordering::Greater) => {}
- Some(Ordering::Less) | None => {
- // Heap path: heap not yet full, or row strictly
- // better than the current boundary.
- let entry_ref = heap_entry.get_or_insert_with(|| {
- state.heap.register_batch(sub_batch.clone())
- });
- if let Some(EvictedRow {
- batch: evicted_batch,
- index: evicted_index,
- row_bytes: evicted_bytes,
- }) = state.heap.add(entry_ref, row, sub_idx)
- {
- // Compare the new boundary (post-eviction heap
- // top) against the evicted row's bytes — both
- // already in encoded form, no clones needed.
- let boundary_changed = state
- .heap
- .max()
- .expect("heap was full to evict; must still be full")
- .row()
- != evicted_bytes.as_slice();
- if boundary_changed {
- // Boundary moved up — prior ties (across
- // all prior batches) and equal_indices
- // accumulated earlier in THIS batch were
- // tied to the old boundary, now strictly
- // worse than the new K-th-best. Discard.
- state.ties.clear();
- equal_indices.clear();
- } else {
- // Boundary unchanged — the evicted row is
- // still tied at the boundary. Gather just
- // that row: holding `evicted_batch` would
- // keep a whole heap batch alive for one row,
- // and one such entry per input batch would
- // again make memory grow with the input.
- let one = UInt32Array::from(vec![evicted_index as u32]);
- state.push_ties(take_record_batch(&evicted_batch, &one)?);
+
+ None => {
+ let (evicted, grown) = state.heap.add(k, key, at);
+ debug_assert!(
+ evicted.is_none(),
+ "a heap that is not full evicts nothing"
+ );
+ admitted_bytes += grown;
+ new_slots += 1;
+ replacements += 1;
+ }
+ Some(Ordering::Less) => {
+ // Replacing the root overwrites its key in place, so
+ // keep a copy to tell whether the boundary moved.
+ evicted_key.clear();
Review Comment:
Every strictly-better eviction in RANK memcpys the old root key into `evicted_key` only to compare it with the new root. PartitionHeap::add could hand the old key back by swapping Vecs instead.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2140,8 +2213,8 @@ impl PartitionedTopKRank {
return Ok(());
}
- // 1. Evaluate + encode partition columns into the reusable
- // scratch (cleared then appended).
+ // 1. Evaluate the partition and ORDER BY columns and encode each once
Review Comment:
PartitionedTopKRank still duplicates PartitionedTopK almost line for line: the same ~14 fields, try_new, the phase-1 evaluate/encode block, the phase-3 insert_rows/compact/try_resize tail, the emit destructuring and size(). Only the per-row admission rule differs.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
Review Comment:
https://github.com/apache/datafusion/blob/7a1b6f0064a51afd388cd330b6cbfd44d0d05e02/datafusion/physical-plan/src/topk/mod.rs#L990
PR adds RecordBatchStore::positional to build the batches/`batch_id -> position` pair, but TopKHeap::emit_with_state still builds the same mapping inline.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1313,6 +1314,145 @@ impl RecordBatchStore {
+ self.batches.capacity() * (size_of::<u32>() + size_of::<RecordBatchEntry>())
+ self.batches_size
}
+
+ /// Rewrite the store to hold only the rows `partitions` still reference,
+ /// once it holds [`STORE_COMPACTION_RATIO`]× more than the `live_slots` of
+ /// them, and repoint every partition at the rows' new places.
+ /// [`PartitionedTopK`] and [`PartitionedTopKRank`] call this at the end of
+ /// every `insert_batch`.
+ ///
+ /// An entry holds every row *admitted* from its input batch and is freed
+ /// only when the last of them is evicted, so when survivors spread thinly
+ /// one live row keeps a whole entry resident and residency tracks the
+ /// *input*, not `partitions × K`: 512 partitions of `K = 1` fed 512 batches
+ /// pin 131 K rows to retain 512. Nothing else bounds that. A single entry is
+ /// no exception — rows admitted then superseded within their own batch stay
+ /// in the gather unreferenced — so this does not skip a one-entry store.
+ /// `RANK` ties add a second way to leave rows unreferenced, since a
+ /// boundary move releases every tie of the partition at once.
+ ///
+ /// Amortized O(1) per admitted row: one pass over the live slots, and it
+ /// cannot recur until the store has taken on another `live_slots` rows.
+ ///
+ /// Rows are rewritten into `batch_size` chunks, not one batch: an entry is
+ /// released only when its last slot is evicted, so a single batch of every
+ /// live row would free nothing until every partition has churned.
+ ///
+ /// Peak residency is the old store plus the new one — chunks are built
+ /// before the old entries drop, and the reservation is not resized until
+ /// `insert_batch` returns — so a pool sized at the steady-state bound can be
+ /// exceeded transiently without erroring.
+ ///
+ /// All-or-nothing: plan the move and interleave, which is the only fallible
+ /// step, before rewriting the slots and the store. A failing interleave
+ /// leaves the operator as it was rather than holding slots pointing at ids
+ /// the store never got.
+ fn compact<P: StoreSlots>(
+ &mut self,
+ partitions: &mut HashMap<Vec<u8>, P>,
+ live_slots: usize,
+ batch_size: usize,
+ ) -> Result<()> {
+ if self.total_rows <= live_slots * STORE_COMPACTION_RATIO {
+ return Ok(());
+ }
+
+ // Scoped so these clones, which keep the old batches alive while the
+ // compacted ones are built, drop before the store is rewritten.
+ let first_id = self.next_batch_id();
+ let (moved, chunks) = {
+ let (old, array_pos) = self.positional();
Review Comment:
compact calls `positional()`, which clones every stored RecordBatch (an Arc bump per column) and builds a fresh HashMap, but compact only needs borrowed `&RecordBatch` refs that it drops before the store is rewritten.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2179,217 +2233,192 @@ impl PartitionedTopKRank {
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
- // 4. Per-partition: classify each row and dispatch.
+ // 2. One pass over the rows in batch order, as in
+ // `PartitionedTopK::insert_batch`: a partition's heap and ties are
+ // only touched by its own rows, which still arrive in ascending row
+ // order, so interleaving partitions cannot change a decision. An
+ // admission, to the heap or to ties, records which row it kept;
+ // phase 3 gathers them all at once.
let k = self.k;
let mut replacements: usize = 0;
+ self.admitted_rows.clear();
+ // The gathered batch's id is known before the batch exists, so slots
+ // can point at it during the pass.
+ let mut pending = self.store.pending();
+ {
+ let pk_rows = &self.partition_scratch_rows;
+ let ob_rows = &self.scratch_rows;
+ let states = &mut self.states;
+ let admitted_rows = &mut self.admitted_rows;
+ let store = &mut self.store;
+ let evicted_key = &mut self.evicted_key;
+ // Accumulated locally and folded in once.
+ let mut interned_bytes = 0usize;
+ let mut admitted_bytes = 0usize;
+ let mut ties_grown = 0usize;
+ let mut new_slots = 0usize;
+ let mut released_slots = 0usize;
- for (pk, indices) in groups.drain() {
- let state = self.states.entry(pk).or_insert_with(|| RankPartitionState {
- heap: TopKHeap::new(k),
- ties: Vec::new(),
- });
-
- // Once the heap is full, a group whose rows are *all* strictly
- // worse than the boundary changes neither the heap nor the
- // ties. Bail before the gather below — at high partition
- // cardinality this is the common case.
- if let Some(max_row) = state.heap.max() {
- let boundary = max_row.row();
- if indices
- .iter()
- .all(|&i| self.scratch_rows.row(i as usize).as_ref() > boundary)
- {
- continue;
+ for row in 0..num_rows {
+ let pk = pk_rows.row(row);
+ let mut interned = false;
+ let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
+ interned = true;
+ RankPartitionState::default()
+ });
+ if interned {
+ interned_bytes += pk.as_ref().len();
}
- }
-
- // Gather this partition's rows into their own batch, as
- // `PartitionedTopK` does. Registering the whole input batch
- // instead would pin it — and charge for it — once per
- // partition key present in the batch, so a batch spanning P
- // partitions would be counted P times over.
- let indices_arr = UInt32Array::from(indices);
- let sub_batch = take_record_batch(batch, &indices_arr)?;
-
- // Indices *into `sub_batch`* of rows from this batch that tied
- // at the boundary. Coalesced into a single tie entry at the end
- // of the partition's loop. Discarded if the boundary moves up
- // mid-loop (those rows were tied to the old boundary, which is
- // now strictly worse than the new K-th).
- let mut equal_indices: Vec<u32> = Vec::new();
- // Lazy-registered: only attached if at least one row reaches
- // the heap from this batch in this partition.
- let mut heap_entry: Option<RecordBatchEntry> = None;
-
- for (sub_idx, &orig_idx) in indices_arr.values().iter().enumerate() {
- let row = self.scratch_rows.row(orig_idx as usize);
-
- // Classify against the current K-th-best (the heap top).
- // `heap.max()` returns `None` while the heap is filling,
- // so unclassified rows fall through to the heap path.
- let classification = state
- .heap
- .max()
- .map(|max_row| row.as_ref().cmp(max_row.row()));
-
- match classification {
+ let key = ob_rows.row(row);
+ let key = key.as_ref();
+ // An admission's row in the gathered batch is its position in
+ // `admitted_rows`, because the gather preserves that order.
+ let at = StoreRef {
+ batch_id: pending.id,
+ row: admitted_rows.len() as u32,
+ };
+ match state.heap.classify(k, key) {
+ // Strictly worse than the boundary: drop the row.
+ Some(Ordering::Greater) => continue,
Some(Ordering::Equal) => {
- equal_indices.push(sub_idx as u32);
+ ties_grown += state.push_tie(at);
+ new_slots += 1;
}
- // Strictly worse than the current boundary: drop the row.
- Some(Ordering::Greater) => {}
- Some(Ordering::Less) | None => {
- // Heap path: heap not yet full, or row strictly
- // better than the current boundary.
- let entry_ref = heap_entry.get_or_insert_with(|| {
- state.heap.register_batch(sub_batch.clone())
- });
- if let Some(EvictedRow {
- batch: evicted_batch,
- index: evicted_index,
- row_bytes: evicted_bytes,
- }) = state.heap.add(entry_ref, row, sub_idx)
- {
- // Compare the new boundary (post-eviction heap
- // top) against the evicted row's bytes — both
- // already in encoded form, no clones needed.
- let boundary_changed = state
- .heap
- .max()
- .expect("heap was full to evict; must still be full")
- .row()
- != evicted_bytes.as_slice();
- if boundary_changed {
- // Boundary moved up — prior ties (across
- // all prior batches) and equal_indices
- // accumulated earlier in THIS batch were
- // tied to the old boundary, now strictly
- // worse than the new K-th-best. Discard.
- state.ties.clear();
- equal_indices.clear();
- } else {
- // Boundary unchanged — the evicted row is
- // still tied at the boundary. Gather just
- // that row: holding `evicted_batch` would
- // keep a whole heap batch alive for one row,
- // and one such entry per input batch would
- // again make memory grow with the input.
- let one = UInt32Array::from(vec![evicted_index as u32]);
- state.push_ties(take_record_batch(&evicted_batch, &one)?);
+
+ None => {
+ let (evicted, grown) = state.heap.add(k, key, at);
+ debug_assert!(
+ evicted.is_none(),
+ "a heap that is not full evicts nothing"
+ );
+ admitted_bytes += grown;
+ new_slots += 1;
+ replacements += 1;
+ }
+ Some(Ordering::Less) => {
+ // Replacing the root overwrites its key in place, so
+ // keep a copy to tell whether the boundary moved.
+ evicted_key.clear();
+ evicted_key.extend_from_slice(
+ state.heap.worst_key().expect("classified, so full"),
+ );
+ let (evicted, grown) = state.heap.add(k, key, at);
+ let evicted = evicted.expect("a full heap evicts");
+ admitted_bytes += grown;
+ if state.heap.worst_key() == Some(evicted_key.as_slice()) {
+ // Boundary unchanged: the evicted row is still
+ // tied at it. Its slot moves to the tie list, and
+ // its store use with it — no gather, no release.
+ ties_grown += state.push_tie(evicted);
+ new_slots += 1;
+ } else {
+ // Boundary moved up: the evicted row and every tie
+ // (from this batch or earlier ones) now rank
+ // below K.
+ store.release(&mut pending, evicted.batch_id);
+ for tie in &state.ties {
+ store.release(&mut pending, tie.batch_id);
}
+ released_slots += state.ties.len();
+ state.ties.clear();
}
replacements += 1;
}
}
+ pending.uses += 1;
+ admitted_rows.push(row as u32);
}
- let registered_with_heap = heap_entry.is_some();
- if let Some(e) = heap_entry {
- state.heap.insert_batch_entry(e);
- state.heap.maybe_compact()?;
- }
-
- // Commit this batch's ties as a single entry.
- if !equal_indices.is_empty() {
- // No row of this group reached the heap, so `sub_batch` is
- // not registered there and reusing it here cannot
- // double-charge it. Combined with every row having tied,
- // `sub_batch` already *is* exactly the tie rows — the
- // gather below would just copy it.
- let tie_batch = if !registered_with_heap
- && equal_indices.len() == sub_batch.num_rows()
- {
- sub_batch
- } else {
- take_record_batch(&sub_batch, &UInt32Array::from(equal_indices))?
- };
- state.push_ties(tie_batch);
- }
+ self.index_bytes += interned_bytes;
+ self.heaps_bytes += admitted_bytes;
+ self.ties_bytes += ties_grown;
+ self.live_slots = self.live_slots + new_slots - released_slots;
}
- // Return the drained scratch map (capacity retained) for the next
- // batch to reuse.
- self.partition_groups = groups;
+ // 3. Gather the rows this batch contributed into a single batch and
+ // hand it to the store, as in `PartitionedTopK::insert_batch`.
+ // No uses left means every admission from this batch was released
+ // again before the pass ended, and the id goes to the next batch.
+ self.store
+ .insert_rows(batch, &self.admitted_rows, pending)?;
if replacements > 0 {
self.metrics.row_replacements.add(replacements);
}
+ self.store
+ .compact(&mut self.states, self.live_slots, self.batch_size)?;
self.reservation.try_resize(self.size())?;
Ok(())
}
- /// Drain all heaps and ties in partition-key order and return the
- /// rows as a stream of coalesced [`RecordBatch`]es ordered by
- /// `(partition_keys, order_keys)`. Within a partition, heap rows
- /// come first (sorted by ob), then tie rows (all sharing the
- /// boundary ob).
+ /// Drain every partition in partition-key order and return the rows as a
+ /// stream of `RecordBatch`es ordered by `(partition_keys, order_keys)`.
+ /// Within a partition, heap rows come first (sorted by ob), then tie rows
+ /// (all sharing the boundary ob).
+ ///
+ /// Only the order is resolved here; [`EmitState::stream`], shared with
+ /// [`PartitionedTopK::emit`], does the rest.
pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
let Self {
schema,
metrics,
- reservation: _,
+ reservation,
expr: _,
row_converter: _,
scratch_rows: _,
partition_exprs: _,
partition_converter: _,
partition_scratch_rows: _,
- mut states,
- partition_groups: _,
+ states,
+ store,
+ admitted_rows: _,
+ evicted_key: _,
+ live_slots,
+ heaps_bytes: _,
+ ties_bytes: _,
+ index_bytes: _,
k: _,
batch_size,
} = self;
- let _timer = metrics.baseline.elapsed_compute().timer();
-
- let mut sorted_pks: Vec<Vec<u8>> = states.keys().cloned().collect();
- sorted_pks.sort();
-
- let mut coalescer = BatchCoalescer::new(Arc::clone(&schema), batch_size);
-
- for pk in sorted_pks {
- let RankPartitionState { mut heap, ties } =
- states.remove(&pk).expect("key from states.keys()");
- if let Some(batch) = heap.emit()? {
- coalescer.push_batch(batch)?;
- }
- for tie in ties {
- coalescer.push_batch(tie.batch)?;
- }
- }
- coalescer.finish_buffered_batch()?;
-
- let mut out: Vec<Result<RecordBatch>> = Vec::new();
- while let Some(b) = coalescer.next_completed_batch() {
- (&b).record_output(&metrics.baseline);
- out.push(Ok(b));
- }
+ let timer = metrics.baseline.elapsed_compute().timer();
+ let mut sorted_states: Vec<(Vec<u8>, RankPartitionState)> =
+ states.into_iter().collect();
+ sorted_states.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
+ drop(timer);
- Ok(Box::pin(RecordBatchStreamAdapter::new(
+ let slots = sorted_states.into_iter().flat_map(|(_key, mut state)| {
+ let heap = state.heap.drain_sorted().into_iter().map(|slot| slot.at);
+ heap.chain(state.ties)
+ });
+ EmitState::stream(
schema,
- futures::stream::iter(out),
- )))
+ metrics,
+ reservation,
+ batch_size,
+ &store,
Review Comment:
Limit interleave inputs to batches referenced by each output chunk
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
Review Comment:
https://github.com/apache/datafusion/blob/7a1b6f0064a51afd388cd330b6cbfd44d0d05e02/datafusion/physical-plan/src/topk/mod.rs#L6019
Comments left stale by the rewrite: the doc and step comments of test_partitioned_topk_rank_boundary_shifts_clears_ties still describe the removed in-flight `equal_indices` list ('must clear both state.ties and the in-flight equal_indices'), and assert_store_matches_slots (line 4948) still names `compact_store`, which this PR replaced with RecordBatchStore::compact.
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "SubhamSinghal (via GitHub)" <gi...@apache.org>.
SubhamSinghal commented on code in PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#discussion_r4182843368
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2179,217 +2233,192 @@ impl PartitionedTopKRank {
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
- // 4. Per-partition: classify each row and dispatch.
+ // 2. One pass over the rows in batch order, as in
+ // `PartitionedTopK::insert_batch`: a partition's heap and ties are
+ // only touched by its own rows, which still arrive in ascending row
+ // order, so interleaving partitions cannot change a decision. An
+ // admission, to the heap or to ties, records which row it kept;
+ // phase 3 gathers them all at once.
let k = self.k;
let mut replacements: usize = 0;
+ self.admitted_rows.clear();
+ // The gathered batch's id is known before the batch exists, so slots
+ // can point at it during the pass.
+ let mut pending = self.store.pending();
+ {
+ let pk_rows = &self.partition_scratch_rows;
+ let ob_rows = &self.scratch_rows;
+ let states = &mut self.states;
+ let admitted_rows = &mut self.admitted_rows;
+ let store = &mut self.store;
+ let evicted_key = &mut self.evicted_key;
+ // Accumulated locally and folded in once.
+ let mut interned_bytes = 0usize;
+ let mut admitted_bytes = 0usize;
+ let mut ties_grown = 0usize;
+ let mut new_slots = 0usize;
+ let mut released_slots = 0usize;
- for (pk, indices) in groups.drain() {
- let state = self.states.entry(pk).or_insert_with(|| RankPartitionState {
- heap: TopKHeap::new(k),
- ties: Vec::new(),
- });
-
- // Once the heap is full, a group whose rows are *all* strictly
- // worse than the boundary changes neither the heap nor the
- // ties. Bail before the gather below — at high partition
- // cardinality this is the common case.
- if let Some(max_row) = state.heap.max() {
- let boundary = max_row.row();
- if indices
- .iter()
- .all(|&i| self.scratch_rows.row(i as usize).as_ref() > boundary)
- {
- continue;
+ for row in 0..num_rows {
+ let pk = pk_rows.row(row);
+ let mut interned = false;
+ let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
+ interned = true;
+ RankPartitionState::default()
+ });
+ if interned {
+ interned_bytes += pk.as_ref().len();
}
- }
-
- // Gather this partition's rows into their own batch, as
- // `PartitionedTopK` does. Registering the whole input batch
- // instead would pin it — and charge for it — once per
- // partition key present in the batch, so a batch spanning P
- // partitions would be counted P times over.
- let indices_arr = UInt32Array::from(indices);
- let sub_batch = take_record_batch(batch, &indices_arr)?;
-
- // Indices *into `sub_batch`* of rows from this batch that tied
- // at the boundary. Coalesced into a single tie entry at the end
- // of the partition's loop. Discarded if the boundary moves up
- // mid-loop (those rows were tied to the old boundary, which is
- // now strictly worse than the new K-th).
- let mut equal_indices: Vec<u32> = Vec::new();
- // Lazy-registered: only attached if at least one row reaches
- // the heap from this batch in this partition.
- let mut heap_entry: Option<RecordBatchEntry> = None;
-
- for (sub_idx, &orig_idx) in indices_arr.values().iter().enumerate() {
- let row = self.scratch_rows.row(orig_idx as usize);
-
- // Classify against the current K-th-best (the heap top).
- // `heap.max()` returns `None` while the heap is filling,
- // so unclassified rows fall through to the heap path.
- let classification = state
- .heap
- .max()
- .map(|max_row| row.as_ref().cmp(max_row.row()));
-
- match classification {
+ let key = ob_rows.row(row);
+ let key = key.as_ref();
+ // An admission's row in the gathered batch is its position in
+ // `admitted_rows`, because the gather preserves that order.
+ let at = StoreRef {
+ batch_id: pending.id,
+ row: admitted_rows.len() as u32,
+ };
+ match state.heap.classify(k, key) {
+ // Strictly worse than the boundary: drop the row.
+ Some(Ordering::Greater) => continue,
Some(Ordering::Equal) => {
Review Comment:
Addressed in f9d7919e1fed26f901ab6b5a2730e0057b85d56d
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2179,217 +2233,192 @@ impl PartitionedTopKRank {
self.row_converter
.append(&mut self.scratch_rows, &ob_arrays)?;
- // 4. Per-partition: classify each row and dispatch.
+ // 2. One pass over the rows in batch order, as in
+ // `PartitionedTopK::insert_batch`: a partition's heap and ties are
+ // only touched by its own rows, which still arrive in ascending row
+ // order, so interleaving partitions cannot change a decision. An
+ // admission, to the heap or to ties, records which row it kept;
+ // phase 3 gathers them all at once.
let k = self.k;
let mut replacements: usize = 0;
+ self.admitted_rows.clear();
+ // The gathered batch's id is known before the batch exists, so slots
+ // can point at it during the pass.
+ let mut pending = self.store.pending();
+ {
+ let pk_rows = &self.partition_scratch_rows;
+ let ob_rows = &self.scratch_rows;
+ let states = &mut self.states;
+ let admitted_rows = &mut self.admitted_rows;
+ let store = &mut self.store;
+ let evicted_key = &mut self.evicted_key;
+ // Accumulated locally and folded in once.
+ let mut interned_bytes = 0usize;
+ let mut admitted_bytes = 0usize;
+ let mut ties_grown = 0usize;
+ let mut new_slots = 0usize;
+ let mut released_slots = 0usize;
- for (pk, indices) in groups.drain() {
- let state = self.states.entry(pk).or_insert_with(|| RankPartitionState {
- heap: TopKHeap::new(k),
- ties: Vec::new(),
- });
-
- // Once the heap is full, a group whose rows are *all* strictly
- // worse than the boundary changes neither the heap nor the
- // ties. Bail before the gather below — at high partition
- // cardinality this is the common case.
- if let Some(max_row) = state.heap.max() {
- let boundary = max_row.row();
- if indices
- .iter()
- .all(|&i| self.scratch_rows.row(i as usize).as_ref() > boundary)
- {
- continue;
+ for row in 0..num_rows {
+ let pk = pk_rows.row(row);
+ let mut interned = false;
+ let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
+ interned = true;
+ RankPartitionState::default()
+ });
+ if interned {
+ interned_bytes += pk.as_ref().len();
}
- }
-
- // Gather this partition's rows into their own batch, as
- // `PartitionedTopK` does. Registering the whole input batch
- // instead would pin it — and charge for it — once per
- // partition key present in the batch, so a batch spanning P
- // partitions would be counted P times over.
- let indices_arr = UInt32Array::from(indices);
- let sub_batch = take_record_batch(batch, &indices_arr)?;
-
- // Indices *into `sub_batch`* of rows from this batch that tied
- // at the boundary. Coalesced into a single tie entry at the end
- // of the partition's loop. Discarded if the boundary moves up
- // mid-loop (those rows were tied to the old boundary, which is
- // now strictly worse than the new K-th).
- let mut equal_indices: Vec<u32> = Vec::new();
- // Lazy-registered: only attached if at least one row reaches
- // the heap from this batch in this partition.
- let mut heap_entry: Option<RecordBatchEntry> = None;
-
- for (sub_idx, &orig_idx) in indices_arr.values().iter().enumerate() {
- let row = self.scratch_rows.row(orig_idx as usize);
-
- // Classify against the current K-th-best (the heap top).
- // `heap.max()` returns `None` while the heap is filling,
- // so unclassified rows fall through to the heap path.
- let classification = state
- .heap
- .max()
- .map(|max_row| row.as_ref().cmp(max_row.row()));
-
- match classification {
+ let key = ob_rows.row(row);
+ let key = key.as_ref();
+ // An admission's row in the gathered batch is its position in
+ // `admitted_rows`, because the gather preserves that order.
+ let at = StoreRef {
+ batch_id: pending.id,
+ row: admitted_rows.len() as u32,
+ };
+ match state.heap.classify(k, key) {
+ // Strictly worse than the boundary: drop the row.
+ Some(Ordering::Greater) => continue,
Some(Ordering::Equal) => {
- equal_indices.push(sub_idx as u32);
+ ties_grown += state.push_tie(at);
+ new_slots += 1;
}
- // Strictly worse than the current boundary: drop the row.
- Some(Ordering::Greater) => {}
- Some(Ordering::Less) | None => {
- // Heap path: heap not yet full, or row strictly
- // better than the current boundary.
- let entry_ref = heap_entry.get_or_insert_with(|| {
- state.heap.register_batch(sub_batch.clone())
- });
- if let Some(EvictedRow {
- batch: evicted_batch,
- index: evicted_index,
- row_bytes: evicted_bytes,
- }) = state.heap.add(entry_ref, row, sub_idx)
- {
- // Compare the new boundary (post-eviction heap
- // top) against the evicted row's bytes — both
- // already in encoded form, no clones needed.
- let boundary_changed = state
- .heap
- .max()
- .expect("heap was full to evict; must still be full")
- .row()
- != evicted_bytes.as_slice();
- if boundary_changed {
- // Boundary moved up — prior ties (across
- // all prior batches) and equal_indices
- // accumulated earlier in THIS batch were
- // tied to the old boundary, now strictly
- // worse than the new K-th-best. Discard.
- state.ties.clear();
- equal_indices.clear();
- } else {
- // Boundary unchanged — the evicted row is
- // still tied at the boundary. Gather just
- // that row: holding `evicted_batch` would
- // keep a whole heap batch alive for one row,
- // and one such entry per input batch would
- // again make memory grow with the input.
- let one = UInt32Array::from(vec![evicted_index as u32]);
- state.push_ties(take_record_batch(&evicted_batch, &one)?);
+
+ None => {
+ let (evicted, grown) = state.heap.add(k, key, at);
+ debug_assert!(
+ evicted.is_none(),
+ "a heap that is not full evicts nothing"
+ );
+ admitted_bytes += grown;
+ new_slots += 1;
+ replacements += 1;
+ }
+ Some(Ordering::Less) => {
+ // Replacing the root overwrites its key in place, so
+ // keep a copy to tell whether the boundary moved.
+ evicted_key.clear();
+ evicted_key.extend_from_slice(
+ state.heap.worst_key().expect("classified, so full"),
+ );
+ let (evicted, grown) = state.heap.add(k, key, at);
+ let evicted = evicted.expect("a full heap evicts");
+ admitted_bytes += grown;
+ if state.heap.worst_key() == Some(evicted_key.as_slice()) {
+ // Boundary unchanged: the evicted row is still
+ // tied at it. Its slot moves to the tie list, and
+ // its store use with it — no gather, no release.
+ ties_grown += state.push_tie(evicted);
+ new_slots += 1;
+ } else {
+ // Boundary moved up: the evicted row and every tie
+ // (from this batch or earlier ones) now rank
+ // below K.
+ store.release(&mut pending, evicted.batch_id);
+ for tie in &state.ties {
+ store.release(&mut pending, tie.batch_id);
}
+ released_slots += state.ties.len();
+ state.ties.clear();
}
replacements += 1;
}
}
+ pending.uses += 1;
+ admitted_rows.push(row as u32);
}
- let registered_with_heap = heap_entry.is_some();
- if let Some(e) = heap_entry {
- state.heap.insert_batch_entry(e);
- state.heap.maybe_compact()?;
- }
-
- // Commit this batch's ties as a single entry.
- if !equal_indices.is_empty() {
- // No row of this group reached the heap, so `sub_batch` is
- // not registered there and reusing it here cannot
- // double-charge it. Combined with every row having tied,
- // `sub_batch` already *is* exactly the tie rows — the
- // gather below would just copy it.
- let tie_batch = if !registered_with_heap
- && equal_indices.len() == sub_batch.num_rows()
- {
- sub_batch
- } else {
- take_record_batch(&sub_batch, &UInt32Array::from(equal_indices))?
- };
- state.push_ties(tie_batch);
- }
+ self.index_bytes += interned_bytes;
+ self.heaps_bytes += admitted_bytes;
+ self.ties_bytes += ties_grown;
+ self.live_slots = self.live_slots + new_slots - released_slots;
}
- // Return the drained scratch map (capacity retained) for the next
- // batch to reuse.
- self.partition_groups = groups;
+ // 3. Gather the rows this batch contributed into a single batch and
+ // hand it to the store, as in `PartitionedTopK::insert_batch`.
+ // No uses left means every admission from this batch was released
+ // again before the pass ended, and the id goes to the next batch.
+ self.store
+ .insert_rows(batch, &self.admitted_rows, pending)?;
if replacements > 0 {
self.metrics.row_replacements.add(replacements);
}
+ self.store
+ .compact(&mut self.states, self.live_slots, self.batch_size)?;
self.reservation.try_resize(self.size())?;
Ok(())
}
- /// Drain all heaps and ties in partition-key order and return the
- /// rows as a stream of coalesced [`RecordBatch`]es ordered by
- /// `(partition_keys, order_keys)`. Within a partition, heap rows
- /// come first (sorted by ob), then tie rows (all sharing the
- /// boundary ob).
+ /// Drain every partition in partition-key order and return the rows as a
+ /// stream of `RecordBatch`es ordered by `(partition_keys, order_keys)`.
+ /// Within a partition, heap rows come first (sorted by ob), then tie rows
+ /// (all sharing the boundary ob).
+ ///
+ /// Only the order is resolved here; [`EmitState::stream`], shared with
+ /// [`PartitionedTopK::emit`], does the rest.
pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
let Self {
schema,
metrics,
- reservation: _,
+ reservation,
expr: _,
row_converter: _,
scratch_rows: _,
partition_exprs: _,
partition_converter: _,
partition_scratch_rows: _,
- mut states,
- partition_groups: _,
+ states,
+ store,
+ admitted_rows: _,
+ evicted_key: _,
+ live_slots,
+ heaps_bytes: _,
+ ties_bytes: _,
+ index_bytes: _,
k: _,
batch_size,
} = self;
- let _timer = metrics.baseline.elapsed_compute().timer();
-
- let mut sorted_pks: Vec<Vec<u8>> = states.keys().cloned().collect();
- sorted_pks.sort();
-
- let mut coalescer = BatchCoalescer::new(Arc::clone(&schema), batch_size);
-
- for pk in sorted_pks {
- let RankPartitionState { mut heap, ties } =
- states.remove(&pk).expect("key from states.keys()");
- if let Some(batch) = heap.emit()? {
- coalescer.push_batch(batch)?;
- }
- for tie in ties {
- coalescer.push_batch(tie.batch)?;
- }
- }
- coalescer.finish_buffered_batch()?;
-
- let mut out: Vec<Result<RecordBatch>> = Vec::new();
- while let Some(b) = coalescer.next_completed_batch() {
- (&b).record_output(&metrics.baseline);
- out.push(Ok(b));
- }
+ let timer = metrics.baseline.elapsed_compute().timer();
+ let mut sorted_states: Vec<(Vec<u8>, RankPartitionState)> =
+ states.into_iter().collect();
+ sorted_states.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
+ drop(timer);
- Ok(Box::pin(RecordBatchStreamAdapter::new(
+ let slots = sorted_states.into_iter().flat_map(|(_key, mut state)| {
+ let heap = state.heap.drain_sorted().into_iter().map(|slot| slot.at);
+ heap.chain(state.ties)
+ });
+ EmitState::stream(
schema,
- futures::stream::iter(out),
- )))
+ metrics,
+ reservation,
+ batch_size,
+ &store,
Review Comment:
Addressed in f9d7919e1fed26f901ab6b5a2730e0057b85d56d
--
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: [PR] perf: PartitionedTopKRank on the shared store with decide-then-gather [datafusion]
Posted by "adriangbot (via GitHub)" <gi...@apache.org>.
adriangbot commented on PR #25968:
URL: https://github.com/apache/datafusion/pull/25968#issuecomment-6019688495
🤖 Benchmark running (GKE) | [trigger](https://github.com/apache/datafusion/pull/25968#issuecomment-6019236908)
**Instance:** `c4a-highmem-16` (12 vCPU / 65 GiB) | `Linux bench-c6019236908-3096-d9mgk 6.12.94+ #1 SMP Fri Aug 21 08:00:16 UTC 2026 aarch64 GNU/Linux`
<details><summary>CPU Details (lscpu)</summary>
```
Architecture: aarch64
CPU op-mode(s): 64-bit
Byte Order: Little Endian
CPU(s): 16
On-line CPU(s) list: 0-15
Vendor ID: ARM
Model name: Neoverse-V2
Model: 1
Thread(s) per core: 1
Core(s) per cluster: 16
Socket(s): -
Cluster(s): 1
Stepping: r0p1
BogoMIPS: 2000.00
Flags: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache: 1 MiB (16 instances)
L1i cache: 1 MiB (16 instances)
L2 cache: 32 MiB (16 instances)
L3 cache: 80 MiB (1 instance)
NUMA node(s): 1
NUMA node0 CPU(s): 0-15
Vulnerability Gather data sampling: Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1: Mitigation; __user pointer sanitization
Vulnerability Spectre v2: Mitigation; CSV2, BHB
Vulnerability Srbds: Not affected
Vulnerability Tsa: Not affected
Vulnerability Tsx async abort: Not affected
Vulnerability Vmscape: Not affected
```
</details>
Comparing partitioned-topk-rank-shared-store (a499fc31de6b724bfd8dd44a6a7b1af82b64e19c) to 4d167a1 (merge-base) [diff](https://github.com/apache/datafusion/compare/4d167a167228a424ef8cc29fd6bea5f17fc23c2a..a499fc31de6b724bfd8dd44a6a7b1af82b64e19c)
<details><summary>Run configuration</summary>
```yaml
run benchmark h2o_medium_window
env:
DATAFUSION_OPTIMIZER_ENABLE_WINDOW_TOPN: "true"
```
</details>
Results will be posted here when complete
---
[File an issue](https://github.com/adriangb/datafusion-benchmarking/issues) against this benchmark runner
--
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