Skip to main content

mz_timely_util/columnar/
batcher.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Types for consolidating, merging, and extracting columnar update collections.
17
18use std::collections::VecDeque;
19use std::marker::PhantomData;
20
21use crate::columnation::ColumnationStack;
22use columnar::Container as _;
23use columnar::Push as _;
24use columnar::bytes::indexed;
25use columnar::{BorrowedOf, Clear, Columnar, Index, Len};
26use columnation::Columnation;
27use differential_dataflow::difference::Semigroup;
28use differential_dataflow::trace::implementations::merge_batcher::{Extractor, Merger};
29use timely::Container;
30use timely::PartialOrder;
31use timely::container::{ContainerBuilder, PushInto};
32use timely::progress::frontier::{Antichain, AntichainRef};
33
34use crate::columnar::Column;
35use crate::columnar::body::ColumnBody;
36
37/// A chunker to transform input data into sorted columns.
38#[derive(Default)]
39pub struct Chunker<C> {
40    /// Buffer into which we'll consolidate.
41    ///
42    /// Also the buffer where we'll stage responses to `extract` and `finish`.
43    /// When these calls return, the buffer is available for reuse.
44    target: C,
45    /// Consolidated buffers ready to go.
46    ready: VecDeque<C>,
47}
48
49impl<C: Container + Clone + 'static> ContainerBuilder for Chunker<C> {
50    type Container = C;
51
52    fn extract(&mut self) -> Option<&mut Self::Container> {
53        if let Some(ready) = self.ready.pop_front() {
54            self.target = ready;
55            Some(&mut self.target)
56        } else {
57            None
58        }
59    }
60
61    fn finish(&mut self) -> Option<&mut Self::Container> {
62        self.extract()
63    }
64}
65
66impl<'a, D, T, R> PushInto<&'a mut Column<(D, T, R)>> for Chunker<ColumnationStack<(D, T, R)>>
67where
68    D: Columnar + Columnation,
69    for<'b> columnar::Ref<'b, D>: Ord + Copy,
70    T: Columnar + Columnation,
71    for<'b> columnar::Ref<'b, T>: Ord + Copy,
72    R: Columnar + Columnation + Semigroup + for<'b> Semigroup<columnar::Ref<'b, R>>,
73    for<'b> columnar::Ref<'b, R>: Ord,
74{
75    fn push_into(&mut self, container: &'a mut Column<(D, T, R)>) {
76        // Sort input data
77        // TODO: consider `Vec<usize>` that we retain, containing indexes.
78        let borrowed = container.borrow();
79        let mut permutation = Vec::with_capacity(borrowed.len());
80        Extend::extend(&mut permutation, borrowed.into_index_iter());
81        permutation.sort();
82
83        self.target.clear();
84        // Iterate over the data, accumulating diffs for like keys.
85        let mut iter = permutation.drain(..);
86        if let Some((data, time, diff)) = iter.next() {
87            let mut owned_data = D::into_owned(data);
88            let mut owned_time = T::into_owned(time);
89
90            let mut prev_data = data;
91            let mut prev_time = time;
92            let mut prev_diff = <R as Columnar>::into_owned(diff);
93
94            for (data, time, diff) in iter {
95                if (&prev_data, &prev_time) == (&data, &time) {
96                    prev_diff.plus_equals(&diff);
97                } else {
98                    if !prev_diff.is_zero() {
99                        D::copy_from(&mut owned_data, prev_data);
100                        T::copy_from(&mut owned_time, prev_time);
101                        let tuple = (owned_data, owned_time, prev_diff);
102                        self.target.push_into(&tuple);
103                        (owned_data, owned_time, prev_diff) = tuple;
104                    }
105                    prev_data = data;
106                    prev_time = time;
107                    R::copy_from(&mut prev_diff, diff);
108                }
109            }
110
111            if !prev_diff.is_zero() {
112                D::copy_from(&mut owned_data, prev_data);
113                T::copy_from(&mut owned_time, prev_time);
114                let tuple = (owned_data, owned_time, prev_diff);
115                self.target.push_into(&tuple);
116            }
117        }
118
119        if !self.target.is_empty() {
120            self.ready.push_back(std::mem::take(&mut self.target));
121        }
122    }
123}
124
125/// A chunker that consolidates `Column<(D, T, R)>` updates into sorted
126/// [`ColumnBody`] chunks, without round-tripping through columnation.
127///
128/// Drop-in counterpart to [`Chunker`] for the merge-batcher path: same control
129/// flow (sort borrowed refs, fold equal `(data, time)` runs, drop zero diffs).
130/// This is where records leave the edge container: the input is whatever the
131/// edge delivered, the output is a body the batcher chains.
132pub struct ColumnChunker<U: Columnar> {
133    /// Body we consolidate into and present to extract/finish callers.
134    target: ColumnBody<U>,
135    /// Sorted, consolidated chunks pending extraction.
136    ready: VecDeque<ColumnBody<U>>,
137}
138
139// Manual impl rather than `#[derive(Default)]`: the derive would synthesize
140// `impl<U: Columnar + Default>`, but `ColumnBody<U>: Default` only requires
141// `U: Columnar`, and adding a spurious `U: Default` bound would propagate
142// through every `ContainerBuilder for ColumnChunker<U>` impl.
143impl<U: Columnar> Default for ColumnChunker<U> {
144    fn default() -> Self {
145        Self {
146            target: ColumnBody::default(),
147            ready: VecDeque::new(),
148        }
149    }
150}
151
152impl<U: Columnar> ContainerBuilder for ColumnChunker<U>
153where
154    U::Container: Clone + 'static,
155{
156    type Container = ColumnBody<U>;
157
158    fn extract(&mut self) -> Option<&mut Self::Container> {
159        if let Some(ready) = self.ready.pop_front() {
160            self.target = ready;
161            Some(&mut self.target)
162        } else {
163            None
164        }
165    }
166
167    fn finish(&mut self) -> Option<&mut Self::Container> {
168        self.extract()
169    }
170}
171
172impl<'a, D, T, R> PushInto<&'a mut Column<(D, T, R)>> for ColumnChunker<(D, T, R)>
173where
174    D: Columnar,
175    for<'b> columnar::Ref<'b, D>: Copy + Ord,
176    T: Columnar,
177    for<'b> columnar::Ref<'b, T>: Copy + Ord,
178    R: Columnar + Default + Semigroup + for<'b> Semigroup<columnar::Ref<'b, R>>,
179    for<'b> columnar::Ref<'b, R>: Ord,
180    for<'b> <D as Columnar>::Container: columnar::Push<columnar::Ref<'b, D>>,
181    for<'b> <T as Columnar>::Container: columnar::Push<columnar::Ref<'b, T>>,
182    for<'b> <R as Columnar>::Container: columnar::Push<&'b R>,
183{
184    fn push_into(&mut self, container: &'a mut Column<(D, T, R)>) {
185        // Clearing keeps the allocations of a typed target, which is the
186        // steady state: possibly a chunk just handed back via `extract`.
187        self.target.clear();
188
189        // Sort input by columnar ref order.
190        let borrowed = container.borrow();
191        let mut permutation = Vec::with_capacity(borrowed.len());
192        Extend::extend(&mut permutation, borrowed.into_index_iter());
193        permutation.sort();
194
195        // Sweep sorted refs, accumulating diffs over equal `(data, time)`
196        // pairs and pushing non-zero results to the target's leaves. Refs
197        // from the input borrow are valid through the sweep, so D and T
198        // are pushed directly via each leaf's `Push<Ref<_>>` impl. Only R
199        // needs an owned scratch since it carries the consolidated sum.
200        {
201            let (target_d, target_t, target_r) = self.target.typed_mut();
202
203            let mut iter = permutation.drain(..);
204            if let Some((data, time, diff)) = iter.next() {
205                let mut prev_data = data;
206                let mut prev_time = time;
207                let mut prev_diff = <R as Columnar>::into_owned(diff);
208
209                for (data, time, diff) in iter {
210                    if (&prev_data, &prev_time) == (&data, &time) {
211                        prev_diff.plus_equals(&diff);
212                    } else {
213                        if !prev_diff.is_zero() {
214                            target_d.push(prev_data);
215                            target_t.push(prev_time);
216                            target_r.push(&prev_diff);
217                        }
218                        prev_data = data;
219                        prev_time = time;
220                        R::copy_from(&mut prev_diff, diff);
221                    }
222                }
223
224                if !prev_diff.is_zero() {
225                    target_d.push(prev_data);
226                    target_t.push(prev_time);
227                    target_r.push(&prev_diff);
228                }
229            }
230        }
231
232        if !self.target.is_empty() {
233            self.ready.push_back(std::mem::take(&mut self.target));
234        }
235    }
236}
237
238/// Advance `*lower` past every position in `[*lower, upper)` where `cmp`
239/// returns true.
240///
241/// On return, `*lower` is the first index `>= initial *lower` where `cmp`
242/// returns false, or `upper` if `cmp` holds through the end.
243///
244/// Takes the predicate as `FnMut(usize) -> bool` rather than a value-bearing
245/// closure so callers can index whichever subset of the input columns they
246/// actually need to compare — for the merger's `(d, t)`-keyed sort, this lets
247/// each probe touch only the D and T leaf views, skipping the diff column.
248///
249/// Compared to a linear scan, this is `O(log K)` for a run of length `K`
250/// satisfying `cmp` — useful when one side of a sorted merge has long runs
251/// dominated by the other side.
252pub(crate) fn gallop(upper: usize, lower: &mut usize, mut cmp: impl FnMut(usize) -> bool) {
253    if *lower < upper && cmp(*lower) {
254        let mut step = 1;
255        while *lower + step < upper && cmp(*lower + step) {
256            *lower += step;
257            step <<= 1;
258        }
259
260        step >>= 1;
261        while step > 0 {
262            if *lower + step < upper && cmp(*lower + step) {
263                *lower += step;
264            }
265            step >>= 1;
266        }
267
268        // `*lower` is the last index where `cmp` holds; step to the first
269        // where it does not.
270        *lower += 1;
271    }
272}
273
274/// Counterpart to `ColInternalMerger` (which merges `ColumnationStack` chunks).
275/// Drives the merge batcher with [`ColumnBody`] chunks, no columnation
276/// detour, by way of the inherent `merge_from` / `extract` methods on
277/// `ColumnBody<(D, T, R)>` below.
278pub struct ColumnMerger<D, T, R> {
279    _marker: PhantomData<(D, T, R)>,
280}
281
282impl<D, T, R> Default for ColumnMerger<D, T, R> {
283    fn default() -> Self {
284        Self {
285            _marker: PhantomData,
286        }
287    }
288}
289
290/// A chunk the merge and extract bodies below write to: the merger's
291/// [`ColumnBody`].
292pub trait MergeChunk<C: Columnar>: Default {
293    /// The typed containers, for writing to.
294    fn typed(&mut self) -> &mut C::Container;
295    /// The chunk as a columnar view.
296    fn view(&self) -> BorrowedOf<'_, C>;
297    /// True when the chunk holds no records.
298    fn is_empty(&self) -> bool;
299}
300
301impl<C: Columnar> MergeChunk<C> for ColumnBody<C> {
302    fn typed(&mut self) -> &mut C::Container {
303        self.typed_mut()
304    }
305    fn view(&self) -> BorrowedOf<'_, C> {
306        self.borrow()
307    }
308    fn is_empty(&self) -> bool {
309        self.is_empty()
310    }
311}
312
313/// Per-chunk merge and extract for sorted [`ColumnBody`] chunks.
314///
315/// These are the building blocks that [`Merger for ColumnMerger`] orchestrates
316/// over chains of chunks. They're inherent methods rather than a trait impl
317/// so the merger can call them without going through any wrapper indirection.
318/// The output side of each is written to, so a serialized output body is
319/// materialized first (see [`ColumnBody::typed_mut`]).
320impl<D, T, R> ColumnBody<(D, T, R)>
321where
322    D: Columnar,
323    for<'a> columnar::Ref<'a, D>: Copy + Ord,
324    T: Columnar + Default + Clone + PartialOrder,
325    for<'a> columnar::Ref<'a, T>: Copy + Ord,
326    R: Columnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
327{
328    /// Merge items from sorted inputs into `self`, advancing positions. See
329    /// [`merge_from`].
330    #[must_use]
331    pub fn merge_from(&mut self, others: &mut [Self], positions: &mut [usize]) -> bool {
332        merge_from(self, others, positions)
333    }
334
335    /// Partition records starting at `*position` into `keep` and `ship`. See
336    /// [`extract`].
337    pub fn extract(
338        &mut self,
339        position: &mut usize,
340        upper: AntichainRef<T>,
341        frontier: &mut Antichain<T>,
342        keep: &mut Self,
343        ship: &mut Self,
344    ) {
345        extract(self, position, upper, frontier, keep, ship)
346    }
347}
348
349/// Merge items from sorted inputs into `target`, advancing positions.
350///
351/// Mirrors the dispatch shape used by the merge-batcher framework:
352/// - **0**: no-op
353/// - **1**: bulk copy (or swap, if `target` is empty and `*pos == 0`)
354/// - **2**: merge two sorted streams, with diff consolidation on equal
355///   `(data, time)` keys and gallop bulk-copy of long single-side runs.
356///
357/// Returns `true` if the merge stopped because the amortized ship-threshold
358/// check inside the inner loop fired (the caller should ship `target` before
359/// the next call). Returns `false` if the merge stopped because at least
360/// one input was exhausted at its position (the caller should refill that
361/// side; `target` may still be at capacity from accumulation across short
362/// calls and the caller should also check `at_capacity` in that case).
363///
364/// The 0- and 1-input dispatches always return `false`: 0 does no work,
365/// 1 is a bulk copy or swap that runs to completion.
366#[must_use]
367pub fn merge_from<D, T, R, Ch>(target: &mut Ch, others: &mut [Ch], positions: &mut [usize]) -> bool
368where
369    D: Columnar,
370    for<'a> columnar::Ref<'a, D>: Copy + Ord,
371    T: Columnar + Default + Clone + PartialOrder,
372    for<'a> columnar::Ref<'a, T>: Copy + Ord,
373    R: Columnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
374    Ch: MergeChunk<(D, T, R)>,
375{
376    match others.len() {
377        0 => false,
378        1 => {
379            let other = &mut others[0];
380            let pos = &mut positions[0];
381            if target.is_empty() && *pos == 0 {
382                std::mem::swap(target, other);
383                return false;
384            }
385            let self_c = target.typed();
386            let src_c = other.view();
387            self_c.extend_from_self(src_c, *pos..other.view().len());
388            *pos = other.view().len();
389            false
390        }
391        2 => {
392            let (left, right) = others.split_at(1);
393            let (left_pos, right_pos) = positions.split_at_mut(1);
394            let left_borrow = left[0].view();
395            let right_borrow = right[0].view();
396
397            let self_c = target.typed();
398
399            // Split the input borrows into per-leaf views.
400            //
401            // A columnar tuple `Borrow::Ref` is recursive: indexing the
402            // tuple borrow walks every leaf (and reconstructs the nested
403            // ref tuple) regardless of which leaves the caller actually
404            // reads. Indexing each leaf view directly cuts probe-path
405            // work to the columns we consult — for the merge step
406            // that's the `(D, T)` key, with the diff column read only
407            // when we push.
408            let l_d = left_borrow.0;
409            let l_t = left_borrow.1;
410            let l_r = left_borrow.2;
411            let r_d = right_borrow.0;
412            let r_t = right_borrow.1;
413            let r_r = right_borrow.2;
414            let upper_l = l_d.len();
415            let upper_r = r_d.len();
416
417            // Mirror the split on the output container. Tuple
418            // containers split into per-leaf containers, which lets us
419            // address each leaf independently — both gallop bulk-copies
420            // and single-record pushes resolve to a primitive operation
421            // per leaf. The leaves stay length-synchronized as long as
422            // every record path pushes exactly one element to each.
423            let (sd, st, sr) = self_c;
424
425            // Pre-size each output leaf for the worst-case merge (no
426            // consolidation). `reserve_for` walks each input's
427            // `as_bytes`, which is accurate for variable-length leaves,
428            // where reserving a record count wouldn't size the byte
429            // buffer correctly. The reservation covers both whole
430            // inputs, however little of them this call consumes, so
431            // reserve only when the inputs fit within two ship-sized
432            // chunks, which bounds it to 4 MiB.
433            let input_bytes = 8
434                * (indexed::length_in_words(&left_borrow)
435                    + indexed::length_in_words(&right_borrow));
436            if input_bytes <= 2 * crate::columnar::SHIP_WORDS * 8 {
437                let inputs = [left_borrow, right_borrow];
438                sd.reserve_for(inputs.iter().map(|b| b.0));
439                st.reserve_for(inputs.iter().map(|b| b.1));
440                sr.reserve_for(inputs.iter().map(|b| b.2));
441            }
442
443            let mut stash = R::default();
444
445            // The size check walks every leaf slice, which is not cheap on
446            // variable-length leaves, so it runs only after spending the
447            // ship threshold's headroom at the inputs' average width.
448            // That bounds uniform rows to just under the ship size. For
449            // mixed widths it is a cadence hint: a stretch of wide rows
450            // can overshoot. `ColumnChunk::settle` enforces the bound for
451            // chunks that reach the pool.
452            let average_bytes = input_bytes / (upper_l + upper_r).max(1);
453            let check_records =
454                (crate::columnar::SHIP_WORDS * 8 / 10 / average_bytes.max(1)).clamp(1, 1024);
455            let mut next_check = sd.len() + check_records;
456            let mut yielded = false;
457
458            while left_pos[0] < upper_l && right_pos[0] < upper_r {
459                let d1 = l_d.get(left_pos[0]);
460                let t1 = l_t.get(left_pos[0]);
461                let d2 = r_d.get(right_pos[0]);
462                let t2 = r_t.get(right_pos[0]);
463                match (d1, t1).cmp(&(d2, t2)) {
464                    std::cmp::Ordering::Less => {
465                        // Common case (interleaved data): single-record
466                        // advance. Skip the gallop call entirely — its
467                        // setup plus the first cmp probe is more
468                        // expensive than just pushing this record and
469                        // re-entering the outer loop. Galloping is only
470                        // worthwhile when there's an actual run, which
471                        // we detect with the peek check below.
472                        sd.push(d1);
473                        st.push(t1);
474                        sr.push(l_r.get(left_pos[0]));
475                        left_pos[0] += 1;
476                        // Long-run case: peek at the next record; if
477                        // it's still strictly less than `(d2, t2)`,
478                        // we have a run worth galloping (and bulk-
479                        // copying).
480                        if left_pos[0] < upper_l
481                            && (l_d.get(left_pos[0]), l_t.get(left_pos[0])) < (d2, t2)
482                        {
483                            let start = left_pos[0];
484                            gallop(
485                                upper_l.min(left_pos[0] + next_check.saturating_sub(sd.len())),
486                                &mut left_pos[0],
487                                |i| (l_d.get(i), l_t.get(i)) < (d2, t2),
488                            );
489                            // Per-leaf bulk copy of the run: each call
490                            // resolves to an `extend_from_slice` on its
491                            // leaf (recursively for nested leaves).
492                            sd.extend_from_self(l_d, start..left_pos[0]);
493                            st.extend_from_self(l_t, start..left_pos[0]);
494                            sr.extend_from_self(l_r, start..left_pos[0]);
495                        }
496                    }
497                    std::cmp::Ordering::Greater => {
498                        // Symmetric on the right side.
499                        sd.push(d2);
500                        st.push(t2);
501                        sr.push(r_r.get(right_pos[0]));
502                        right_pos[0] += 1;
503                        if right_pos[0] < upper_r
504                            && (r_d.get(right_pos[0]), r_t.get(right_pos[0])) < (d1, t1)
505                        {
506                            let start = right_pos[0];
507                            gallop(
508                                upper_r.min(right_pos[0] + next_check.saturating_sub(sd.len())),
509                                &mut right_pos[0],
510                                |i| (r_d.get(i), r_t.get(i)) < (d1, t1),
511                            );
512                            sd.extend_from_self(r_d, start..right_pos[0]);
513                            st.extend_from_self(r_t, start..right_pos[0]);
514                            sr.extend_from_self(r_r, start..right_pos[0]);
515                        }
516                    }
517                    std::cmp::Ordering::Equal => {
518                        let r1 = l_r.get(left_pos[0]);
519                        let r2 = r_r.get(right_pos[0]);
520                        R::copy_from(&mut stash, r1);
521                        stash.plus_equals(&r2);
522                        if !stash.is_zero() {
523                            sd.push(d1);
524                            st.push(t1);
525                            sr.push(&stash);
526                        }
527                        left_pos[0] += 1;
528                        right_pos[0] += 1;
529                    }
530                }
531
532                if sd.len() >= next_check {
533                    use columnar::Borrow as _;
534                    if crate::columnar::at_serialized_capacity(&(
535                        sd.borrow(),
536                        st.borrow(),
537                        sr.borrow(),
538                    )) {
539                        yielded = true;
540                        break;
541                    }
542                    next_check = sd.len() + check_records;
543                }
544            }
545            yielded
546        }
547        // `Merger::merge` only ever calls `merge_from` with 0/1/2-input
548        // slices (k-way merge isn't part of the merge-batcher contract).
549        n => unreachable!("merge_from called with {n} inputs; expected 0, 1, or 2"),
550    }
551}
552
553/// Partition records of `source` starting at `*position` into `keep` (times
554/// beyond `upper`, retained for the next round) and `ship` (times not beyond
555/// `upper`, sealed into the output batch). Updates `frontier` with the
556/// times of kept records.
557///
558/// The caller invokes `extract` repeatedly until `*position >= source.len()`,
559/// swapping out a full output buffer between calls. This shape exists
560/// because the framework only checks `at_capacity()` between calls, so
561/// without an inner-loop yield a single call could quietly produce
562/// oversized output chunks.
563pub fn extract<D, T, R, Ch>(
564    source: &Ch,
565    position: &mut usize,
566    upper: AntichainRef<T>,
567    frontier: &mut Antichain<T>,
568    keep: &mut Ch,
569    ship: &mut Ch,
570) where
571    D: Columnar,
572    for<'a> columnar::Ref<'a, D>: Copy + Ord,
573    T: Columnar + Default + Clone + PartialOrder,
574    for<'a> columnar::Ref<'a, T>: Copy + Ord,
575    R: Columnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
576    Ch: MergeChunk<(D, T, R)>,
577{
578    let keep_c = keep.typed();
579    let ship_c = ship.typed();
580
581    let self_view = source.view();
582    let len = self_view.len();
583
584    use columnar::Borrow as _;
585    let mut owned_t = T::default();
586    while *position < len
587        && !crate::columnar::at_serialized_capacity(&keep_c.borrow())
588        && !crate::columnar::at_serialized_capacity(&ship_c.borrow())
589    {
590        let (_, time, _) = self_view.get(*position);
591        T::copy_from(&mut owned_t, time);
592        if upper.less_equal(&owned_t) {
593            // `insert_with` only clones when the time isn't already
594            // present in the antichain.
595            frontier.insert_with(&owned_t, |t| t.clone());
596            keep_c.extend_from_self(self_view, *position..*position + 1);
597        } else {
598            ship_c.extend_from_self(self_view, *position..*position + 1);
599        }
600        *position += 1;
601    }
602}
603
604/// `Merger` impl driving [`MergeBatcher`] over [`ColumnBody`] chunks,
605/// built on the inherent `ColumnBody::merge_from` and `ColumnBody::extract`
606/// methods.
607/// Exhausted input chunks are recycled through `stash`, and remaining full
608/// chunks on a drained side move to the output directly, with no per-element
609/// copy.
610///
611/// [`MergeBatcher`]: differential_dataflow::trace::implementations::merge_batcher::MergeBatcher
612impl<D, T, R> Merger for ColumnMerger<D, T, R>
613where
614    D: Columnar,
615    for<'a> columnar::Ref<'a, D>: Copy + Ord,
616    T: Columnar + Default + Clone + Ord + PartialOrder,
617    for<'a> columnar::Ref<'a, T>: Copy + Ord,
618    R: Columnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
619{
620    type Chunk = ColumnBody<(D, T, R)>;
621
622    fn merge(
623        &mut self,
624        list1: Vec<Self::Chunk>,
625        list2: Vec<Self::Chunk>,
626        output: &mut Vec<Self::Chunk>,
627        stash: &mut Vec<Self::Chunk>,
628    ) {
629        let mut list1 = list1.into_iter();
630        let mut list2 = list2.into_iter();
631
632        let mut heads = [
633            list1.next().unwrap_or_default(),
634            list2.next().unwrap_or_default(),
635        ];
636        let mut positions = [0usize, 0usize];
637
638        let mut result = empty_chunk(stash);
639
640        // Main merge loop: both sides have data.
641        loop {
642            let upper_l = heads[0].borrow().len();
643            let upper_r = heads[1].borrow().len();
644            if positions[0] >= upper_l || positions[1] >= upper_r {
645                break;
646            }
647
648            // Whole-chunk passthrough fast path: when one head's tail (from
649            // its current position) sorts entirely before the other head's
650            // current record, the head moves to `output` wholesale, with two
651            // probe records in place of per-record compares and per-leaf
652            // byte copies. Restricted to `positions[i] == 0` so the head can
653            // be handed off intact; a partial tail is what gallop already
654            // handles inside the merge loop.
655            let lhs_passthrough = positions[0] == 0 && upper_l > 0 && {
656                let lhs = heads[0].borrow();
657                let rhs = heads[1].borrow();
658                let last_l = (lhs.0.get(upper_l - 1), lhs.1.get(upper_l - 1));
659                let cur_r = (rhs.0.get(positions[1]), rhs.1.get(positions[1]));
660                last_l < cur_r
661            };
662            if lhs_passthrough {
663                if !result.is_empty() {
664                    output.push(std::mem::take(&mut result));
665                    result = empty_chunk(stash);
666                }
667                let head = std::mem::replace(&mut heads[0], list1.next().unwrap_or_default());
668                output.push(head);
669                positions[0] = 0;
670                continue;
671            }
672
673            let rhs_passthrough = positions[1] == 0 && upper_r > 0 && {
674                let lhs = heads[0].borrow();
675                let rhs = heads[1].borrow();
676                let last_r = (rhs.0.get(upper_r - 1), rhs.1.get(upper_r - 1));
677                let cur_l = (lhs.0.get(positions[0]), lhs.1.get(positions[0]));
678                last_r < cur_l
679            };
680            if rhs_passthrough {
681                if !result.is_empty() {
682                    output.push(std::mem::take(&mut result));
683                    result = empty_chunk(stash);
684                }
685                let head = std::mem::replace(&mut heads[1], list2.next().unwrap_or_default());
686                output.push(head);
687                positions[1] = 0;
688                continue;
689            }
690
691            // Per-record merge. `merge_from` returns `true` when its inner
692            // amortized ship-threshold check fires — short-circuit the
693            // outer `at_capacity` walk in that case.
694            let yielded = result.merge_from(&mut heads, &mut positions);
695
696            if positions[0] >= heads[0].borrow().len() {
697                let old = std::mem::replace(&mut heads[0], list1.next().unwrap_or_default());
698                recycle_chunk(old, stash);
699                positions[0] = 0;
700            }
701            if positions[1] >= heads[1].borrow().len() {
702                let old = std::mem::replace(&mut heads[1], list2.next().unwrap_or_default());
703                recycle_chunk(old, stash);
704                positions[1] = 0;
705            }
706            if yielded || result.at_capacity() {
707                output.push(std::mem::take(&mut result));
708                result = empty_chunk(stash);
709            }
710        }
711
712        // Drain remaining from each side: copy partial head, then append
713        // full chunks directly to output (no per-element copy).
714        drain_side(
715            &mut heads[0],
716            &mut positions[0],
717            &mut list1,
718            &mut result,
719            output,
720            stash,
721        );
722        drain_side(
723            &mut heads[1],
724            &mut positions[1],
725            &mut list2,
726            &mut result,
727            output,
728            stash,
729        );
730        if !result.is_empty() {
731            output.push(result);
732        }
733    }
734
735    fn len(chunk: &Self::Chunk) -> usize {
736        chunk.len()
737    }
738
739    fn allocation(chunk: &Self::Chunk) -> (usize, usize, usize) {
740        // Serialized footprint stands in for both `size` and `capacity`: the
741        // chunk owns one logical allocation worth of leaf storage, and we
742        // ship/recycle the whole thing rather than tracking per-leaf
743        // capacities. Treating `size == capacity` matches how the framework
744        // accounts already-shipped chunks (no slack to absorb).
745        let bytes = chunk.length_in_bytes();
746        (bytes, bytes, 1)
747    }
748}
749
750impl<D, T, R> Extractor for ColumnMerger<D, T, R>
751where
752    D: Columnar,
753    for<'a> columnar::Ref<'a, D>: Copy + Ord,
754    T: Columnar + Default + Clone + Ord + PartialOrder,
755    for<'a> columnar::Ref<'a, T>: Copy + Ord,
756    R: Columnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
757{
758    type Time = T;
759
760    fn extract(
761        &mut self,
762        merged: Vec<Self::Chunk>,
763        upper: AntichainRef<Self::Time>,
764        frontier: &mut Antichain<Self::Time>,
765        ship: &mut Vec<Self::Chunk>,
766        kept: &mut Vec<Self::Chunk>,
767        stash: &mut Vec<Self::Chunk>,
768    ) {
769        let mut keep = empty_chunk(stash);
770        let mut ready = empty_chunk(stash);
771
772        for mut buffer in merged {
773            let mut position = 0;
774            let len = buffer.borrow().len();
775            while position < len {
776                buffer.extract(&mut position, upper, frontier, &mut keep, &mut ready);
777                if keep.at_capacity() {
778                    kept.push(std::mem::take(&mut keep));
779                    keep = empty_chunk(stash);
780                }
781                if ready.at_capacity() {
782                    ship.push(std::mem::take(&mut ready));
783                    ready = empty_chunk(stash);
784                }
785            }
786            recycle_chunk(buffer, stash);
787        }
788        if !keep.is_empty() {
789            kept.push(keep);
790        }
791        if !ready.is_empty() {
792            ship.push(ready);
793        }
794    }
795}
796
797/// Pop a chunk from `stash` or allocate a fresh one. Stashed chunks are
798/// already cleared via `recycle_chunk`, so they're ready for push.
799#[inline]
800pub(crate) fn empty_chunk<C: Columnar>(stash: &mut Vec<ColumnBody<C>>) -> ColumnBody<C> {
801    stash.pop().unwrap_or_default()
802}
803
804/// Reset `chunk` to an empty `Typed` and push it to `stash` for reuse.
805///
806/// Chunks recycled here come from the merger and chunker, both of which
807/// produce `Typed`; only the typed allocations are worth caching for reuse.
808/// A serialized chunk has no typed-side allocation to preserve, so we simply
809/// drop it: `empty_chunk` will produce a fresh default just as cheaply, and
810/// pushing it onto `stash` would only displace useful recycled allocations.
811#[inline]
812pub(crate) fn recycle_chunk<C: Columnar>(mut chunk: ColumnBody<C>, stash: &mut Vec<ColumnBody<C>>) {
813    if let ColumnBody::Typed(c) = &mut chunk {
814        c.clear();
815        stash.push(chunk);
816    }
817}
818
819/// Drain remaining items from one side into `result` / `output`.
820///
821/// Copies the partially-consumed head into `result` via `merge_from`'s 1-input
822/// path, then appends remaining full chunks directly to `output` without
823/// per-element copy.
824fn drain_side<D, T, R>(
825    head: &mut ColumnBody<(D, T, R)>,
826    pos: &mut usize,
827    list: &mut std::vec::IntoIter<ColumnBody<(D, T, R)>>,
828    result: &mut ColumnBody<(D, T, R)>,
829    output: &mut Vec<ColumnBody<(D, T, R)>>,
830    stash: &mut Vec<ColumnBody<(D, T, R)>>,
831) where
832    D: Columnar,
833    for<'a> columnar::Ref<'a, D>: Copy + Ord,
834    T: Columnar + Default + Clone + PartialOrder,
835    for<'a> columnar::Ref<'a, T>: Copy + Ord,
836    R: Columnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
837{
838    if *pos < head.borrow().len() {
839        // 1-input dispatch — bulk copy that runs to completion; the yield
840        // signal is unused.
841        let _ = result.merge_from(std::slice::from_mut(head), std::slice::from_mut(pos));
842    }
843    if !result.is_empty() {
844        output.push(std::mem::take(result));
845        *result = empty_chunk(stash);
846    }
847    Extend::extend(output, list);
848}
849
850#[cfg(test)]
851mod tests {
852    use timely::dataflow::channels::ContainerBytes;
853
854    use super::*;
855
856    /// Re-encode `column` as the `Align` variant, to drive the chunker over serialized
857    /// input.
858    ///
859    /// `into_bytes` writes whole `u64` words, read back in native byte order.
860    fn serialize<C: Columnar>(column: &Column<C>) -> Column<C> {
861        let mut bytes: Vec<u8> = Vec::new();
862        column.into_bytes(&mut bytes);
863        assert_eq!(bytes.len() % 8, 0);
864        let words = bytes
865            .chunks_exact(8)
866            .map(|w| u64::from_ne_bytes(w.try_into().expect("chunk is 8 bytes")))
867            .collect();
868        Column::Align(words)
869    }
870
871    /// Drive a single `push_into` call with `inputs` and collect the
872    /// consolidated output (if any) as owned tuples.
873    fn run_chunker<D, T, R>(inputs: &[(D, T, R)]) -> Vec<(D, T, R)>
874    where
875        D: Columnar + Clone,
876        for<'a> columnar::Ref<'a, D>: Copy + Ord,
877        T: Columnar + Clone,
878        for<'a> columnar::Ref<'a, T>: Copy + Ord,
879        R: Columnar + Clone + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
880        for<'a> columnar::Ref<'a, R>: Ord,
881        <(D, T, R) as Columnar>::Container: Clone,
882        for<'a> <(D, T, R) as Columnar>::Container: columnar::Push<&'a (D, T, R)>,
883        <(D, T, R) as Columnar>::Container: columnar::Push<(D, T, R)>,
884        for<'a> <D as Columnar>::Container: columnar::Push<columnar::Ref<'a, D>>,
885        for<'a> <T as Columnar>::Container: columnar::Push<columnar::Ref<'a, T>>,
886        for<'a> <R as Columnar>::Container: columnar::Push<&'a R>,
887    {
888        let mut input: Column<(D, T, R)> = Default::default();
889        for tuple in inputs.iter().cloned() {
890            input.push_into(tuple);
891        }
892
893        let mut chunker: ColumnChunker<(D, T, R)> = Default::default();
894        chunker.push_into(&mut input);
895
896        let mut out = Vec::new();
897        while let Some(chunk) = chunker.extract() {
898            for (d, t, r) in chunk.borrow().into_index_iter() {
899                out.push((D::into_owned(d), T::into_owned(t), R::into_owned(r)));
900            }
901        }
902        out
903    }
904
905    #[mz_ore::test]
906    fn empty_input_yields_no_chunk() {
907        let mut chunker: ColumnChunker<(u64, u64, i64)> = Default::default();
908        let mut input: Column<(u64, u64, i64)> = Default::default();
909        chunker.push_into(&mut input);
910        assert!(chunker.extract().is_none());
911        assert!(chunker.finish().is_none());
912    }
913
914    #[mz_ore::test]
915    fn unsorted_input_is_sorted() {
916        let out = run_chunker(&[(3u64, 0u64, 1i64), (1u64, 0u64, 1i64), (2u64, 0u64, 1i64)]);
917        assert_eq!(out, vec![(1, 0, 1), (2, 0, 1), (3, 0, 1)]);
918    }
919
920    #[mz_ore::test]
921    fn serialized_input_is_consolidated() {
922        // Callers hand the chunker whatever the upstream edge delivered, which is
923        // serialized once the data crossed an exchange.
924        let mut input: Column<(u64, u64, i64)> = Default::default();
925        for tuple in [
926            (2u64, 0u64, 1i64),
927            (1, 0, 1),
928            (2, 0, 2),
929            (3, 0, 1),
930            (3, 0, -1),
931        ] {
932            input.push_into(tuple);
933        }
934        let mut input = serialize(&input);
935
936        let mut chunker: ColumnChunker<(u64, u64, i64)> = Default::default();
937        chunker.push_into(&mut input);
938
939        let mut out = Vec::new();
940        while let Some(chunk) = chunker.extract() {
941            for (d, t, r) in chunk.borrow().into_index_iter() {
942                out.push((*d, *t, *r));
943            }
944        }
945        assert_eq!(out, vec![(1, 0, 1), (2, 0, 3)]);
946    }
947
948    #[mz_ore::test]
949    fn duplicate_keys_consolidate() {
950        let out = run_chunker(&[(1u64, 0u64, 1i64), (1u64, 0u64, 2i64), (1u64, 0u64, -1i64)]);
951        assert_eq!(out, vec![(1, 0, 2)]);
952    }
953
954    #[mz_ore::test]
955    fn diffs_summing_to_zero_are_dropped() {
956        let out = run_chunker(&[(1u64, 0u64, 1i64), (1u64, 0u64, -1i64)]);
957        assert!(out.is_empty());
958    }
959
960    #[mz_ore::test]
961    fn mixed_consolidation() {
962        // (1, 0): 1 + 2 + (-3) = 0  -> dropped
963        // (2, 0): 1            = 1  -> kept
964        // (1, 1): 5            = 5  -> kept (different time from the (1, 0) group)
965        let out = run_chunker(&[
966            (1u64, 0u64, 1i64),
967            (2u64, 0u64, 1i64),
968            (1u64, 0u64, 2i64),
969            (1u64, 1u64, 5i64),
970            (1u64, 0u64, -3i64),
971        ]);
972        assert_eq!(out, vec![(1, 1, 5), (2, 0, 1)]);
973    }
974
975    #[mz_ore::test]
976    fn key_val_tuple_data() {
977        // Exercise the actual val-batcher shape: `D = (K, V)`.
978        let out = run_chunker(&[
979            ((1u64, 10u64), 0u64, 1i64),
980            ((1u64, 10u64), 0u64, 1i64),
981            ((1u64, 11u64), 0u64, 1i64),
982            ((2u64, 10u64), 0u64, 1i64),
983        ]);
984        assert_eq!(
985            out,
986            vec![((1, 10), 0, 2), ((1, 11), 0, 1), ((2, 10), 0, 1),]
987        );
988    }
989
990    #[mz_ore::test]
991    fn buffer_reuse_across_calls() {
992        // Two sequential push_into calls; second runs after extract returned
993        // the first chunk, exercising the in-place clear path.
994        let mut input1: Column<(u64, u64, i64)> = Default::default();
995        input1.push_into((1u64, 0u64, 1i64));
996        input1.push_into((2u64, 0u64, 1i64));
997
998        let mut input2: Column<(u64, u64, i64)> = Default::default();
999        input2.push_into((3u64, 0u64, 1i64));
1000        input2.push_into((1u64, 0u64, 1i64));
1001
1002        let mut chunker: ColumnChunker<(u64, u64, i64)> = Default::default();
1003        chunker.push_into(&mut input1);
1004
1005        // Hand back the first chunk via extract, simulating the merge batcher
1006        // taking ownership of the &mut and then returning.
1007        {
1008            let _ = chunker.extract().expect("first chunk");
1009        }
1010
1011        chunker.push_into(&mut input2);
1012
1013        let chunk = chunker.extract().expect("second chunk");
1014        let collected: Vec<_> = chunk
1015            .borrow()
1016            .into_index_iter()
1017            .map(|(d, t, r)| (u64::into_owned(d), u64::into_owned(t), i64::into_owned(r)))
1018            .collect();
1019        assert_eq!(collected, vec![(1, 0, 1), (3, 0, 1)]);
1020    }
1021
1022    /// Build a `ColumnBody<((u64, u64), u64, i64)>` from a slice of tuples.
1023    fn col(rows: &[((u64, u64), u64, i64)]) -> ColumnBody<((u64, u64), u64, i64)> {
1024        let mut c: ColumnBody<((u64, u64), u64, i64)> = Default::default();
1025        for &t in rows {
1026            c.push_into(t);
1027        }
1028        c
1029    }
1030
1031    fn collect_chunks(
1032        chunks: &[ColumnBody<((u64, u64), u64, i64)>],
1033    ) -> Vec<((u64, u64), u64, i64)> {
1034        chunks
1035            .iter()
1036            .flat_map(|c| {
1037                c.borrow().into_index_iter().map(|((k, v), t, r)| {
1038                    (
1039                        (u64::into_owned(k), u64::into_owned(v)),
1040                        u64::into_owned(t),
1041                        i64::into_owned(r),
1042                    )
1043                })
1044            })
1045            .collect()
1046    }
1047
1048    /// Disjoint-range chains exercise the whole-chunk passthrough fast path:
1049    /// every chunk in chain1 is sortable-before every chunk in chain2, so
1050    /// each outer-loop iteration should hand a chunk straight to `output`
1051    /// without recursing through the per-record merge.
1052    #[mz_ore::test]
1053    fn merger_disjoint_chains_passthrough() {
1054        let chain1 = vec![
1055            col(&[((0, 0), 0, 1), ((1, 0), 0, 1)]),
1056            col(&[((2, 0), 0, 1), ((3, 0), 0, 1)]),
1057        ];
1058        let chain2 = vec![
1059            col(&[((10, 0), 0, 1), ((11, 0), 0, 1)]),
1060            col(&[((12, 0), 0, 1), ((13, 0), 0, 1)]),
1061        ];
1062
1063        let mut merger: ColumnMerger<(u64, u64), u64, i64> = Default::default();
1064        let mut output = Vec::new();
1065        let mut stash = Vec::new();
1066        Merger::merge(&mut merger, chain1, chain2, &mut output, &mut stash);
1067
1068        let collected = collect_chunks(&output);
1069        let expected: Vec<_> = (0..4u64)
1070            .map(|d| ((d, 0u64), 0u64, 1i64))
1071            .chain((10..14u64).map(|d| ((d, 0u64), 0u64, 1i64)))
1072            .collect();
1073        assert_eq!(collected, expected);
1074    }
1075
1076    /// Interleaved chains never satisfy the passthrough condition; each
1077    /// outer iteration falls through to `merge_from`. Same correctness
1078    /// expectation, exercises the non-passthrough path under
1079    /// `Merger::merge`.
1080    #[mz_ore::test]
1081    fn merger_interleaved_chains() {
1082        // Even keys on one chain, odd on the other; chunks alternate so the
1083        // per-record path is the only viable route.
1084        let chain1 = vec![
1085            col(&[((0, 0), 0, 1), ((2, 0), 0, 1)]),
1086            col(&[((4, 0), 0, 1), ((6, 0), 0, 1)]),
1087        ];
1088        let chain2 = vec![
1089            col(&[((1, 0), 0, 1), ((3, 0), 0, 1)]),
1090            col(&[((5, 0), 0, 1), ((7, 0), 0, 1)]),
1091        ];
1092
1093        let mut merger: ColumnMerger<(u64, u64), u64, i64> = Default::default();
1094        let mut output = Vec::new();
1095        let mut stash = Vec::new();
1096        Merger::merge(&mut merger, chain1, chain2, &mut output, &mut stash);
1097
1098        let collected = collect_chunks(&output);
1099        let expected: Vec<_> = (0..8u64).map(|d| ((d, 0u64), 0u64, 1i64)).collect();
1100        assert_eq!(collected, expected);
1101    }
1102
1103    /// Passthrough must consolidate adjacent equal keys at chunk
1104    /// boundaries — i.e., must NOT fire when `chain1`'s last record's
1105    /// `(d, t)` equals `chain2`'s first.
1106    #[mz_ore::test]
1107    fn merger_passthrough_respects_equal_boundary() {
1108        // chain1's last == chain2's first key: equal-key consolidation
1109        // must kick in (sum of diffs would be 2). If passthrough fired
1110        // erroneously, both records would land in different output chunks
1111        // unconsolidated.
1112        let chain1 = vec![col(&[((0, 0), 0, 1), ((5, 0), 0, 1)])];
1113        let chain2 = vec![col(&[((5, 0), 0, 1), ((10, 0), 0, 1)])];
1114
1115        let mut merger: ColumnMerger<(u64, u64), u64, i64> = Default::default();
1116        let mut output = Vec::new();
1117        let mut stash = Vec::new();
1118        Merger::merge(&mut merger, chain1, chain2, &mut output, &mut stash);
1119
1120        let collected = collect_chunks(&output);
1121        assert_eq!(
1122            collected,
1123            vec![((0, 0), 0, 1), ((5, 0), 0, 2), ((10, 0), 0, 1)]
1124        );
1125    }
1126}
1127
1128#[cfg(test)]
1129mod proptests {
1130    //! Property tests for `ColumnBody::merge_from` and `ColumnBody::extract`.
1131    //!
1132    //! Strategy: generate sorted+consolidated inputs (the merger's input
1133    //! contract), drive `merge_from` / `extract` the same way the framework
1134    //! would, and compare against a brute-force reference impl.
1135    //!
1136    //! Test types are `D = (u64, u64)`, `T = u64`, `R = i64` drawn from small
1137    //! ranges so that equal-key collisions are common and the consolidation
1138    //! path actually runs.
1139    use super::*;
1140    use mz_ore::cast::CastFrom;
1141    use proptest::prelude::*;
1142    use timely::progress::frontier::Antichain;
1143
1144    type Tuple = ((u64, u64), u64, i64);
1145
1146    /// Reference consolidation: sort by `(data, time)`, sum diffs over equal
1147    /// pairs, drop zeros.
1148    fn consolidate(mut v: Vec<Tuple>) -> Vec<Tuple> {
1149        v.sort();
1150        let mut out: Vec<Tuple> = Vec::new();
1151        for (d, t, r) in v {
1152            if let Some(last) = out.last_mut() {
1153                if last.0 == d && last.1 == t {
1154                    last.2 += r;
1155                    continue;
1156                }
1157            }
1158            out.push((d, t, r));
1159        }
1160        out.retain(|x| x.2 != 0);
1161        out
1162    }
1163
1164    /// Strategy for sorted+consolidated input lists. Ranges are small to
1165    /// encourage equal-key collisions.
1166    fn arb_consolidated() -> impl Strategy<Value = Vec<Tuple>> {
1167        prop::collection::vec(((0u64..5, 0u64..5), 0u64..3, -3i64..=3i64), 0..30)
1168            .prop_map(consolidate)
1169    }
1170
1171    fn build_column(v: &[Tuple]) -> ColumnBody<Tuple> {
1172        let mut col: ColumnBody<Tuple> = Default::default();
1173        for tup in v {
1174            col.push_into(*tup);
1175        }
1176        col
1177    }
1178
1179    /// The body in `ColumnBody::Words` form when `words` is set, as a store hands it back.
1180    fn in_form(col: ColumnBody<Tuple>, words: bool) -> ColumnBody<Tuple> {
1181        if !words {
1182            return col;
1183        }
1184        let mut bytes = Vec::new();
1185        col.write_into(&mut bytes).expect("vec writes");
1186        ColumnBody::Words(bytemuck::allocation::pod_collect_to_vec(&bytes))
1187    }
1188
1189    fn collect_column(col: &ColumnBody<Tuple>) -> Vec<Tuple> {
1190        col.borrow()
1191            .into_index_iter()
1192            .map(|((k, v), t, r)| {
1193                (
1194                    (u64::into_owned(k), u64::into_owned(v)),
1195                    u64::into_owned(t),
1196                    i64::into_owned(r),
1197                )
1198            })
1199            .collect()
1200    }
1201
1202    /// Drive a 2-way merge the same way `Merger::merge` would: a 2-input
1203    /// call until one side exhausts, then a 1-input drain for whichever
1204    /// side still has data.
1205    fn drive_merge(left: ColumnBody<Tuple>, right: ColumnBody<Tuple>) -> ColumnBody<Tuple> {
1206        let mut self_col: ColumnBody<Tuple> = Default::default();
1207        let mut others = [left, right];
1208        let mut positions = [0usize, 0];
1209        let _ = self_col.merge_from(&mut others, &mut positions);
1210
1211        let [left_done, right_done] = others;
1212        let [left_pos, right_pos] = positions;
1213
1214        if left_pos < left_done.borrow().len() {
1215            let mut tail = [left_done];
1216            let mut p = [left_pos];
1217            let _ = self_col.merge_from(&mut tail, &mut p);
1218        } else if right_pos < right_done.borrow().len() {
1219            let mut tail = [right_done];
1220            let mut p = [right_pos];
1221            let _ = self_col.merge_from(&mut tail, &mut p);
1222        }
1223
1224        self_col
1225    }
1226
1227    proptest! {
1228        /// `merge_from` with two sorted+consolidated inputs equals the
1229        /// reference consolidate(union).
1230        #[mz_ore::test]
1231        #[cfg_attr(miri, ignore)]
1232        fn merge_from_equals_consolidated_union(
1233            a in arb_consolidated(),
1234            b in arb_consolidated(),
1235            a_words in any::<bool>(),
1236            b_words in any::<bool>(),
1237        ) {
1238            let merged = drive_merge(
1239                in_form(build_column(&a), a_words),
1240                in_form(build_column(&b), b_words),
1241            );
1242
1243            let mut union = a.clone();
1244            Extend::extend(&mut union, b.iter().copied());
1245            let expected = consolidate(union);
1246
1247            prop_assert_eq!(collect_column(&merged), expected);
1248        }
1249
1250        /// `merge_from` 1-input bulk-copy from a non-zero position equals
1251        /// `other[*pos..]`.
1252        #[mz_ore::test]
1253        #[cfg_attr(miri, ignore)]
1254        fn merge_from_one_input_drains_tail(
1255            data in arb_consolidated(),
1256            pos_frac in 0u32..=100,
1257            self_words in any::<bool>(),
1258            other_words in any::<bool>(),
1259        ) {
1260            // Cap at len so we always have a valid position.
1261            let len = data.len();
1262            let start_pos = if len == 0 { 0 } else {
1263                (usize::cast_from(pos_frac) * len) / 101
1264            };
1265
1266            // Self starts non-empty so we exercise the bulk-copy path, not the
1267            // empty-self swap shortcut.
1268            let mut self_col: ColumnBody<Tuple> = Default::default();
1269            let sentinel: Tuple = ((u64::MAX, u64::MAX), 0, 1);
1270            self_col.push_into(sentinel);
1271            // A serialized target is materialized before the copy appends to it.
1272            let mut self_col = in_form(self_col, self_words);
1273
1274            let mut others = [in_form(build_column(&data), other_words)];
1275            let mut positions = [start_pos];
1276            let _ = self_col.merge_from(&mut others, &mut positions);
1277
1278            let mut expected = vec![sentinel];
1279            Extend::extend(&mut expected, data[start_pos..].iter().copied());
1280
1281            prop_assert_eq!(collect_column(&self_col), expected);
1282            prop_assert_eq!(positions[0], len);
1283        }
1284
1285        /// `merge_from` 1-input swap shortcut: empty self + pos=0 should
1286        /// produce a column equal to the input.
1287        #[mz_ore::test]
1288        #[cfg_attr(miri, ignore)]
1289        fn merge_from_empty_self_swap(data in arb_consolidated(), words in any::<bool>()) {
1290            let mut self_col: ColumnBody<Tuple> = Default::default();
1291            let mut others = [in_form(build_column(&data), words)];
1292            let mut positions = [0usize];
1293            let _ = self_col.merge_from(&mut others, &mut positions);
1294
1295            prop_assert_eq!(collect_column(&self_col), data);
1296        }
1297
1298        /// `extract` partitions correctly:
1299        ///   - keep ∪ ship multiset-equals self
1300        ///   - upper.less_equal(t) for every kept time
1301        ///   - !upper.less_equal(t) for every shipped time
1302        ///   - frontier covers every kept time
1303        #[mz_ore::test]
1304        #[cfg_attr(miri, ignore)]
1305        fn extract_partitions_by_frontier(
1306            data in arb_consolidated(),
1307            upper_time in 0u64..=4,
1308            words in any::<bool>(),
1309        ) {
1310            let mut self_col = in_form(build_column(&data), words);
1311            let upper = Antichain::from_elem(upper_time);
1312            let mut frontier: Antichain<u64> = Antichain::new();
1313            let mut keep: ColumnBody<Tuple> = Default::default();
1314            let mut ship: ColumnBody<Tuple> = Default::default();
1315            let mut position = 0;
1316
1317            self_col.extract(
1318                &mut position,
1319                upper.borrow(),
1320                &mut frontier,
1321                &mut keep,
1322                &mut ship,
1323            );
1324
1325            // Single call drains the input (we removed the at_capacity yield).
1326            prop_assert_eq!(position, data.len());
1327
1328            let kept = collect_column(&keep);
1329            let shipped = collect_column(&ship);
1330
1331            // Partition predicate: kept times >= upper, shipped times < upper.
1332            for (_, t, _) in &kept {
1333                prop_assert!(
1334                    upper.borrow().less_equal(t),
1335                    "kept time {} should satisfy upper.less_equal", t,
1336                );
1337            }
1338            for (_, t, _) in &shipped {
1339                prop_assert!(
1340                    !upper.borrow().less_equal(t),
1341                    "shipped time {} should NOT satisfy upper.less_equal", t,
1342                );
1343            }
1344
1345            // Union (multiset) equals input.
1346            let mut union = kept.clone();
1347            Extend::extend(&mut union, shipped.iter().copied());
1348            union.sort();
1349            let mut expected_sorted = data.clone();
1350            expected_sorted.sort();
1351            prop_assert_eq!(union, expected_sorted);
1352
1353            // Frontier dominates every kept time.
1354            for (_, t, _) in &kept {
1355                prop_assert!(
1356                    frontier.less_equal(t),
1357                    "frontier should dominate kept time {}", t,
1358                );
1359            }
1360        }
1361
1362        /// Empty input → no work, frontier untouched, position = 0.
1363        #[mz_ore::test]
1364        #[cfg_attr(miri, ignore)]
1365        fn extract_empty_input(upper_time in 0u64..=4) {
1366            let mut self_col: ColumnBody<Tuple> = Default::default();
1367            let upper = Antichain::from_elem(upper_time);
1368            let mut frontier: Antichain<u64> = Antichain::new();
1369            let mut keep: ColumnBody<Tuple> = Default::default();
1370            let mut ship: ColumnBody<Tuple> = Default::default();
1371            let mut position = 0;
1372
1373            self_col.extract(
1374                &mut position,
1375                upper.borrow(),
1376                &mut frontier,
1377                &mut keep,
1378                &mut ship,
1379            );
1380
1381            prop_assert_eq!(position, 0);
1382            prop_assert!(collect_column(&keep).is_empty());
1383            prop_assert!(collect_column(&ship).is_empty());
1384            prop_assert!(frontier.elements().is_empty());
1385        }
1386    }
1387}