Skip to main content

mz_timely_util/columnar/
chunk.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! [`ColumnChunk`]: differential's [`Chunk`] over [`ColumnBody`] updates.
11//!
12//! A chunk is a sorted, consolidated run of `(D, T, R)` updates in the flat
13//! columnar layout, in one of two homes:
14//!
15//! * **Resident**: an `Rc`-shared [`ColumnBody`] on the heap. Fresh input,
16//!   merge output, and small tails live here.
17//! * **Spilled**: the serialized body in the process [`Pool`], with the record
18//!   count and the first and last data items resident. The pool owns residency
19//!   from there, with slots under a memory budget and compression and device
20//!   pageout under pressure, and a body that dies before pressure reaches it
21//!   is freed without I/O.
22//!
23//! Reads of a spilled body are copy-out and scoped to the call that needs
24//! them, the contract that lets the pool evict with no reader accounting
25//! (see [`mz_ore::pool`]).
26//!
27//! Spilling happens in [`Chunk::settle`], the trait's designated commit point:
28//! chunks moved to settled output are handed to the pool while the chunk
29//! type's [`SpillGate`] is open. Grading is by serialized
30//! bytes, the ship size [`Column`] already targets, rather than by the
31//! record-count `TARGET`, since record count does not bound bytes for
32//! variable-width data.
33//!
34//! Chunks whose data is a `(key, val)` pair additionally implement
35//! [`UnloadChunk`], the bulk-read capability: sorted probe keys in, matching
36//! updates appended to caller-owned staging, with `locate` answered from the
37//! resident fence metadata so a probe set faults only the chunk bodies it
38//! actually touches.
39
40use std::borrow::Cow;
41#[cfg(test)]
42use std::cell::Cell;
43use std::cell::RefCell;
44use std::collections::VecDeque;
45use std::marker::PhantomData;
46use std::rc::Rc;
47use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
48use std::sync::{Arc, OnceLock};
49
50use columnar::bytes::indexed;
51use columnar::{Borrow, BorrowedOf, Columnar, Container as _, Index, Len, Push as _};
52use differential_dataflow::difference::Semigroup;
53use differential_dataflow::lattice::Lattice;
54use differential_dataflow::trace::chunk::Chunk;
55use mz_ore::cast::CastFrom;
56use mz_ore::pool::{ChunkHandle, ChunkHints, ExtentCodec, IDENTITY_CODEC, Pool, TypedBody};
57use smallvec::SmallVec;
58use timely::Accountable;
59use timely::PartialOrder;
60use timely::container::{ContainerBuilder, PushInto};
61use timely::progress::Timestamp;
62use timely::progress::frontier::{Antichain, AntichainRef};
63
64use crate::columnar::batcher::{ColumnChunker, gallop};
65use crate::columnar::body::{ColumnBody, borrow_words};
66use crate::columnar::unload::UnloadChunk;
67use crate::columnar::{Column, at_serialized_capacity};
68
69pub mod metrics;
70
71/// The gate of [`ComputeSpill`] chunks. See [`set_compute_spill_enabled`].
72static COMPUTE_SPILL_ENABLED: AtomicBool = AtomicBool::new(false);
73
74/// The gate of [`StorageSpill`] chunks. See [`set_storage_spill_enabled`].
75static STORAGE_SPILL_ENABLED: AtomicBool = AtomicBool::new(false);
76
77/// The gate for bodies spilled through [`try_spill_ref`]. See
78/// [`set_sink_spill_enabled`].
79static SINK_SPILL_ENABLED: AtomicBool = AtomicBool::new(false);
80
81thread_local! {
82    /// A thread-scoped pool override, taking precedence over the global
83    /// enable flag and pool. Lets tests and benches spill through a private
84    /// pool without touching process-global state.
85    static SPILL_OVERRIDE: RefCell<Option<Pool>> = const { RefCell::new(None) };
86
87    /// A thread-scoped depth-floor override, taking precedence over the
88    /// global value. Lets tests pin the floor without racing concurrently
89    /// running tests on the process-global state.
90    #[cfg(test)]
91    static COMPRESS_MIN_DEPTH_OVERRIDE: Cell<Option<u8>> = const { Cell::new(None) };
92
93    /// The same for the floor of bodies spilled through [`try_spill_ref`].
94    #[cfg(test)]
95    static SINK_COMPRESS_MIN_DEPTH_OVERRIDE: Cell<Option<u8>> = const { Cell::new(None) };
96
97    /// Reusable staging for call-scoped reads of spilled bodies.
98    static READ_SCRATCH: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
99}
100
101/// Which process-wide gate decides whether a [`ColumnChunk`] spills.
102///
103/// Compute and storage dataflows share a process and its worker threads, so
104/// the gate is part of the chunk type: each consumer names the gate of the
105/// subsystem that owns it, and one subsystem's flag cannot spill another's
106/// chunks. Every gate takes effect at the next commit, and only once
107/// `apply_pool_config` has installed the pool. With no pool installed chunks
108/// stay resident whatever the gate says.
109pub trait SpillGate: 'static {
110    /// Whether chunks of this gate spill at commit.
111    fn enabled() -> bool;
112}
113
114/// The gate of compute's chunk batchers. See [`set_compute_spill_enabled`].
115pub enum ComputeSpill {}
116
117impl SpillGate for ComputeSpill {
118    fn enabled() -> bool {
119        COMPUTE_SPILL_ENABLED.load(Ordering::Relaxed)
120    }
121}
122
123/// The gate of storage's upsert chunk batchers. See
124/// [`set_storage_spill_enabled`].
125pub enum StorageSpill {}
126
127impl SpillGate for StorageSpill {
128    fn enabled() -> bool {
129        STORAGE_SPILL_ENABLED.load(Ordering::Relaxed)
130    }
131}
132
133/// Enable or disable spilling of [`ComputeSpill`] chunks. Already-spilled
134/// chunks are unaffected either way.
135pub fn set_compute_spill_enabled(enabled: bool) {
136    COMPUTE_SPILL_ENABLED.store(enabled, Ordering::Relaxed);
137}
138
139/// Enable or disable spilling of [`StorageSpill`] chunks. Already-spilled
140/// chunks are unaffected either way.
141pub fn set_storage_spill_enabled(enabled: bool) {
142    STORAGE_SPILL_ENABLED.store(enabled, Ordering::Relaxed);
143}
144
145/// Enable or disable spilling of bodies offered through [`try_spill_ref`],
146/// which is how compute's MV sink correction buffer spills. Like the
147/// [`SpillGate`]s, it takes effect only once `apply_pool_config` has
148/// installed the pool.
149pub fn set_sink_spill_enabled(enabled: bool) {
150    SINK_SPILL_ENABLED.store(enabled, Ordering::Relaxed);
151}
152
153/// Set or unset the pool through which this thread's chunk spills are
154/// routed, taking precedence over the gates and the process pool. `None`
155/// restores the global resolution.
156pub fn set_spill_override(pool: Option<Pool>) {
157    SPILL_OVERRIDE.with(|cell| *cell.borrow_mut() = pool);
158}
159
160/// The youngest generational depth whose spilled bodies are compressed. See
161/// [`set_compress_min_depth`].
162static COMPRESS_MIN_DEPTH: AtomicU8 = AtomicU8::new(DEFAULT_COMPRESS_MIN_DEPTH);
163
164/// Set the youngest generational depth whose spilled bodies are compressed.
165///
166/// A chunk at depth `d` is rewritten (merged, extracted, advanced) with
167/// frequency proportional to `2^-d` under geometric merging, so compressing
168/// a shallow chunk buys a short stay in the pool at the cost of a guaranteed
169/// near-term codec round-trip: the body is encoded only to be read back and
170/// decoded by the next rewrite. Generations below the floor spill under the
171/// identity codec instead: still budgeted and backed like every extent,
172/// but encode and decode are copies. The floor never exempts a body from the
173/// pool, so it cannot grow unbudgeted resident state.
174///
175/// The floor cannot strand a long-lived body uncompressed: a chunk that a
176/// merge carries forward untouched also ages a generation, and its body is
177/// re-spilled under the compressing codec when it crosses the floor (see
178/// `survive_merge`).
179///
180/// `0` compresses every spilled body. Consulted at every commit, so changes
181/// apply to running dataflows.
182pub fn set_compress_min_depth(depth: u8) {
183    COMPRESS_MIN_DEPTH.store(depth, Ordering::Relaxed);
184}
185
186/// Set or unset a thread-scoped depth-floor override, taking precedence over
187/// [`set_compress_min_depth`]. Tests run concurrently and must not race on
188/// the process-global floor.
189#[cfg(test)]
190pub fn set_compress_min_depth_override(depth: Option<u8>) {
191    COMPRESS_MIN_DEPTH_OVERRIDE.with(|cell| cell.set(depth));
192}
193
194/// The depth floor in effect for this thread's commits.
195fn compress_min_depth() -> u8 {
196    #[cfg(test)]
197    if let Some(depth) = COMPRESS_MIN_DEPTH_OVERRIDE.with(|cell| cell.get()) {
198        return depth;
199    }
200    COMPRESS_MIN_DEPTH.load(Ordering::Relaxed)
201}
202
203/// The compression floor of bodies spilled through [`try_spill_ref`]. See
204/// [`set_sink_compress_min_depth`].
205static SINK_COMPRESS_MIN_DEPTH: AtomicU8 = AtomicU8::new(DEFAULT_COMPRESS_MIN_DEPTH);
206
207/// Set the youngest generational depth whose bodies spilled through
208/// [`try_spill_ref`] are compressed. Those bodies take this floor in place of
209/// [`set_compress_min_depth`]'s, with the same meaning.
210///
211/// Applies to bodies spilled after the change. A body already spilled keeps
212/// its codec: the consumer owns its chunks, so no survival re-spills it.
213pub fn set_sink_compress_min_depth(depth: u8) {
214    SINK_COMPRESS_MIN_DEPTH.store(depth, Ordering::Relaxed);
215}
216
217/// Set or unset a thread-scoped override of [`set_sink_compress_min_depth`].
218#[cfg(test)]
219pub fn set_sink_compress_min_depth_override(depth: Option<u8>) {
220    SINK_COMPRESS_MIN_DEPTH_OVERRIDE.with(|cell| cell.set(depth));
221}
222
223/// The sink depth floor in effect for this thread's spills.
224fn sink_compress_min_depth() -> u8 {
225    #[cfg(test)]
226    if let Some(depth) = SINK_COMPRESS_MIN_DEPTH_OVERRIDE.with(|cell| cell.get()) {
227        return depth;
228    }
229    SINK_COMPRESS_MIN_DEPTH.load(Ordering::Relaxed)
230}
231
232/// The codec a body at `depth` stores under, identity below the compression
233/// floor `floor` and lz4 at and past it, paired with whether that codec
234/// compresses. Callers read the floor once and pass it, so the pair cannot
235/// disagree with itself when the floor moves under a concurrent commit.
236fn codec_for_depth(depth: u8, floor: u8) -> (&'static dyn ExtentCodec, bool) {
237    if depth < floor {
238        (&IDENTITY_CODEC, false)
239    } else {
240        (&LZ4_CODEC, true)
241    }
242}
243
244/// The pool a body of `len_bytes` spills into while `enabled`, or `None` when
245/// it stays resident.
246///
247/// The one place the spill decision lives: the thread override, the gate, the
248/// installed pool, and the size floor.
249fn spill_target(enabled: bool, len_bytes: usize) -> Option<Pool> {
250    resolve_pool(enabled).filter(|_| len_bytes >= SPILL_MIN_BYTES)
251}
252
253/// The thread's override pool, else the installed pool while `enabled`.
254fn resolve_pool(enabled: bool) -> Option<Pool> {
255    if let Some(pool) = SPILL_OVERRIDE.with(|cell| cell.borrow().clone()) {
256        return Some(pool);
257    }
258    if enabled {
259        crate::pool_config::active_pool()
260    } else {
261        None
262    }
263}
264
265/// Scratch capacity retained across reads, in words. A read larger than this
266/// releases the buffer afterward, so a thread's scratch does not ratchet to
267/// the largest body it ever carried (heap no pool gauge can see).
268const SCRATCH_RETAIN_WORDS: usize = 1 << 18;
269
270/// Run `f` with this thread's read scratch, cleared of any previous use.
271fn with_scratch<Out>(f: impl FnOnce(&mut Vec<u64>) -> Out) -> Out {
272    READ_SCRATCH.with(|cell| {
273        let mut scratch = cell.take();
274        scratch.clear();
275        let out = f(&mut scratch);
276        if scratch.capacity() > SCRATCH_RETAIN_WORDS {
277            scratch.clear();
278            scratch.shrink_to_fit();
279        }
280        cell.replace(scratch);
281        out
282    })
283}
284
285/// The serialized-byte size committed chunks aim for, matching the ship size
286/// of the columnar merge machinery.
287const COMMIT_BYTES: usize = 2 << 20;
288
289/// Bodies smaller than this stay resident: the pool's smallest size class is
290/// 64 KiB, so spilling below it trades no meaningful memory for slot waste.
291///
292/// Sub-floor bodies are invisible to the pool's budget, which is safe only
293/// while they are rare. `settle` coalesces toward `COMMIT_BYTES` before
294/// committing, so in the harness only a final `done` tail commits below the
295/// floor. A caller that commits many small chunks directly accumulates
296/// unbudgeted heap, and no accounting here would catch it.
297const SPILL_MIN_BYTES: usize = 64 << 10;
298
299/// The default compression depth floor: fresh (depth 0) bodies spill
300/// uncompressed.
301///
302/// A fresh chunk is consumed by its first merge with certainty, so
303/// compressing it can never save pool bytes for longer than one merge
304/// cadence and always costs a full encode plus decode. Depth 1 and beyond
305/// have survived a merge and wait geometrically longer for the next, so
306/// their compression amortizes.
307const DEFAULT_COMPRESS_MIN_DEPTH: u8 = 1;
308
309/// Records of a body with `len` records in `bytes` that fit in `space`
310/// bytes at the body's average width, keeping 5% of `COMMIT_BYTES` as a
311/// margin for per-piece framing. Uniform rows cut this way fill their size
312/// class and leave one short remainder that `settle` can coalesce. Uneven
313/// widths can still overflow, so callers check the cut piece.
314fn cut_records(len: usize, bytes: usize, space: usize) -> usize {
315    let space = space.saturating_sub(COMMIT_BYTES / 20);
316    (len.saturating_mul(space) / bytes.max(1)).min(len)
317}
318
319/// Whether a body is big enough to commit on its own.
320fn at_commit_size<C: Columnar>(body: &ColumnBody<C>) -> bool {
321    body.length_in_bytes() >= COMMIT_BYTES - COMMIT_BYTES / 10
322}
323
324/// Narrow a columnar ref to a shorter lifetime, so refs from different
325/// borrows, such as a probe column and a chunk's own columns, can be compared
326/// (the refs are lifetime-invariant).
327#[inline(always)]
328fn rr<'b, 'a: 'b, C: Columnar>(item: columnar::Ref<'a, C>) -> columnar::Ref<'b, C> {
329    columnar::ContainerOf::<C>::reborrow_ref(item)
330}
331
332/// A spilled chunk body: the serialized column in the pool, plus the resident
333/// metadata every [`Chunk`] must answer without fetching. That metadata is
334/// the record count, the first and last data items (the fence entries
335/// [`UnloadChunk::locate`] consults), and the time bounds `extract` consults
336/// to pass frontier-disjoint chunks through without loading them.
337pub struct SpilledBody<D: Columnar, T, G> {
338    /// Number of updates in the body.
339    records: usize,
340    /// The first and last data items, as a two-element container. One
341    /// container rather than two singletons, so the leaf allocations are not
342    /// duplicated per fence.
343    fences: D::Container,
344    /// The minimal and maximal times in the body, shared with the pooled
345    /// body and filled on first use (see [`PooledBody`]). The minimal times
346    /// fold into `extract`'s residual frontier when the chunk is kept whole.
347    /// Some contained time is greater-or-equal to a frontier exactly when
348    /// some maximal time is, which is `extract`'s ship-whole test.
349    time_bounds: Arc<OnceLock<TimeBounds<T>>>,
350    /// Whether the body was inserted under the compressing codec. The pool
351    /// stores the codec itself and reads decode through it, so this is the
352    /// only handle chunk code has on what a body is stored as, and it is
353    /// what `survive_merge` consults to decide a body wants migrating.
354    /// Deriving that from depth instead would tie it to a single transition
355    /// and miss every path that skips it.
356    compressed: bool,
357    /// The body's serialized size, as it was before the pool's codec saw
358    /// it. Retained because the pool reports no per-chunk figure, and a
359    /// chunk that reported nothing would drop its operator's share of the
360    /// batcher's memory out of the introspection tables.
361    len_bytes: usize,
362    /// The pool chunk holding the serialized column.
363    handle: ChunkHandle,
364    /// Carries the chunk's [`SpillGate`], which the resident variant has no
365    /// field to hold.
366    gate: PhantomData<G>,
367}
368
369/// A sorted, consolidated run of `(D, T, R)` updates, resident or spilled.
370///
371/// Every chunk carries a generational depth counting the merge cadences it
372/// has lived through: fresh chunks are depth 0, a merge output is one
373/// generation past its deepest input (saturating at `u8::MAX`, where
374/// remerged long-lived chunks stay), a chunk a merge carries forward
375/// untouched also gains a generation (see `survive_merge`), and rewrites
376/// within a generation (extract, advance, settle coalescing) preserve
377/// depth.
378///
379/// Depth belongs to the chunk, not to the body: a body outlives the chunks
380/// that share it, and aging must not depend on whether a caller happens to
381/// hold the only reference. At spill time the depth becomes the pool's
382/// [`ChunkHints`], so repeatedly merged (older, colder) data lands in deeper
383/// eviction bands. Hints are fixed at insert, so a chunk aged without a
384/// re-spill keeps the band it spilled into.
385///
386/// `G` is the [`SpillGate`] that decides whether commits spill.
387pub enum ColumnChunk<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> {
388    /// Body on the heap, shared via `Rc`, with its generational depth.
389    Resident(Rc<ColumnBody<(D, T, R)>>, u8),
390    /// Body in the pool, with its generational depth. See [`SpilledBody`].
391    Spilled(Rc<SpilledBody<D, T, G>>, u8),
392}
393
394impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Clone for ColumnChunk<D, T, R, G> {
395    fn clone(&self) -> Self {
396        match self {
397            ColumnChunk::Resident(col, depth) => ColumnChunk::Resident(Rc::clone(col), *depth),
398            ColumnChunk::Spilled(body, depth) => ColumnChunk::Spilled(Rc::clone(body), *depth),
399        }
400    }
401}
402
403impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Default for ColumnChunk<D, T, R, G> {
404    fn default() -> Self {
405        ColumnChunk::Resident(Rc::new(ColumnBody::default()), 0)
406    }
407}
408
409impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Accountable for ColumnChunk<D, T, R, G> {
410    fn record_count(&self) -> i64 {
411        i64::try_from(self.records()).expect("record count fits i64")
412    }
413}
414
415impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> ColumnChunk<D, T, R, G> {
416    /// Wrap a sorted, consolidated, non-empty body as a resident chunk of
417    /// the youngest generation.
418    pub fn from_body(body: ColumnBody<(D, T, R)>) -> Self {
419        mz_ore::soft_assert_no_log!(!body.is_empty(), "chunks must be non-empty");
420        ColumnChunk::Resident(Rc::new(body), 0)
421    }
422
423    /// Append pieces of at most `COMMIT_BYTES`, preserving order and
424    /// generational depth. A single update may exceed the bound because it
425    /// cannot be split.
426    fn push_bounded(body: ColumnBody<(D, T, R)>, depth: u8, out: &mut VecDeque<Self>) {
427        let len = body.len();
428        let bytes = body.length_in_bytes();
429        if len <= 1 || bytes <= COMMIT_BYTES {
430            if len > 0 {
431                out.push_back(Self::Resident(Rc::new(body), depth));
432            }
433            return;
434        }
435        Self::push_cuts(
436            &body,
437            cut_records(len, bytes, COMMIT_BYTES).max(1),
438            depth,
439            out,
440        );
441    }
442
443    /// Append `body` in consecutive pieces of `records` records. A piece
444    /// that still exceeds `COMMIT_BYTES`, from uneven widths, is halved until
445    /// it fits or holds one record. Halving bounds the recursion depth by
446    /// log2 of `records`, where cutting again at the piece's own average
447    /// width can shrink a piece holding one wide record by only a few
448    /// percent per level.
449    fn push_cuts(
450        body: &ColumnBody<(D, T, R)>,
451        records: usize,
452        depth: u8,
453        out: &mut VecDeque<Self>,
454    ) {
455        let view = body.borrow();
456        Self::push_range(view, 0..view.len(), records, depth, out);
457    }
458
459    /// [`Self::push_cuts`] over `range` of `view`. An oversized piece is
460    /// dropped before descending, and the halves are cut again from `view`,
461    /// so transient memory is one piece rather than one copy of a wide
462    /// update per level.
463    fn push_range(
464        view: BorrowedOf<'_, (D, T, R)>,
465        range: std::ops::Range<usize>,
466        records: usize,
467        depth: u8,
468        out: &mut VecDeque<Self>,
469    ) {
470        let mut start = range.start;
471        while start < range.end {
472            let end = range.end.min(start + records);
473            let mut part = <(D, T, R) as Columnar>::Container::default();
474            part.extend_from_self(view, start..end);
475            let part = ColumnBody::Typed(part);
476            if end - start > 1 && part.length_in_bytes() > COMMIT_BYTES {
477                drop(part);
478                Self::push_range(view, start..end, (end - start).div_ceil(2), depth, out);
479            } else {
480                out.push_back(Self::Resident(Rc::new(part), depth));
481            }
482            start = end;
483        }
484    }
485
486    /// The body, owned. A spilled body is copied out of the pool within this
487    /// call. A shared resident body is copied in its current form.
488    pub fn into_body(self) -> ColumnBody<(D, T, R)> {
489        match self {
490            ColumnChunk::Resident(col, _) => {
491                Rc::try_unwrap(col).unwrap_or_else(|shared| shared.duplicate())
492            }
493            ColumnChunk::Spilled(body, _) => match Rc::try_unwrap(body) {
494                Ok(spilled) => match spilled.handle.take_typed() {
495                    Ok(typed) => {
496                        typed
497                            .into_any()
498                            .downcast::<PooledBody<D, T, R>>()
499                            .expect("chunk bodies are pooled as `PooledBody`")
500                            .body
501                    }
502                    Err(handle) => read_words(&handle),
503                },
504                // A shared body is duplicated in its current form, as a
505                // shared resident body is.
506                Err(shared) => shared.handle.with_typed(|typed| match typed {
507                    Some(typed) => pooled::<D, T, R>(typed).body.duplicate(),
508                    None => read_words(&shared.handle),
509                }),
510            },
511        }
512    }
513
514    /// The body for the duration of `f`: a resident body is borrowed, a
515    /// spilled body is loaded from the pool for the call and dropped after it.
516    pub fn with_body<F, X>(&self, f: F) -> X
517    where
518        F: FnOnce(&ColumnBody<(D, T, R)>) -> X,
519    {
520        match self {
521            ColumnChunk::Resident(col, _) => f(col),
522            ColumnChunk::Spilled(body, _) => {
523                let mut f = Some(f);
524                let borrowed = body.handle.with_typed(|typed| {
525                    typed.map(|typed| f.take().expect("unused")(&pooled::<D, T, R>(typed).body))
526                });
527                match borrowed {
528                    Some(out) => out,
529                    None => f.take().expect("unused")(&read_words(&body.handle)),
530                }
531            }
532        }
533    }
534
535    /// True when the body lives in the pool.
536    pub fn is_spilled(&self) -> bool {
537        matches!(self, ColumnChunk::Spilled(_, _))
538    }
539
540    /// The number of updates, from resident state only.
541    fn records(&self) -> usize {
542        match self {
543            ColumnChunk::Resident(col, _) => col.len(),
544            ColumnChunk::Spilled(body, _) => body.records,
545        }
546    }
547
548    /// The generational depth, from resident state only.
549    fn depth(&self) -> u8 {
550        match self {
551            ColumnChunk::Resident(_, depth) | ColumnChunk::Spilled(_, depth) => *depth,
552        }
553    }
554
555    /// The first and last data items, from resident state only.
556    fn data_span(&self) -> (columnar::Ref<'_, D>, columnar::Ref<'_, D>) {
557        match self {
558            ColumnChunk::Resident(col, _) => {
559                let data = col.borrow().0;
560                (data.get(0), data.get(data.len() - 1))
561            }
562            ColumnChunk::Spilled(body, _) => {
563                let fences = body.fences.borrow();
564                (fences.get(0), fences.get(1))
565            }
566        }
567    }
568
569    /// Commit a non-empty body at the given generational depth: spill it to
570    /// the pool when `G` is open and the body is worth a slot, else keep it
571    /// resident.
572    fn commit(body: ColumnBody<(D, T, R)>, depth: u8) -> Self
573    where
574        D: PoolColumnar,
575        T: Timestamp + PoolColumnar,
576        R: PoolColumnar,
577    {
578        let len_bytes = body.length_in_bytes();
579        metrics::record(metrics::Stage::Commit, body.len(), len_bytes);
580        mz_ore::soft_assert_no_log!(!body.is_empty(), "chunks must be non-empty");
581        match spill_target(G::enabled(), len_bytes) {
582            Some(pool) => Self::spill_body(body, &pool, depth),
583            None => ColumnChunk::Resident(Rc::new(body), depth),
584        }
585    }
586
587    /// Spill a non-empty body into `pool` unconditionally, capturing the
588    /// resident fence metadata.
589    ///
590    /// Generations below the compression depth floor store under the
591    /// identity codec: rewritten too soon for compression to amortize, they
592    /// stay budgeted and backed while encode and decode reduce to
593    /// copies.
594    fn spill_body(body: ColumnBody<(D, T, R)>, pool: &Pool, depth: u8) -> Self
595    where
596        D: PoolColumnar,
597        T: Timestamp + PoolColumnar,
598        R: PoolColumnar,
599    {
600        let (codec, compressed) = codec_for_depth(depth, compress_min_depth());
601        let len_bytes = body.length_in_bytes();
602        let view = body.borrow();
603        let records = view.len();
604        let mut fences = D::Container::default();
605        fences.push(view.0.get(0));
606        fences.push(view.0.get(records - 1));
607        let time_bounds = Arc::new(OnceLock::new());
608        let pooled = PooledBody {
609            body,
610            bounds: Arc::clone(&time_bounds),
611            compute: |body| {
612                let (lower, upper) = Self::time_bounds(body);
613                (lower, upper.into())
614            },
615        };
616        let handle = pool.insert_typed(Box::new(pooled), ChunkHints { depth }, codec);
617        ColumnChunk::Spilled(
618            Rc::new(SpilledBody {
619                records,
620                fences,
621                time_bounds,
622                compressed,
623                len_bytes,
624                handle,
625                gate: PhantomData,
626            }),
627            depth,
628        )
629    }
630
631    /// Age a chunk that a merge carried forward untouched by one generation.
632    /// Depth counts merge cadences lived through, not rewrites, so a
633    /// pass-through survivor ages like a merged chunk; the bump rides on the
634    /// chunk, so it is free whether or not the body is shared.
635    ///
636    /// An identity-coded body at or past the floor wants migrating, so a
637    /// sole owner re-spills it compressed; without the re-spill,
638    /// key-disjoint input would keep its whole spilled backlog
639    /// identity-coded for as long as it lived. The test is the body's stored
640    /// codec against the floor, not a depth transition, so a migration that
641    /// cannot happen now (a shared body, no pool installed, a floor lowered
642    /// long after the spill) is retried at the next survival rather than
643    /// consumed. A shared body is skipped because re-spilling this reference
644    /// cannot change what the other holder stores, and the compaction merger
645    /// that shares bodies rewrites its clones immediately.
646    fn survive_merge(self) -> Self
647    where
648        D: PoolColumnar,
649        T: Timestamp + PoolColumnar,
650        R: PoolColumnar,
651    {
652        let depth = self.depth().saturating_add(1);
653        match self {
654            ColumnChunk::Resident(col, _) => ColumnChunk::Resident(col, depth),
655            ColumnChunk::Spilled(body, was) => {
656                let migrate = !body.compressed && depth >= compress_min_depth();
657                if !migrate || Rc::strong_count(&body) > 1 {
658                    return ColumnChunk::Spilled(body, depth);
659                }
660                match resolve_pool(G::enabled()) {
661                    Some(pool) => {
662                        let body = ColumnChunk::Spilled(body, was).into_body();
663                        Self::spill_body(body, &pool, depth)
664                    }
665                    None => ColumnChunk::Spilled(body, depth),
666                }
667            }
668        }
669    }
670
671    /// The chunk's time bounds: borrowed from the stored metadata for
672    /// spilled bodies, computed by a time-column scan for resident ones. The
673    /// scan costs less than the copy it lets `extract` avoid when the chunk
674    /// passes through whole.
675    fn chunk_time_bounds(&self) -> (Cow<'_, Antichain<T>>, Cow<'_, [T]>)
676    where
677        T: Timestamp,
678    {
679        match self {
680            ColumnChunk::Resident(col, _) => {
681                let (lower, upper) = Self::time_bounds(col);
682                (Cow::Owned(lower), Cow::Owned(upper))
683            }
684            ColumnChunk::Spilled(body, _) => {
685                // Eviction serializes the body under the chunk's state lock
686                // and fills the bounds cell from there, so the lock order is
687                // state lock, then cell. Taking the state lock from inside
688                // the cell's initializer deadlocks against an evictor.
689                if body.time_bounds.get().is_none() {
690                    let filled = body.handle.with_typed(|typed| {
691                        typed
692                            .map(|typed| pooled::<D, T, R>(typed).bounds())
693                            .is_some()
694                    });
695                    // Leaving the typed form fills the bounds, so this is
696                    // reached only by bodies spilled some other way.
697                    if !filled {
698                        let (lower, upper) = Self::time_bounds(&read_words(&body.handle));
699                        let _ = body.time_bounds.set((lower, upper.into()));
700                    }
701                }
702                let (lower, upper) = body.time_bounds.get().expect("time bounds filled above");
703                (Cow::Borrowed(lower), Cow::Borrowed(&upper[..]))
704            }
705        }
706    }
707
708    /// The time bounds of a non-empty body: the antichain of minimal times
709    /// (every contained time is greater-or-equal to some element) and the
710    /// set of maximal times (some contained time is greater-or-equal to a
711    /// frontier exactly when some maximal one is).
712    fn time_bounds(body: &ColumnBody<(D, T, R)>) -> (Antichain<T>, Vec<T>)
713    where
714        T: Timestamp,
715    {
716        let (_, times, _) = body.borrow();
717        let mut lower = Antichain::new();
718        let mut upper: Vec<T> = Vec::new();
719        // One owned time reused across the scan, so times with owned
720        // allocations do not allocate per element; the bound sets clone only
721        // the elements they retain.
722        let mut time = T::minimum();
723        for i in 0..times.len() {
724            time.copy_from(rr::<T>(times.get(i)));
725            if !upper.iter().any(|u| PartialOrder::less_equal(&time, u)) {
726                upper.retain(|u| !PartialOrder::less_equal(u, &time));
727                upper.push(time.clone());
728            }
729            lower.insert_ref(&time);
730        }
731        (lower, upper)
732    }
733}
734
735/// The chunk-side [`ExtentCodec`]: a little-endian `u32` body-length prefix
736/// followed by one lz4 block, the framing
737/// `lz4_flex::block::compress_prepend_size` produces. Every chunk consumer
738/// passes [`LZ4_CODEC`] at insert; the pool itself has no codec opinion.
739#[derive(Debug)]
740pub struct Lz4Codec;
741
742/// The [`Lz4Codec`] instance chunk consumers pass to
743/// [`Pool::insert_with`].
744pub static LZ4_CODEC: Lz4Codec = Lz4Codec;
745
746impl ExtentCodec for Lz4Codec {
747    fn encode(&self, body: &[u8], out: &mut Vec<u8>) {
748        let max_out = lz4_flex::block::get_maximum_output_size(body.len());
749        out.resize(4 + max_out, 0);
750        let len = u32::try_from(body.len()).expect("chunk bodies are bounded by the size classes");
751        out[..4].copy_from_slice(&len.to_le_bytes());
752        let compressed = lz4_flex::block::compress_into(body, &mut out[4..])
753            .expect("output sized to the maximum");
754        out.truncate(4 + compressed);
755    }
756
757    fn decode(&self, stored: &[u8], body: &mut [u8]) {
758        let prefix: [u8; 4] = stored[..4].try_into().expect("prefix length");
759        let len = usize::try_from(u32::from_le_bytes(prefix)).expect("length fits usize");
760        assert_eq!(
761            len,
762            body.len(),
763            "destination must match the encoded body length"
764        );
765        let written = lz4_flex::block::decompress_into(&stored[4..], body)
766            .expect("stored bytes hold a valid lz4 block");
767        assert_eq!(written, body.len(), "decoded length mismatch");
768    }
769}
770
771/// A spilled chunk's time bounds: the antichain of minimal times and the set
772/// of maximal times (see `ColumnChunk::time_bounds`).
773type TimeBounds<T> = (Antichain<T>, SmallVec<[T; 1]>);
774
775/// A columnar type a spilled chunk can hold in its typed form. Spill threads serialize and drop
776/// typed bodies, so the containers must be `Send`. The pooled body shares its time bounds with
777/// the chunk through an `Arc`, so the values must also be `Sync`.
778pub trait PoolColumnar: Columnar<Container: Send> + Send + Sync {}
779
780impl<C: Columnar<Container: Send> + Send + Sync> PoolColumnar for C {}
781
782/// A [`ColumnBody`] as the pool holds it: in its typed form until the pool
783/// has to serialize it.
784///
785/// The time bounds are computed on first use and shared with the chunk's
786/// [`SpilledBody`]. Serialization fills them before the typed form can be
787/// dropped, so a chunk that has left its typed form never needs a decode to
788/// answer `extract`'s pass-through test.
789struct PooledBody<D: Columnar, T: Columnar, R: Columnar> {
790    body: ColumnBody<(D, T, R)>,
791    bounds: Arc<OnceLock<TimeBounds<T>>>,
792    compute: fn(&ColumnBody<(D, T, R)>) -> TimeBounds<T>,
793}
794
795impl<D: Columnar, T: Columnar, R: Columnar> PooledBody<D, T, R> {
796    fn bounds(&self) -> &TimeBounds<T> {
797        self.bounds.get_or_init(|| (self.compute)(&self.body))
798    }
799}
800
801impl<D: Columnar, T: Columnar, R: Columnar> std::fmt::Debug for PooledBody<D, T, R> {
802    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
803        f.debug_struct("PooledBody")
804            .field("len_bytes", &self.body.length_in_bytes())
805            .finish()
806    }
807}
808
809impl<D: PoolColumnar + 'static, T: PoolColumnar + 'static, R: PoolColumnar + 'static> TypedBody
810    for PooledBody<D, T, R>
811{
812    fn words(&self) -> usize {
813        self.body.length_in_bytes() / 8
814    }
815
816    fn serialize_into(&self, dst: &mut [u64]) {
817        self.bounds();
818        let len_bytes = self.body.length_in_bytes();
819        let bytes: &mut [u8] = bytemuck::cast_slice_mut(dst);
820        let mut cursor = std::io::Cursor::new(bytes);
821        self.body
822            .write_into(&mut cursor)
823            .expect("the destination is sized to the serialized body");
824        assert_eq!(
825            usize::try_from(cursor.position()).expect("usize position"),
826            len_bytes,
827            "serialized body must fill the destination exactly",
828        );
829    }
830
831    fn as_any(&self) -> &dyn std::any::Any {
832        self
833    }
834
835    fn into_any(self: Box<Self>) -> Box<dyn std::any::Any> {
836        self
837    }
838}
839
840/// A copy of a spilled body, in serialized form.
841fn read_words<C: Columnar>(handle: &ChunkHandle) -> ColumnBody<C> {
842    let mut words = Vec::new();
843    handle.read_into(&mut words);
844    ColumnBody::Words(words)
845}
846
847/// The [`PooledBody`] a chunk's typed body is.
848fn pooled<D: Columnar + 'static, T: Columnar + 'static, R: Columnar + 'static>(
849    typed: &dyn TypedBody,
850) -> &PooledBody<D, T, R> {
851    typed
852        .as_any()
853        .downcast_ref::<PooledBody<D, T, R>>()
854        .expect("chunk bodies are pooled as `PooledBody`")
855}
856
857/// Serialize a body into a pool slot, writing its serialized form through a cursor over the
858/// slot memory. A serialized body's encoding is one copy. Sizing is exact, so a short or
859/// overlong write is a contract violation and panics.
860fn spill_serialized<C: Columnar>(
861    body: &ColumnBody<C>,
862    pool: &Pool,
863    len_bytes: usize,
864    hints: ChunkHints,
865    codec: &'static dyn ExtentCodec,
866) -> ChunkHandle {
867    mz_ore::soft_assert_eq_no_log!(len_bytes % 8, 0);
868    pool.insert_with(len_bytes / 8, hints, codec, |dst| {
869        let bytes: &mut [u8] = bytemuck::cast_slice_mut(dst);
870        let mut cursor = std::io::Cursor::new(bytes);
871        body.write_into(&mut cursor)
872            .expect("the slot is sized to the serialized body");
873        assert_eq!(
874            usize::try_from(cursor.position()).expect("usize position"),
875            len_bytes,
876            "serialized body must fill the chunk exactly",
877        );
878    })
879}
880
881/// Spill a serialized copy of `body` into the process pool, leaving `body` untouched, or
882/// `None` when the body stays resident.
883///
884/// A body stays resident when the gate [`set_sink_spill_enabled`] sets is off, when no pool is
885/// installed, or when it is smaller than `SPILL_MIN_BYTES`. `depth` is the body's generational
886/// depth: against the floor [`set_sink_compress_min_depth`] sets, it selects the stored codec,
887/// and it selects the pool's eviction band.
888///
889/// For consumers that keep their own chunk representation and so cannot use [`ColumnChunk`];
890/// the two share the spill decision through `spill_target`. The encode writes straight into
891/// the pool slot, so a spilled body costs no intermediate allocation and the caller can
892/// [`ColumnBody::clear`] and keep its allocation. A caller that gets `None` back still owns
893/// the body and must keep it resident itself.
894pub fn try_spill_ref<C: Columnar>(body: &ColumnBody<C>, depth: u8) -> Option<ChunkHandle> {
895    let len_bytes = body.length_in_bytes();
896    let pool = spill_target(SINK_SPILL_ENABLED.load(Ordering::Relaxed), len_bytes)?;
897    let (codec, _) = codec_for_depth(depth, sink_compress_min_depth());
898    Some(spill_serialized(
899        body,
900        &pool,
901        len_bytes,
902        ChunkHints { depth },
903        codec,
904    ))
905}
906
907impl<D, T, R, G> Chunk for ColumnChunk<D, T, R, G>
908where
909    G: SpillGate,
910    D: PoolColumnar,
911    for<'a> columnar::Ref<'a, D>: Copy + Ord,
912    T: PoolColumnar + Default + Timestamp + Lattice + Ord,
913    for<'a> columnar::Ref<'a, T>: Copy + Ord,
914    R: PoolColumnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
915{
916    type Time = T;
917
918    /// A nominal record count for the harness's fuel and ladder accounting,
919    /// not a bound. Actual chunk sizing is by serialized bytes: `merge` and
920    /// `extract` cut output at the [`Column`] ship threshold, and `settle`
921    /// grades by `at_commit_size`, so a chunk of narrow records can hold more
922    /// records than this and nothing here consults it.
923    const TARGET: usize = 65536;
924
925    fn len(&self) -> usize {
926        self.records()
927    }
928
929    /// [`ColumnBody::merge_from`] does the work: gallop bulk-copies for disjoint
930    /// runs, semigroup consolidation on equal `(data, time)`, output cut at
931    /// the ship threshold.
932    ///
933    /// Fronts whose data ranges are disjoint never load at all: the resident
934    /// fence entries decide, and the lower front moves to the output whole.
935    fn merge(in1: &mut VecDeque<Self>, in2: &mut VecDeque<Self>, out: &mut VecDeque<Self>) {
936        // Disjoint fast path: when one front lies strictly below the other's
937        // first data item (equal boundary data could still interleave on
938        // time), the merged prefix through the shared horizon is exactly that
939        // front, unchanged.
940        let (a_first, a_last) = in1
941            .front()
942            .expect("caller guarantees non-empty input")
943            .data_span();
944        let (b_first, b_last) = in2
945            .front()
946            .expect("caller guarantees non-empty input")
947            .data_span();
948        let a_low = rr::<D>(a_last) < rr::<D>(b_first);
949        let b_low = rr::<D>(b_last) < rr::<D>(a_first);
950        if a_low {
951            let chunk = in1.pop_front().expect("front observed above");
952            out.push_back(chunk.survive_merge());
953            return;
954        }
955        if b_low {
956            let chunk = in2.pop_front().expect("front observed above");
957            out.push_back(chunk.survive_merge());
958            return;
959        }
960
961        let a = in1.pop_front().expect("caller guarantees non-empty input");
962        let b = in2.pop_front().expect("caller guarantees non-empty input");
963        // Merged output is one generation past its deepest input. A survivor
964        // (untouched or rewritten from its remainder) keeps its own depth.
965        let depths = [a.depth(), b.depth()];
966        let out_depth = depths[0].max(depths[1]).saturating_add(1);
967        // A spilled side keeps its body so an untouched survivor returns
968        // without a rewrite. A typed-resident body is cheaper to take out
969        // and re-insert than to duplicate, which keeping it shared would
970        // force on `into_body`.
971        let keep = |chunk: &Self| match chunk {
972            ColumnChunk::Spilled(body, _) if !body.handle.is_typed() => Some(Rc::clone(body)),
973            _ => None,
974        };
975        let respill = [a.is_spilled(), b.is_spilled()];
976        let mut spill_a = keep(&a);
977        let mut spill_b = keep(&b);
978        let mut cols = [a.into_body(), b.into_body()];
979        let mut positions = [0usize, 0usize];
980        loop {
981            let mut result: ColumnBody<(D, T, R)> = ColumnBody::default();
982            let yielded = result.merge_from(&mut cols, &mut positions);
983            if !result.is_empty() {
984                out.push_back(ColumnChunk::Resident(Rc::new(result), out_depth));
985            }
986            if !yielded {
987                break;
988            }
989        }
990        // The disjoint fast paths above move fronts without reading a row, so
991        // only this path counts as merge work.
992        metrics::record(metrics::Stage::Merge, positions[0] + positions[1], 0);
993        let [col_a, col_b] = &mut cols;
994        // Per input side: the loaded column and the merge's consumed position
995        // within it, the side's pre-merge depth, its original spilled body
996        // when it had one, and the deque a survivor returns to.
997        for (col, pos, depth, spilled, respill, queue) in [
998            (
999                col_a,
1000                positions[0],
1001                depths[0],
1002                &mut spill_a,
1003                respill[0],
1004                in1,
1005            ),
1006            (
1007                col_b,
1008                positions[1],
1009                depths[1],
1010                &mut spill_b,
1011                respill[1],
1012                in2,
1013            ),
1014        ] {
1015            let len = col.len();
1016            if pos == 0 && len > 0 {
1017                // Untouched survivor: restore it as it was (the loaded copy
1018                // is dropped), aged one generation by its survival.
1019                let chunk = match spilled.take() {
1020                    Some(body) => ColumnChunk::Spilled(body, depth).survive_merge(),
1021                    // A body taken out of the pool goes back in.
1022                    None if respill => Self::commit(std::mem::take(col), depth.saturating_add(1)),
1023                    None => {
1024                        ColumnChunk::Resident(Rc::new(std::mem::take(col)), depth).survive_merge()
1025                    }
1026                };
1027                queue.push_front(chunk);
1028            } else if pos < len {
1029                let view = col.borrow();
1030                let mut rest = <(D, T, R) as Columnar>::Container::default();
1031                rest.extend_from_self(view, pos..len);
1032                queue.push_front(ColumnChunk::Resident(
1033                    Rc::new(ColumnBody::Typed(rest)),
1034                    depth,
1035                ));
1036            }
1037        }
1038    }
1039
1040    /// Partition one front chunk by `frontier`, folding kept times into
1041    /// `residual`. One chunk per call, so the harness settles both sides
1042    /// between chunks. Output is cut at the ship threshold.
1043    fn extract(
1044        input: &mut VecDeque<Self>,
1045        frontier: AntichainRef<T>,
1046        residual: &mut timely::progress::Antichain<T>,
1047        keep: &mut VecDeque<Self>,
1048        ship: &mut VecDeque<Self>,
1049    ) {
1050        let Some(chunk) = input.pop_front() else {
1051            return;
1052        };
1053        // Whole-chunk pass-through from the resident time bounds: a chunk
1054        // the frontier is entirely past ships unchanged, one entirely at or
1055        // past the frontier keeps unchanged. Spilled bodies pass through
1056        // without a load, a re-commit, or any codec work; only chunks the
1057        // frontier actually splits are loaded below.
1058        let (time_lower, time_upper) = chunk.chunk_time_bounds();
1059        if time_upper.iter().all(|t| !frontier.less_equal(t)) {
1060            ship.push_back(chunk);
1061            return;
1062        }
1063        if time_lower.elements().iter().all(|m| frontier.less_equal(m)) {
1064            // The residual must lower-bound every kept time, which is the
1065            // chunk's lower bound antichain by construction.
1066            for m in time_lower.elements() {
1067                residual.insert_ref(m);
1068            }
1069            keep.push_back(chunk);
1070            return;
1071        }
1072        // Partitioning rewrites within a generation, so both sides keep the
1073        // input chunk's depth.
1074        let depth = chunk.depth();
1075        let mut col = chunk.into_body();
1076        let len = col.len();
1077        let mut pos = 0;
1078        let mut keep_col: ColumnBody<(D, T, R)> = ColumnBody::default();
1079        let mut ship_col: ColumnBody<(D, T, R)> = ColumnBody::default();
1080        // TODO: rewrite the underlying `ColumnBody::extract` as two passes, the
1081        // time column first to find run boundaries, then bulk per-range
1082        // copies of the remaining leaves.
1083        // Move a side's accumulation to its queue, at the ship threshold
1084        // mid-loop, or any non-empty remainder at the end.
1085        let cut = |col: &mut ColumnBody<(D, T, R)>, queue: &mut VecDeque<Self>, force: bool| {
1086            if !col.is_empty() && (force || at_serialized_capacity(&col.borrow())) {
1087                queue.push_back(ColumnChunk::Resident(Rc::new(std::mem::take(col)), depth));
1088            }
1089        };
1090        while pos < len {
1091            col.extract(&mut pos, frontier, residual, &mut keep_col, &mut ship_col);
1092            if pos < len {
1093                cut(&mut keep_col, keep, false);
1094                cut(&mut ship_col, ship, false);
1095            }
1096        }
1097        cut(&mut keep_col, keep, true);
1098        cut(&mut ship_col, ship, true);
1099    }
1100
1101    /// Advance times by `frontier` and consolidate, withholding the trailing
1102    /// `D` group as the carry unless `done` (its updates may continue in input
1103    /// this call has not seen).
1104    ///
1105    /// The input concatenates into the carry's container, so a group that
1106    /// grows across many calls is appended to, not rebuilt. Each record is
1107    /// copied once on arrival, keeping the run linear. Advancing is
1108    /// lattice-monotone but not order-monotone, so each group's advanced
1109    /// times are re-sorted before adjacent equal times fold.
1110    fn advance(
1111        input: &mut VecDeque<Self>,
1112        frontier: AntichainRef<T>,
1113        done: bool,
1114        out: &mut VecDeque<Self>,
1115    ) {
1116        let Some(front) = input.pop_front() else {
1117            return;
1118        };
1119        // Advancing rewrites within a generation, so output and carry keep
1120        // the deepest input depth. Only merges increment.
1121        let mut depth = front.depth();
1122        // Concatenate the input into one body, reusing the front chunk's
1123        // storage when it is exclusively owned (the usual case: it is last
1124        // call's carry).
1125        let mut base = front.into_body();
1126        {
1127            let base_c = base.typed_mut();
1128            for chunk in input.drain(..) {
1129                depth = depth.max(chunk.depth());
1130                let col = chunk.into_body();
1131                let view = col.borrow();
1132                base_c.extend_from_self(view, 0..view.len());
1133            }
1134        }
1135        let view = base.borrow();
1136        let total = view.len();
1137        if total == 0 {
1138            return;
1139        }
1140        let data = view.0;
1141
1142        // Giant-group early-out: if the whole input is one `D` group, nothing
1143        // is provably complete. Unless `done`, push it all back as the carry.
1144        if !done && data.get(0) == data.get(total - 1) {
1145            input.push_front(ColumnChunk::Resident(Rc::new(base), depth));
1146            return;
1147        }
1148
1149        // The processing bound: everything, or everything before the trailing
1150        // `D` group when it must be withheld.
1151        let end = if done {
1152            total
1153        } else {
1154            let last = data.get(total - 1);
1155            let mut end = total - 1;
1156            while end > 0 && data.get(end - 1) == last {
1157                end -= 1;
1158            }
1159            end
1160        };
1161        // Count only the rows this call advances. The withheld carry is
1162        // counted by the call that finally processes it, so a group spanning
1163        // many calls counts once.
1164        metrics::record(metrics::Stage::Advance, end, 0);
1165
1166        let mut result = <(D, T, R) as Columnar>::Container::default();
1167        // Per-group scratch: advanced owned times with owned diffs.
1168        let mut scratch: Vec<(T, R)> = Vec::new();
1169        let mut index = 0;
1170        // Cut output at the commit size, checked amortized by emitted records
1171        // (the size test walks the container's leaves, so probing it per
1172        // record would be quadratic). Records, not groups: a single group may
1173        // carry arbitrarily many advanced times, and a cut is legal anywhere
1174        // in the sorted sequence, so bounding by records keeps the largest
1175        // possible output chunk within one check period of the target. It
1176        // must not outgrow the pool's largest size class, past which a body
1177        // degrades to a permanently resident heap chunk.
1178        const CUT_CHECK_RECORDS: usize = 1024;
1179        let mut records_since_check = 0usize;
1180        // TODO: the output leaves are addressed independently, so a group
1181        // that folds nothing (no time collisions, no zeroed diffs) could bulk
1182        // `extend_from_self` the D leaf over the whole group range and push
1183        // only the advanced times and diffs per record, and a singleton group
1184        // (the common case for mostly-unique D) could skip the scratch and
1185        // sort round trip entirely.
1186        while index < end {
1187            let group_d = data.get(index);
1188            scratch.clear();
1189            while index < end && data.get(index) == group_d {
1190                let (_, t, r) = view.get(index);
1191                let mut owned_t = T::into_owned(t);
1192                owned_t.advance_by(frontier);
1193                scratch.push((owned_t, R::into_owned(r)));
1194                index += 1;
1195            }
1196            scratch.sort_by(|a, b| a.0.cmp(&b.0));
1197            let mut run = scratch.drain(..).peekable();
1198            while let Some((t, mut r)) = run.next() {
1199                while run.peek().is_some_and(|(t2, _)| *t2 == t) {
1200                    let (_, r2) = run.next().expect("peeked");
1201                    r.plus_equals(&r2);
1202                }
1203                if !r.is_zero() {
1204                    result.0.push(group_d);
1205                    result.1.push(&t);
1206                    result.2.push(&r);
1207                    records_since_check += 1;
1208                    if records_since_check >= CUT_CHECK_RECORDS {
1209                        records_since_check = 0;
1210                        if u64::cast_from(indexed::length_in_words(&result.borrow()))
1211                            >= u64::cast_from(COMMIT_BYTES / 8)
1212                        {
1213                            out.push_back(ColumnChunk::Resident(
1214                                Rc::new(ColumnBody::Typed(std::mem::take(&mut result))),
1215                                depth,
1216                            ));
1217                        }
1218                    }
1219                }
1220            }
1221        }
1222        if !result.is_empty() {
1223            out.push_back(ColumnChunk::Resident(
1224                Rc::new(ColumnBody::Typed(result)),
1225                depth,
1226            ));
1227        }
1228
1229        // Rebuild the withheld trailing group as the carry.
1230        if end < total {
1231            let mut carry = <(D, T, R) as Columnar>::Container::default();
1232            carry.extend_from_self(view, end..total);
1233            input.push_front(ColumnChunk::Resident(
1234                Rc::new(ColumnBody::Typed(carry)),
1235                depth,
1236            ));
1237        }
1238    }
1239
1240    /// Grade by serialized bytes and commit: spilled chunks pass through
1241    /// untouched, resident chunks at the commit size commit as they are, and
1242    /// smaller neighbors coalesce until the accumulation reaches it.
1243    /// Committing is the spill hook (see `ColumnChunk::commit`). Unless
1244    /// `done`, a tail below the commit size returns to the front of `input`.
1245    fn settle(input: &mut VecDeque<Self>, done: bool, out: &mut VecDeque<Self>) {
1246        Self::settle_graded(input, done, out, true)
1247    }
1248}
1249
1250impl<D, T, R, G> ColumnChunk<D, T, R, G>
1251where
1252    G: SpillGate,
1253    D: PoolColumnar,
1254    T: PoolColumnar + Timestamp,
1255    R: PoolColumnar,
1256    for<'a> columnar::Ref<'a, D>: Ord,
1257    for<'a> columnar::Ref<'a, T>: Ord,
1258{
1259    /// [`Chunk::settle`], with `commit` choosing what a graded chunk becomes.
1260    ///
1261    /// A caller that reads its output back immediately passes `false`: the
1262    /// chunk is graded resident, so the body is not serialized into a pool
1263    /// slot only to be copied straight back out, and the pool's budget is
1264    /// not charged for a body whose lifetime ends at the next read.
1265    fn settle_graded(
1266        input: &mut VecDeque<Self>,
1267        done: bool,
1268        out: &mut VecDeque<Self>,
1269        commit: bool,
1270    ) {
1271        // Resident chunks below the commit size accumulate into `acc` until
1272        // it reaches that size. Its depth is the deepest among the chunks it
1273        // holds, since coalescing rewrites within a generation.
1274        let mut acc: Option<(ColumnBody<(D, T, R)>, u8)> = None;
1275        while let Some(chunk) = input.pop_front() {
1276            let (rc, depth) = match chunk {
1277                spilled @ ColumnChunk::Spilled(_, _) => {
1278                    if let Some((body, depth)) = acc.take() {
1279                        out.push_back(Self::grade(body, depth, commit));
1280                    }
1281                    out.push_back(spilled);
1282                    continue;
1283                }
1284                ColumnChunk::Resident(rc, depth) => (rc, depth),
1285            };
1286            if rc.length_in_bytes() > COMMIT_BYTES && rc.len() > 1 {
1287                // Cut by borrow, so a shared body is copied once, into its
1288                // pieces.
1289                let records = cut_records(rc.len(), rc.length_in_bytes(), COMMIT_BYTES).max(1);
1290                let mut pieces = VecDeque::new();
1291                Self::push_cuts(&rc, records, depth, &mut pieces);
1292                for piece in pieces.into_iter().rev() {
1293                    input.push_front(piece);
1294                }
1295                continue;
1296            }
1297            let full = at_commit_size(&rc);
1298            // A chunk is copied into `acc` from its borrow, so a shared body
1299            // is never unwrapped.
1300            let fits = acc.as_ref().is_some_and(|(body, _)| {
1301                body.length_in_bytes().saturating_add(rc.length_in_bytes()) <= COMMIT_BYTES
1302            });
1303            if !full
1304                && fits
1305                && let Some((mut body, acc_depth)) = acc.take()
1306            {
1307                let view = rc.borrow();
1308                body.typed_mut().extend_from_self(view, 0..view.len());
1309                let acc_depth = acc_depth.max(depth);
1310                if at_commit_size(&body) {
1311                    out.push_back(Self::grade(body, acc_depth, commit));
1312                } else {
1313                    acc = Some((body, acc_depth));
1314                }
1315                continue;
1316            }
1317            // The chunk does not fit in `acc`. If the chunk is below the
1318            // commit size, as many of its records as fit move into `acc` and
1319            // the rest return to the front of `input`. Without that move, a
1320            // stream of chunks just over half the bound would commit each one
1321            // at about half the bound. Either way `acc` then goes to `out`.
1322            if let Some((mut body, acc_depth)) = acc.take() {
1323                let len = rc.len();
1324                let prefix = if full {
1325                    0
1326                } else {
1327                    let space = COMMIT_BYTES.saturating_sub(body.length_in_bytes());
1328                    cut_records(len, rc.length_in_bytes(), space)
1329                };
1330                if prefix == 0 || prefix >= len {
1331                    out.push_back(Self::grade(body, acc_depth, commit));
1332                } else {
1333                    let view = rc.borrow();
1334                    body.typed_mut().extend_from_self(view, 0..prefix);
1335                    let mut rest = <(D, T, R) as Columnar>::Container::default();
1336                    rest.extend_from_self(view, prefix..len);
1337                    input.push_front(ColumnChunk::Resident(
1338                        Rc::new(ColumnBody::Typed(rest)),
1339                        depth,
1340                    ));
1341                    let acc_depth = acc_depth.max(depth);
1342                    if body.length_in_bytes() > COMMIT_BYTES {
1343                        // Uneven record widths pushed `acc` past the bound.
1344                        let mut pieces = VecDeque::new();
1345                        Self::push_bounded(body, acc_depth, &mut pieces);
1346                        for piece in pieces {
1347                            let ColumnChunk::Resident(piece, piece_depth) = piece else {
1348                                unreachable!("push_bounded emits resident pieces");
1349                            };
1350                            let piece =
1351                                Rc::try_unwrap(piece).unwrap_or_else(|piece| piece.duplicate());
1352                            out.push_back(Self::grade(piece, piece_depth, commit));
1353                        }
1354                    } else {
1355                        out.push_back(Self::grade(body, acc_depth, commit));
1356                    }
1357                    continue;
1358                }
1359            }
1360            let body = Rc::try_unwrap(rc).unwrap_or_else(|rc| rc.duplicate());
1361            if full {
1362                out.push_back(Self::grade(body, depth, commit));
1363            } else {
1364                acc = Some((body, depth));
1365            }
1366        }
1367        if let Some((body, depth)) = acc {
1368            if done {
1369                out.push_back(Self::grade(body, depth, commit));
1370            } else {
1371                input.push_front(ColumnChunk::Resident(Rc::new(body), depth));
1372            }
1373        }
1374    }
1375
1376    /// A graded body as a chunk: committed, which may spill it, or left
1377    /// resident.
1378    fn grade(body: ColumnBody<(D, T, R)>, depth: u8, commit: bool) -> Self {
1379        if commit {
1380            Self::commit(body, depth)
1381        } else {
1382            ColumnChunk::Resident(Rc::new(body), depth)
1383        }
1384    }
1385}
1386
1387/// Append every update in `view` whose key matches a probe at or after
1388/// `*probe_index` into `staging`, per the [`UnloadChunk`] consume-index
1389/// protocol: probes strictly below the view's last key are consumed, a probe
1390/// equal to it is extracted but left for the next chunk.
1391fn extract_view_into<'v, 'p, K, V, T, R>(
1392    view: BorrowedOf<'v, ((K, V), T, R)>,
1393    probes: BorrowedOf<'p, K>,
1394    probe_index: &mut usize,
1395    staging: &mut <((K, V), T, R) as Columnar>::Container,
1396) where
1397    K: Columnar,
1398    V: Columnar,
1399    T: Columnar,
1400    R: Columnar,
1401    for<'b> columnar::Ref<'b, K>: Copy + Ord,
1402{
1403    let keys = view.0.0;
1404    let len = keys.len();
1405    let last = keys.get(len - 1);
1406    let count = probes.len();
1407    let mut pos = 0;
1408    while *probe_index < count {
1409        let probe = probes.get(*probe_index);
1410        mz_ore::soft_assert_no_log!(
1411            *probe_index == 0 || rr::<K>(probes.get(*probe_index - 1)) < rr::<K>(probe),
1412            "probe keys must be sorted and deduplicated"
1413        );
1414        if rr::<K>(probe) > rr::<K>(last) {
1415            return;
1416        }
1417        gallop(len, &mut pos, |i| rr::<K>(keys.get(i)) < rr::<K>(probe));
1418        let start = pos;
1419        while pos < len && rr::<K>(keys.get(pos)) == rr::<K>(probe) {
1420            pos += 1;
1421        }
1422        staging.extend_from_self(view, start..pos);
1423        if rr::<K>(probe) == rr::<K>(last) {
1424            return;
1425        }
1426        *probe_index += 1;
1427    }
1428}
1429
1430impl<K, V, T, R, G> UnloadChunk for ColumnChunk<(K, V), T, R, G>
1431where
1432    G: SpillGate,
1433    K: PoolColumnar,
1434    for<'a> columnar::Ref<'a, K>: Copy + Ord,
1435    V: PoolColumnar,
1436    for<'a> columnar::Ref<'a, V>: Copy + Ord,
1437    T: PoolColumnar + Default + Timestamp + Lattice + Ord,
1438    for<'a> columnar::Ref<'a, T>: Copy + Ord,
1439    R: PoolColumnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
1440{
1441    /// The flat columnar accumulation. Appends are bulk column-range copies,
1442    /// and a group straddling chunks stitches by plain concatenation.
1443    type Staging = <((K, V), T, R) as Columnar>::Container;
1444
1445    /// A borrowed key column, e.g. of a `Column<K>` the consumer assembled
1446    /// from its sorted, deduplicated probe keys.
1447    type Probes<'a> = BorrowedOf<'a, K>;
1448
1449    fn probe_count(probes: Self::Probes<'_>) -> usize {
1450        probes.len()
1451    }
1452
1453    fn locate(&self, probes: Self::Probes<'_>, probe_index: usize) -> std::cmp::Ordering {
1454        let probe = probes.get(probe_index);
1455        // A data ref is a `(key ref, val ref)` tuple, so the key fences are a
1456        // projection of the data fences.
1457        let (first, last) = self.data_span();
1458        let (first, last) = (first.0, last.0);
1459        if rr::<K>(probe) < rr::<K>(first) {
1460            std::cmp::Ordering::Less
1461        } else if rr::<K>(probe) > rr::<K>(last) {
1462            std::cmp::Ordering::Greater
1463        } else {
1464            std::cmp::Ordering::Equal
1465        }
1466    }
1467
1468    fn extract_into(
1469        &self,
1470        probes: Self::Probes<'_>,
1471        probe_index: &mut usize,
1472        staging: &mut Self::Staging,
1473    ) {
1474        match self {
1475            ColumnChunk::Resident(col, _) => {
1476                extract_view_into::<K, V, T, R>(col.borrow(), probes, probe_index, staging);
1477            }
1478            ColumnChunk::Spilled(body, _) => body.handle.with_typed(|typed| match typed {
1479                Some(typed) => {
1480                    let view = pooled::<(K, V), T, R>(typed).body.borrow();
1481                    extract_view_into::<K, V, T, R>(view, probes, probe_index, staging);
1482                }
1483                None => with_scratch(|scratch| {
1484                    // NOTE: deliberately the non-admitting read. One probe
1485                    // set touching a chunk is weak evidence it will be
1486                    // touched again, and probing a spilled trace must not
1487                    // accrete it back into residency. The cost is a full
1488                    // decode per probe set against an evicted chunk.
1489                    body.handle.read_into(scratch);
1490                    let view = borrow_words::<((K, V), T, R)>(scratch);
1491                    extract_view_into::<K, V, T, R>(view, probes, probe_index, staging);
1492                }),
1493            }),
1494        }
1495    }
1496
1497    fn fetch_into(&self, staging: &mut Self::Staging) {
1498        match self {
1499            ColumnChunk::Resident(col, _) => {
1500                let view = col.borrow();
1501                staging.extend_from_self(view, 0..view.len());
1502            }
1503            ColumnChunk::Spilled(body, _) => body.handle.with_typed(|typed| match typed {
1504                Some(typed) => {
1505                    let view = pooled::<(K, V), T, R>(typed).body.borrow();
1506                    staging.extend_from_self(view, 0..view.len());
1507                }
1508                None => with_scratch(|scratch| {
1509                    body.handle.read_into(scratch);
1510                    let view = borrow_words::<((K, V), T, R)>(scratch);
1511                    staging.extend_from_self(view, 0..view.len());
1512                }),
1513            }),
1514        }
1515    }
1516}
1517
1518/// A batch builder over [`ColumnChunk`] input that delegates to a builder
1519/// over [`ColumnBody`] input, loading each chunk's body as it is pushed.
1520///
1521/// This is the adapter that lets a [`ChunkBatcher`] feed the body-input batch
1522/// builders (and through them the existing spine layouts):
1523/// the batcher's chains carry pool-spillable chunks, and bodies are read back
1524/// copy-out only at the seal, one chunk at a time.
1525///
1526/// [`ChunkBatcher`]: differential_dataflow::trace::chunk::ChunkBatcher
1527pub struct UnchunkBuilder<Bu, D: Columnar, T: Columnar, R: Columnar, G: SpillGate> {
1528    inner: Bu,
1529    _marker: std::marker::PhantomData<(D, T, R, G)>,
1530}
1531
1532impl<Bu: Default, D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Default
1533    for UnchunkBuilder<Bu, D, T, R, G>
1534{
1535    fn default() -> Self {
1536        Self {
1537            inner: Bu::default(),
1538            _marker: std::marker::PhantomData,
1539        }
1540    }
1541}
1542
1543impl<Bu, D, T, R, G> differential_dataflow::trace::Builder for UnchunkBuilder<Bu, D, T, R, G>
1544where
1545    Bu: differential_dataflow::trace::Builder<Input = ColumnBody<(D, T, R)>> + ChainState,
1546    D: Columnar + 'static,
1547    T: Columnar + 'static,
1548    R: Columnar + 'static,
1549    G: SpillGate,
1550{
1551    type Input = ColumnChunk<D, T, R, G>;
1552    type Time = Bu::Time;
1553    type Output = Bu::Output;
1554
1555    fn push(&mut self, chunk: &mut Self::Input) {
1556        let mut body = std::mem::take(chunk).into_body();
1557        self.inner.push(&mut body);
1558    }
1559
1560    fn done(self) -> Option<Self::Output> {
1561        self.inner.done()
1562    }
1563}
1564
1565impl<Bu, D, T, R, G>
1566    differential_dataflow::trace::implementations::merge_batcher::Sealer<ColumnChunk<D, T, R, G>>
1567    for UnchunkBuilder<Bu, D, T, R, G>
1568where
1569    Bu: differential_dataflow::trace::Builder<Input = ColumnBody<(D, T, R)>> + ChainState,
1570    D: Columnar + 'static,
1571    T: Columnar + 'static,
1572    R: Columnar + 'static,
1573    G: SpillGate,
1574{
1575    type Output = Bu::Output;
1576
1577    fn seal(chain: &mut Vec<ColumnChunk<D, T, R, G>>) -> Option<Self::Output> {
1578        use differential_dataflow::trace::Builder;
1579
1580        let mut state = Bu::State::default();
1581        for chunk in chain.iter() {
1582            // A resident body folds for the price of a borrow, so it goes to
1583            // `observe` whatever the builder asked for: the state gets exact
1584            // figures for free. Folding a spilled body costs a second pool
1585            // read on top of the push below, so it waits on `wants_bodies`.
1586            if !chunk.is_spilled() || Bu::wants_bodies() {
1587                chunk.with_body(|body| Bu::observe(&mut state, body));
1588            } else {
1589                Bu::observe_records(&mut state, chunk.records());
1590            }
1591        }
1592        let mut builder = Self {
1593            inner: Bu::from_state(state),
1594            _marker: std::marker::PhantomData,
1595        };
1596        // One chunk at a time through `push`, so peak transient memory is a
1597        // single loaded body rather than the whole chain at once.
1598        for chunk in chain.iter_mut() {
1599            builder.push(chunk);
1600        }
1601        chain.clear();
1602        builder.done()
1603    }
1604}
1605
1606/// A builder whose batches carry state derived from a whole chain, computed
1607/// before the chain's first push.
1608///
1609/// [`Sealer::seal`] receives the chain at once, which a chain of pool-backed
1610/// chunks cannot supply without holding every body resident at the same time.
1611/// An implementor splits the derivation instead: a caller folds the chain into
1612/// [`State`](Self::State) one entry at a time, then builds from it.
1613///
1614/// A caller folds each chain entry exactly once, through
1615/// [`observe`](Self::observe) when it holds the entry's contents and through
1616/// [`observe_records`](Self::observe_records) when it does not, so an
1617/// implementor may accumulate the same figure in both without double
1618/// counting. Which one an entry takes is the caller's choice, so an
1619/// implementor reads no meaning into it beyond what each carries.
1620///
1621/// [`Sealer::seal`]: differential_dataflow::trace::implementations::merge_batcher::Sealer::seal
1622pub trait ChainState: differential_dataflow::trace::Builder {
1623    /// State accumulated across a chain.
1624    type State: Default;
1625
1626    /// Whether the state is worth reading a chain entry's contents for when
1627    /// they are not already at hand. A caller that holds them passes them on
1628    /// regardless.
1629    fn wants_bodies() -> bool;
1630
1631    /// Fold one chain entry's contents into `state`.
1632    fn observe(state: &mut Self::State, input: &Self::Input);
1633
1634    /// Fold one chain entry's update count into `state`, for a caller that
1635    /// reads no bodies.
1636    fn observe_records(state: &mut Self::State, records: usize);
1637
1638    /// Build with `state` installed.
1639    fn from_state(state: Self::State) -> Self;
1640}
1641
1642/// A chunker for `arrange_core` over [`ColumnChunk`]s: sorts and consolidates
1643/// raw input columns through a [`ColumnChunker`] and wraps its output chunks.
1644pub struct ChunkChunker<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> {
1645    inner: ColumnChunker<(D, T, R)>,
1646    ready: VecDeque<ColumnChunk<D, T, R, G>>,
1647    staged: ColumnChunk<D, T, R, G>,
1648}
1649
1650impl<D, T, R, G> Default for ChunkChunker<D, T, R, G>
1651where
1652    D: Columnar,
1653    T: Columnar,
1654    R: Columnar,
1655    G: SpillGate,
1656    ColumnChunker<(D, T, R)>: Default,
1657{
1658    fn default() -> Self {
1659        Self {
1660            inner: Default::default(),
1661            ready: VecDeque::new(),
1662            staged: Default::default(),
1663        }
1664    }
1665}
1666
1667impl<'a, D, T, R, G> PushInto<&'a mut Column<(D, T, R)>> for ChunkChunker<D, T, R, G>
1668where
1669    D: Columnar,
1670    T: Columnar,
1671    R: Columnar,
1672    G: SpillGate,
1673    ColumnChunker<(D, T, R)>: PushInto<&'a mut Column<(D, T, R)>>,
1674{
1675    fn push_into(&mut self, item: &'a mut Column<(D, T, R)>) {
1676        self.inner.push_into(item);
1677    }
1678}
1679
1680impl<D, T, R, G> ContainerBuilder for ChunkChunker<D, T, R, G>
1681where
1682    D: Columnar + 'static,
1683    T: Columnar + 'static,
1684    R: Columnar + 'static,
1685    G: SpillGate,
1686    ColumnChunker<(D, T, R)>: ContainerBuilder<Container = ColumnBody<(D, T, R)>>,
1687{
1688    type Container = ColumnChunk<D, T, R, G>;
1689
1690    fn extract(&mut self) -> Option<&mut Self::Container> {
1691        if self.ready.is_empty() {
1692            let body = self.inner.extract()?;
1693            ColumnChunk::push_bounded(std::mem::take(body), 0, &mut self.ready);
1694        }
1695        self.staged = self.ready.pop_front()?;
1696        Some(&mut self.staged)
1697    }
1698
1699    fn finish(&mut self) -> Option<&mut Self::Container> {
1700        if self.ready.is_empty() {
1701            let body = self.inner.finish()?;
1702            ColumnChunk::push_bounded(std::mem::take(body), 0, &mut self.ready);
1703        }
1704        self.staged = self.ready.pop_front()?;
1705        Some(&mut self.staged)
1706    }
1707}
1708
1709/// The [`ChunkBatcher`] of a chunk chain, reporting resident bytes to the
1710/// batcher size logger.
1711///
1712/// `S` seals each extracted chain into a batch. A caller that wants the chain
1713/// itself takes [`AccountedChunkChainBatcher`] instead.
1714///
1715/// [`ChunkBatcher`]: differential_dataflow::trace::chunk::ChunkBatcher
1716pub type AccountedChunkBatcher<D, T, R, G, S> =
1717    differential_dataflow::trace::implementations::merge_batcher::MergeBatcher<
1718        ChunkChunker<D, T, R, G>,
1719        AccountedChunkMerger<D, T, R, G>,
1720        S,
1721    >;
1722
1723/// The [`AccountedChunkBatcher`] of a caller that wants the merged chain rather
1724/// than a batch built from it, such as the temporal-bucket store.
1725pub type AccountedChunkChainBatcher<D, T, R, G> = crate::operator::ConsolidatingBatcher<
1726    ChunkChunker<D, T, R, G>,
1727    AccountedChunkMerger<D, T, R, G>,
1728>;
1729
1730/// The chunk merger of [`AccountedChunkBatcher`]: differential's merger with
1731/// a resident readied side, plus the [`Merger::allocation`] figures the
1732/// `mz_arrangement_batcher_*_raw` introspection tables are assembled from.
1733///
1734/// A chunk reports the bytes of the body it holds whether that body sits on
1735/// the heap or in the pool. A spilled body is not free: the pool keeps it in
1736/// a slot, or compressed in an extent, or on the device, and only the last
1737/// of those is off the process's books. Which tier holds it is the pool's
1738/// own business and its metrics report that split, so attributing the body
1739/// to the operator that owns it is what keeps these tables whole.
1740///
1741/// [`Merger::allocation`]: differential_dataflow::trace::implementations::merge_batcher::Merger::allocation
1742pub struct AccountedChunkMerger<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> {
1743    inner: differential_dataflow::trace::chunk::ChunkMerger<ColumnChunk<D, T, R, G>>,
1744}
1745
1746impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Default
1747    for AccountedChunkMerger<D, T, R, G>
1748{
1749    fn default() -> Self {
1750        Self {
1751            inner: Default::default(),
1752        }
1753    }
1754}
1755
1756impl<D, T, R, G> differential_dataflow::trace::implementations::merge_batcher::Merger
1757    for AccountedChunkMerger<D, T, R, G>
1758where
1759    D: PoolColumnar + 'static,
1760    T: PoolColumnar + Timestamp + 'static,
1761    R: PoolColumnar + 'static,
1762    G: SpillGate,
1763    for<'a> columnar::Ref<'a, D>: Ord,
1764    for<'a> columnar::Ref<'a, T>: Ord,
1765    ColumnChunk<D, T, R, G>: Chunk,
1766    <ColumnChunk<D, T, R, G> as Chunk>::Time: Clone + PartialOrder + 'static,
1767{
1768    type Chunk = ColumnChunk<D, T, R, G>;
1769
1770    fn merge(
1771        &mut self,
1772        list1: Vec<Self::Chunk>,
1773        list2: Vec<Self::Chunk>,
1774        output: &mut Vec<Self::Chunk>,
1775        stash: &mut Vec<Self::Chunk>,
1776    ) {
1777        self.inner.merge(list1, list2, output, stash)
1778    }
1779
1780    fn len(chunk: &Self::Chunk) -> usize {
1781        Chunk::len(chunk)
1782    }
1783
1784    fn allocation(chunk: &Self::Chunk) -> (usize, usize, usize) {
1785        let bytes = match chunk {
1786            ColumnChunk::Resident(col, _) => col.length_in_bytes(),
1787            ColumnChunk::Spilled(body, _) => body.len_bytes,
1788        };
1789        (bytes, bytes, 1)
1790    }
1791}
1792
1793impl<D, T, R, G> differential_dataflow::trace::implementations::merge_batcher::Extractor
1794    for AccountedChunkMerger<D, T, R, G>
1795where
1796    D: PoolColumnar + 'static,
1797    T: PoolColumnar + Timestamp + 'static,
1798    R: PoolColumnar + 'static,
1799    G: SpillGate,
1800    for<'a> columnar::Ref<'a, D>: Ord,
1801    for<'a> columnar::Ref<'a, T>: Ord,
1802    ColumnChunk<D, T, R, G>: Chunk,
1803    <ColumnChunk<D, T, R, G> as Chunk>::Time: Clone + PartialOrder + 'static,
1804{
1805    type Time = <ColumnChunk<D, T, R, G> as Chunk>::Time;
1806
1807    fn extract(
1808        &mut self,
1809        merged: Vec<Self::Chunk>,
1810        upper: AntichainRef<Self::Time>,
1811        frontier: &mut Antichain<Self::Time>,
1812        readied: &mut Vec<Self::Chunk>,
1813        kept: &mut Vec<Self::Chunk>,
1814        _stash: &mut Vec<Self::Chunk>,
1815    ) {
1816        // Differential's merger settles both sides with committing settles.
1817        // The readied side is handed to a builder that loads every chunk
1818        // back, so committing it spills bodies the next call copies out
1819        // again, and charges the pool's budget for them in between. Drive
1820        // the loop here instead and grade that side resident. The kept side
1821        // stays committed: it is the side that lives on, and spilling it is
1822        // the point.
1823        let mut input: VecDeque<Self::Chunk> = merged.into();
1824        let (mut keep, mut shipped) = (VecDeque::new(), VecDeque::new());
1825        let (mut kept_q, mut shipped_q) = (VecDeque::new(), VecDeque::new());
1826        while !input.is_empty() {
1827            Chunk::extract(&mut input, upper, frontier, &mut keep, &mut shipped);
1828            Chunk::settle(&mut keep, false, &mut kept_q);
1829            ColumnChunk::settle_graded(&mut shipped, false, &mut shipped_q, false);
1830        }
1831        Chunk::settle(&mut keep, true, &mut kept_q);
1832        ColumnChunk::settle_graded(&mut shipped, true, &mut shipped_q, false);
1833        Extend::extend(kept, kept_q);
1834        Extend::extend(readied, shipped_q);
1835    }
1836}
1837
1838#[cfg(test)]
1839mod tests {
1840    //! Property tests for the [`Chunk`] and [`UnloadChunk`] contracts on
1841    //! [`ColumnChunk`].
1842    //!
1843    //! Strategy: generate sorted+consolidated inputs (the chunk invariant),
1844    //! drive the trait methods the way the differential harness does, and
1845    //! compare against brute-force references on owned tuples. Test types are
1846    //! `D = (u64, u64)`, `T = u64`, `R = i64` from small ranges so equal-key
1847    //! collisions are common and consolidation actually runs.
1848
1849    use differential_dataflow::batcher::Extract;
1850    use differential_dataflow::trace::chunk::ChunkBatch;
1851    use mz_ore::pool::Pool;
1852    use proptest::prelude::*;
1853    use timely::container::PushInto;
1854    use timely::progress::Antichain;
1855
1856    use crate::columnar::unload::UnloadBatch;
1857
1858    use super::*;
1859
1860    type Tuple = ((u64, u64), u64, i64);
1861    type TestChunk = ColumnChunk<(u64, u64), u64, i64, ComputeSpill>;
1862    /// A batcher over [`TestChunk`]s that hands its chain back rather than sealing it.
1863    type TestChunkBatcher = crate::operator::ConsolidatingBatcher<
1864        ChunkChunker<(u64, u64), u64, i64, ComputeSpill>,
1865        differential_dataflow::trace::chunk::ChunkMerger<TestChunk>,
1866    >;
1867
1868    /// The delegated codec's stored form is byte-identical to the extent
1869    /// store's previous hard-coded framing: a little-endian `u32`
1870    /// body-length prefix followed by one lz4 block, which is exactly what
1871    /// `compress_prepend_size` produces.
1872    #[mz_ore::test]
1873    fn lz4_codec_matches_the_previous_extent_framing() {
1874        let body: Vec<u8> = (0..100_000u32).flat_map(|i| i.to_le_bytes()).collect();
1875        let mut stored = Vec::new();
1876        LZ4_CODEC.encode(&body, &mut stored);
1877        assert_eq!(stored, lz4_flex::block::compress_prepend_size(&body));
1878        let mut round = vec![0u8; body.len()];
1879        LZ4_CODEC.decode(&stored, &mut round);
1880        assert_eq!(round, body);
1881    }
1882
1883    #[mz_ore::test]
1884    #[should_panic(expected = "destination must match")]
1885    fn lz4_codec_decode_length_mismatch_panics() {
1886        let mut stored = Vec::new();
1887        LZ4_CODEC.encode(&[7u8; 64], &mut stored);
1888        let mut short = vec![0u8; 32];
1889        LZ4_CODEC.decode(&stored, &mut short);
1890    }
1891
1892    /// Reference consolidation: sort by `(data, time)`, sum diffs over equal
1893    /// pairs, drop zeros.
1894    fn consolidate(mut v: Vec<Tuple>) -> Vec<Tuple> {
1895        v.sort();
1896        let mut out: Vec<Tuple> = Vec::new();
1897        for (d, t, r) in v {
1898            if let Some(last) = out.last_mut() {
1899                if last.0 == d && last.1 == t {
1900                    last.2 += r;
1901                    continue;
1902                }
1903            }
1904            out.push((d, t, r));
1905        }
1906        out.retain(|x| x.2 != 0);
1907        out
1908    }
1909
1910    fn arb_consolidated() -> impl Strategy<Value = Vec<Tuple>> {
1911        prop::collection::vec(((0u64..5, 0u64..5), 0u64..4, -3i64..=3i64), 0..40)
1912            .prop_map(consolidate)
1913    }
1914
1915    fn build_column(v: &[Tuple]) -> ColumnBody<Tuple> {
1916        let mut col: ColumnBody<Tuple> = Default::default();
1917        for tup in v {
1918            col.push_into(*tup);
1919        }
1920        col
1921    }
1922
1923    fn collect_column(col: &ColumnBody<Tuple>) -> Vec<Tuple> {
1924        col.borrow()
1925            .into_index_iter()
1926            .map(|((k, v), t, r)| {
1927                (
1928                    (u64::into_owned(k), u64::into_owned(v)),
1929                    u64::into_owned(t),
1930                    i64::into_owned(r),
1931                )
1932            })
1933            .collect()
1934    }
1935
1936    fn collect_chunks(chunks: impl IntoIterator<Item = TestChunk>) -> Vec<Tuple> {
1937        chunks
1938            .into_iter()
1939            .flat_map(|chunk| collect_column(&chunk.into_body()))
1940            .collect()
1941    }
1942
1943    fn collect_staging(staging: &<Tuple as Columnar>::Container) -> Vec<Tuple> {
1944        staging
1945            .borrow()
1946            .into_index_iter()
1947            .map(|((k, v), t, r)| {
1948                (
1949                    (u64::into_owned(k), u64::into_owned(v)),
1950                    u64::into_owned(t),
1951                    i64::into_owned(r),
1952                )
1953            })
1954            .collect()
1955    }
1956
1957    /// Cut consolidated data into non-empty chunks at the given points.
1958    fn chunked(data: &[Tuple], cuts: &[usize]) -> VecDeque<TestChunk> {
1959        let mut chunks = VecDeque::new();
1960        let mut start = 0;
1961        for cut in cuts {
1962            let end = (start + 1 + cut % 7).min(data.len());
1963            if end > start {
1964                chunks.push_back(ColumnChunk::from_body(build_column(&data[start..end])));
1965                start = end;
1966            }
1967        }
1968        if start < data.len() {
1969            chunks.push_back(ColumnChunk::from_body(build_column(&data[start..])));
1970        }
1971        chunks
1972    }
1973
1974    /// The chunked cut, with every chunk force-spilled through a private pool
1975    /// (bounds captured, bodies in the pool) regardless of size thresholds.
1976    fn chunked_spilled(data: &[Tuple], cuts: &[usize], pool: &Pool) -> VecDeque<TestChunk> {
1977        chunked(data, cuts)
1978            .into_iter()
1979            .map(|chunk| force_spill(chunk, pool))
1980            .collect()
1981    }
1982
1983    /// Whether a spilled chunk's body is stored compressed. Deliberately
1984    /// does not retain the body: an `Rc` held across a `survive_merge` would
1985    /// itself make the body shared and suppress the migration under test.
1986    fn body_compressed(chunk: &TestChunk) -> bool {
1987        match chunk {
1988            ColumnChunk::Spilled(body, _) => body.compressed,
1989            ColumnChunk::Resident(_, _) => panic!("chunk must be spilled"),
1990        }
1991    }
1992
1993    /// Spill one chunk through `pool`, bypassing the size threshold and
1994    /// keeping the chunk's depth.
1995    fn force_spill(chunk: TestChunk, pool: &Pool) -> TestChunk {
1996        let depth = chunk.depth();
1997        TestChunk::spill_body(chunk.into_body(), pool, depth)
1998    }
1999
2000    /// The batcher size logger reports a body's bytes wherever the body
2001    /// lives, so an operator's share does not vanish when a chunk spills.
2002    #[mz_ore::test]
2003    #[cfg_attr(miri, ignore)]
2004    fn allocation_reports_a_body_wherever_it_lives() {
2005        use differential_dataflow::trace::implementations::merge_batcher::Merger;
2006
2007        let data: Vec<Tuple> = (0..64u64).map(|i| ((i, i), 0, 1)).collect();
2008        let resident = TestChunk::from_body(build_column(&data));
2009        let (size, capacity, allocations) =
2010            AccountedChunkMerger::<(u64, u64), u64, i64, ComputeSpill>::allocation(&resident);
2011        assert!(size > 0, "a resident body reports its bytes");
2012        assert_eq!((capacity, allocations), (size, 1));
2013
2014        let spilled = force_spill(resident, &test_pool());
2015        assert_eq!(
2016            AccountedChunkMerger::<(u64, u64), u64, i64, ComputeSpill>::allocation(&spilled),
2017            (size, capacity, allocations),
2018            "spilling a body does not change what its owner holds"
2019        );
2020    }
2021
2022    /// A chunk that reaches the seal resident is handed back resident, even
2023    /// with a pool installed. The readied side goes straight to a builder
2024    /// that loads every chunk, so committing it there would serialize a body
2025    /// the next call copies out again.
2026    ///
2027    /// A body the batcher spilled earlier, while merging chains it was
2028    /// holding, passes through as it is: that spill is the one worth paying
2029    /// for, and undoing it would be another copy.
2030    #[mz_ore::test]
2031    #[cfg_attr(miri, ignore)]
2032    fn seal_readies_resident_chunks() {
2033        // One push, so nothing merges before the seal and the chunk reaches
2034        // `extract` resident. Comfortably past the 64 KiB spill floor at 32
2035        // bytes per record, so a committing settle would spill it.
2036        let data: Vec<Tuple> = (0..20_000u64).map(|i| ((i, i), 0, 1)).collect();
2037
2038        set_spill_override(Some(test_pool()));
2039        let mut batcher =
2040            AccountedChunkChainBatcher::<(u64, u64), u64, i64, ComputeSpill>::new(None, 0);
2041        batcher.push_chunk(TestChunk::from_body(build_column(&data)));
2042        let (chain, _frontier) = batcher.extract(Antichain::new().borrow());
2043        let chain = chain.unwrap_or_default();
2044        set_spill_override(None);
2045
2046        assert!(!chain.is_empty(), "the seal ships what was pushed");
2047        assert!(
2048            chain.iter().all(|chunk| !chunk.is_spilled()),
2049            "a chunk that arrived resident is readied resident"
2050        );
2051    }
2052
2053    /// A single pool shared by every test in the module. A pool reserves a
2054    /// large slab of address space, so one per test (let alone per proptest
2055    /// case) exhausts the VM map under parallel test threads.
2056    fn test_pool() -> Pool {
2057        static POOL: std::sync::OnceLock<Pool> = std::sync::OnceLock::new();
2058        POOL.get_or_init(|| Pool::new().expect("pool creation"))
2059            .clone()
2060    }
2061
2062    proptest! {
2063        /// A full batcher round trip: push chunked inputs, seal everything,
2064        /// and compare with the reference consolidation of the union.
2065        #[mz_ore::test]
2066        #[cfg_attr(miri, ignore)]
2067        fn batcher_round_trip(
2068            inputs in prop::collection::vec(arb_consolidated(), 1..6),
2069            cuts in prop::collection::vec(0usize..7, 0..8),
2070        ) {
2071            let mut batcher = TestChunkBatcher::new(None, 0);
2072            let mut union = Vec::new();
2073            for input in &inputs {
2074                Extend::extend(&mut union, input.iter().copied());
2075                for chunk in chunked(input, &cuts) {
2076                    batcher.push_chunk(chunk);
2077                }
2078            }
2079            // An empty upper ships everything.
2080            let (sealed, _frontier) = batcher.extract(Antichain::new().borrow());
2081            let sealed = sealed.unwrap_or_default();
2082            prop_assert_eq!(collect_chunks(sealed), consolidate(union));
2083        }
2084
2085        /// The same round trip over force-spilled inputs: merge and extract
2086        /// read bodies back from the pool call-scoped.
2087        #[mz_ore::test]
2088        #[cfg_attr(miri, ignore)]
2089        fn batcher_round_trip_spilled(
2090            inputs in prop::collection::vec(arb_consolidated(), 1..4),
2091            cuts in prop::collection::vec(0usize..7, 0..6),
2092        ) {
2093            let pool = test_pool();
2094            let mut batcher = TestChunkBatcher::new(None, 0);
2095            let mut union = Vec::new();
2096            for input in &inputs {
2097                Extend::extend(&mut union, input.iter().copied());
2098                for chunk in chunked_spilled(input, &cuts, &pool) {
2099                    batcher.push_chunk(chunk);
2100                }
2101            }
2102            let (sealed, _frontier) = batcher.extract(Antichain::new().borrow());
2103            let sealed = sealed.unwrap_or_default();
2104            prop_assert_eq!(collect_chunks(sealed), consolidate(union));
2105        }
2106
2107        /// Sealing at an intermediate upper partitions by time and reports
2108        /// the kept lower envelope as the frontier.
2109        #[mz_ore::test]
2110        #[cfg_attr(miri, ignore)]
2111        fn seal_partitions_by_time(
2112            input in arb_consolidated(),
2113            cuts in prop::collection::vec(0usize..7, 0..8),
2114            upper in 0u64..5,
2115        ) {
2116            let mut batcher = TestChunkBatcher::new(None, 0);
2117            for chunk in chunked(&input, &cuts) {
2118                batcher.push_chunk(chunk);
2119            }
2120            let (shipped, frontier) = batcher.extract(Antichain::from_elem(upper).borrow());
2121            let shipped = shipped.unwrap_or_default();
2122            let frontier = frontier.to_owned();
2123            let expected_shipped: Vec<Tuple> =
2124                input.iter().copied().filter(|(_, t, _)| *t < upper).collect();
2125            prop_assert_eq!(collect_chunks(shipped), consolidate(expected_shipped));
2126
2127            let kept_min = input.iter().filter(|(_, t, _)| *t >= upper).map(|(_, t, _)| *t).min();
2128            prop_assert_eq!(frontier.elements().first().copied(), kept_min);
2129
2130            let (rest, _frontier) = batcher.extract(Antichain::new().borrow());
2131            let rest = rest.unwrap_or_default();
2132            let expected_rest: Vec<Tuple> =
2133                input.iter().copied().filter(|(_, t, _)| *t >= upper).collect();
2134            prop_assert_eq!(collect_chunks(rest), consolidate(expected_rest));
2135        }
2136
2137        /// The intermediate-upper partition of `seal_partitions_by_time`, over
2138        /// force-spilled inputs: bodies read back from the pool and split by
2139        /// time in one seal.
2140        #[mz_ore::test]
2141        #[cfg_attr(miri, ignore)]
2142        fn seal_partitions_by_time_spilled(
2143            input in arb_consolidated(),
2144            cuts in prop::collection::vec(0usize..7, 0..8),
2145            upper in 0u64..5,
2146        ) {
2147            let pool = test_pool();
2148            let mut batcher = TestChunkBatcher::new(None, 0);
2149            for chunk in chunked_spilled(&input, &cuts, &pool) {
2150                batcher.push_chunk(chunk);
2151            }
2152            let (shipped, frontier) = batcher.extract(Antichain::from_elem(upper).borrow());
2153            let shipped = shipped.unwrap_or_default();
2154            let frontier = frontier.to_owned();
2155            let expected_shipped: Vec<Tuple> =
2156                input.iter().copied().filter(|(_, t, _)| *t < upper).collect();
2157            prop_assert_eq!(collect_chunks(shipped), consolidate(expected_shipped));
2158
2159            let kept_min = input.iter().filter(|(_, t, _)| *t >= upper).map(|(_, t, _)| *t).min();
2160            prop_assert_eq!(frontier.elements().first().copied(), kept_min);
2161
2162            let (rest, _frontier) = batcher.extract(Antichain::new().borrow());
2163            let rest = rest.unwrap_or_default();
2164            let expected_rest: Vec<Tuple> =
2165                input.iter().copied().filter(|(_, t, _)| *t >= upper).collect();
2166            prop_assert_eq!(collect_chunks(rest), consolidate(expected_rest));
2167        }
2168
2169        /// `advance` equals per-record time advancement plus reference
2170        /// consolidation, including across a `done = false` carry.
2171        #[mz_ore::test]
2172        #[cfg_attr(miri, ignore)]
2173        fn advance_matches_reference(
2174            input in arb_consolidated(),
2175            cuts in prop::collection::vec(0usize..7, 0..8),
2176            frontier_elem in 0u64..5,
2177        ) {
2178            let frontier = Antichain::from_elem(frontier_elem);
2179            let mut chunks = chunked(&input, &cuts);
2180            let mut out = VecDeque::new();
2181            TestChunk::advance(&mut chunks, frontier.borrow(), false, &mut out);
2182            TestChunk::advance(&mut chunks, frontier.borrow(), true, &mut out);
2183            prop_assert!(chunks.is_empty());
2184
2185            let expected = consolidate(
2186                input
2187                    .iter()
2188                    .map(|&(d, mut t, r)| {
2189                        t.advance_by(frontier.borrow());
2190                        (d, t, r)
2191                    })
2192                    .collect(),
2193            );
2194            prop_assert_eq!(collect_chunks(out), expected);
2195        }
2196
2197        /// `settle` preserves contents and order, moves everything on `done`,
2198        /// and coalesces small neighbors.
2199        #[mz_ore::test]
2200        #[cfg_attr(miri, ignore)]
2201        fn settle_preserves_and_packs(
2202            input in arb_consolidated(),
2203            cuts in prop::collection::vec(0usize..7, 1..8),
2204        ) {
2205            let mut chunks = chunked(&input, &cuts);
2206            let mut out = VecDeque::new();
2207            TestChunk::settle(&mut chunks, true, &mut out);
2208            prop_assert!(chunks.is_empty());
2209            // Test chunks are far below the byte threshold, so maximal
2210            // packing coalesces everything into a single chunk.
2211            prop_assert!(out.len() <= 1);
2212            prop_assert_eq!(collect_chunks(out), input);
2213        }
2214
2215        /// `ChunkBatch::extract_into` over sorted, deduplicated probe keys
2216        /// equals the reference filter, resident and spilled alike, straddled
2217        /// keys included.
2218        #[mz_ore::test]
2219        #[cfg_attr(miri, ignore)]
2220        fn unload_extract_matches_filter(
2221            input in arb_consolidated(),
2222            cuts in prop::collection::vec(0usize..7, 0..8),
2223            probe_keys in prop::collection::btree_set(0u64..6, 0..6),
2224            spill in any::<bool>(),
2225        ) {
2226            prop_assume!(!input.is_empty());
2227            let pool = test_pool();
2228            let chunks: Vec<TestChunk> = if spill {
2229                chunked_spilled(&input, &cuts, &pool).into()
2230            } else {
2231                chunked(&input, &cuts).into()
2232            };
2233            let batch = ChunkBatch::new(chunks);
2234
2235            let mut probe_col = <u64 as Columnar>::Container::default();
2236            for key in &probe_keys {
2237                probe_col.push(*key);
2238            }
2239            let mut staging = <Tuple as Columnar>::Container::default();
2240            batch.extract_into(probe_col.borrow(), &mut staging);
2241
2242            let expected: Vec<Tuple> = input
2243                .iter()
2244                .copied()
2245                .filter(|((k, _), _, _)| probe_keys.contains(k))
2246                .collect();
2247            prop_assert_eq!(collect_staging(&staging), expected);
2248
2249            // The scan path reproduces the batch exactly, resident and
2250            // spilled alike.
2251            let mut staging = <Tuple as Columnar>::Container::default();
2252            batch.fetch_into(&mut staging);
2253            prop_assert_eq!(collect_staging(&staging), input);
2254        }
2255    }
2256
2257    /// `locate` answers the three-way span comparison for every probe
2258    /// placement: below, within, and past the chunk's keys.
2259    #[mz_ore::test]
2260    fn locate_spans_keys() {
2261        let chunk = TestChunk::from_body(build_column(&[
2262            ((2, 0), 0, 1),
2263            ((4, 0), 0, 1),
2264            ((6, 0), 0, 1),
2265        ]));
2266        let mut probe_col = <u64 as Columnar>::Container::default();
2267        for key in [0u64, 2, 3, 6, 9] {
2268            probe_col.push(key);
2269        }
2270        let probes = probe_col.borrow();
2271        use std::cmp::Ordering::*;
2272        let expected = [Less, Equal, Equal, Equal, Greater];
2273        for (index, expected) in expected.iter().enumerate() {
2274            assert_eq!(chunk.locate(probes, index), *expected, "probe {index}");
2275        }
2276    }
2277
2278    /// Collect chunk contents while asserting each chunk's serialized size
2279    /// stays within `bound` bytes.
2280    fn collect_bounded(chunks: impl IntoIterator<Item = TestChunk>, bound: usize) -> Vec<Tuple> {
2281        let mut collected = Vec::new();
2282        for chunk in chunks {
2283            let col = chunk.into_body();
2284            let bytes = col.length_in_bytes();
2285            assert!(bytes <= bound, "chunk of {bytes} bytes exceeds {bound}");
2286            Extend::extend(&mut collected, collect_column(&col));
2287        }
2288        collected
2289    }
2290
2291    type WideUpdate = ((u64, String), u64, i64);
2292    type WideChunk = ColumnChunk<(u64, String), u64, i64, ComputeSpill>;
2293
2294    fn wide_column(keys: impl Iterator<Item = u64>, bytes: usize) -> ColumnBody<WideUpdate> {
2295        let mut column = ColumnBody::default();
2296        for key in keys {
2297            column.push_into(&((key, "x".repeat(bytes)), 0, 1));
2298        }
2299        column
2300    }
2301
2302    fn assert_wide_byte_bound(chunks: VecDeque<WideChunk>, expected: usize, payload_bytes: usize) {
2303        let mut keys = Vec::new();
2304        for chunk in chunks {
2305            let column = chunk.into_body();
2306            assert!(
2307                column.length_in_bytes() <= COMMIT_BYTES || column.len() == 1,
2308                "{} bytes in a {}-record chunk",
2309                column.length_in_bytes(),
2310                column.len(),
2311            );
2312            let view = column.borrow();
2313            for index in 0..view.len() {
2314                let ((key, payload), time, diff) = view.get(index);
2315                assert_eq!(payload.len(), payload_bytes);
2316                assert!(payload.iter().all(|byte| *byte == b'x'));
2317                assert_eq!((*time, *diff), (0, 1));
2318                keys.push(*key);
2319            }
2320        }
2321        assert_eq!(keys, (0..u64::cast_from(expected)).collect::<Vec<_>>());
2322    }
2323
2324    #[mz_ore::test]
2325    fn chunker_enforces_byte_bound() {
2326        let mut chunker = ChunkChunker::default();
2327        let mut input: Column<WideUpdate> = wide_column((0..4000).rev(), 3000).into();
2328        chunker.push_into(&mut input);
2329        let mut chunks = VecDeque::new();
2330        if let Some(chunk) = chunker.extract() {
2331            chunks.push_back(std::mem::take(chunk));
2332        }
2333        while let Some(chunk) = chunker.finish() {
2334            chunks.push_back(std::mem::take(chunk));
2335        }
2336        assert_wide_byte_bound(chunks, 4000, 3000);
2337    }
2338
2339    #[mz_ore::test]
2340    fn merge_settle_enforces_byte_bound() {
2341        let mut left = VecDeque::from([WideChunk::from_body(wide_column(
2342            (0..2000).step_by(2),
2343            2100,
2344        ))]);
2345        let mut right = VecDeque::from([WideChunk::from_body(wide_column(
2346            (1..2000).step_by(2),
2347            2100,
2348        ))]);
2349        let mut merged = VecDeque::new();
2350        while !left.is_empty() && !right.is_empty() {
2351            WideChunk::merge(&mut left, &mut right, &mut merged);
2352        }
2353        merged.append(&mut left);
2354        merged.append(&mut right);
2355        let mut settled = VecDeque::new();
2356        WideChunk::settle(&mut merged, true, &mut settled);
2357        assert_wide_byte_bound(settled, 2000, 2100);
2358    }
2359
2360    #[mz_ore::test]
2361    fn settle_enforces_byte_bound_after_coalescing() {
2362        let mut input = VecDeque::from([
2363            WideChunk::from_body(wide_column(0..400, 3000)),
2364            WideChunk::from_body(wide_column(400..800, 3000)),
2365        ]);
2366        let mut settled = VecDeque::new();
2367        WideChunk::settle(&mut input, true, &mut settled);
2368        assert_wide_byte_bound(settled, 800, 3000);
2369    }
2370
2371    #[mz_ore::test]
2372    fn settle_byte_bound_allows_indivisible_update() {
2373        let mut input = VecDeque::from([WideChunk::from_body(wide_column(0..1, 2 * COMMIT_BYTES))]);
2374        let mut settled = VecDeque::new();
2375        WideChunk::settle(&mut input, true, &mut settled);
2376        assert_wide_byte_bound(settled, 1, 2 * COMMIT_BYTES);
2377    }
2378
2379    /// One record just under the bound among many narrow ones, so a cut at
2380    /// the average width leaves the piece holding the wide record over the
2381    /// bound.
2382    #[mz_ore::test]
2383    fn push_bounded_splits_uneven_widths() {
2384        let mut column: ColumnBody<WideUpdate> = ColumnBody::default();
2385        column.push_into(&((0, "x".repeat(COMMIT_BYTES - 4096)), 0, 1));
2386        for key in 1..20_000u64 {
2387            column.push_into(&((key, "x".to_string()), 0, 1));
2388        }
2389        assert!(column.length_in_bytes() > COMMIT_BYTES);
2390        let mut out = VecDeque::new();
2391        WideChunk::push_bounded(column, 3, &mut out);
2392        let mut keys = Vec::new();
2393        for chunk in out {
2394            let ColumnChunk::Resident(_, depth) = &chunk else {
2395                panic!("pieces are resident");
2396            };
2397            assert_eq!(*depth, 3, "pieces keep the input's depth");
2398            let column = chunk.into_body();
2399            assert!(
2400                column.length_in_bytes() <= COMMIT_BYTES || column.len() == 1,
2401                "{} bytes in a {}-record piece",
2402                column.length_in_bytes(),
2403                column.len(),
2404            );
2405            let view = column.borrow();
2406            for index in 0..view.len() {
2407                let ((key, _), _, _) = view.get(index);
2408                keys.push(*key);
2409            }
2410        }
2411        assert_eq!(keys, (0..20_000u64).collect::<Vec<_>>());
2412    }
2413
2414    /// Each side is under the bound, so any oversized output would have to
2415    /// come from `merge_from` itself. One input interleaves record by record,
2416    /// the other has runs long enough to gallop.
2417    #[mz_ore::test]
2418    fn merge_output_within_byte_bound_before_settle() {
2419        let interleaved = (
2420            wide_column((0..1600).step_by(2), 2100),
2421            wide_column((1..1600).step_by(2), 2100),
2422        );
2423        let runs = (
2424            wide_column((0..500).chain(1000..1100), 2100),
2425            wide_column(500..1000, 2100),
2426        );
2427        for (left, right) in [interleaved, runs] {
2428            let expected = left.len() + right.len();
2429            let mut left = VecDeque::from([WideChunk::from_body(left)]);
2430            let mut right = VecDeque::from([WideChunk::from_body(right)]);
2431            let mut merged = VecDeque::new();
2432            while !left.is_empty() && !right.is_empty() {
2433                WideChunk::merge(&mut left, &mut right, &mut merged);
2434            }
2435            assert!(merged.len() > 1, "merge never cut its output");
2436            merged.append(&mut left);
2437            merged.append(&mut right);
2438            assert_wide_byte_bound(merged, expected, 2100);
2439        }
2440    }
2441
2442    #[mz_ore::test]
2443    fn settle_split_preserves_depth() {
2444        let column = Rc::new(wide_column(0..2000, 2100));
2445        let shared = Rc::clone(&column);
2446        let mut input = VecDeque::from([WideChunk::Resident(column, 3)]);
2447        let mut settled = VecDeque::new();
2448        WideChunk::settle(&mut input, true, &mut settled);
2449        assert!(settled.len() > 1, "oversized chunk was not split");
2450        for chunk in &settled {
2451            assert_eq!(chunk.depth(), 3, "split piece changed generation");
2452        }
2453        assert_eq!(shared.len(), 2000, "shared body was mutated");
2454        assert_wide_byte_bound(settled, 2000, 2100);
2455    }
2456
2457    /// The last piece of a split coalesces with a shallower neighbor and
2458    /// commits at the deeper depth.
2459    #[mz_ore::test]
2460    fn settle_split_then_coalesce_keeps_depth() {
2461        let mut input = VecDeque::from([
2462            WideChunk::Resident(Rc::new(wide_column(0..800, 3000)), 2),
2463            WideChunk::Resident(Rc::new(wide_column(800..810, 3000)), 0),
2464        ]);
2465        let mut settled = VecDeque::new();
2466        WideChunk::settle(&mut input, true, &mut settled);
2467        assert!(settled.len() > 1, "oversized chunk was not split");
2468        for chunk in &settled {
2469            assert_eq!(chunk.depth(), 2, "coalescing lost the deeper generation");
2470        }
2471        assert_wide_byte_bound(settled, 810, 3000);
2472    }
2473
2474    /// Chunks of just over half the bound: unless settle moves part of each
2475    /// chunk into the column it is accumulating, every chunk commits at about
2476    /// half a slot.
2477    #[mz_ore::test]
2478    fn settle_fills_accumulated_column_from_next_chunk() {
2479        let per_chunk = 370;
2480        let mut input: VecDeque<WideChunk> = (0..8u64)
2481            .map(|i| {
2482                let start = i * per_chunk;
2483                WideChunk::from_body(wide_column(start..start + per_chunk, 3000))
2484            })
2485            .collect();
2486        let chunk_bytes = input[0].clone().into_body().length_in_bytes();
2487        assert!(2 * chunk_bytes > COMMIT_BYTES && chunk_bytes < COMMIT_BYTES);
2488        let mut settled = VecDeque::new();
2489        WideChunk::settle(&mut input, true, &mut settled);
2490        let sizes: Vec<usize> = settled
2491            .iter()
2492            .map(|chunk| chunk.clone().into_body().length_in_bytes())
2493            .collect();
2494        let (last, rest) = sizes.split_last().expect("settled output");
2495        assert!(*last <= COMMIT_BYTES);
2496        for size in rest {
2497            assert!(
2498                *size >= COMMIT_BYTES - COMMIT_BYTES / 10 && *size <= COMMIT_BYTES,
2499                "committed {size} bytes, sizes {sizes:?}",
2500            );
2501        }
2502        assert_wide_byte_bound(settled, 8 * 370, 3000);
2503    }
2504
2505    /// Advancing a large input cuts the output into several chunks near the
2506    /// ship threshold, and their concatenation is the reference result.
2507    #[mz_ore::test]
2508    #[cfg_attr(miri, ignore)]
2509    fn advance_cuts_large_output() {
2510        let records: Vec<Tuple> = (0..300_000u64).map(|k| ((k, 0), 0, 1)).collect();
2511        let mut input = VecDeque::from([ColumnChunk::from_body(build_column(&records))]);
2512        let frontier = Antichain::from_elem(0u64);
2513        let mut out = VecDeque::new();
2514        TestChunk::advance(&mut input, frontier.borrow(), true, &mut out);
2515        assert!(input.is_empty());
2516        assert!(
2517            out.len() >= 2,
2518            "expected a cut output, got {} chunk(s)",
2519            out.len()
2520        );
2521        assert_eq!(collect_bounded(out, 2 * COMMIT_BYTES), records);
2522    }
2523
2524    /// An input that is entirely one `D` group is withheld whole as the
2525    /// carry unless `done`: none of it is provably complete.
2526    #[mz_ore::test]
2527    #[cfg_attr(miri, ignore)]
2528    fn advance_withholds_giant_group() {
2529        let records: Vec<Tuple> = (0..100u64).map(|t| ((7, 7), t, 1)).collect();
2530        let mut input: VecDeque<TestChunk> = VecDeque::new();
2531        for piece in records.chunks(30) {
2532            input.push_back(ColumnChunk::from_body(build_column(piece)));
2533        }
2534        let frontier = Antichain::from_elem(50u64);
2535        let mut out = VecDeque::new();
2536        TestChunk::advance(&mut input, frontier.borrow(), false, &mut out);
2537        assert!(out.is_empty(), "nothing may ship from a single open group");
2538        assert_eq!(input.len(), 1, "the whole input becomes one carry chunk");
2539        // Sealing the carry advances and consolidates it.
2540        TestChunk::advance(&mut input, frontier.borrow(), true, &mut out);
2541        assert!(input.is_empty());
2542        let advanced = records.iter().map(|&(d, t, r)| (d, t.max(50), r)).collect();
2543        assert_eq!(collect_chunks(out), consolidate(advanced));
2544    }
2545
2546    /// Chunks the extract frontier does not split pass through whole from
2547    /// their resident time bounds: spilled bodies land on their side still
2548    /// spilled, with no load or re-commit, and a kept chunk's minimal times
2549    /// feed the residual frontier.
2550    #[mz_ore::test]
2551    #[cfg_attr(miri, ignore)]
2552    fn extract_passes_frontier_disjoint_chunks_through() {
2553        set_spill_override(Some(test_pool()));
2554        let low: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), i % 4, 1)).collect();
2555        let high: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 6 + i % 4, 1)).collect();
2556        let spilled_chunk = |data: &[Tuple]| {
2557            let chunk = TestChunk::commit(build_column(&consolidate(data.to_vec())), 1);
2558            assert!(chunk.is_spilled());
2559            chunk
2560        };
2561
2562        // A frontier between the two chunks' time ranges: the low chunk
2563        // ships whole and the high chunk keeps whole, both still spilled
2564        // (no load, no re-commit), and the residual is the kept chunk's
2565        // minimal time.
2566        let mut input = VecDeque::from([spilled_chunk(&low), spilled_chunk(&high)]);
2567        let frontier = Antichain::from_elem(5u64);
2568        let mut residual = Antichain::new();
2569        let (mut keep, mut ship) = (VecDeque::new(), VecDeque::new());
2570        while !input.is_empty() {
2571            TestChunk::extract(
2572                &mut input,
2573                frontier.borrow(),
2574                &mut residual,
2575                &mut keep,
2576                &mut ship,
2577            );
2578        }
2579        assert_eq!(ship.len(), 1);
2580        assert!(ship[0].is_spilled(), "shipped whole: body untouched");
2581        assert_eq!(keep.len(), 1);
2582        assert!(keep[0].is_spilled(), "kept whole: body untouched");
2583        assert_eq!(residual, Antichain::from_elem(6));
2584        let shipped = ship.pop_front().unwrap().into_body();
2585        assert_eq!(collect_column(&shipped), consolidate(low));
2586        let kept = keep.pop_front().unwrap().into_body();
2587        assert_eq!(collect_column(&kept), consolidate(high));
2588        set_spill_override(None);
2589    }
2590
2591    /// Extracting a large chunk at an intermediate frontier cuts both sides
2592    /// into several chunks and partitions exactly by time.
2593    #[mz_ore::test]
2594    #[cfg_attr(miri, ignore)]
2595    fn extract_cuts_large_output() {
2596        let records: Vec<Tuple> = (0..300_000u64).map(|k| ((k, 0), k % 2, 1)).collect();
2597        let mut input = VecDeque::from([ColumnChunk::from_body(build_column(&records))]);
2598        let frontier = Antichain::from_elem(1u64);
2599        let mut residual = Antichain::new();
2600        let (mut keep, mut ship) = (VecDeque::new(), VecDeque::new());
2601        while !input.is_empty() {
2602            TestChunk::extract(
2603                &mut input,
2604                frontier.borrow(),
2605                &mut residual,
2606                &mut keep,
2607                &mut ship,
2608            );
2609        }
2610        assert!(
2611            keep.len() >= 2,
2612            "expected a cut keep side, got {} chunk(s)",
2613            keep.len()
2614        );
2615        assert!(
2616            ship.len() >= 2,
2617            "expected a cut ship side, got {} chunk(s)",
2618            ship.len()
2619        );
2620        let kept: Vec<Tuple> = records.iter().copied().filter(|r| r.1 >= 1).collect();
2621        let shipped: Vec<Tuple> = records.iter().copied().filter(|r| r.1 < 1).collect();
2622        assert_eq!(collect_bounded(keep, 2 * COMMIT_BYTES), kept);
2623        assert_eq!(collect_bounded(ship, 2 * COMMIT_BYTES), shipped);
2624        assert_eq!(residual, Antichain::from_elem(1));
2625    }
2626
2627    /// `locate` answers from resident metadata on spilled chunks and follows
2628    /// the probe-relative-to-span convention.
2629    #[mz_ore::test]
2630    fn locate_uses_resident_bounds() {
2631        let pool = test_pool();
2632        let data: Vec<Tuple> = vec![((2, 0), 0, 1), ((4, 0), 0, 1)];
2633        let chunk = force_spill(ColumnChunk::from_body(build_column(&data)), &pool);
2634
2635        let mut probe_col = <u64 as Columnar>::Container::default();
2636        for key in [1u64, 3, 5] {
2637            probe_col.push(key);
2638        }
2639        let probes = probe_col.borrow();
2640        assert_eq!(chunk.locate(probes, 0), std::cmp::Ordering::Less);
2641        assert_eq!(chunk.locate(probes, 1), std::cmp::Ordering::Equal);
2642        assert_eq!(chunk.locate(probes, 2), std::cmp::Ordering::Greater);
2643    }
2644
2645    /// A body large enough to spill round-trips through the pool with resident
2646    /// metadata intact, and the batcher produces spilled sealed output.
2647    #[mz_ore::test]
2648    #[cfg_attr(miri, ignore)] // too slow
2649    fn spill_round_trip() {
2650        set_spill_override(Some(test_pool()));
2651
2652        let data: Vec<Tuple> = (0..40_000u64)
2653            .map(|i| ((i / 4, i % 4), i % 8, 1i64))
2654            .collect();
2655        let data = consolidate(data);
2656
2657        let column = build_column(&data);
2658        let committed = TestChunk::commit(column, 0);
2659        assert!(committed.is_spilled(), "large body must spill");
2660        assert_eq!(committed.len(), data.len());
2661        assert_eq!(collect_column(&committed.clone().into_body()), data);
2662
2663        let mut batcher = TestChunkBatcher::new(None, 0);
2664        for piece in data.chunks(10_000) {
2665            batcher.push_chunk(ColumnChunk::from_body(build_column(piece)));
2666        }
2667        let (sealed, _frontier) = batcher.extract(Antichain::new().borrow());
2668        let sealed = sealed.unwrap_or_default();
2669        assert!(
2670            sealed.iter().any(ColumnChunk::is_spilled),
2671            "sealed output should contain spilled chunks",
2672        );
2673        assert_eq!(collect_chunks(sealed), data);
2674
2675        set_spill_override(None);
2676    }
2677
2678    /// Merging spilled chains loads bodies call-scoped and consolidates
2679    /// correctly, and an untouched survivor keeps its spilled body.
2680    #[mz_ore::test]
2681    #[cfg_attr(miri, ignore)] // too slow
2682    fn merge_spilled_chains() {
2683        set_spill_override(Some(test_pool()));
2684
2685        let a: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect();
2686        let b: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 0, 2i64)).collect();
2687
2688        let mut in1 = VecDeque::from([TestChunk::commit(build_column(&a), 0)]);
2689        let mut in2 = VecDeque::from([TestChunk::commit(build_column(&b), 0)]);
2690        assert!(in1[0].is_spilled() && in2[0].is_spilled());
2691
2692        let mut out = VecDeque::new();
2693        while !in1.is_empty() && !in2.is_empty() {
2694            TestChunk::merge(&mut in1, &mut in2, &mut out);
2695        }
2696        for tail in in1.drain(..).chain(in2.drain(..)) {
2697            out.push_back(tail);
2698        }
2699
2700        let expected: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 0, 3i64)).collect();
2701        assert_eq!(collect_chunks(out), expected);
2702
2703        set_spill_override(None);
2704    }
2705
2706    /// A merge whose fronts have disjoint key ranges pushes the untouched
2707    /// survivor back in its original (spilled) form rather than rewriting it.
2708    #[mz_ore::test]
2709    fn merge_untouched_survivor_stays_spilled() {
2710        let pool = test_pool();
2711        let low: Vec<Tuple> = (0..100u64).map(|i| ((i, 0), 0, 1i64)).collect();
2712        let high: Vec<Tuple> = (1000..1100u64).map(|i| ((i, 0), 0, 1i64)).collect();
2713
2714        let mut in1 = VecDeque::from([force_spill(
2715            ColumnChunk::from_body(build_column(&low)),
2716            &pool,
2717        )]);
2718        let mut in2 = VecDeque::from([force_spill(
2719            ColumnChunk::from_body(build_column(&high)),
2720            &pool,
2721        )]);
2722        let mut out = VecDeque::new();
2723        TestChunk::merge(&mut in1, &mut in2, &mut out);
2724
2725        // `low` is fully consumed. `high` was never touched and must come
2726        // back spilled.
2727        assert!(in1.is_empty());
2728        assert_eq!(in2.len(), 1);
2729        assert!(in2[0].is_spilled(), "untouched survivor must stay spilled");
2730        let mut all = collect_chunks(out);
2731        Extend::extend(&mut all, collect_chunks(in2.drain(..)));
2732        let mut expected = low;
2733        Extend::extend(&mut expected, high);
2734        assert_eq!(all, expected);
2735    }
2736
2737    /// Merge output is one generation past its deepest input, a survivor
2738    /// rewritten from its remainder keeps its own depth, and a chunk passed
2739    /// through the disjoint fast path ages by its survival.
2740    #[mz_ore::test]
2741    fn merge_derives_generational_depth() {
2742        let low: Vec<Tuple> = (0..100u64).map(|i| ((i, 0), 0, 1i64)).collect();
2743        let high: Vec<Tuple> = (50..150u64).map(|i| ((i, 0), 0, 1i64)).collect();
2744        let mut in1 = VecDeque::from([ColumnChunk::from_body(build_column(&low))]);
2745        let mut in2 = VecDeque::from([ColumnChunk::from_body(build_column(&high))]);
2746        assert_eq!(in1[0].depth(), 0, "fresh chunks start at depth 0");
2747        let mut out = VecDeque::new();
2748        TestChunk::merge(&mut in1, &mut in2, &mut out);
2749        assert!(!out.is_empty());
2750        for chunk in &out {
2751            assert_eq!(chunk.depth(), 1, "merge output is one past its inputs");
2752        }
2753        // The merge runs through the shared horizon, so `high` survives with
2754        // its unmerged remainder at its original depth.
2755        assert!(in1.is_empty());
2756        assert_eq!(in2.len(), 1);
2757        assert_eq!(in2[0].depth(), 0, "rewritten survivor keeps its depth");
2758
2759        // A disjoint merge moves the lower front to the output with its data
2760        // unchanged, one generation older for having outlived the merge.
2761        let mut in1 = VecDeque::from([ColumnChunk::Resident(Rc::new(build_column(&low)), 3)]);
2762        let far: Vec<Tuple> = (1000..1100u64).map(|i| ((i, 0), 0, 1i64)).collect();
2763        let mut in2 = VecDeque::from([ColumnChunk::from_body(build_column(&far))]);
2764        let mut out = VecDeque::new();
2765        TestChunk::merge(&mut in1, &mut in2, &mut out);
2766        assert_eq!(out.len(), 1);
2767        assert_eq!(out[0].depth(), 4, "pass-through ages a generation");
2768        assert_eq!(collect_chunks(out), low);
2769    }
2770
2771    /// Advance output and carry keep the deepest input depth, since
2772    /// compaction rewrites within a generation.
2773    #[mz_ore::test]
2774    fn advance_preserves_depth() {
2775        let data: Vec<Tuple> = (0..100u64).map(|i| ((i, 0), 1, 1i64)).collect();
2776        let mut input = VecDeque::from([
2777            ColumnChunk::Resident(Rc::new(build_column(&data[..50])), 2),
2778            ColumnChunk::Resident(Rc::new(build_column(&data[50..])), 1),
2779        ]);
2780        let frontier = Antichain::from_elem(5u64);
2781        let mut out = VecDeque::new();
2782        TestChunk::advance(&mut input, frontier.borrow(), false, &mut out);
2783        for chunk in out.iter().chain(input.iter()) {
2784            assert_eq!(chunk.depth(), 2);
2785        }
2786        TestChunk::advance(&mut input, frontier.borrow(), true, &mut out);
2787        assert!(input.is_empty());
2788        assert!(!out.is_empty());
2789        for chunk in &out {
2790            assert_eq!(chunk.depth(), 2);
2791        }
2792    }
2793
2794    /// Settle commits at the deepest depth among coalesced chunks, and a
2795    /// commit large enough to spill carries the depth into its spilled
2796    /// metadata (and thus into the pool hints).
2797    #[mz_ore::test]
2798    #[cfg_attr(miri, ignore)] // too slow
2799    fn settle_commits_at_accumulated_depth() {
2800        set_spill_override(Some(test_pool()));
2801        let big: Vec<Tuple> = (0..60_000u64).map(|i| ((i, 0), 0, 1i64)).collect();
2802        let mut input = VecDeque::from([
2803            ColumnChunk::Resident(Rc::new(build_column(&big)), 1),
2804            ColumnChunk::Resident(Rc::new(build_column(&[((0, 0), 0, 1)])), 0),
2805            ColumnChunk::Resident(Rc::new(build_column(&[((1, 0), 0, 1)])), 2),
2806        ]);
2807        let mut out = VecDeque::new();
2808        TestChunk::settle(&mut input, true, &mut out);
2809        assert!(input.is_empty());
2810        assert_eq!(out.len(), 2);
2811        assert!(out[0].is_spilled(), "large commit must spill");
2812        assert_eq!(out[0].depth(), 1, "sole commit keeps its depth");
2813        assert!(!out[1].is_spilled(), "small commit stays resident");
2814        assert_eq!(out[1].depth(), 2, "coalesced commit takes the max depth");
2815        set_spill_override(None);
2816    }
2817
2818    /// The settle carry commits at a monotone size threshold rather than the
2819    /// periodic ship window, so mid-window chunk sizes cannot make it grow
2820    /// past the target unbounded.
2821    #[mz_ore::test]
2822    #[cfg_attr(miri, ignore)] // too slow
2823    fn settle_carry_commits_at_target() {
2824        // Two inputs fit in one slot. A third must start another chunk.
2825        let chunk_rows = u64::cast_from(800_000usize / 32);
2826        let mut input: VecDeque<TestChunk> = (0..4u64)
2827            .map(|c| {
2828                let data: Vec<Tuple> = (0..chunk_rows)
2829                    .map(|i| ((c * chunk_rows + i, 0), 0, 1i64))
2830                    .collect();
2831                ColumnChunk::from_body(build_column(&data))
2832            })
2833            .collect();
2834        let mut out = VecDeque::new();
2835        TestChunk::settle(&mut input, true, &mut out);
2836        // Catches the fixture drifting above `at_commit_size`, where settle
2837        // commits each chunk as-is and the size cap below holds vacuously.
2838        assert!(out.len() < 4, "nothing coalesced");
2839        for chunk in &out {
2840            let col = chunk.clone().into_body();
2841            assert!(
2842                col.length_in_bytes() <= COMMIT_BYTES,
2843                "settled chunk of {} bytes exceeds the commit target",
2844                col.length_in_bytes(),
2845            );
2846        }
2847        assert_eq!(
2848            collect_chunks(out).len(),
2849            usize::try_from(4 * chunk_rows).unwrap(),
2850        );
2851    }
2852
2853    #[mz_ore::test]
2854    fn small_chunks_stay_resident() {
2855        set_spill_override(Some(test_pool()));
2856        let committed = TestChunk::commit(build_column(&[((1, 1), 0, 1)]), 0);
2857        assert!(!committed.is_spilled());
2858        set_spill_override(None);
2859    }
2860
2861    /// The smallest column whose serialized size reaches `SPILL_MIN_BYTES`.
2862    /// One record less sits under the spill floor.
2863    fn column_at_spill_floor() -> (ColumnBody<Tuple>, u64) {
2864        let mut col: ColumnBody<Tuple> = ColumnBody::default();
2865        let mut n = 0u64;
2866        while col.length_in_bytes() < SPILL_MIN_BYTES {
2867            col.push_into(((n, n), 0, 1));
2868            n += 1;
2869        }
2870        (col, n)
2871    }
2872
2873    /// Bodies straddling the spill floor: one record under stays resident,
2874    /// at the floor spills.
2875    #[mz_ore::test]
2876    fn spill_floor_boundary() {
2877        set_spill_override(Some(test_pool()));
2878        let (col, n) = column_at_spill_floor();
2879        let mut under: ColumnBody<Tuple> = ColumnBody::default();
2880        for m in 0..n - 1 {
2881            under.push_into(((m, m), 0, 1));
2882        }
2883        assert!(under.length_in_bytes() < SPILL_MIN_BYTES);
2884        assert!(!TestChunk::commit(under, 0).is_spilled());
2885        assert!(TestChunk::commit(col, 0).is_spilled());
2886        set_spill_override(None);
2887    }
2888
2889    /// The compression depth floor picks the codec, not whether a body
2890    /// spills: shallow generations store at identity, the floor and deeper
2891    /// at lz4, and every depth spills and round-trips.
2892    #[mz_ore::test]
2893    fn spill_codec_depth_floor() {
2894        set_spill_override(Some(test_pool()));
2895        set_compress_min_depth_override(Some(2));
2896        // Codec identity via Debug: ZST statics and dyn vtables make
2897        // pointer comparison unreliable. The flag must agree with the codec,
2898        // since it is what decides whether a body wants migrating.
2899        let codec_name = |depth: u8| {
2900            let (codec, compressed) = codec_for_depth(depth, compress_min_depth());
2901            let name = format!("{:?}", codec);
2902            assert_eq!(compressed, name == "Lz4Codec", "flag tracks the codec");
2903            name
2904        };
2905        assert_eq!(codec_name(0), "IdentityCodec");
2906        assert_eq!(codec_name(1), "IdentityCodec");
2907        assert_eq!(codec_name(2), "Lz4Codec");
2908        assert_eq!(codec_name(u8::MAX), "Lz4Codec");
2909
2910        let data: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect();
2911        let data = consolidate(data);
2912        let column = build_column(&data);
2913        for depth in [0u8, 1, 2, 3] {
2914            let chunk = TestChunk::commit(column.clone(), depth);
2915            assert!(chunk.is_spilled(), "depth {depth} must spill");
2916            assert_eq!(collect_column(&chunk.into_body()), data);
2917        }
2918        set_spill_override(None);
2919        set_compress_min_depth_override(None);
2920
2921        // The default floor stores only fresh (depth 0) bodies at identity.
2922        set_compress_min_depth_override(Some(DEFAULT_COMPRESS_MIN_DEPTH));
2923        assert_eq!(codec_name(0), "IdentityCodec");
2924        assert_eq!(codec_name(1), "Lz4Codec");
2925        set_compress_min_depth_override(None);
2926    }
2927
2928    /// Bodies spilled through `try_spill_ref` store under the codec the sink
2929    /// floor picks, whatever the chunk floor says. A zero-budget pool writes
2930    /// every insert straight to an extent, so the written bytes show the codec.
2931    #[mz_ore::test]
2932    #[cfg_attr(miri, ignore)]
2933    fn sink_spill_codec_follows_sink_floor() {
2934        static POOL: std::sync::OnceLock<Pool> = std::sync::OnceLock::new();
2935        let pool = POOL
2936            .get_or_init(|| {
2937                let pool = Pool::new().expect("pool creation");
2938                pool.set_budget(0);
2939                pool
2940            })
2941            .clone();
2942        set_spill_override(Some(pool.clone()));
2943        // Identical records, which lz4 shrinks far below their length.
2944        let mut col: ColumnBody<Tuple> = ColumnBody::default();
2945        while col.length_in_bytes() < SPILL_MIN_BYTES {
2946            col.push_into(((0, 0), 0, 1));
2947        }
2948        let len = u64::cast_from(col.length_in_bytes());
2949        let written = |chunk_floor: u8, sink_floor: u8| {
2950            set_compress_min_depth_override(Some(chunk_floor));
2951            set_sink_compress_min_depth_override(Some(sink_floor));
2952            let before = pool.stats().extent_bytes_written;
2953            let handle = try_spill_ref(&col, 1).expect("the override pool takes the body");
2954            let written = pool.stats().extent_bytes_written - before;
2955            drop(handle);
2956            written
2957        };
2958        assert_eq!(
2959            written(0, u8::MAX),
2960            len,
2961            "below the sink floor, the body stores uncompressed"
2962        );
2963        assert!(
2964            written(u8::MAX, 0) < len / 2,
2965            "at the sink floor, the body stores compressed"
2966        );
2967        set_spill_override(None);
2968        set_compress_min_depth_override(None);
2969        set_sink_compress_min_depth_override(None);
2970    }
2971
2972    /// A chunk a merge carries forward untouched ages a generation, and a
2973    /// spilled body crossing the compression floor by doing so is re-spilled
2974    /// under the compressing codec. Key-disjoint input takes that path on
2975    /// every merge, so without the crossing its backlog would stay
2976    /// identity-coded for as long as it lived.
2977    #[mz_ore::test]
2978    #[cfg_attr(miri, ignore)] // too slow
2979    fn merge_survivor_crosses_compression_floor() {
2980        set_spill_override(Some(test_pool()));
2981        set_compress_min_depth_override(Some(1));
2982
2983        let low = consolidate((0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
2984        let far = consolidate((100_000..120_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
2985        let fresh_far = || VecDeque::from([TestChunk::commit(build_column(&far), 0)]);
2986
2987        // Fresh spilled chunks sit below the floor, so both store identity
2988        // coded, and their data ranges are disjoint.
2989        let mut in1 = VecDeque::from([TestChunk::commit(build_column(&low), 0)]);
2990        let mut in2 = fresh_far();
2991        assert!(in1[0].is_spilled() && in2[0].is_spilled());
2992        assert!(
2993            !body_compressed(&in1[0]),
2994            "a fresh body below the floor is identity coded"
2995        );
2996
2997        let mut out = VecDeque::new();
2998        TestChunk::merge(&mut in1, &mut in2, &mut out);
2999        assert_eq!(out.len(), 1);
3000        let survived = out.pop_front().expect("the lower front passes through");
3001        assert_eq!(survived.depth(), 1, "survival ages across the floor");
3002        assert!(
3003            survived.is_spilled(),
3004            "the crossing re-spills, it does not evict"
3005        );
3006        assert!(
3007            body_compressed(&survived),
3008            "the survivor is re-spilled under the compressing codec"
3009        );
3010
3011        // Past the floor the next survival is a metadata-only bump: the body
3012        // is already compressed and stays where it is.
3013        let mut in1 = VecDeque::from([survived]);
3014        let mut in2 = fresh_far();
3015        let mut out = VecDeque::new();
3016        TestChunk::merge(&mut in1, &mut in2, &mut out);
3017        assert_eq!(out.len(), 1);
3018        assert_eq!(out[0].depth(), 2, "an aged survivor keeps aging");
3019        assert!(out[0].is_spilled());
3020        assert_eq!(
3021            collect_chunks(out),
3022            low,
3023            "the body reads back intact across both survivals"
3024        );
3025
3026        set_spill_override(None);
3027        set_compress_min_depth_override(None);
3028    }
3029
3030    /// Aging does not depend on holding the only reference to a body. The
3031    /// trace's compaction merger feeds `merge` clones of a source batch's
3032    /// chunks and keeps the batch alive throughout, so a shared body must
3033    /// still age. It must not be re-spilled: the other holder goes on
3034    /// storing the original whatever this reference does, and the merger
3035    /// rewrites its clone immediately.
3036    #[mz_ore::test]
3037    #[cfg_attr(miri, ignore)] // too slow
3038    fn merge_survivor_ages_while_shared() {
3039        set_spill_override(Some(test_pool()));
3040        set_compress_min_depth_override(Some(1));
3041
3042        let low = consolidate((0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
3043        let far = consolidate((100_000..120_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
3044
3045        // The source batch's chunk, held for the whole merge as the spine
3046        // holds it.
3047        let source = TestChunk::commit(build_column(&low), 0);
3048        let ColumnChunk::Spilled(source_body, 0) = &source else {
3049            panic!("a fresh commit above the spill floor is spilled at depth 0");
3050        };
3051        let source_body = Rc::clone(source_body);
3052
3053        let mut in1 = VecDeque::from([source.clone()]);
3054        let mut in2 = VecDeque::from([TestChunk::commit(build_column(&far), 0)]);
3055        let mut out = VecDeque::new();
3056        TestChunk::merge(&mut in1, &mut in2, &mut out);
3057
3058        assert_eq!(out.len(), 1);
3059        assert_eq!(out[0].depth(), 1, "a shared body ages all the same");
3060        let ColumnChunk::Spilled(survived_body, _) = &out[0] else {
3061            panic!("the survivor stays spilled");
3062        };
3063        assert!(
3064            Rc::ptr_eq(&source_body, survived_body),
3065            "a shared body is aged in place, not re-spilled"
3066        );
3067        assert_eq!(source.depth(), 0, "the other holder is left as it was");
3068
3069        // Past the floor, where no re-spill is in question, a shared body
3070        // goes on aging rather than pinning at the crossing depth.
3071        let mut in1 = VecDeque::from([out.pop_front().expect("survivor observed above")]);
3072        let mut in2 = VecDeque::from([TestChunk::commit(build_column(&far), 0)]);
3073        let mut out = VecDeque::new();
3074        TestChunk::merge(&mut in1, &mut in2, &mut out);
3075        assert_eq!(out.len(), 1);
3076        assert_eq!(out[0].depth(), 2, "aging past the floor is not pinned");
3077        assert_eq!(collect_chunks(out), low);
3078
3079        set_spill_override(None);
3080        set_compress_min_depth_override(None);
3081    }
3082
3083    /// A migration that cannot happen when a body first qualifies is retried
3084    /// at the next survival, never consumed. Each case leaves an
3085    /// identity-coded body at or past the floor, which would be stranded
3086    /// uncompressed for the rest of its life if the test were a depth
3087    /// transition rather than the body's stored codec.
3088    #[mz_ore::test]
3089    #[cfg_attr(miri, ignore)] // too slow
3090    fn survive_merge_retries_missed_migrations() {
3091        let low = consolidate((0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
3092        let far = consolidate((100_000..120_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
3093
3094        // Age a chunk one generation through a disjoint merge, which passes
3095        // the lower front through `survive_merge`.
3096        let survive = |chunk: TestChunk| {
3097            let mut in1 = VecDeque::from([chunk]);
3098            let mut in2 = VecDeque::from([TestChunk::commit(build_column(&far), 0)]);
3099            let mut out = VecDeque::new();
3100            TestChunk::merge(&mut in1, &mut in2, &mut out);
3101            out.pop_front().expect("the lower front passes through")
3102        };
3103
3104        // No pool installed when the body qualifies: spilling can be toggled
3105        // off at runtime while existing handles stay valid.
3106        set_spill_override(Some(test_pool()));
3107        set_compress_min_depth_override(Some(1));
3108        let chunk = TestChunk::commit(build_column(&low), 0);
3109        assert!(!body_compressed(&chunk));
3110        set_spill_override(None);
3111        let chunk = survive(chunk);
3112        assert_eq!(chunk.depth(), 1, "aging does not need a pool");
3113        assert!(!body_compressed(&chunk), "no pool, no migration");
3114        set_spill_override(Some(test_pool()));
3115        let chunk = survive(chunk);
3116        assert!(
3117            body_compressed(&chunk),
3118            "the migration retries once a pool is back"
3119        );
3120
3121        // Shared when the body qualifies: the compaction merger holds the
3122        // source batch while merging clones of its chunks.
3123        let chunk = TestChunk::commit(build_column(&low), 0);
3124        let held = chunk.clone();
3125        let chunk = survive(chunk);
3126        assert!(!body_compressed(&chunk), "shared, so not migrated");
3127        drop(held);
3128        let chunk = survive(chunk);
3129        assert!(
3130            body_compressed(&chunk),
3131            "the migration retries once the body is unshared"
3132        );
3133
3134        // The floor lowered long after the body spilled, which is what an
3135        // operator reaches for under pool pressure. Nothing here is a
3136        // transition: the body is already several generations past the new
3137        // floor when it moves.
3138        set_compress_min_depth_override(Some(8));
3139        let chunk = TestChunk::commit(build_column(&low), 3);
3140        assert!(!body_compressed(&chunk));
3141        set_compress_min_depth_override(Some(1));
3142        let chunk = survive(chunk);
3143        assert_eq!(chunk.depth(), 4);
3144        assert!(
3145            body_compressed(&chunk),
3146            "lowering the floor migrates bodies already past it"
3147        );
3148
3149        set_spill_override(None);
3150        set_compress_min_depth_override(None);
3151    }
3152
3153    /// One test, because the gates are process-global.
3154    #[mz_ore::test]
3155    #[cfg_attr(miri, ignore)]
3156    fn spill_gates_are_independent() {
3157        let installed = crate::pool_config::apply_pool_config(
3158            crate::pool_config::PoolPagerConfig {
3159                budget_bytes: 32 << 20,
3160                spill_threads: 1,
3161                eager_backing: false,
3162                rss_target_bytes: 16 << 20,
3163                file_release_interval: std::time::Duration::ZERO,
3164                file_release_bytes: 0,
3165            },
3166            crate::pool_config::ExtentBackend::Swap,
3167        );
3168        assert!(installed, "pool reservation failed");
3169        // A body at the spill floor, so the gates alone decide.
3170        let (col, _) = column_at_spill_floor();
3171        let compute = |col: &ColumnBody<Tuple>| TestChunk::commit(col.clone(), 0).is_spilled();
3172        let storage = |col: &ColumnBody<Tuple>| {
3173            ColumnChunk::<(u64, u64), u64, i64, StorageSpill>::commit(col.clone(), 0).is_spilled()
3174        };
3175        let sink = |col: &ColumnBody<Tuple>| try_spill_ref(col, 0).is_some();
3176
3177        assert!(!compute(&col), "all gates off");
3178        assert!(!storage(&col), "all gates off");
3179        assert!(!sink(&col), "all gates off");
3180
3181        set_storage_spill_enabled(true);
3182        assert!(storage(&col), "the storage gate spills storage chunks");
3183        assert!(
3184            !compute(&col),
3185            "the storage gate must not spill compute chunks"
3186        );
3187        assert!(!sink(&col), "the storage gate must not spill sink bodies");
3188        set_storage_spill_enabled(false);
3189
3190        set_compute_spill_enabled(true);
3191        assert!(compute(&col), "the compute gate spills compute chunks");
3192        assert!(
3193            !storage(&col),
3194            "the compute gate must not spill storage chunks"
3195        );
3196        assert!(!sink(&col), "the compute gate must not spill sink bodies");
3197        set_compute_spill_enabled(false);
3198
3199        set_sink_spill_enabled(true);
3200        assert!(sink(&col), "the sink gate spills sink bodies");
3201        assert!(
3202            !compute(&col),
3203            "the sink gate must not spill compute chunks"
3204        );
3205        assert!(
3206            !storage(&col),
3207            "the sink gate must not spill storage chunks"
3208        );
3209        set_sink_spill_enabled(false);
3210        set_compress_min_depth_override(None);
3211    }
3212
3213    /// Re-spilling an already-serialized body exercises the `ColumnBody::Words`
3214    /// branch of the pooled body's serialization and round-trips
3215    /// byte-identically. A zero budget sends every insert straight to an
3216    /// extent, so each body is serialized and reads back as words.
3217    #[mz_ore::test]
3218    #[cfg_attr(miri, ignore)] // reserves a full-size pool
3219    fn spill_align_round_trip() {
3220        let pool = Pool::new().expect("pool reservation");
3221        pool.set_budget(0);
3222        let data: Vec<Tuple> = (0..64u64).map(|k| ((k, k), 0, 1)).collect();
3223        let spilled = force_spill(ColumnChunk::from_body(build_column(&data)), &pool);
3224        let column = spilled.into_body();
3225        let ColumnBody::Words(words) = &column else {
3226            panic!("an evicted body reads back as ColumnBody::Words");
3227        };
3228        let words = words.clone();
3229        let respilled = force_spill(ColumnChunk::from_body(column), &pool);
3230        let reread = respilled.into_body();
3231        let ColumnBody::Words(words2) = &reread else {
3232            panic!("an evicted body reads back as ColumnBody::Words");
3233        };
3234        assert_eq!(&words, words2, "byte-identical round trip");
3235        assert_eq!(collect_column(&reread), data);
3236    }
3237
3238    /// Reads every chunk's time bounds while spill threads evict it. The
3239    /// spill threads fill the bounds under the chunk's state lock, so a
3240    /// reader that takes the locks in the other order hangs this test.
3241    #[mz_ore::test]
3242    #[cfg_attr(miri, ignore)] // reserves a full-size pool
3243    fn time_bounds_race_spill_thread_eviction() {
3244        let (done_tx, done_rx) = std::sync::mpsc::channel();
3245        std::thread::spawn(move || {
3246            let pool = Pool::new().expect("pool reservation");
3247            pool.set_budget(0);
3248            pool.set_spill_threads(4);
3249            let data: Vec<Tuple> = (0..2048u64).map(|k| ((k, k), k % 7, 1)).collect();
3250            for _ in 0..2000 {
3251                let chunk = force_spill(ColumnChunk::from_body(build_column(&data)), &pool);
3252                let (lower, upper) = chunk.chunk_time_bounds();
3253                assert_eq!(lower.elements(), &[0]);
3254                assert_eq!(&upper[..], &[6]);
3255            }
3256            pool.set_spill_threads(0);
3257            done_tx.send(()).expect("receiver alive");
3258        });
3259        done_rx
3260            .recv_timeout(std::time::Duration::from_secs(120))
3261            .expect("time bounds reads deadlocked against spill-thread eviction");
3262    }
3263
3264    #[mz_ore::test]
3265    fn merge_depth_saturates() {
3266        let a = ColumnChunk::Resident(
3267            Rc::new(build_column(&[((1, 0), 0, 1), ((3, 0), 0, 1)])),
3268            u8::MAX,
3269        );
3270        let b = ColumnChunk::Resident(
3271            Rc::new(build_column(&[((2, 0), 0, 1), ((4, 0), 0, 1)])),
3272            u8::MAX,
3273        );
3274        let mut in1 = VecDeque::from([a]);
3275        let mut in2 = VecDeque::from([b]);
3276        let mut out = VecDeque::new();
3277        TestChunk::merge(&mut in1, &mut in2, &mut out);
3278        for chunk in out.iter().chain(in1.iter()).chain(in2.iter()) {
3279            assert_eq!(chunk.depth(), u8::MAX, "depth saturates");
3280        }
3281    }
3282
3283    #[mz_ore::test]
3284    fn into_body_copies_shared_resident() {
3285        let data: Vec<Tuple> = vec![((1, 1), 0, 1), ((2, 2), 0, 1)];
3286        let a = TestChunk::from_body(build_column(&data));
3287        let b = a.clone();
3288        assert_eq!(collect_column(&a.into_body()), data);
3289        assert_eq!(collect_column(&b.into_body()), data);
3290    }
3291}