kumarUjjawal commented on code in PR #27136:
URL: https://github.com/apache/datafusion/pull/27136#discussion_r4730161310
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1917,26 +1957,162 @@ 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.
+ ///
+ /// 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.
///
- /// 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.
+ /// `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(());
+ }
Review Comment:
Skip reservation updates for empty batches
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2584,147 +2655,146 @@ impl PartitionedTopKRank {
/// Within a partition, heap rows come first (sorted by ob), then tie rows
/// (all sharing the boundary ob).
pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
- self.core.emit_with(|mut state| {
- let heap = state.heap.drain_sorted();
- // `RANK` is `1 + (rows with a strictly smaller ORDER BY value)`.
- // Counting positions is only valid because the retained set is a
- // *complete* order-prefix of the partition: the heap keeps the K
- // smallest keys and the ties only add rows equal to the boundary,
so
- // no row with a smaller key than a retained row was ever dropped.
- //
- // The ties all sit at the boundary, the heap's largest key, so
they
- // share the rank of the first heap row holding it. Ties exist only
- // while the heap is full, so a heap with no rows has none.
- let boundary_rank = heap.last().map_or(0, |worst| {
- heap.partition_point(|slot| slot.key < worst.key) as u64 + 1
- });
- // Over the sorted heap, a row either ties with its predecessor and
- // repeats its rank or starts a new one at its own 1-based
position.
- let mut prev: Option<Vec<u8>> = None;
- let mut rank = 0;
- let heap = heap.into_iter().zip(1u64..).map(move |(slot,
position)| {
- if prev.as_ref() != Some(&slot.key) {
- rank = position;
- }
- prev = Some(slot.key);
- (slot.at, rank)
- });
- heap.chain(state.ties.into_iter().map(move |at| (at,
boundary_rank)))
- })
+ self.core.emit_with(
+ |mut state| {
+ let heap = state.heap.drain_sorted();
+ // `RANK` is `1 + (rows with a strictly smaller ORDER BY
value)`.
+ // Counting positions is only valid because the retained set
is a
+ // *complete* order-prefix of the partition: the heap keeps
the K
+ // smallest keys and the ties only add rows equal to the
boundary, so
+ // no row with a smaller key than a retained row was ever
dropped.
+ //
+ // The ties all sit at the boundary, the heap's largest key,
so they
+ // share the rank of the first heap row holding it. Ties exist
only
+ // while the heap is full, so a heap with no rows has none.
+ let boundary_rank = heap.last().map_or(0, |worst| {
+ heap.partition_point(|slot| slot.key < worst.key) as u64 +
1
+ });
+ // Over the sorted heap, a row either ties with its
predecessor and
+ // repeats its rank or starts a new one at its own 1-based
position.
+ let mut prev: Option<Vec<u8>> = None;
+ let mut rank = 0;
+ let heap = heap.into_iter().zip(1u64..).map(move |(slot,
position)| {
+ if prev.as_ref() != Some(&slot.key) {
+ rank = position;
+ }
+ prev = Some(slot.key);
+ (slot.at, rank)
+ });
+ heap.chain(state.ties.into_iter().map(move |at| (at,
boundary_rank)))
+ },
+ EmitOrder::Collect,
+ )
}
/// Total memory currently held by this operator, including every
/// partition's heap and ties and every batch the store still pins. O(1),
/// see [`PartitionedTopKCore::allocated_size`].
fn size(&self) -> usize {
- size_of::<Self>() + self.core.allocated_size() + self.ties_bytes
+ size_of::<Self>() + self.core.allocated_size()
}
}
-/// A run of rows from a single source [`RecordBatch`] sharing one
-/// distinct ORDER BY value. Materialized at emit time via
-/// [`take_record_batch`].
-///
-/// The batch is referenced by `batch_id` rather than held directly, so the
-/// operator-scoped [`RecordBatchStore`] can charge each distinct source
-/// batch once however many entries reference it. Holding a batch per entry
-/// and charging its bytes per entry would inflate the reservation by a
-/// factor of (partitions × K), since a single batch contributes an entry to
-/// every partition and ob group it touches.
-#[derive(Debug)]
-struct GroupEntry {
- /// Indices into the batch identified by `batch_id`. Always non-empty
- /// by construction.
- row_indices: Vec<u32>,
- /// Key into `PartitionedTopKDenseRank::store`.
- batch_id: u32,
-}
-
/// Per-partition state for `DENSE_RANK()` semantics.
///
-/// A `HashMap<Vec<u8>, Vec<GroupEntry>>` keyed by the row-encoded ORDER
-/// BY bytes, capped at `k` distinct keys. Each key's `Vec<GroupEntry>`
-/// holds every row seen at that ob value, one entry per contributing
-/// source `RecordBatch`.
-#[derive(Default)]
+/// Every retained row of the partition, grouped by ORDER BY value: `groups`
+/// maps each of the at most `k` distinct-smallest values seen so far to where
+/// every row holding it lives in the store. Like [`RankPartitionState`], this
+/// holds only store coordinates: the output columns of every retained row live
+/// in the operator's one shared [`RecordBatchStore`].
+#[derive(Debug, Default)]
struct DenseRankPartitionState {
- groups: HashMap<Vec<u8>, Vec<GroupEntry>>,
+ /// Keyed by the row-encoded ORDER BY bytes, capped at `k` keys. Each
+ /// group's rows are in the order they were admitted, which `emit` keeps:
+ /// arrival order, reversed for a batch visited back to front.
+ groups: HashMap<Vec<u8>, Vec<StoreRef>>,
/// The same keys as `groups`, in a max-heap: the admission boundary
/// (the largest tracked ob value) is an O(1) `peek()` check, and
/// admission / removal are O(log K).
///
/// INVARIANT: `keys` and `groups.keys()` hold the same set. Every
/// insertion into / removal from `groups` must mirror into `keys`.
keys: BinaryHeap<Vec<u8>>,
- /// Running total of the heap allocations owned by the *contents* of
- /// `groups` and `keys`: the key bytes, the per-key `Vec<GroupEntry>`
- /// buffers, and each entry's `row_indices`. Excludes the two
- /// containers' own tables, which `capacity()` reports in O(1).
- ///
- /// INVARIANT: equals `recompute_contents_bytes` (test-only, so not
- /// linkable from rustdoc). Every mutation of `groups` or `keys` must
- /// adjust it; the
- /// `test_partitioned_topk_dense_rank_contents_bytes_tracks_recompute`
- /// test checks this against a full recompute after a randomized
- /// workload.
- contents_bytes: usize,
}
impl DenseRankPartitionState {
- fn size(&self) -> usize {
- let table_overhead = self.groups.capacity()
- * (size_of::<Vec<u8>>() + size_of::<Vec<GroupEntry>>());
- // The heap's backing Vec: one `Vec<u8>` slot per reserved element.
- let keys_overhead = self.keys.capacity() * size_of::<Vec<u8>>();
- table_overhead + self.contents_bytes + keys_overhead
- }
-
- /// Bytes owned by one entry's `row_indices` buffer.
- fn entry_bytes(entry: &GroupEntry) -> usize {
- entry.row_indices.capacity() * size_of::<u32>()
+ /// Track the previously unseen ob value `key`, holding the row at `at` as
+ /// its only row, and return the bytes this newly allocated.
+ ///
+ /// `keys` and `groups` each own a copy of the key bytes. The table is
+ /// charged through `allocation_size` rather than `capacity`, which a
+ /// removal can lower without freeing anything, so the running total stays
+ /// exact across evictions.
+ fn insert_group(&mut self, key: &[u8], at: StoreRef) -> usize {
+ let table_before = self.groups.allocation_size();
+ let heap_before = self.keys.capacity();
+ let heap_key = key.to_vec();
+ let map_key = key.to_vec();
+ let rows = vec![at];
+ let grown = heap_key.capacity()
+ + map_key.capacity()
+ + rows.capacity() * size_of::<StoreRef>();
+ self.keys.push(heap_key);
+ self.groups.insert(map_key, rows);
+ grown
+ + (self.groups.allocation_size() - table_before)
+ + (self.keys.capacity() - heap_before) * size_of::<Vec<u8>>()
+ }
+
+ /// Replace the largest tracked ob value with the smaller, previously
+ /// unseen `key`, holding the row at `at` as its only row, reusing the old
+ /// key buffers and letting `PeekMut` sift down, so a steady-state eviction
+ /// allocates nothing. Every old row goes back through `admission`.
+ fn replace_max(&mut self, key: &[u8], at: StoreRef, admission: &mut
Admission<'_>) {
+ let table_before = self.groups.allocation_size();
+ let mut heap_key = self
+ .keys
+ .peek_mut()
+ .expect("a full partition holds k >= 1 keys");
+ let (mut map_key, mut rows) = self
+ .groups
+ .remove_entry(heap_key.as_slice())
+ .expect("keys mirrors groups");
+ // A group's rows from one batch sit next to each other, so each run of
+ // them drops its uses with one store lookup rather than one per row.
+ for run in rows.chunk_by(|a, b| a.batch_id == b.batch_id) {
+ admission.release_n(run[0].batch_id, run.len());
+ }
+ admission.replacements += rows.len();
+ admission.freed += heap_key.capacity()
+ + map_key.capacity()
+ + rows.capacity() * size_of::<StoreRef>();
+
+ heap_key.clear();
+ heap_key.extend_from_slice(key);
+ map_key.clear();
+ map_key.extend_from_slice(key);
Review Comment:
Release oversized buffers when dense-rank keys shrink
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1361,8 +1345,9 @@ impl RecordBatchStore {
/// 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`.
+ /// [`PartitionedTopK`], [`PartitionedTopKRank`] and
+ /// [`PartitionedTopKDenseRank`] call this at the end of every
+ /// `insert_batch`.
Review Comment:
Porting `DENSE_RANK` to this compactor exposes unbounded tie groups to its
all-row `coords` allocation. If churn in smaller groups triggers compaction
while a large tied group survives, the compactor allocates 16 bytes per live
row on 64-bit targets and builds a second copy of the live batches before the
caller resizes the reservation. That peak can exceed the pool without being
checked. Generate coordinates one chunk at a time and account for the
replacement batches while the old store is still live.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1976,12 +2162,24 @@ impl<S: StoreSlots> PartitionedTopKCore<S> {
let timer = metrics.baseline.elapsed_compute().timer();
let mut sorted: Vec<(Vec<u8>, S)> = partitions.into_iter().collect();
sorted.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
- drop(timer);
+ let sorted_bytes =
+ sorted.capacity() * (size_of::<Vec<u8>>() + size_of::<S>()) +
index_bytes;
- let slots = sorted
+ let rows = sorted
.into_iter()
.map(|(_key, state)| state)
.flat_map(drain);
+ let (slots, slots_bytes): (EmitSlots, usize) = match order {
+ EmitOrder::Collect => {
+ let mut slots = Vec::with_capacity(live_slots);
+ slots.extend(rows);
+ let bytes = slots.capacity() * size_of::<(StoreRef, u64)>();
+ (Box::new(slots.into_iter()), bytes)
+ }
+ EmitOrder::Lazy => (Box::new(rows), sorted_bytes + state_bytes),
Review Comment:
Release memory reservations as dense-rank state drains
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
Review Comment:
https://github.com/apache/datafusion/blob/f168960ff125539a09e863de32c4d6138970f180/datafusion/physical-plan/src/topk/mod.rs#L2119-L2120
`DENSE_RANK` now interleaves rows in hash-map order during compaction,
before it emits them in partition order. With a 256-row batch size, an `Int8`
dictionary payload, and partitions of 128, 128, and 256 rows, the first two
partitions can share 96 values while the third uses 96 disjoint values. Sorted
emission fits the dictionary in each chunk, but compaction can place the third
partition between the first two and fail with `DictionaryKeyOverflowError`.
Split compaction chunks that cannot be represented, or leave their original
batches in place.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1976,12 +2162,24 @@ impl<S: StoreSlots> PartitionedTopKCore<S> {
let timer = metrics.baseline.elapsed_compute().timer();
let mut sorted: Vec<(Vec<u8>, S)> = partitions.into_iter().collect();
sorted.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
- drop(timer);
+ let sorted_bytes =
+ sorted.capacity() * (size_of::<Vec<u8>>() + size_of::<S>()) +
index_bytes;
- let slots = sorted
+ let rows = sorted
.into_iter()
.map(|(_key, state)| state)
.flat_map(drain);
+ let (slots, slots_bytes): (EmitSlots, usize) = match order {
+ EmitOrder::Collect => {
+ let mut slots = Vec::with_capacity(live_slots);
+ slots.extend(rows);
+ let bytes = slots.capacity() * size_of::<(StoreRef, u64)>();
+ (Box::new(slots.into_iter()), bytes)
+ }
+ EmitOrder::Lazy => (Box::new(rows), sorted_bytes + state_bytes),
Review Comment:
In Lazy emit mode the stream reserves `sorted_bytes + state_bytes` for its
whole life, even though each partition's state is dropped as soon as its rows
are pulled.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1917,26 +1957,162 @@ 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.
+ ///
+ /// 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.
///
- /// 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.
+ /// `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.
+ // 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
Review Comment:
The walk direction is chosen by comparing only the last row with the nearest
earlier row of its own partition, then applied to every partition in the batch,
so partitions whose values move the other way are walked worst first.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2584,147 +2655,146 @@ impl PartitionedTopKRank {
/// Within a partition, heap rows come first (sorted by ob), then tie rows
/// (all sharing the boundary ob).
pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
- self.core.emit_with(|mut state| {
- let heap = state.heap.drain_sorted();
- // `RANK` is `1 + (rows with a strictly smaller ORDER BY value)`.
- // Counting positions is only valid because the retained set is a
- // *complete* order-prefix of the partition: the heap keeps the K
- // smallest keys and the ties only add rows equal to the boundary,
so
- // no row with a smaller key than a retained row was ever dropped.
- //
- // The ties all sit at the boundary, the heap's largest key, so
they
- // share the rank of the first heap row holding it. Ties exist only
- // while the heap is full, so a heap with no rows has none.
- let boundary_rank = heap.last().map_or(0, |worst| {
- heap.partition_point(|slot| slot.key < worst.key) as u64 + 1
- });
- // Over the sorted heap, a row either ties with its predecessor and
- // repeats its rank or starts a new one at its own 1-based
position.
- let mut prev: Option<Vec<u8>> = None;
- let mut rank = 0;
- let heap = heap.into_iter().zip(1u64..).map(move |(slot,
position)| {
- if prev.as_ref() != Some(&slot.key) {
- rank = position;
- }
- prev = Some(slot.key);
- (slot.at, rank)
- });
- heap.chain(state.ties.into_iter().map(move |at| (at,
boundary_rank)))
- })
+ self.core.emit_with(
+ |mut state| {
+ let heap = state.heap.drain_sorted();
+ // `RANK` is `1 + (rows with a strictly smaller ORDER BY
value)`.
+ // Counting positions is only valid because the retained set
is a
+ // *complete* order-prefix of the partition: the heap keeps
the K
+ // smallest keys and the ties only add rows equal to the
boundary, so
+ // no row with a smaller key than a retained row was ever
dropped.
+ //
+ // The ties all sit at the boundary, the heap's largest key,
so they
+ // share the rank of the first heap row holding it. Ties exist
only
+ // while the heap is full, so a heap with no rows has none.
+ let boundary_rank = heap.last().map_or(0, |worst| {
+ heap.partition_point(|slot| slot.key < worst.key) as u64 +
1
+ });
+ // Over the sorted heap, a row either ties with its
predecessor and
+ // repeats its rank or starts a new one at its own 1-based
position.
+ let mut prev: Option<Vec<u8>> = None;
+ let mut rank = 0;
+ let heap = heap.into_iter().zip(1u64..).map(move |(slot,
position)| {
+ if prev.as_ref() != Some(&slot.key) {
+ rank = position;
+ }
+ prev = Some(slot.key);
+ (slot.at, rank)
+ });
+ heap.chain(state.ties.into_iter().map(move |at| (at,
boundary_rank)))
+ },
+ EmitOrder::Collect,
+ )
}
/// Total memory currently held by this operator, including every
/// partition's heap and ties and every batch the store still pins. O(1),
/// see [`PartitionedTopKCore::allocated_size`].
fn size(&self) -> usize {
- size_of::<Self>() + self.core.allocated_size() + self.ties_bytes
+ size_of::<Self>() + self.core.allocated_size()
}
}
-/// A run of rows from a single source [`RecordBatch`] sharing one
-/// distinct ORDER BY value. Materialized at emit time via
-/// [`take_record_batch`].
-///
-/// The batch is referenced by `batch_id` rather than held directly, so the
-/// operator-scoped [`RecordBatchStore`] can charge each distinct source
-/// batch once however many entries reference it. Holding a batch per entry
-/// and charging its bytes per entry would inflate the reservation by a
-/// factor of (partitions × K), since a single batch contributes an entry to
-/// every partition and ob group it touches.
-#[derive(Debug)]
-struct GroupEntry {
- /// Indices into the batch identified by `batch_id`. Always non-empty
- /// by construction.
- row_indices: Vec<u32>,
- /// Key into `PartitionedTopKDenseRank::store`.
- batch_id: u32,
-}
-
/// Per-partition state for `DENSE_RANK()` semantics.
///
-/// A `HashMap<Vec<u8>, Vec<GroupEntry>>` keyed by the row-encoded ORDER
-/// BY bytes, capped at `k` distinct keys. Each key's `Vec<GroupEntry>`
-/// holds every row seen at that ob value, one entry per contributing
-/// source `RecordBatch`.
-#[derive(Default)]
+/// Every retained row of the partition, grouped by ORDER BY value: `groups`
+/// maps each of the at most `k` distinct-smallest values seen so far to where
+/// every row holding it lives in the store. Like [`RankPartitionState`], this
+/// holds only store coordinates: the output columns of every retained row live
+/// in the operator's one shared [`RecordBatchStore`].
+#[derive(Debug, Default)]
struct DenseRankPartitionState {
- groups: HashMap<Vec<u8>, Vec<GroupEntry>>,
+ /// Keyed by the row-encoded ORDER BY bytes, capped at `k` keys. Each
+ /// group's rows are in the order they were admitted, which `emit` keeps:
+ /// arrival order, reversed for a batch visited back to front.
+ groups: HashMap<Vec<u8>, Vec<StoreRef>>,
/// The same keys as `groups`, in a max-heap: the admission boundary
/// (the largest tracked ob value) is an O(1) `peek()` check, and
/// admission / removal are O(log K).
///
/// INVARIANT: `keys` and `groups.keys()` hold the same set. Every
/// insertion into / removal from `groups` must mirror into `keys`.
keys: BinaryHeap<Vec<u8>>,
- /// Running total of the heap allocations owned by the *contents* of
- /// `groups` and `keys`: the key bytes, the per-key `Vec<GroupEntry>`
- /// buffers, and each entry's `row_indices`. Excludes the two
- /// containers' own tables, which `capacity()` reports in O(1).
- ///
- /// INVARIANT: equals `recompute_contents_bytes` (test-only, so not
- /// linkable from rustdoc). Every mutation of `groups` or `keys` must
- /// adjust it; the
- /// `test_partitioned_topk_dense_rank_contents_bytes_tracks_recompute`
- /// test checks this against a full recompute after a randomized
- /// workload.
- contents_bytes: usize,
}
impl DenseRankPartitionState {
- fn size(&self) -> usize {
- let table_overhead = self.groups.capacity()
- * (size_of::<Vec<u8>>() + size_of::<Vec<GroupEntry>>());
- // The heap's backing Vec: one `Vec<u8>` slot per reserved element.
- let keys_overhead = self.keys.capacity() * size_of::<Vec<u8>>();
- table_overhead + self.contents_bytes + keys_overhead
- }
-
- /// Bytes owned by one entry's `row_indices` buffer.
- fn entry_bytes(entry: &GroupEntry) -> usize {
- entry.row_indices.capacity() * size_of::<u32>()
+ /// Track the previously unseen ob value `key`, holding the row at `at` as
+ /// its only row, and return the bytes this newly allocated.
+ ///
+ /// `keys` and `groups` each own a copy of the key bytes. The table is
+ /// charged through `allocation_size` rather than `capacity`, which a
+ /// removal can lower without freeing anything, so the running total stays
+ /// exact across evictions.
+ fn insert_group(&mut self, key: &[u8], at: StoreRef) -> usize {
+ let table_before = self.groups.allocation_size();
+ let heap_before = self.keys.capacity();
+ let heap_key = key.to_vec();
+ let map_key = key.to_vec();
+ let rows = vec![at];
+ let grown = heap_key.capacity()
+ + map_key.capacity()
+ + rows.capacity() * size_of::<StoreRef>();
+ self.keys.push(heap_key);
+ self.groups.insert(map_key, rows);
+ grown
+ + (self.groups.allocation_size() - table_before)
+ + (self.keys.capacity() - heap_before) * size_of::<Vec<u8>>()
+ }
+
+ /// Replace the largest tracked ob value with the smaller, previously
+ /// unseen `key`, holding the row at `at` as its only row, reusing the old
+ /// key buffers and letting `PeekMut` sift down, so a steady-state eviction
+ /// allocates nothing. Every old row goes back through `admission`.
+ fn replace_max(&mut self, key: &[u8], at: StoreRef, admission: &mut
Admission<'_>) {
Review Comment:
`replace_max` removes the boundary entry from `groups` and inserts a new one
on every eviction. hashbrown can leave a tombstone each time, so a table with K
live keys can be forced to rehash or double, and each eviction also hashes the
key twice.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1917,26 +1957,162 @@ 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.
+ ///
+ /// 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.
///
- /// 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.
+ /// `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.
+ // 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)
+ });
Review Comment:
Avoid reversing a whole batch on one partition's trend
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1976,12 +2162,24 @@ impl<S: StoreSlots> PartitionedTopKCore<S> {
let timer = metrics.baseline.elapsed_compute().timer();
let mut sorted: Vec<(Vec<u8>, S)> = partitions.into_iter().collect();
sorted.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
- drop(timer);
+ let sorted_bytes =
+ sorted.capacity() * (size_of::<Vec<u8>>() + size_of::<S>()) +
index_bytes;
- let slots = sorted
+ let rows = sorted
.into_iter()
.map(|(_key, state)| state)
.flat_map(drain);
+ let (slots, slots_bytes): (EmitSlots, usize) = match order {
Review Comment:
`EmitOrder` is passed as a runtime argument at each of the three emit_with
call sites, although it depends only on the state type S, just like
`StoreSlots::ORDER_FREE`.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -1976,12 +2162,24 @@ impl<S: StoreSlots> PartitionedTopKCore<S> {
let timer = metrics.baseline.elapsed_compute().timer();
let mut sorted: Vec<(Vec<u8>, S)> = partitions.into_iter().collect();
sorted.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
- drop(timer);
+ let sorted_bytes =
+ sorted.capacity() * (size_of::<Vec<u8>>() + size_of::<S>()) +
index_bytes;
- let slots = sorted
+ let rows = sorted
.into_iter()
.map(|(_key, state)| state)
.flat_map(drain);
+ let (slots, slots_bytes): (EmitSlots, usize) = match order {
+ EmitOrder::Collect => {
+ let mut slots = Vec::with_capacity(live_slots);
+ slots.extend(rows);
+ let bytes = slots.capacity() * size_of::<(StoreRef, u64)>();
+ (Box::new(slots.into_iter()), bytes)
Review Comment:
Keep eager rank emission on resolved coordinates
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2297,21 +2448,26 @@ impl EmitState {
/// Build the next chunk, or `None` once every retained row has been
/// emitted.
fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
- if self.pos == self.ordered.len() {
- return Ok(None);
- }
let _timer = self.metrics.baseline.elapsed_compute().timer();
- let start = self.pos;
- let end = (start + self.batch_size).min(self.ordered.len());
- self.pos = end;
+ self.indices.clear();
+ self.ranks.clear();
+ for (slot, rank) in (&mut self.slots).take(self.batch_size) {
+ let array_pos = *self
+ .positions
+ .get(&slot.batch_id)
Review Comment:
EmitState::next_batch now does a HashMap lookup in `positions` for every
emitted row. The old DENSE_RANK emitter resolved the batch position once per
run of rows from one batch.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2362,16 +2518,6 @@ struct RankPartitionState {
ties: Vec<StoreRef>,
}
-impl RankPartitionState {
- /// Add a tie at `at`, returning the bytes this newly allocated for the
- /// operator to fold into its running total, as [`PartitionHeap::add`]
does.
- fn push_tie(&mut self, at: StoreRef) -> usize {
- let before = self.ties.capacity();
- self.ties.push(at);
- (self.ties.capacity() - before) * size_of::<StoreRef>()
- }
-}
-
impl StoreSlots for RankPartitionState {
Review Comment:
RankPartitionState keeps the default ORDER_FREE = false, but the set of rows
RANK keeps (every row at or below the K-th value, boundary ties included) does
not depend on arrival order either. RANK therefore misses the falling-batch
walk even though falling input hurts it the same way.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -2827,379 +2844,92 @@ impl PartitionedTopKDenseRank {
metrics: &ExecutionPlanMetricsSet,
ranked_schema: Option<SchemaRef>,
) -> Result<Self> {
- assert!(k > 0, "PartitionedTopKDenseRank requires k > 0");
- let reservation =
-
MemoryConsumer::new(format!("PartitionedTopKDenseRank[{partition_id}]"))
- .register(&runtime.memory_pool);
-
- let order_sort_fields = build_sort_fields(&order_expr, schema)?;
- let row_converter = RowConverter::new(order_sort_fields)?;
- let scratch_rows =
- row_converter.empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW *
batch_size);
-
- let partition_converter = RowConverter::new(partition_sort_fields)?;
- let partition_scratch_rows = partition_converter
- .empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);
-
Ok(Self {
- emit_ranks: ranked_schema.is_some(),
- output_schema: ranked_schema.unwrap_or_else(|| Arc::clone(schema)),
- metrics: TopKMetrics::new(metrics, partition_id),
- reservation,
- expr: order_expr,
- row_converter,
- scratch_rows,
- partition_exprs,
- partition_converter,
- partition_scratch_rows,
- states: HashMap::new(),
- partition_groups: HashMap::new(),
- ob_runs: HashMap::new(),
- store: RecordBatchStore::new(),
- k,
- batch_size,
+ core: PartitionedTopKCore::try_new(
+ "PartitionedTopKDenseRank",
+ partition_id,
+ schema,
+ partition_exprs,
+ partition_sort_fields,
+ order_expr,
+ k,
+ batch_size,
+ runtime,
+ metrics,
+ ranked_schema,
+ )?,
})
}
- /// Encode PARTITION BY and ORDER BY columns once, demultiplex the
- /// batch's rows by partition key, then per partition bucket the rows
- /// by distinct ob value and merge each bucket into the partition
- /// state as one [`GroupEntry`].
+ /// Encode the partition and ORDER BY columns once each for the whole
batch,
+ /// run every row through its partition's group admission, then register
+ /// the admitted rows in the shared store with one gather.
pub(crate) fn insert_batch(&mut self, batch: &RecordBatch) -> Result<()> {
- let elapsed_compute = self.metrics.baseline.elapsed_compute().clone();
- let _timer = elapsed_compute.timer();
-
- let num_rows = batch.num_rows();
- if num_rows == 0 {
- return Ok(());
- }
-
- // Register this batch with the store up front. `uses` is bumped
- // once per `GroupEntry` created below but lives on this local
- // entry, so the store sees a single insert per batch rather than
- // one per group — and `insert` drops batches that retained
- // nothing without ever charging for them.
- let mut batch_entry = self.store.register(batch.clone());
- let batch_id = batch_entry.id;
-
- // 1. Encode partition columns.
- let pk_arrays: Vec<ArrayRef> = self
- .partition_exprs
- .iter()
- .map(|e| e.evaluate(batch).and_then(|v| v.into_array(num_rows)))
- .collect::<Result<_>>()?;
- self.partition_scratch_rows.clear();
- self.partition_converter
- .append(&mut self.partition_scratch_rows, &pk_arrays)?;
-
- // 2. Group this batch's row indices by partition key.
- // `partition_groups` is a reused scratch map: taken out here
- // and drained below, so its backing table is allocated once
- // for the operator, not once per batch. `entry_ref` owns the
- // key only on Vacant, so it allocates one `Vec<u8>` per
- // distinct partition rather than one per row.
- let mut groups = std::mem::take(&mut self.partition_groups);
- groups.clear();
- {
- let pk_rows = &self.partition_scratch_rows;
- for i in 0..num_rows {
- groups
- .entry_ref(pk_rows.row(i).as_ref())
- .or_default()
- .push(i as u32);
- }
- }
-
- // 3. Evaluate ORDER BY columns and encode ONCE.
- let ob_arrays: Vec<ArrayRef> = self
- .expr
- .iter()
- .map(|e| e.expr.evaluate(batch).and_then(|v|
v.into_array(num_rows)))
- .collect::<Result<_>>()?;
- self.scratch_rows.clear();
- self.row_converter
- .append(&mut self.scratch_rows, &ob_arrays)?;
-
- let k = self.k;
- let mut replacements: usize = 0;
-
- // 4. Per-partition: bucket this batch's rows by distinct ob value
- // (within-call accumulation), then merge each bucket into the
- // partition state as a single `GroupEntry`.
- for (pk, indices) in groups.drain() {
- let state = self
- .states
- .entry(pk)
- .or_insert_with(DenseRankPartitionState::default);
-
- // Bucket by ob key. `ob_runs` is a reused scratch map (taken
- // out and drained below) so its backing table is allocated
- // once, not once per distinct partition key. `entry_ref` owns
- // the key only on Vacant, so repeated rows of the same ob
- // value don't re-allocate.
- let mut runs = std::mem::take(&mut self.ob_runs);
- runs.clear();
- // Once the partition holds its full K distinct ob values, the
- // largest of them is the bar a new value must beat, and that bar
- // only ever gets stricter: with K values held there is no free
- // slot left for a new (possibly larger) one, and the only way in
- // from here is to evict that largest and put something strictly
- // smaller in its place. So a row worse than today's bar is worse
- // than every later bar too — it is not held now and can never be
- // admitted — and can be dropped before it costs a bucket. Rows
- // *equal* to the bar must still go through: that value is one of
- // the K being held, so its rows belong to a live group.
- let boundary: Option<&[u8]> = if state.groups.len() == k {
- state.keys.peek().map(Vec::as_slice)
- } else {
- None
- };
- for &orig_idx in &indices {
- let ob_row = self.scratch_rows.row(orig_idx as usize);
- if boundary.is_some_and(|b| ob_row.as_ref() > b) {
- continue;
- }
- runs.entry_ref(ob_row.as_ref()).or_default().push(orig_idx);
- }
-
- for (ob_key, run_indices) in runs.drain() {
- // Case A: ob already tracked — push this batch's run as a
- // new `GroupEntry` (one entry per contributing batch).
- if let Some(entries) = state.groups.get_mut(&ob_key) {
- batch_entry.uses += 1;
- let before = entries.capacity() * size_of::<GroupEntry>();
- let entry = GroupEntry {
- row_indices: run_indices,
- batch_id,
- };
- state.contents_bytes +=
DenseRankPartitionState::entry_bytes(&entry);
- entries.push(entry);
- // The push may have grown the buffer.
- state.contents_bytes +=
- entries.capacity() * size_of::<GroupEntry>() - before;
- continue;
- }
-
- // Case B: new ob, room available.
- if state.groups.len() < k {
- batch_entry.uses += 1;
- state.insert_new_group(ob_key, run_indices, batch_id);
- continue;
+ let k = self.core.k;
+ self.core
+ .insert_batch_with(batch, |state, key, at, admission| {
+ // Once the partition holds its full K distinct ob values, the
+ // largest of them is the bar a new value must beat, and that
bar
+ // only ever gets stricter: the only way in from here is to
evict
+ // that largest and put something strictly smaller in its
place. So
+ // a row worse than today's bar can never be admitted. Rows
*equal*
+ // to it must still go through: that value is one of the K
being
+ // held, so its rows belong to a live group.
+ let full = state.groups.len() == k;
+ if full && state.keys.peek().is_some_and(|max| key >
max.as_slice()) {
+ return false;
}
-
- // Case C: new ob, at K distinct keys. The largest tracked
- // ob value is the admission boundary.
- let max_key = state.keys.peek().expect("state.groups has k >=
1 keys");
- if ob_key.as_slice() < max_key.as_slice() {
- // Evict the entire max-key group, from both the map
- // and its ordered mirror. `keys` and `groups` own
- // separate copies of the key bytes, so both are
- // uncharged — with their own capacities, which is why
- // `remove_entry` is used to recover the map's copy
- // rather than assuming it matches the popped one.
- let evicted_key = state.keys.pop().expect("max key
present");
- let (map_key, evicted) = state
- .groups
- .remove_entry(&evicted_key)
- .expect("keys mirrors groups");
- state.contents_bytes -= evicted_key.capacity()
- + map_key.capacity()
- + evicted.capacity() * size_of::<GroupEntry>()
- + evicted
- .iter()
- .map(DenseRankPartitionState::entry_bytes)
- .sum::<usize>();
- for e in &evicted {
- replacements += e.row_indices.len();
- if e.batch_id == batch_id {
- // Admitted earlier in this same call, so the
- // store has not seen `batch_entry` yet — drop
- // the pending use rather than calling `unuse`,
- // which panics on an unregistered id.
- batch_entry.uses -= 1;
- } else {
- self.store.unuse(e.batch_id);
- }
- }
- batch_entry.uses += 1;
- state.insert_new_group(ob_key, run_indices, batch_id);
+ if let Some(rows) = state.groups.get_mut(key) {
+ admission.grown += push_slot(rows, at);
+ } else if full {
+ // Every row of the boundary group, from this batch or
+ // earlier ones, now ranks below K.
+ state.replace_max(key, at, admission);
+ } else {
+ admission.grown += state.insert_group(key, at);
}
- // else: ob >= max — drop the whole run.
- }
-
- // Return the drained scratch map (capacity retained) for the
- // next partition to reuse.
- self.ob_runs = runs;
- }
-
- // Return the drained scratch map (capacity retained) for the next
- // batch to reuse.
- self.partition_groups = groups;
-
- // Charges `batch` once if any group retained rows from it.
- self.store.insert(batch_entry);
-
- if replacements > 0 {
- self.metrics.row_replacements.add(replacements);
- }
- self.reservation.try_resize(self.size())?;
+ true
+ })?;
+ self.core.reservation.try_resize(self.size())?;
Ok(())
}
- /// Drain all per-partition maps in partition-key order and return
- /// the rows as a stream of coalesced [`RecordBatch`]es ordered by
- /// `(partition_keys, order_keys)`. Within a partition the distinct
- /// ob keys are sorted (byte-comparable encoding == sort order) so
- /// emitted rows are in ob-sorted order.
+ /// 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 the distinct ob keys are sorted (byte-comparable
+ /// encoding == sort order), and a group's rows keep the order they were
+ /// admitted in: arrival order, reversed for a batch visited back to front.
+ ///
+ /// The partitions are drained as the stream is polled: a group already
+ /// holds one 8-byte [`StoreRef`] per row, so collecting `(StoreRef, u64)`
+ /// pairs up front would make emit need more memory than accumulating did,
+ /// up to every row of one huge tied group at once.
pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
- let Self {
- output_schema,
- emit_ranks,
- metrics,
- reservation: _,
- expr: _,
- row_converter: _,
- scratch_rows: _,
- partition_exprs: _,
- partition_converter: _,
- partition_scratch_rows: _,
- mut states,
- partition_groups: _,
- ob_runs: _,
- store,
- 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 out: Vec<Result<RecordBatch>> = Vec::new();
-
- // Gather every retained row with a single `interleave_record_batch`
- // per output batch rather than one `take_record_batch` per
- // `GroupEntry`. A group entry holds only the rows one source batch
- // contributed at one ob value, so entries are numerous and tiny —
- // with P partitions, K distinct ob values and B contributing
- // batches there are up to P × K × B of them, and gathering each
- // one separately builds and tears down that many `RecordBatch`es.
- // `interleave` takes `(batch_pos, row)` pairs across *different*
- // source batches in one call, which is exactly the shape here.
- //
- // The pairs are pushed in emit order — partitions in sorted key
- // order, ob values ascending within a partition, entries in
- // insertion order within an ob value — so the interleaved output
- // is already ordered and needs no post-sort.
- //
- // `batch_refs` holds only the batches the current chunk references
- // and is rebuilt per chunk: for Dictionary columns `interleave`
- // does work for every input array it is handed, referenced or not,
- // so passing the whole store to each chunk made emit
- // O(chunks × store batches). A batch's slot is resolved once per
- // entry, not per row.
- let mut batch_refs: Vec<&RecordBatch> = Vec::new();
- let mut batch_id_pos: HashMap<u32, usize> = HashMap::new();
- let mut indices: Vec<(usize, usize)> = Vec::with_capacity(batch_size);
- let mut sorted_obs: Vec<(Vec<u8>, Vec<GroupEntry>)> = Vec::new();
- // Parallel to `indices`: each row's `DENSE_RANK()`, when emitted.
- let mut ranks: Option<Vec<u64>> =
- emit_ranks.then(|| Vec::with_capacity(batch_size));
-
- // Chunk at `batch_size` so the operator emits the same batch sizes
- // as before and no single `interleave` output exceeds `batch_size`.
- for pk in sorted_pks {
- let DenseRankPartitionState {
- groups,
- keys: _,
- contents_bytes: _,
- } = states.remove(&pk).expect("key from states.keys()");
- // Sort the <= K distinct ob keys so rows emit ascending
- // (byte-comparable encoding == sort order).
- sorted_obs.extend(groups);
- sorted_obs.sort_by(|a, b| a.0.cmp(&b.0));
- // `DENSE_RANK` is the 1-based index of a row's distinct ob value
- // within its partition, and the state holds exactly the K
- // distinct-smallest values — so the loop counter *is* the rank,
- // shared by every row of the group.
- for (dense_rank, (_ob, entries)) in
(1u64..).zip(sorted_obs.drain(..)) {
- for entry in entries {
- let batch = &store
- .get(entry.batch_id)
- .expect("retained batch_id present in store")
- .batch;
- // Resolved lazily so a chunk boundary inside the entry
- // re-registers its batch in the next chunk's slice.
- let mut array_pos = None;
- for row in entry.row_indices {
- let pos = *array_pos.get_or_insert_with(|| {
-
*batch_id_pos.entry(entry.batch_id).or_insert_with(|| {
- batch_refs.push(batch);
- batch_refs.len() - 1
- })
- });
- indices.push((pos, row as usize));
- if let Some(ranks) = &mut ranks {
- ranks.push(dense_rank);
- }
- if indices.len() == batch_size {
- let b = interleave_record_batch(&batch_refs,
&indices)?;
- let ranks = ranks.as_mut().map(|r| r.drain(..));
- out.push(Ok(finish_chunk(
- b,
- ranks,
- &output_schema,
- &metrics,
- )?));
- indices.clear();
- batch_refs.clear();
- batch_id_pos.clear();
- array_pos = None;
- }
- }
- }
- }
- }
- if !indices.is_empty() {
- let b = interleave_record_batch(&batch_refs, &indices)?;
- let ranks = ranks.as_mut().map(|r| r.drain(..));
- out.push(Ok(finish_chunk(b, ranks, &output_schema, &metrics)?));
- }
-
- Ok(Box::pin(RecordBatchStreamAdapter::new(
- output_schema,
- futures::stream::iter(out),
- )))
+ self.core.emit_with(
+ |state| {
+ let mut groups: Vec<(Vec<u8>, Vec<StoreRef>)> =
+ state.groups.into_iter().collect();
+ groups.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
Review Comment:
Reuse dense-rank group sorting storage across partitions
--
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]