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