jayzhan211 commented on code in PR #27136:
URL: https://github.com/apache/datafusion/pull/27136#discussion_r4649861535
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1917,26 +1957,152 @@ impl<S: StoreSlots> PartitionedTopKCore<S> {
Ok(())
}
- /// Phase 3: gather the rows this batch contributed into a single batch and
- /// hand it to the store, then compact the store if it needs it. Only rows
- /// admitted at some point during the pass are kept, so what stays pinned
is
- /// bounded by admissions rather than by input size — and the entry is
- /// freed as soon as the last slot referencing it is released.
+ /// Run every row of `batch` through `admit` against its partition's state,
+ /// then gather the admitted rows into the store and compact it: the whole
+ /// of `insert_batch` but the admission rule, which is all that differs
+ /// between the three operators.
///
- /// No uses left on `pending` means every admission from this batch was
- /// released again before the pass ended, so there is nothing to keep and
- /// the id goes back to the next batch.
+ /// Both column sets are encoded once for the whole batch, then the rows
+ /// are visited in batch order, or back to front for an
+ /// [`StoreSlots::ORDER_FREE`] state, rather than grouped by partition.
+ /// Interleaving partitions cannot change a decision — a state is only read
+ /// and written by its own partition's rows, which still reach it in the
+ /// order the pass walks — and it costs no pass over the partitions seen so
+ /// far, which would be quadratic in the input whenever partition count
+ /// grows with it. Only keys are copied during the pass; an admission
+ /// records where its row will live, and one gather afterwards materializes
+ /// the batch's admissions once, however many partitions they went to. Only
+ /// rows admitted at some point during the pass are kept, so what stays
+ /// pinned is bounded by admissions rather than by input size, and the
+ /// entry is freed as soon as the last slot referencing it is released.
+ ///
+ /// `admit` gets the row's partition state, its encoded ORDER BY key, the
+ /// slot the row takes if admitted, and the [`Admission`] it reports
+ /// through, and returns whether it admitted the row.
///
/// The caller resizes the reservation afterwards, since only it knows its
/// full size.
- fn finish_batch(
+ fn insert_batch_with(
&mut self,
batch: &RecordBatch,
- pending: PendingEntry,
- replacements: usize,
- ) -> Result<()> {
+ mut admit: impl FnMut(&mut S, &[u8], StoreRef, &mut Admission<'_>) ->
bool,
+ ) -> Result<()>
+ where
+ S: Default,
+ {
+ let elapsed_compute = self.metrics.baseline.elapsed_compute().clone();
+ let _timer = elapsed_compute.timer();
+
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+ self.encode(batch)?;
+
+ self.admitted_rows.clear();
+ // The gathered batch does not exist yet, but its id does, so a slot
can
+ // point at it during the pass with no back-patching afterwards.
+ let pending_id = self.store.next_batch_id();
+ let mut admission = Admission {
+ store: &mut self.store,
+ pending_id,
+ pending_released: 0,
+ grown: 0,
+ freed: 0,
+ released_slots: 0,
+ replacements: 0,
+ };
+ // Accumulated locally and folded in once, so the running totals are
not
+ // touched per row.
+ let mut interned_bytes = 0usize;
+ let num_rows = batch.num_rows();
+ // Front to back, a batch whose ORDER BY values fall, such as
+ // `ORDER BY ts DESC` over rows stored by ascending `ts`, makes nearly
+ // every row a new best that displaces one. Back to front, the first K
+ // per partition fill the state and the boundary check drops the rest,
+ // which only saves work when partitions get more than K rows each.
+ let backwards = S::ORDER_FREE
+ && num_rows > self.k.saturating_mul(self.partitions.len())
+ && self.scratch_rows.row(num_rows - 1) < self.scratch_rows.row(0);
Review Comment:
@SubhamSinghal thanks for applying the walk. The check I suggested compares
rows of different partitions when a batch crosses a partition boundary, so
input sorted by the partition key is walked worst first: at 1,000 partitions it
evicts 4.08M rows instead of 0 and is 1.18x slower than `main` (189 → 222 ms).
Comparing the last row with the nearest earlier row of its own partition fixes
this, and also catches interleaved partitions that fall at different levels
(per-host counters), which the current check misses. Could you apply this and
add the two tests below?
```suggestion
// Only rows of one partition compete, so the last row is compared
with
// the nearest earlier row of its own partition: in input sorted by
the
// partition key, the batch's first row belongs to another partition.
let last = num_rows - 1;
let last_pk = self.partition_scratch_rows.row(last);
let backwards = S::ORDER_FREE
&& num_rows > self.k.saturating_mul(self.partitions.len())
&& (0..last)
.rev()
.find(|&row| self.partition_scratch_rows.row(row) == last_pk)
.is_some_and(|prev| {
self.scratch_rows.row(last) < self.scratch_rows.row(prev)
});
```
<details>
<summary>Tests (both fail with the current check)</summary>
```rs
/// A batch sorted by partition key, each partition's best row first, is
/// walked front to back even though its last row ranks above its first:
/// those rows belong to different partitions.
#[tokio::test]
async fn
test_partitioned_topk_dense_rank_rising_runs_across_partitions() -> Result<()>
{
let (schema, mut state) = build_partitioned_topk_dense_rank(1)?;
let pks: Vec<i32> = [1; 500].into_iter().chain([2; 500]).collect();
let vals: Vec<i32> = (1000..1500).chain(0..500).collect();
state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
assert_eq!(state.core.metrics.row_replacements.value(), 0);
let rows = pk_val_rows(state.emit()?).await?;
assert_eq!(rows, vec![(1, 1000), (2, 0)]);
Ok(())
}
/// Interleaved partitions whose values fall at different levels are
/// walked back to front, although the last row ranks below the first.
#[tokio::test]
async fn
test_partitioned_topk_dense_rank_falling_partitions_at_different_levels()
-> Result<()> {
let (schema, mut state) = build_partitioned_topk_dense_rank(1)?;
let pks: Vec<i32> = (0..1000).map(|i| 1 + i % 2).collect();
let vals: Vec<i32> = (0..1000)
.map(|i| if i % 2 == 0 { 1000 - i } else { 5000 - i })
.collect();
state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
assert_eq!(state.core.metrics.row_replacements.value(), 0);
let rows = pk_val_rows(state.emit()?).await?;
assert_eq!(rows, vec![(1, 2), (2, 4001)]);
Ok(())
}
```
With the suggestion, the 154 `topk` unit tests, clippy and the `window*` and
`topk` sqllogictests pass.
</details>
<details>
<summary>Measurements: main, this PR, with the suggestion</summary>
`elapsed_compute` of `PartitionedTopKExec` in ms, `DENSE_RANK() OVER
(PARTITION BY pk ORDER BY ob DESC)`, `enable_window_topn = true`,
`target_partitions = 1` unless noted, median of 11 interleaved runs (7 for the
counters row), evicted rows in parentheses.
| input | main | this PR | suggestion |
|---|---|---|---|
| sorted by `pk, ob DESC`, 1K partitions, K = 2 | 188.6 | 221.6 (4.08M) |
101.6 (0) |
| same, 100 partitions | 105.0 | 108.2 (419K) | 96.6 (0) |
| same, 10K partitions | 308.6 | 131.2 (743K) | 108.1 (0) |
| same, 1K partitions, 10 distinct `ob` | 126.8 | 154.3 (2.33M) | 137.6 (0) |
| same, 1K partitions, `target_partitions = 8` | 311.0 | 226.6 (2.17M) |
146.7 (20) |
| ascending `ob`, 10 partitions interleaved, K = 10 | 711.6 | 210.7 | 212.0 |
| same, 100 partitions | 1320 | 333.2 | 347.0 |
| 10 counters at different levels, K = 10 | 955.1 | 1210 (16.05M) | 330.3
(244K) |
| random, 1K partitions | 233.7 | 143.0 | 149.9 |
| every batch ends in a partition seen nowhere else in it | 100.8 | 96.8 |
123.3 |
The last row is the worst case: the search scans the whole batch when the
last row's partition appears nowhere else in it. Comparing only with the row
just before (O(1)) avoids that scan but misses the counters input (1120 ms).
```sql
-- 10M rows; sorted by partition key, best row first
COPY (SELECT value % 1000 AS pk, random() AS ob FROM generate_series(1,
10000000)
ORDER BY pk ASC, ob DESC) TO 'sorted_p1000.parquet' STORED AS PARQUET;
-- 20M rows; 10 counters interleaved, rising at different levels
COPY (SELECT value % 10 AS pk, value + (9 - value % 10) * 1000000000 AS ob
FROM generate_series(1, 20000000) ORDER BY value) TO
'offset_p10.parquet' STORED AS PARQUET;
```
</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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]