Skip to main content

mz_persist_client/internal/
trace.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//! An append-only collection of compactable update batches. The Spine below is
11//! a fork of Differential Dataflow's [Spine] with minimal modifications. The
12//! original Spine code is designed for incremental (via "fuel"ing) synchronous
13//! merge of in-memory batches. Persist doesn't want compaction to block
14//! incoming writes and, in fact, may in the future elect to push the work of
15//! compaction onto another machine entirely via RPC. As a result, we abuse the
16//! Spine code as follows:
17//!
18//! [Spine]: differential_dataflow::trace::implementations::spine_fueled::Spine
19//!
20//! - The normal Spine works in terms of [Batch] impls. A `Batch` is added to
21//!   the Spine. As progress is made, the Spine will merge two batches together
22//!   by: constructing a [Batch::Merger], giving it bits of fuel to
23//!   incrementally perform the merge (which spreads out the work, keeping
24//!   latencies even), and then once it's done fueling extracting the new single
25//!   output `Batch` and discarding the inputs.
26//! - Persist instead represents a batch of blob data with a [HollowBatch]
27//!   pointer which contains the normal `Batch` metadata plus the keys necessary
28//!   to retrieve the updates.
29//! - [SpineBatch] wraps `HollowBatch` and has a [FuelingMerge] companion
30//!   (analogous to `Batch::Merger`) that allows us to represent a merge as it
31//!   is fueling. Normally, this would represent real incremental compaction
32//!   progress, but in persist, it's simply a bookkeeping mechanism. Once fully
33//!   fueled, the `FuelingMerge` is turned into a fueled [SpineBatch],
34//!   which to the Spine is indistinguishable from a merged batch. At this
35//!   point, it is eligible for asynchronous compaction and a `FueledMergeReq`
36//!   is generated.
37//! - At any later point, this request may be answered via
38//!   [Trace::apply_merge_res_checked] or [Trace::apply_merge_res_unchecked].
39//!   This internally replaces the`SpineBatch`, which has no
40//!   effect on the structure of `Spine` but replaces the metadata
41//!   in persist's state to point at the new batch.
42//! - `SpineBatch` is explictly allowed to accumulate a list of `HollowBatch`s.
43//!   This decouples compaction from Spine progress and also allows us to reduce
44//!   write amplification by merging `N` batches at once where `N` can be
45//!   greater than 2.
46//!
47//! [Batch]: differential_dataflow::trace::Batch
48//! [Batch::Merger]: differential_dataflow::trace::Batch::Merger
49
50use std::cmp::Ordering;
51use std::collections::{BTreeMap, BTreeSet};
52use std::fmt::{Debug, Display};
53use std::mem;
54use std::ops::Range;
55use std::sync::Arc;
56
57use arrayvec::ArrayVec;
58use differential_dataflow::difference::Monoid;
59use differential_dataflow::lattice::Lattice;
60use differential_dataflow::trace::Description;
61use itertools::Itertools;
62use mz_ore::cast::CastFrom;
63use mz_persist::metrics::ColumnarMetrics;
64use mz_persist_types::Codec64;
65use serde::{Serialize, Serializer};
66use timely::PartialOrder;
67use timely::progress::frontier::AntichainRef;
68use timely::progress::{Antichain, Timestamp};
69use tracing::{error, warn};
70
71use crate::internal::paths::WriterKey;
72use crate::internal::state::{HollowBatch, RunId};
73
74use super::state::RunPart;
75
76#[derive(Debug, Clone, PartialEq)]
77pub struct FueledMergeReq<T> {
78    pub id: SpineId,
79    pub desc: Description<T>,
80    pub inputs: Vec<IdHollowBatch<T>>,
81}
82
83#[derive(Debug)]
84pub struct FueledMergeRes<T> {
85    pub output: HollowBatch<T>,
86    pub input: CompactionInput,
87    pub new_active_compaction: Option<ActiveCompaction>,
88}
89
90/// An append-only collection of compactable update batches.
91///
92/// In an effort to keep our fork of Spine as close as possible to the original,
93/// we push as many changes as possible into this wrapper.
94#[derive(Debug, Clone)]
95pub struct Trace<T> {
96    spine: Spine<T>,
97    pub(crate) roundtrip_structure: bool,
98}
99
100#[cfg(any(test, debug_assertions))]
101impl<T: PartialEq> PartialEq for Trace<T> {
102    fn eq(&self, other: &Self) -> bool {
103        // Deconstruct self and other so we get a compile failure if new fields
104        // are added.
105        let Trace {
106            spine: _,
107            roundtrip_structure: _,
108        } = self;
109        let Trace {
110            spine: _,
111            roundtrip_structure: _,
112        } = other;
113
114        // Intentionally use HollowBatches for this comparison so we ignore
115        // differences in spine layers.
116        self.batches().eq(other.batches())
117    }
118}
119
120impl<T: Timestamp + Lattice> Default for Trace<T> {
121    fn default() -> Self {
122        Self {
123            spine: Spine::new(),
124            roundtrip_structure: true,
125        }
126    }
127}
128
129#[derive(Clone, Debug, Serialize)]
130pub struct ThinSpineBatch<T> {
131    pub(crate) level: usize,
132    pub(crate) desc: Description<T>,
133    pub(crate) parts: Vec<SpineId>,
134    /// NB: this exists to validate legacy batch bounds during the migration;
135    /// it can be deleted once the roundtrip_structure flag is permanently rolled out.
136    pub(crate) descs: Vec<Description<T>>,
137}
138
139impl<T: PartialEq> PartialEq for ThinSpineBatch<T> {
140    fn eq(&self, other: &Self) -> bool {
141        // Ignore the temporary descs vector when comparing for equality.
142        (self.level, &self.desc, &self.parts).eq(&(other.level, &other.desc, &other.parts))
143    }
144}
145
146#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
147pub struct ThinMerge<T> {
148    pub(crate) since: Antichain<T>,
149    pub(crate) remaining_work: usize,
150    pub(crate) active_compaction: Option<ActiveCompaction>,
151}
152
153impl<T: Clone> ThinMerge<T> {
154    fn fueling(merge: &FuelingMerge<T>) -> Self {
155        ThinMerge {
156            since: merge.since.clone(),
157            remaining_work: merge.remaining_work,
158            active_compaction: None,
159        }
160    }
161
162    fn fueled(batch: &SpineBatch<T>) -> Self {
163        ThinMerge {
164            since: batch.desc.since().clone(),
165            remaining_work: 0,
166            active_compaction: batch.active_compaction.clone(),
167        }
168    }
169}
170
171/// This is a "flattened" representation of a Trace. Goals:
172/// - small updates to the trace should result in small differences in the `FlatTrace`;
173/// - two `FlatTrace`s should be efficient to diff;
174/// - converting to and from a `Trace` should be relatively straightforward.
175///
176/// These goals are all somewhat in tension, and the space of possible representations is pretty
177/// large. See individual fields for comments on some of the tradeoffs.
178#[derive(Clone, Debug)]
179pub struct FlatTrace<T> {
180    pub(crate) since: Antichain<T>,
181    /// Hollow batches without an associated ID. If this flattened trace contains spine batches,
182    /// we can figure out which legacy batch belongs in which spine batch by comparing the `desc`s.
183    /// Previously, we serialized a trace as just this list of batches. Keeping this data around
184    /// helps ensure backwards compatibility. In the near future, we may still keep some batches
185    /// here to help minimize the size of diffs -- rewriting all the hollow batches in a shard
186    /// can be prohibitively expensive. Eventually, we'd like to remove this in favour of the
187    /// collection below.
188    pub(crate) legacy_batches: BTreeMap<Arc<HollowBatch<T>>, ()>,
189    /// Hollow batches _with_ an associated ID. Spine batches can reference these hollow batches
190    /// by id directly.
191    pub(crate) hollow_batches: BTreeMap<SpineId, Arc<HollowBatch<T>>>,
192    /// Spine batches stored by ID. We reference hollow batches by ID, instead of inlining them,
193    /// to make differential updates smaller when two batches merge together. We also store the
194    /// level on the batch, instead of mapping from level to a list of batches... the level of a
195    /// spine batch doesn't change over time, but the list of batches at a particular level does.
196    pub(crate) spine_batches: BTreeMap<SpineId, ThinSpineBatch<T>>,
197    /// In-progress merges. We store this by spine id instead of level to prepare for some possible
198    /// generalizations to spine (merging N of M batches at a level). This is also a natural place
199    /// to store incremental merge progress in the future.
200    pub(crate) merges: BTreeMap<SpineId, ThinMerge<T>>,
201}
202
203impl<T: Timestamp + Lattice> Trace<T> {
204    pub(crate) fn flatten(&self) -> FlatTrace<T> {
205        let since = self.spine.since.clone();
206        let mut legacy_batches = BTreeMap::new();
207        let mut hollow_batches = BTreeMap::new();
208        let mut spine_batches = BTreeMap::new();
209        let mut merges = BTreeMap::new();
210
211        let mut push_spine_batch = |level: usize, batch: &SpineBatch<T>| {
212            let id = batch.id();
213            let desc = batch.desc.clone();
214            let mut parts = Vec::with_capacity(batch.parts.len());
215            let mut descs = Vec::with_capacity(batch.parts.len());
216            for IdHollowBatch { id, batch } in &batch.parts {
217                parts.push(*id);
218                descs.push(batch.desc.clone());
219                // Ideally, we'd like to put all batches in the hollow_batches collection, since
220                // tracking the spine id reduces ambiguity and makes diffing cheaper. However,
221                // we currently keep most batches in the legacy collection for backwards
222                // compatibility.
223                // As an exception, we add batches with empty time ranges to hollow_batches:
224                // they're otherwise not guaranteed to be unique, and since we only started writing
225                // them down recently there's no backwards compatibility risk.
226                if batch.desc.lower() == batch.desc.upper() {
227                    hollow_batches.insert(*id, Arc::clone(batch));
228                } else {
229                    legacy_batches.insert(Arc::clone(batch), ());
230                }
231            }
232
233            let spine_batch = ThinSpineBatch {
234                level,
235                desc,
236                parts,
237                descs,
238            };
239            spine_batches.insert(id, spine_batch);
240        };
241
242        for (level, state) in self.spine.merging.iter().enumerate() {
243            for batch in &state.batches {
244                push_spine_batch(level, batch);
245                if let Some(c) = &batch.active_compaction {
246                    let previous = merges.insert(batch.id, ThinMerge::fueled(batch));
247                    assert!(
248                        previous.is_none(),
249                        "recording a compaction for a batch that already exists! (level={level}, id={:?}, compaction={c:?})",
250                        batch.id,
251                    )
252                }
253            }
254            if let Some(IdFuelingMerge { id, merge }) = state.merge.as_ref() {
255                let previous = merges.insert(*id, ThinMerge::fueling(merge));
256                assert!(
257                    previous.is_none(),
258                    "fueling a merge for a batch that already exists! (level={level}, id={id:?}, merge={merge:?})"
259                )
260            }
261        }
262
263        if !self.roundtrip_structure {
264            assert!(hollow_batches.is_empty());
265            spine_batches.clear();
266            merges.clear();
267        }
268
269        FlatTrace {
270            since,
271            legacy_batches,
272            hollow_batches,
273            spine_batches,
274            merges,
275        }
276    }
277    pub(crate) fn unflatten(value: FlatTrace<T>) -> Result<Self, String> {
278        let FlatTrace {
279            since,
280            legacy_batches,
281            mut hollow_batches,
282            spine_batches,
283            mut merges,
284        } = value;
285
286        // If the flattened representation has spine batches (or is empty)
287        // we know to preserve the structure for this trace.
288        let roundtrip_structure = !spine_batches.is_empty() || legacy_batches.is_empty();
289
290        // The flattened trace is decoded from an untrusted blob: any invariant
291        // a crafted or corrupted value can violate must surface as a decode
292        // error here, never as a panic in the spine code below.
293        //
294        // Bound the total logical len of all batches. The spine's maintenance
295        // arithmetic (`len.next_power_of_two()`, summing lens of merged
296        // batches) overflows on absurd lens, and no real trace has anywhere
297        // near this many updates.
298        const MAX_TOTAL_LEN: usize = usize::MAX >> 3;
299        let mut total_len = 0usize;
300        for batch in legacy_batches.keys().chain(hollow_batches.values()) {
301            total_len = total_len
302                .checked_add(batch.len)
303                .filter(|len| *len <= MAX_TOTAL_LEN)
304                .ok_or_else(|| {
305                    format!("total len of batches exceeds the maximum trace size: {batch:?}")
306                })?;
307        }
308
309        // We need to look up legacy batches somehow, but we don't have a spine id for them.
310        // Instead, we rely on the fact that the spine must store them in antichain order.
311        // Our timestamp type may not be totally ordered, so we need to implement our own comparator
312        // here. Persist's invariants ensure that all the frontiers we're comparing are comparable,
313        // though.
314        let compare_chains = |left: &Antichain<T>, right: &Antichain<T>| {
315            if PartialOrder::less_than(left, right) {
316                Ordering::Less
317            } else if PartialOrder::less_than(right, left) {
318                Ordering::Greater
319            } else {
320                Ordering::Equal
321            }
322        };
323        let mut legacy_batches: Vec<_> = legacy_batches.into_iter().map(|(k, _)| k).collect();
324        legacy_batches.sort_by(|a, b| compare_chains(a.desc.lower(), b.desc.lower()).reverse());
325
326        let mut pop_batch = |id: SpineId,
327                             expected_desc: Option<&Description<T>>|
328         -> Result<_, String> {
329            if let Some(batch) = hollow_batches.remove(&id) {
330                if let Some(desc) = expected_desc {
331                    // We don't expect the desc's upper and lower to change for a given spine id.
332                    if desc.lower() != batch.desc.lower() || desc.upper() != batch.desc.upper() {
333                        return Err(format!(
334                            "hollow batch desc {:?} did not match the spine batch desc {:?} for {id:?}",
335                            batch.desc, desc
336                        ));
337                    }
338                    // Due to the way thin spine batches are diffed, the sinces can be out of sync.
339                    // This should be rare, and hopefully impossible once we change how diffs work.
340                    if desc.since() != batch.desc.since() {
341                        warn!(
342                            "unexpected since out of sync for spine batch: {:?} != {:?}",
343                            desc.since().elements(),
344                            batch.desc.since().elements()
345                        );
346                    }
347                }
348                return Ok(IdHollowBatch { id, batch });
349            }
350            let mut batch = legacy_batches
351                .pop()
352                .ok_or_else(|| format!("missing referenced hollow batch {id:?}"))?;
353
354            let Some(expected_desc) = expected_desc else {
355                return Ok(IdHollowBatch { id, batch });
356            };
357
358            if expected_desc.lower() != batch.desc.lower() {
359                return Err(format!(
360                    "hollow batch lower {:?} did not match expected lower {:?}",
361                    batch.desc.lower().elements(),
362                    expected_desc.lower().elements()
363                ));
364            }
365
366            // Empty legacy batches are not deterministic: different nodes may split them up
367            // in different ways. For now, we rearrange them such to match the spine data.
368            if batch.parts.is_empty() && batch.run_splits.is_empty() && batch.len == 0 {
369                let mut new_upper = batch.desc.upper().clone();
370
371                // While our current batch is too small, and there's another empty batch
372                // in the list, roll it in.
373                while PartialOrder::less_than(&new_upper, expected_desc.upper()) {
374                    let Some(next_batch) = legacy_batches.pop() else {
375                        break;
376                    };
377                    if next_batch.is_empty() {
378                        new_upper.clone_from(next_batch.desc.upper());
379                    } else {
380                        legacy_batches.push(next_batch);
381                        break;
382                    }
383                }
384
385                // If our current batch is too large, split it by the expected upper
386                // and preserve the remainder.
387                if PartialOrder::less_than(expected_desc.upper(), &new_upper) {
388                    legacy_batches.push(Arc::new(HollowBatch::empty(Description::new(
389                        expected_desc.upper().clone(),
390                        new_upper.clone(),
391                        batch.desc.since().clone(),
392                    ))));
393                    new_upper.clone_from(expected_desc.upper());
394                }
395                batch = Arc::new(HollowBatch::empty(Description::new(
396                    batch.desc.lower().clone(),
397                    new_upper,
398                    batch.desc.since().clone(),
399                )))
400            }
401
402            if expected_desc.upper() != batch.desc.upper() {
403                return Err(format!(
404                    "hollow batch upper {:?} did not match expected upper {:?}",
405                    batch.desc.upper().elements(),
406                    expected_desc.upper().elements()
407                ));
408            }
409
410            Ok(IdHollowBatch { id, batch })
411        };
412
413        let (upper, next_id) = if let Some((id, batch)) = spine_batches.last_key_value() {
414            (batch.desc.upper().clone(), id.1)
415        } else {
416            (Antichain::from_elem(T::minimum()), 0)
417        };
418        // Real spine levels are logarithmic in the total len of the trace, so
419        // this bound is far above any legitimate level while keeping the
420        // allocation below trivial.
421        const MAX_LEVELS: usize = 256;
422        let levels = spine_batches
423            .first_key_value()
424            .map(|(_, batch)| batch.level.saturating_add(1))
425            .unwrap_or(0);
426        if levels > MAX_LEVELS {
427            return Err(format!(
428                "spine level {} exceeds the maximum {MAX_LEVELS}",
429                levels - 1
430            ));
431        }
432        let mut merging = vec![MergeState::default(); levels];
433        for (id, batch) in spine_batches {
434            let level = batch.level;
435
436            if batch.descs.len() > batch.parts.len() {
437                return Err(format!(
438                    "spine batch {id:?} has more descs ({}) than parts ({})",
439                    batch.descs.len(),
440                    batch.parts.len()
441                ));
442            }
443            let descs = batch.descs.iter().map(Some).chain(std::iter::repeat_n(
444                None,
445                batch.parts.len() - batch.descs.len(),
446            ));
447            let parts = batch
448                .parts
449                .into_iter()
450                .zip_eq(descs)
451                .map(|(id, desc)| pop_batch(id, desc))
452                .collect::<Result<Vec<_>, _>>()?;
453            // A spine batch's parts tile its id range (`SpineBatch::id`
454            // `debug_assert`s the endpoints). Real batches always have at least
455            // one part: an empty batch still carries an empty hollow batch.
456            // Validate the full tiling, not just the endpoints: downstream
457            // maintenance (`fueled_merge_reqs_before_ms` -> `id_range` in
458            // compaction, `apply_merge_res_checked`) `assert_eq!`s that the
459            // collected part ids are contiguous, so non-adjacent parts that
460            // happen to hit the right endpoints would panic later instead of
461            // here.
462            if parts.first().map(|x| x.id.0) != Some(id.0)
463                || parts.last().map(|x| x.id.1) != Some(id.1)
464                || parts.windows(2).any(|w| w[0].id.1 != w[1].id.0)
465            {
466                return Err(format!(
467                    "spine batch {id:?} parts do not tile the batch's id range"
468                ));
469            }
470            let len = parts.iter().map(|p| (*p).batch.len).sum();
471            let active_compaction = merges.remove(&id).and_then(|m| m.active_compaction);
472            let batch = SpineBatch {
473                id,
474                desc: batch.desc,
475                parts,
476                active_compaction,
477                len,
478            };
479
480            let state = merging.get_mut(level).ok_or_else(|| {
481                format!("spine batch {id:?} level {level} out of bounds ({levels} levels)")
482            })?;
483
484            state.try_push_batch(batch)?;
485            if let Some(id) = state.id() {
486                if let Some(merge) = merges.remove(&id) {
487                    state.merge = Some(IdFuelingMerge {
488                        id,
489                        merge: FuelingMerge {
490                            since: merge.since,
491                            remaining_work: merge.remaining_work,
492                        },
493                    })
494                }
495            }
496        }
497
498        let mut trace = Trace {
499            spine: Spine {
500                effort: 1,
501                next_id,
502                since,
503                upper,
504                merging,
505            },
506            roundtrip_structure,
507        };
508
509        fn check_empty(name: &str, len: usize) -> Result<(), String> {
510            if len != 0 {
511                Err(format!("{len} {name} left after reconstructing spine"))
512            } else {
513                Ok(())
514            }
515        }
516
517        if roundtrip_structure {
518            check_empty("legacy batches", legacy_batches.len())?;
519        } else {
520            // If the structure wasn't actually serialized, we may have legacy batches left over.
521            for batch in legacy_batches.into_iter().rev() {
522                // `Spine::insert` asserts that pushed batches are non-empty
523                // and contiguous; check this here so that a corrupted batch
524                // results in a decode error instead of a panic.
525                if batch.desc.lower() == batch.desc.upper() {
526                    return Err(format!(
527                        "legacy batch has an empty time range: {:?}",
528                        batch.desc
529                    ));
530                }
531                if batch.desc.lower() != trace.upper() {
532                    return Err(format!(
533                        "legacy batch lower {:?} does not match the trace upper {:?}",
534                        batch.desc.lower().elements(),
535                        trace.upper().elements()
536                    ));
537                }
538                trace.push_batch_no_merge_reqs(Arc::unwrap_or_clone(batch));
539            }
540        }
541        check_empty("hollow batches", hollow_batches.len())?;
542        check_empty("merges", merges.len())?;
543
544        // The same check that's `debug_assert`ed when mutating a trace we
545        // built ourselves; for a trace reconstructed from untrusted data it
546        // must be a hard error, both to keep corrupted state from being used
547        // and because the write side would panic on it anyway (e.g. `Spine`'s
548        // batch invariants and the full-level/merge correspondence).
549        trace
550            .validate()
551            .map_err(|err| format!("reconstructed trace failed validation: {err}"))?;
552
553        Ok(trace)
554    }
555}
556
557#[derive(Clone, Debug, Default)]
558pub(crate) struct SpineMetrics {
559    pub compact_batches: u64,
560    pub compacting_batches: u64,
561    pub noncompact_batches: u64,
562}
563
564impl<T> Trace<T> {
565    pub fn since(&self) -> &Antichain<T> {
566        &self.spine.since
567    }
568
569    pub fn upper(&self) -> &Antichain<T> {
570        &self.spine.upper
571    }
572
573    pub fn map_batches<'a, F: FnMut(&'a HollowBatch<T>)>(&'a self, mut f: F) {
574        for batch in self.batches() {
575            f(batch);
576        }
577    }
578
579    pub fn batches(&self) -> impl Iterator<Item = &HollowBatch<T>> {
580        self.spine
581            .spine_batches()
582            .flat_map(|b| b.parts.as_slice())
583            .map(|b| &*b.batch)
584    }
585
586    pub fn num_spine_batches(&self) -> usize {
587        self.spine.spine_batches().count()
588    }
589
590    #[cfg(test)]
591    pub fn num_hollow_batches(&self) -> usize {
592        self.batches().count()
593    }
594
595    #[cfg(test)]
596    pub fn num_updates(&self) -> usize {
597        self.batches().map(|b| b.len).sum()
598    }
599}
600
601impl<T: Timestamp + Lattice> Trace<T> {
602    pub fn downgrade_since(&mut self, since: &Antichain<T>) {
603        self.spine.since.clone_from(since);
604    }
605
606    #[must_use]
607    pub fn push_batch(&mut self, batch: HollowBatch<T>) -> Vec<FueledMergeReq<T>> {
608        let mut merge_reqs = Vec::new();
609        self.spine.insert(
610            batch,
611            &mut SpineLog::Enabled {
612                merge_reqs: &mut merge_reqs,
613            },
614        );
615        debug_assert_eq!(self.spine.validate(), Ok(()), "{:?}", self);
616        // Spine::roll_up (internally used by insert) clears all batches out of
617        // levels below a target by walking up from level 0 and merging each
618        // level into the next (providing the necessary fuel). In practice, this
619        // means we'll get a series of requests like `(a, b), (a, b, c), ...`.
620        // It's a waste to do all of these (we'll throw away the results), so we
621        // filter out any that are entirely covered by some other request.
622        Self::remove_redundant_merge_reqs(merge_reqs)
623    }
624
625    pub fn claim_compaction(&mut self, id: SpineId, compaction: ActiveCompaction) {
626        // TODO: we ought to be able to look up the id for a batch by binary searching the levels.
627        // In the meantime, search backwards, since most compactions are for recent batches.
628        for batch in self.spine.spine_batches_mut().rev() {
629            if batch.id == id {
630                batch.active_compaction = Some(compaction);
631                break;
632            }
633        }
634    }
635
636    /// The same as [Self::push_batch] but without the `FueledMergeReq`s, which
637    /// account for a surprising amount of cpu in prod. database-issues#5411
638    pub(crate) fn push_batch_no_merge_reqs(&mut self, batch: HollowBatch<T>) {
639        self.spine.insert(batch, &mut SpineLog::Disabled);
640    }
641
642    /// Apply some amount of effort to trace maintenance.
643    ///
644    /// The units of effort are updates, and the method should be thought of as
645    /// analogous to inserting as many empty updates, where the trace is
646    /// permitted to perform proportionate work.
647    ///
648    /// Returns true if this did work and false if it left the spine unchanged.
649    #[must_use]
650    pub fn exert(&mut self, fuel: usize) -> (Vec<FueledMergeReq<T>>, bool) {
651        let mut merge_reqs = Vec::new();
652        let did_work = self.spine.exert(
653            fuel,
654            &mut SpineLog::Enabled {
655                merge_reqs: &mut merge_reqs,
656            },
657        );
658        debug_assert_eq!(self.spine.validate(), Ok(()), "{:?}", self);
659        // See the comment in [Self::push_batch].
660        let merge_reqs = Self::remove_redundant_merge_reqs(merge_reqs);
661        (merge_reqs, did_work)
662    }
663
664    /// Validates invariants.
665    ///
666    /// See `Spine::validate` for details.
667    pub fn validate(&self) -> Result<(), String> {
668        self.spine.validate()
669    }
670
671    /// Obtain all fueled merge reqs that either have no active compaction, or the previous
672    /// compaction was started at or before the threshold time, in order from oldest to newest.
673    pub(crate) fn fueled_merge_reqs_before_ms(
674        &self,
675        threshold_ms: u64,
676        threshold_writer: Option<WriterKey>,
677    ) -> impl Iterator<Item = FueledMergeReq<T>> + '_ {
678        self.spine
679            .spine_batches()
680            .filter(move |b| {
681                let noncompact = !b.is_compact();
682                let old_writer = threshold_writer.as_ref().map_or(false, |min_writer| {
683                    b.parts.iter().any(|b| {
684                        b.batch
685                            .parts
686                            .iter()
687                            .any(|p| p.writer_key().map_or(false, |writer| writer < *min_writer))
688                    })
689                });
690                noncompact || old_writer
691            })
692            .filter(move |b| {
693                // Either there's no active compaction, or the last active compaction
694                // is not after the timeout timestamp.
695                b.active_compaction
696                    .as_ref()
697                    .map_or(true, move |c| c.start_ms <= threshold_ms)
698            })
699            .map(|b| FueledMergeReq {
700                id: b.id,
701                desc: b.desc.clone(),
702                inputs: b.parts.clone(),
703            })
704    }
705
706    // This is only called with the results of one `insert` and so the length of
707    // `merge_reqs` is bounded by the number of levels in the spine (or possibly
708    // some small constant multiple?). The number of levels is logarithmic in the
709    // number of updates in the spine, so this number should stay very small. As
710    // a result, we simply use the naive O(n^2) algorithm here instead of doing
711    // anything fancy with e.g. interval trees.
712    fn remove_redundant_merge_reqs(
713        mut merge_reqs: Vec<FueledMergeReq<T>>,
714    ) -> Vec<FueledMergeReq<T>> {
715        // Returns true if b0 covers b1, false otherwise.
716        fn covers<T: PartialOrder>(b0: &FueledMergeReq<T>, b1: &FueledMergeReq<T>) -> bool {
717            // TODO: can we relax or remove this since check?
718            b0.id.covers(b1.id) && b0.desc.since() == b1.desc.since()
719        }
720
721        let mut ret = Vec::<FueledMergeReq<T>>::with_capacity(merge_reqs.len());
722        // In practice, merge_reqs will come in sorted such that the "large"
723        // requests are later. Take advantage of this by processing back to
724        // front.
725        while let Some(merge_req) = merge_reqs.pop() {
726            let covered = ret.iter().any(|r| covers(r, &merge_req));
727            if !covered {
728                // Now check if anything we've already staged is covered by this
729                // new req. In practice, the merge_reqs come in sorted and so
730                // this `retain` is a no-op.
731                ret.retain(|r| !covers(&merge_req, r));
732                ret.push(merge_req);
733            }
734        }
735        ret
736    }
737
738    pub fn spine_metrics(&self) -> SpineMetrics {
739        let mut metrics = SpineMetrics::default();
740        for batch in self.spine.spine_batches() {
741            if batch.is_compact() {
742                metrics.compact_batches += 1;
743            } else if batch.is_merging() {
744                metrics.compacting_batches += 1;
745            } else {
746                metrics.noncompact_batches += 1;
747            }
748        }
749        metrics
750    }
751}
752
753impl<T: Timestamp + Lattice + Codec64> Trace<T> {
754    pub fn apply_merge_res_checked<D: Codec64 + Monoid + PartialEq>(
755        &mut self,
756        res: &FueledMergeRes<T>,
757        metrics: &ColumnarMetrics,
758    ) -> ApplyMergeResult {
759        for batch in self.spine.spine_batches_mut().rev() {
760            let result = batch.maybe_replace_checked::<D>(res, metrics);
761            if result.matched() {
762                return result;
763            }
764        }
765        ApplyMergeResult::NotAppliedNoMatch
766    }
767
768    pub fn apply_merge_res_unchecked(&mut self, res: &FueledMergeRes<T>) -> ApplyMergeResult {
769        for batch in self.spine.spine_batches_mut().rev() {
770            let result = batch.maybe_replace_unchecked(res);
771            if result.matched() {
772                return result;
773            }
774        }
775        ApplyMergeResult::NotAppliedNoMatch
776    }
777
778    pub fn apply_tombstone_merge(&mut self, desc: &Description<T>) -> ApplyMergeResult {
779        for batch in self.spine.spine_batches_mut().rev() {
780            let result = batch.maybe_replace_with_tombstone(desc);
781            if result.matched() {
782                return result;
783            }
784        }
785        ApplyMergeResult::NotAppliedNoMatch
786    }
787}
788
789/// A log of what transitively happened during a Spine operation: e.g.
790/// FueledMergeReqs were generated.
791enum SpineLog<'a, T> {
792    Enabled {
793        merge_reqs: &'a mut Vec<FueledMergeReq<T>>,
794    },
795    Disabled,
796}
797
798#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
799pub enum CompactionInput {
800    /// We don't know what our inputs were; this should only be used for
801    /// unchecked legacy replacements.
802    Legacy,
803    /// This compaction output is a total replacement for all batches in this id range.
804    IdRange(SpineId),
805    /// This compaction output replaces the specified runs in this id range.
806    PartialBatch(SpineId, BTreeSet<RunId>),
807}
808
809#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
810pub struct SpineId(pub usize, pub usize);
811
812impl Display for SpineId {
813    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
814        write!(f, "[{}, {})", self.0, self.1)
815    }
816}
817
818impl Serialize for SpineId {
819    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
820    where
821        S: Serializer,
822    {
823        let SpineId(lo, hi) = self;
824        serializer.serialize_str(&format!("{lo}-{hi}"))
825    }
826}
827
828/// Creates a `SpineId` that covers the range of ids in the set.
829pub fn id_range(ids: BTreeSet<SpineId>) -> SpineId {
830    let mut id_iter = ids.iter().copied();
831    let Some(mut result) = id_iter.next() else {
832        panic!("at least one batch must be present")
833    };
834
835    for id in id_iter {
836        assert_eq!(
837            result.1, id.0,
838            "expected contiguous ids, but {result:?} is not adjacent to {id:?} in ids {ids:?}"
839        );
840        result.1 = id.1;
841    }
842    result
843}
844
845impl SpineId {
846    fn covers(self, other: SpineId) -> bool {
847        self.0 <= other.0 && other.1 <= self.1
848    }
849}
850
851#[derive(Debug, Clone, PartialEq)]
852pub struct IdHollowBatch<T> {
853    pub id: SpineId,
854    pub batch: Arc<HollowBatch<T>>,
855}
856
857#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
858pub struct ActiveCompaction {
859    pub start_ms: u64,
860}
861
862#[derive(Debug, Clone, PartialEq)]
863struct SpineBatch<T> {
864    id: SpineId,
865    desc: Description<T>,
866    parts: Vec<IdHollowBatch<T>>,
867    active_compaction: Option<ActiveCompaction>,
868    // A cached version of parts.iter().map(|x| x.len).sum()
869    len: usize,
870}
871
872impl<T> SpineBatch<T> {
873    fn merged(batch: IdHollowBatch<T>) -> Self
874    where
875        T: Clone,
876    {
877        Self {
878            id: batch.id,
879            desc: batch.batch.desc.clone(),
880            len: batch.batch.len,
881            parts: vec![batch],
882            active_compaction: None,
883        }
884    }
885}
886
887#[derive(Debug, Copy, Clone)]
888pub enum ApplyMergeResult {
889    AppliedExact,
890    AppliedSubset,
891    NotAppliedNoMatch,
892    NotAppliedInvalidSince,
893    NotAppliedTooManyUpdates,
894}
895
896impl ApplyMergeResult {
897    pub fn applied(&self) -> bool {
898        match self {
899            ApplyMergeResult::AppliedExact | ApplyMergeResult::AppliedSubset => true,
900            _ => false,
901        }
902    }
903    pub fn matched(&self) -> bool {
904        match self {
905            ApplyMergeResult::AppliedExact
906            | ApplyMergeResult::AppliedSubset
907            | ApplyMergeResult::NotAppliedTooManyUpdates => true,
908            _ => false,
909        }
910    }
911}
912
913impl<T: Timestamp + Lattice> SpineBatch<T> {
914    pub fn lower(&self) -> &Antichain<T> {
915        self.desc().lower()
916    }
917
918    pub fn upper(&self) -> &Antichain<T> {
919        self.desc().upper()
920    }
921
922    fn id(&self) -> SpineId {
923        debug_assert_eq!(self.parts.first().map(|x| x.id.0), Some(self.id.0));
924        debug_assert_eq!(self.parts.last().map(|x| x.id.1), Some(self.id.1));
925        self.id
926    }
927
928    pub fn is_compact(&self) -> bool {
929        // A compact batch has at most one run.
930        // This check used to be if there was at most one hollow batch with at most one run,
931        // but that was a bit too strict since introducing incremental compaction.
932        // Incremental compaction can result in a batch with a single run, but multiple empty
933        // hollow batches, which we still consider compact. As levels are merged, we
934        // will eventually clean up the empty hollow batches.
935        self.parts
936            .iter()
937            .map(|p| p.batch.run_meta.len())
938            .sum::<usize>()
939            <= 1
940    }
941
942    pub fn is_merging(&self) -> bool {
943        self.active_compaction.is_some()
944    }
945
946    fn desc(&self) -> &Description<T> {
947        &self.desc
948    }
949
950    pub fn len(&self) -> usize {
951        // NB: This is an upper bound on len for a non-compact batch; we won't know for sure until
952        // we compact it.
953        debug_assert_eq!(
954            self.len,
955            self.parts.iter().map(|x| x.batch.len).sum::<usize>()
956        );
957        self.len
958    }
959
960    pub fn is_empty(&self) -> bool {
961        self.len() == 0
962    }
963
964    pub fn empty(
965        id: SpineId,
966        lower: Antichain<T>,
967        upper: Antichain<T>,
968        since: Antichain<T>,
969    ) -> Self {
970        SpineBatch::merged(IdHollowBatch {
971            id,
972            batch: Arc::new(HollowBatch::empty(Description::new(lower, upper, since))),
973        })
974    }
975
976    pub fn begin_merge(
977        bs: &[Self],
978        compaction_frontier: Option<AntichainRef<T>>,
979    ) -> Option<IdFuelingMerge<T>> {
980        let from = bs.first()?.id().0;
981        let until = bs.last()?.id().1;
982        let id = SpineId(from, until);
983        let mut sinces = bs.iter().map(|b| b.desc().since());
984        let mut since = sinces.next()?.clone();
985        for b in bs {
986            since.join_assign(b.desc().since())
987        }
988        if let Some(compaction_frontier) = compaction_frontier {
989            since.join_assign(&compaction_frontier.to_owned());
990        }
991        let remaining_work = bs.iter().map(|x| x.len()).sum();
992        Some(IdFuelingMerge {
993            id,
994            merge: FuelingMerge {
995                since,
996                remaining_work,
997            },
998        })
999    }
1000
1001    #[cfg(test)]
1002    fn describe(&self, extended: bool) -> String {
1003        let SpineBatch {
1004            id,
1005            parts,
1006            desc,
1007            active_compaction,
1008            len,
1009        } = self;
1010        let compaction = match active_compaction {
1011            None => "".to_owned(),
1012            Some(c) => format!(" (c@{})", c.start_ms),
1013        };
1014        match extended {
1015            false => format!(
1016                "[{}-{}]{:?}{:?}{}/{}{compaction}",
1017                id.0,
1018                id.1,
1019                desc.lower().elements(),
1020                desc.upper().elements(),
1021                parts.len(),
1022                len
1023            ),
1024            true => {
1025                format!(
1026                    "[{}-{}]{:?}{:?}{:?} {}/{}{}{compaction}",
1027                    id.0,
1028                    id.1,
1029                    desc.lower().elements(),
1030                    desc.upper().elements(),
1031                    desc.since().elements(),
1032                    parts.len(),
1033                    len,
1034                    parts
1035                        .iter()
1036                        .flat_map(|x| x.batch.parts.iter())
1037                        .map(|x| format!(" {}", x.printable_name()))
1038                        .collect::<Vec<_>>()
1039                        .join("")
1040                )
1041            }
1042        }
1043    }
1044}
1045
1046impl<T: Timestamp + Lattice + Codec64> SpineBatch<T> {
1047    fn diffs_sum<'a, D: Monoid + Codec64>(
1048        parts: impl IntoIterator<Item = &'a RunPart<T>>,
1049        metrics: &ColumnarMetrics,
1050    ) -> Option<D> {
1051        let mut sum = D::zero();
1052        for part in parts {
1053            sum.plus_equals(&part.diffs_sum::<D>(metrics)?);
1054        }
1055        Some(sum)
1056    }
1057
1058    /// Get the diff sum from the given batch for the given runs.
1059    /// Returns `None` if the runs aren't present or any parts don't have statistics.
1060    fn diffs_sum_for_runs<D: Monoid + Codec64>(
1061        batch: &HollowBatch<T>,
1062        run_ids: &[RunId],
1063        metrics: &ColumnarMetrics,
1064    ) -> Option<D> {
1065        let mut run_ids = BTreeSet::from_iter(run_ids.iter().copied());
1066        let mut sum = D::zero();
1067
1068        for (meta, run) in batch.runs() {
1069            let id = meta.id?;
1070            if run_ids.remove(&id) {
1071                sum.plus_equals(&Self::diffs_sum(run, metrics)?);
1072            }
1073        }
1074
1075        run_ids.is_empty().then_some(sum)
1076    }
1077
1078    fn maybe_replace_with_tombstone(&mut self, desc: &Description<T>) -> ApplyMergeResult {
1079        let exact_match =
1080            desc.lower() == self.desc().lower() && desc.upper() == self.desc().upper();
1081
1082        let empty_batch = HollowBatch::empty(desc.clone());
1083        if exact_match {
1084            *self = SpineBatch::merged(IdHollowBatch {
1085                id: self.id(),
1086                batch: Arc::new(empty_batch),
1087            });
1088            return ApplyMergeResult::AppliedExact;
1089        }
1090
1091        if let Some((id, range)) = self.find_replacement_range(desc) {
1092            self.perform_subset_replacement(&empty_batch, id, range, None)
1093        } else {
1094            ApplyMergeResult::NotAppliedNoMatch
1095        }
1096    }
1097
1098    fn construct_batch_with_runs_replaced(
1099        original: &HollowBatch<T>,
1100        run_ids: &[RunId],
1101        replacement: &HollowBatch<T>,
1102    ) -> Result<HollowBatch<T>, ApplyMergeResult> {
1103        if run_ids.is_empty() {
1104            return Err(ApplyMergeResult::NotAppliedNoMatch);
1105        }
1106
1107        let orig_run_ids: BTreeSet<_> = original.runs().filter_map(|(meta, _)| meta.id).collect();
1108        let run_ids: BTreeSet<_> = run_ids.iter().cloned().collect();
1109        if !orig_run_ids.is_superset(&run_ids) {
1110            return Err(ApplyMergeResult::NotAppliedNoMatch);
1111        }
1112
1113        let runs: Vec<_> = original
1114            .runs()
1115            .filter(|(meta, _)| {
1116                !run_ids.contains(&meta.id.expect("id should be present at this point"))
1117            })
1118            .chain(replacement.runs())
1119            .collect();
1120
1121        let len = runs.iter().filter_map(|(meta, _)| meta.len).sum::<usize>();
1122
1123        let run_meta = runs
1124            .iter()
1125            .map(|(meta, _)| *meta)
1126            .cloned()
1127            .collect::<Vec<_>>();
1128
1129        let parts = runs
1130            .iter()
1131            .flat_map(|(_, parts)| *parts)
1132            .cloned()
1133            .collect::<Vec<_>>();
1134
1135        let run_splits = {
1136            let mut splits = Vec::with_capacity(run_meta.len().saturating_sub(1));
1137            let mut pointer = 0;
1138            for (i, (_, parts)) in runs.into_iter().enumerate() {
1139                if parts.is_empty() {
1140                    continue;
1141                }
1142                if i < run_meta.len() - 1 {
1143                    splits.push(pointer + parts.len());
1144                }
1145                pointer += parts.len();
1146            }
1147            splits
1148        };
1149
1150        Ok(HollowBatch::new(
1151            replacement.desc.clone(),
1152            parts,
1153            len,
1154            run_meta,
1155            run_splits,
1156        ))
1157    }
1158
1159    fn maybe_replace_checked<D>(
1160        &mut self,
1161        res: &FueledMergeRes<T>,
1162        metrics: &ColumnarMetrics,
1163    ) -> ApplyMergeResult
1164    where
1165        D: Monoid + Codec64 + PartialEq + Debug,
1166    {
1167        // The spine's and merge res's sinces don't need to match (which could occur if Spine
1168        // has been reloaded from state due to compare_and_set mismatch), but if so, the Spine
1169        // since must be in advance of the merge res since.
1170        if !PartialOrder::less_equal(res.output.desc.since(), self.desc().since()) {
1171            return ApplyMergeResult::NotAppliedInvalidSince;
1172        }
1173
1174        let new_diffs_sum = Self::diffs_sum(res.output.parts.iter(), metrics);
1175        let num_batches = self.parts.len();
1176
1177        let result = match &res.input {
1178            CompactionInput::IdRange(id) => {
1179                self.handle_id_range_replacement::<D>(res, id, new_diffs_sum, metrics)
1180            }
1181            CompactionInput::PartialBatch(id, runs) => {
1182                self.handle_partial_batch_replacement::<D>(res, *id, runs, new_diffs_sum, metrics)
1183            }
1184            CompactionInput::Legacy => self.maybe_replace_checked_classic::<D>(res, metrics),
1185        };
1186
1187        let num_batches_after = self.parts.len();
1188        assert!(
1189            num_batches_after <= num_batches,
1190            "replacing parts should not increase the number of batches"
1191        );
1192        result
1193    }
1194
1195    fn handle_id_range_replacement<D>(
1196        &mut self,
1197        res: &FueledMergeRes<T>,
1198        id: &SpineId,
1199        new_diffs_sum: Option<D>,
1200        metrics: &ColumnarMetrics,
1201    ) -> ApplyMergeResult
1202    where
1203        D: Monoid + Codec64 + PartialEq + Debug,
1204    {
1205        let range = self
1206            .parts
1207            .iter()
1208            .enumerate()
1209            .filter_map(|(i, p)| {
1210                if id.covers(p.id) {
1211                    Some((i, p.id))
1212                } else {
1213                    None
1214                }
1215            })
1216            .collect::<Vec<_>>();
1217
1218        let ids: BTreeSet<_> = range.iter().map(|(_, id)| *id).collect();
1219
1220        // If ids is empty, it means that we didn't find any parts that match the id range.
1221        // We also check that the id matches the range of ids we found.
1222        // At scale, sometimes regular compaction will race forced compaction,
1223        // for things like the catalog. In that case, we may have a
1224        // replacement that no longer lines up with the spine batches.
1225        // I think this is because forced compaction ignores the active_compaction
1226        // and just goes for it. This is slightly annoying but probably the right behavior
1227        // for a functions whose prefix is `force_`, so we just return
1228        // NotAppliedNoMatch here.
1229        if ids.is_empty() || id != &id_range(ids) {
1230            return ApplyMergeResult::NotAppliedNoMatch;
1231        }
1232
1233        // This is the range of hollow batches that we will replace.
1234        let (min, max) = match range.iter().map(|(i, _)| *i).minmax() {
1235            itertools::MinMaxResult::NoElements => return ApplyMergeResult::NotAppliedNoMatch,
1236            itertools::MinMaxResult::OneElement(elt) => (elt, elt),
1237            itertools::MinMaxResult::MinMax(min, max) => (min, max),
1238        };
1239        let replacement_range = min..max + 1;
1240
1241        // We need to replace a range of parts. Here we don't care about the run_indices
1242        // because we must be replacing the entire part(s)
1243        let old_diffs_sum = Self::diffs_sum::<D>(
1244            self.parts[replacement_range.clone()]
1245                .iter()
1246                .flat_map(|p| p.batch.parts.iter()),
1247            metrics,
1248        );
1249
1250        Self::validate_diffs_sum_match(old_diffs_sum, new_diffs_sum, "id range replacement");
1251
1252        self.perform_subset_replacement(
1253            &res.output,
1254            *id,
1255            replacement_range,
1256            res.new_active_compaction.clone(),
1257        )
1258    }
1259
1260    fn handle_partial_batch_replacement<D>(
1261        &mut self,
1262        res: &FueledMergeRes<T>,
1263        id: SpineId,
1264        runs: &BTreeSet<RunId>,
1265        new_diffs_sum: Option<D>,
1266        metrics: &ColumnarMetrics,
1267    ) -> ApplyMergeResult
1268    where
1269        D: Monoid + Codec64 + PartialEq + Debug,
1270    {
1271        if runs.is_empty() {
1272            return ApplyMergeResult::NotAppliedNoMatch;
1273        }
1274
1275        let part = self.parts.iter().enumerate().find(|(_, p)| p.id == id);
1276        let Some((i, batch)) = part else {
1277            return ApplyMergeResult::NotAppliedNoMatch;
1278        };
1279        let replacement_range = i..(i + 1);
1280
1281        let replacement_desc = &res.output.desc;
1282        let existing_desc = &batch.batch.desc;
1283        assert_eq!(
1284            replacement_desc.lower(),
1285            existing_desc.lower(),
1286            "batch lower should match, but {:?} != {:?}",
1287            replacement_desc.lower(),
1288            existing_desc.lower()
1289        );
1290        assert_eq!(
1291            replacement_desc.upper(),
1292            existing_desc.upper(),
1293            "batch upper should match, but {:?} != {:?}",
1294            replacement_desc.upper(),
1295            existing_desc.upper()
1296        );
1297        if !PartialOrder::less_equal(existing_desc.since(), replacement_desc.since()) {
1298            error!(
1299                "batch since should advance, but {:?} !<= {:?}",
1300                existing_desc.since(),
1301                replacement_desc.since()
1302            );
1303            return ApplyMergeResult::NotAppliedInvalidSince;
1304        }
1305
1306        let batch = &batch.batch;
1307        let run_ids = runs.iter().cloned().collect::<Vec<_>>();
1308
1309        match Self::construct_batch_with_runs_replaced(batch, &run_ids, &res.output) {
1310            Ok(new_batch) => {
1311                let old_diffs_sum = Self::diffs_sum_for_runs::<D>(batch, &run_ids, metrics);
1312                Self::validate_diffs_sum_match(
1313                    old_diffs_sum,
1314                    new_diffs_sum,
1315                    "partial batch replacement",
1316                );
1317                let old_batch_diff_sum = Self::diffs_sum::<D>(batch.parts.iter(), metrics);
1318                let new_batch_diff_sum = Self::diffs_sum::<D>(new_batch.parts.iter(), metrics);
1319                Self::validate_diffs_sum_match(
1320                    old_batch_diff_sum,
1321                    new_batch_diff_sum,
1322                    "sanity checking diffs sum for replaced runs",
1323                );
1324                self.perform_subset_replacement(
1325                    &new_batch,
1326                    id,
1327                    replacement_range,
1328                    res.new_active_compaction.clone(),
1329                )
1330            }
1331            Err(err) => err,
1332        }
1333    }
1334
1335    fn validate_diffs_sum_match<D>(
1336        old_diffs_sum: Option<D>,
1337        new_diffs_sum: Option<D>,
1338        context: &str,
1339    ) where
1340        D: Monoid + Codec64 + PartialEq + Debug,
1341    {
1342        let new_diffs_sum = new_diffs_sum.unwrap_or_else(D::zero);
1343        if let Some(old_diffs_sum) = old_diffs_sum {
1344            assert_eq!(
1345                old_diffs_sum, new_diffs_sum,
1346                "merge res diffs sum ({:?}) did not match spine batch diffs sum ({:?}) ({})",
1347                new_diffs_sum, old_diffs_sum, context
1348            )
1349        }
1350    }
1351
1352    /// This is the "legacy" way of replacing a spine batch with a merge result.
1353    /// It is used in moments when we don't have the full compaction input
1354    /// information.
1355    /// Eventually we should strive to roundtrip Spine IDs everywhere and
1356    /// deprecate this method.
1357    fn maybe_replace_checked_classic<D>(
1358        &mut self,
1359        res: &FueledMergeRes<T>,
1360        metrics: &ColumnarMetrics,
1361    ) -> ApplyMergeResult
1362    where
1363        D: Monoid + Codec64 + PartialEq + Debug,
1364    {
1365        // The spine's and merge res's sinces don't need to match (which could occur if Spine
1366        // has been reloaded from state due to compare_and_set mismatch), but if so, the Spine
1367        // since must be in advance of the merge res since.
1368        if !PartialOrder::less_equal(res.output.desc.since(), self.desc().since()) {
1369            return ApplyMergeResult::NotAppliedInvalidSince;
1370        }
1371
1372        let new_diffs_sum = Self::diffs_sum(res.output.parts.iter(), metrics);
1373
1374        // If our merge result exactly matches a spine batch, we can swap it in directly
1375        let exact_match = res.output.desc.lower() == self.desc().lower()
1376            && res.output.desc.upper() == self.desc().upper();
1377        if exact_match {
1378            let old_diffs_sum = Self::diffs_sum::<D>(
1379                self.parts.iter().flat_map(|p| p.batch.parts.iter()),
1380                metrics,
1381            );
1382
1383            if let (Some(old_diffs_sum), Some(new_diffs_sum)) = (old_diffs_sum, new_diffs_sum) {
1384                assert_eq!(
1385                    old_diffs_sum, new_diffs_sum,
1386                    "merge res diffs sum ({:?}) did not match spine batch diffs sum ({:?})",
1387                    new_diffs_sum, old_diffs_sum
1388                );
1389            }
1390
1391            // Spine internally has an invariant about a batch being at some level
1392            // or higher based on the len. We could end up violating this invariant
1393            // if we increased the length of the batch.
1394            //
1395            // A res output with length greater than the existing spine batch implies
1396            // a compaction has already been applied to this range, and with a higher
1397            // rate of consolidation than this one. This could happen as a result of
1398            // compaction's memory bound limiting the amount of consolidation possible.
1399            if res.output.len > self.len() {
1400                return ApplyMergeResult::NotAppliedTooManyUpdates;
1401            }
1402            *self = SpineBatch::merged(IdHollowBatch {
1403                id: self.id(),
1404                batch: Arc::new(res.output.clone()),
1405            });
1406            return ApplyMergeResult::AppliedExact;
1407        }
1408
1409        // Try subset replacement
1410        if let Some((id, range)) = self.find_replacement_range(&res.output.desc) {
1411            let old_diffs_sum = Self::diffs_sum::<D>(
1412                self.parts[range.clone()]
1413                    .iter()
1414                    .flat_map(|p| p.batch.parts.iter()),
1415                metrics,
1416            );
1417
1418            if let (Some(old_diffs_sum), Some(new_diffs_sum)) = (old_diffs_sum, new_diffs_sum) {
1419                assert_eq!(
1420                    old_diffs_sum, new_diffs_sum,
1421                    "merge res diffs sum ({:?}) did not match spine batch diffs sum ({:?})",
1422                    new_diffs_sum, old_diffs_sum
1423                );
1424            }
1425
1426            self.perform_subset_replacement(
1427                &res.output,
1428                id,
1429                range,
1430                res.new_active_compaction.clone(),
1431            )
1432        } else {
1433            ApplyMergeResult::NotAppliedNoMatch
1434        }
1435    }
1436
1437    /// This is the even more legacy way of replacing a spine batch with a merge result.
1438    /// It is used in moments when we don't have the full compaction input
1439    /// information, and we don't have the diffs sum.
1440    /// Eventually we should strive to roundtrip Spine IDs and diffs sums everywhere and
1441    /// deprecate this method.
1442    fn maybe_replace_unchecked(&mut self, res: &FueledMergeRes<T>) -> ApplyMergeResult {
1443        // The spine's and merge res's sinces don't need to match (which could occur if Spine
1444        // has been reloaded from state due to compare_and_set mismatch), but if so, the Spine
1445        // since must be in advance of the merge res since.
1446        if !PartialOrder::less_equal(res.output.desc.since(), self.desc().since()) {
1447            return ApplyMergeResult::NotAppliedInvalidSince;
1448        }
1449
1450        // If our merge result exactly matches a spine batch, we can swap it in directly
1451        let exact_match = res.output.desc.lower() == self.desc().lower()
1452            && res.output.desc.upper() == self.desc().upper();
1453        if exact_match {
1454            // Spine internally has an invariant about a batch being at some level
1455            // or higher based on the len. We could end up violating this invariant
1456            // if we increased the length of the batch.
1457            //
1458            // A res output with length greater than the existing spine batch implies
1459            // a compaction has already been applied to this range, and with a higher
1460            // rate of consolidation than this one. This could happen as a result of
1461            // compaction's memory bound limiting the amount of consolidation possible.
1462            if res.output.len > self.len() {
1463                return ApplyMergeResult::NotAppliedTooManyUpdates;
1464            }
1465
1466            *self = SpineBatch::merged(IdHollowBatch {
1467                id: self.id(),
1468                batch: Arc::new(res.output.clone()),
1469            });
1470            return ApplyMergeResult::AppliedExact;
1471        }
1472
1473        // Try subset replacement
1474        if let Some((id, range)) = self.find_replacement_range(&res.output.desc) {
1475            self.perform_subset_replacement(
1476                &res.output,
1477                id,
1478                range,
1479                res.new_active_compaction.clone(),
1480            )
1481        } else {
1482            ApplyMergeResult::NotAppliedNoMatch
1483        }
1484    }
1485
1486    /// Find the range of parts that can be replaced by the merge result
1487    fn find_replacement_range(&self, desc: &Description<T>) -> Option<(SpineId, Range<usize>)> {
1488        // It is possible the structure of the spine has changed since the merge res
1489        // was created, such that it no longer exactly matches the description of a
1490        // spine batch. This can happen if another merge has happened in the interim,
1491        // or if spine needed to be rebuilt from state.
1492        //
1493        // When this occurs, we can still attempt to slot the merge res in to replace
1494        // the parts of a fueled merge. e.g. if the res is for `[1,3)` and the parts
1495        // are `[0,1),[1,2),[2,3),[3,4)`, we can swap out the middle two parts for res.
1496
1497        let mut lower = None;
1498        let mut upper = None;
1499
1500        for (i, batch) in self.parts.iter().enumerate() {
1501            if batch.batch.desc.lower() == desc.lower() {
1502                lower = Some((i, batch.id.0));
1503            }
1504            if batch.batch.desc.upper() == desc.upper() {
1505                upper = Some((i, batch.id.1));
1506            }
1507            if lower.is_some() && upper.is_some() {
1508                break;
1509            }
1510        }
1511
1512        match (lower, upper) {
1513            (Some((lower_idx, id_lower)), Some((upper_idx, id_upper))) => {
1514                Some((SpineId(id_lower, id_upper), lower_idx..(upper_idx + 1)))
1515            }
1516            _ => None,
1517        }
1518    }
1519
1520    /// Perform the actual subset replacement
1521    fn perform_subset_replacement(
1522        &mut self,
1523        res: &HollowBatch<T>,
1524        spine_id: SpineId,
1525        range: Range<usize>,
1526        new_active_compaction: Option<ActiveCompaction>,
1527    ) -> ApplyMergeResult {
1528        let SpineBatch {
1529            id,
1530            parts,
1531            desc,
1532            active_compaction: _,
1533            len: _,
1534        } = self;
1535
1536        let mut new_parts = vec![];
1537        new_parts.extend_from_slice(&parts[..range.start]);
1538        new_parts.push(IdHollowBatch {
1539            id: spine_id,
1540            batch: Arc::new(res.clone()),
1541        });
1542        new_parts.extend_from_slice(&parts[range.end..]);
1543
1544        let res = if range.len() == parts.len() {
1545            ApplyMergeResult::AppliedExact
1546        } else {
1547            ApplyMergeResult::AppliedSubset
1548        };
1549
1550        let new_spine_batch = SpineBatch {
1551            id: *id,
1552            desc: desc.to_owned(),
1553            len: new_parts.iter().map(|x| x.batch.len).sum(),
1554            parts: new_parts,
1555            active_compaction: new_active_compaction,
1556        };
1557
1558        if new_spine_batch.len() > self.len() {
1559            return ApplyMergeResult::NotAppliedTooManyUpdates;
1560        }
1561
1562        *self = new_spine_batch;
1563        res
1564    }
1565}
1566
1567#[derive(Debug, Clone, PartialEq, Serialize)]
1568pub struct FuelingMerge<T> {
1569    pub(crate) since: Antichain<T>,
1570    pub(crate) remaining_work: usize,
1571}
1572
1573#[derive(Debug, Clone, PartialEq, Serialize)]
1574pub struct IdFuelingMerge<T> {
1575    id: SpineId,
1576    merge: FuelingMerge<T>,
1577}
1578
1579impl<T: Timestamp + Lattice> FuelingMerge<T> {
1580    /// Perform some amount of work, decrementing `fuel`.
1581    ///
1582    /// If `fuel` is non-zero after the call, the merging is complete and one
1583    /// should call `done` to extract the merged results.
1584    // TODO(benesch): rewrite to avoid usage of `as`.
1585    #[allow(clippy::as_conversions)]
1586    fn work(&mut self, _: &[SpineBatch<T>], fuel: &mut isize) {
1587        let used = std::cmp::min(*fuel as usize, self.remaining_work);
1588        self.remaining_work = self.remaining_work.saturating_sub(used);
1589        *fuel -= used as isize;
1590    }
1591
1592    /// Extracts merged results.
1593    ///
1594    /// This method should only be called after `work` has been called and has
1595    /// not brought `fuel` to zero. Otherwise, the merge is still in progress.
1596    fn done(
1597        self,
1598        bs: ArrayVec<SpineBatch<T>, BATCHES_PER_LEVEL>,
1599        log: &mut SpineLog<'_, T>,
1600    ) -> Option<SpineBatch<T>> {
1601        let first = bs.first()?;
1602        let last = bs.last()?;
1603        let id = SpineId(first.id().0, last.id().1);
1604        assert!(id.0 < id.1);
1605        let lower = first.desc().lower().clone();
1606        let upper = last.desc().upper().clone();
1607        let since = self.since;
1608
1609        // Special case empty batches.
1610        if bs.iter().all(SpineBatch::is_empty) {
1611            return Some(SpineBatch::empty(id, lower, upper, since));
1612        }
1613
1614        let desc = Description::new(lower, upper, since);
1615        let len = bs.iter().map(SpineBatch::len).sum();
1616
1617        // Pre-size the merged_parts Vec. Benchmarking has shown that, at least
1618        // in the worst case, the double iteration is absolutely worth having
1619        // merged_parts pre-sized.
1620        let mut merged_parts_len = 0;
1621        for b in &bs {
1622            merged_parts_len += b.parts.len();
1623        }
1624        let mut merged_parts = Vec::with_capacity(merged_parts_len);
1625        for b in bs {
1626            merged_parts.extend(b.parts)
1627        }
1628        // Sanity check the pre-size code.
1629        debug_assert_eq!(merged_parts.len(), merged_parts_len);
1630
1631        if let SpineLog::Enabled { merge_reqs } = log {
1632            merge_reqs.push(FueledMergeReq {
1633                id,
1634                desc: desc.clone(),
1635                inputs: merged_parts.clone(),
1636            });
1637        }
1638
1639        Some(SpineBatch {
1640            id,
1641            desc,
1642            len,
1643            parts: merged_parts,
1644            active_compaction: None,
1645        })
1646    }
1647}
1648
1649/// The maximum number of batches per level in the spine.
1650/// In practice, we probably want a larger max and a configurable soft cap, but using a
1651/// stack-friendly data structure and keeping this number low makes this safer during the
1652/// initial rollout.
1653const BATCHES_PER_LEVEL: usize = 2;
1654
1655/// An append-only collection of update batches.
1656///
1657/// The `Spine` is a general-purpose trace implementation based on collection
1658/// and merging immutable batches of updates. It is generic with respect to the
1659/// batch type, and can be instantiated for any implementor of `trace::Batch`.
1660///
1661/// ## Design
1662///
1663/// This spine is represented as a list of layers, where each element in the
1664/// list is either
1665///
1666///   1. MergeState::Vacant  empty
1667///   2. MergeState::Single  a single batch
1668///   3. MergeState::Double  a pair of batches
1669///
1670/// Each "batch" has the option to be `None`, indicating a non-batch that
1671/// nonetheless acts as a number of updates proportionate to the level at which
1672/// it exists (for bookkeeping).
1673///
1674/// Each of the batches at layer i contains at most 2^i elements. The sequence
1675/// of batches should have the upper bound of one match the lower bound of the
1676/// next. Batches may be logically empty, with matching upper and lower bounds,
1677/// as a bookkeeping mechanism.
1678///
1679/// Each batch at layer i is treated as if it contains exactly 2^i elements,
1680/// even though it may actually contain fewer elements. This allows us to
1681/// decouple the physical representation from logical amounts of effort invested
1682/// in each batch. It allows us to begin compaction and to reduce the number of
1683/// updates, without compromising our ability to continue to move updates along
1684/// the spine. We are explicitly making the trade-off that while some batches
1685/// might compact at lower levels, we want to treat them as if they contained
1686/// their full set of updates for accounting reasons (to apply work to higher
1687/// levels).
1688///
1689/// We maintain the invariant that for any in-progress merge at level k there
1690/// should be fewer than 2^k records at levels lower than k. That is, even if we
1691/// were to apply an unbounded amount of effort to those records, we would not
1692/// have enough records to prompt a merge into the in-progress merge. Ideally,
1693/// we maintain the extended invariant that for any in-progress merge at level
1694/// k, the remaining effort required (number of records minus applied effort) is
1695/// less than the number of records that would need to be added to reach 2^k
1696/// records in layers below.
1697///
1698/// ## Mathematics
1699///
1700/// When a merge is initiated, there should be a non-negative *deficit* of
1701/// updates before the layers below could plausibly produce a new batch for the
1702/// currently merging layer. We must determine a factor of proportionality, so
1703/// that newly arrived updates provide at least that amount of "fuel" towards
1704/// the merging layer, so that the merge completes before lower levels invade.
1705///
1706/// ### Deficit:
1707///
1708/// A new merge is initiated only in response to the completion of a prior
1709/// merge, or the introduction of new records from outside. The latter case is
1710/// special, and will maintain our invariant trivially, so we will focus on the
1711/// former case.
1712///
1713/// When a merge at level k completes, assuming we have maintained our invariant
1714/// then there should be fewer than 2^k records at lower levels. The newly
1715/// created merge at level k+1 will require up to 2^k+2 units of work, and
1716/// should not expect a new batch until strictly more than 2^k records are
1717/// added. This means that a factor of proportionality of four should be
1718/// sufficient to ensure that the merge completes before a new merge is
1719/// initiated.
1720///
1721/// When new records get introduced, we will need to roll up any batches at
1722/// lower levels, which we treat as the introduction of records. Each of these
1723/// virtual records introduced should either be accounted for the fuel it should
1724/// contribute, as it results in the promotion of batches closer to in-progress
1725/// merges.
1726///
1727/// ### Fuel sharing
1728///
1729/// We like the idea of applying fuel preferentially to merges at *lower*
1730/// levels, under the idea that they are easier to complete, and we benefit from
1731/// fewer total merges in progress. This does delay the completion of merges at
1732/// higher levels, and may not obviously be a total win. If we choose to do
1733/// this, we should make sure that we correctly account for completed merges at
1734/// low layers: they should still extract fuel from new updates even though they
1735/// have completed, at least until they have paid back any "debt" to higher
1736/// layers by continuing to provide fuel as updates arrive.
1737#[derive(Debug, Clone)]
1738struct Spine<T> {
1739    effort: usize,
1740    next_id: usize,
1741    since: Antichain<T>,
1742    upper: Antichain<T>,
1743    merging: Vec<MergeState<T>>,
1744}
1745
1746impl<T> Spine<T> {
1747    /// All batches in the spine, oldest to newest.
1748    pub fn spine_batches(&self) -> impl Iterator<Item = &SpineBatch<T>> {
1749        self.merging.iter().rev().flat_map(|m| &m.batches)
1750    }
1751
1752    /// All (mutable) batches in the spine, oldest to newest.
1753    pub fn spine_batches_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut SpineBatch<T>> {
1754        self.merging.iter_mut().rev().flat_map(|m| &mut m.batches)
1755    }
1756}
1757
1758impl<T: Timestamp + Lattice> Spine<T> {
1759    /// Allocates a fueled `Spine`.
1760    ///
1761    /// This trace will merge batches progressively, with each inserted batch
1762    /// applying a multiple of the batch's length in effort to each merge. The
1763    /// `effort` parameter is that multiplier. This value should be at least one
1764    /// for the merging to happen; a value of zero is not helpful.
1765    pub fn new() -> Self {
1766        Spine {
1767            effort: 1,
1768            next_id: 0,
1769            since: Antichain::from_elem(T::minimum()),
1770            upper: Antichain::from_elem(T::minimum()),
1771            merging: Vec::new(),
1772        }
1773    }
1774
1775    /// Apply some amount of effort to trace maintenance.
1776    ///
1777    /// The units of effort are updates, and the method should be thought of as
1778    /// analogous to inserting as many empty updates, where the trace is
1779    /// permitted to perform proportionate work.
1780    ///
1781    /// Returns true if this did work and false if it left the spine unchanged.
1782    fn exert(&mut self, effort: usize, log: &mut SpineLog<'_, T>) -> bool {
1783        self.tidy_layers();
1784        if self.reduced() {
1785            return false;
1786        }
1787
1788        if self.merging.iter().any(|b| b.merge.is_some()) {
1789            let fuel = isize::try_from(effort).unwrap_or(isize::MAX);
1790            // If any merges exist, we can directly call `apply_fuel`.
1791            self.apply_fuel(&fuel, log);
1792        } else {
1793            // Otherwise, we'll need to introduce fake updates to move merges
1794            // along.
1795
1796            // Introduce an empty batch with roughly *effort number of virtual updates.
1797            let level = usize::cast_from(effort.next_power_of_two().trailing_zeros());
1798            let id = self.next_id();
1799            self.introduce_batch(
1800                SpineBatch::empty(
1801                    id,
1802                    self.upper.clone(),
1803                    self.upper.clone(),
1804                    self.since.clone(),
1805                ),
1806                level,
1807                log,
1808            );
1809        }
1810        true
1811    }
1812
1813    pub fn next_id(&mut self) -> SpineId {
1814        let id = self.next_id;
1815        self.next_id += 1;
1816        SpineId(id, self.next_id)
1817    }
1818
1819    // Ideally, this method acts as insertion of `batch`, even if we are not yet
1820    // able to begin merging the batch. This means it is a good time to perform
1821    // amortized work proportional to the size of batch.
1822    pub fn insert(&mut self, batch: HollowBatch<T>, log: &mut SpineLog<'_, T>) {
1823        assert!(batch.desc.lower() != batch.desc.upper());
1824        assert_eq!(batch.desc.lower(), &self.upper);
1825
1826        let id = self.next_id();
1827        let batch = SpineBatch::merged(IdHollowBatch {
1828            id,
1829            batch: Arc::new(batch),
1830        });
1831
1832        self.upper.clone_from(batch.upper());
1833
1834        // If `batch` and the most recently inserted batch are both empty,
1835        // we can just fuse them.
1836        if batch.is_empty() {
1837            if let Some(position) = self.merging.iter().position(|m| !m.is_vacant()) {
1838                if self.merging[position].is_single() && self.merging[position].is_empty() {
1839                    self.insert_at(batch, position);
1840                    // Since we just inserted a batch, we should always have work to complete...
1841                    // but otherwise we just leave this layer vacant.
1842                    if let Some(merged) = self.complete_at(position, log) {
1843                        self.merging[position] = MergeState::single(merged);
1844                    }
1845                    return;
1846                }
1847            }
1848        }
1849
1850        // Normal insertion for the batch.
1851        let index = batch.len().next_power_of_two();
1852        self.introduce_batch(batch, usize::cast_from(index.trailing_zeros()), log);
1853    }
1854
1855    /// Returns true when the trace is considered *structurally reduced*.
1856    ///
1857    /// Reduced == the total number of runs (across every
1858    /// `SpineBatch` and all of their inner hollow batches) is < 2. In other
1859    /// words, there are either zero runs (fully empty) or exactly one logical
1860    /// run of data remaining.
1861    fn reduced(&self) -> bool {
1862        self.spine_batches()
1863            .map(|b| {
1864                b.parts
1865                    .iter()
1866                    .map(|p| p.batch.run_meta.len())
1867                    .sum::<usize>()
1868            })
1869            .sum::<usize>()
1870            < 2
1871    }
1872
1873    /// Describes the merge progress of layers in the trace.
1874    ///
1875    /// Intended for diagnostics rather than public consumption.
1876    #[allow(dead_code)]
1877    fn describe(&self) -> Vec<(usize, usize)> {
1878        self.merging
1879            .iter()
1880            .map(|b| (b.batches.len(), b.len()))
1881            .collect()
1882    }
1883
1884    /// Introduces a batch at an indicated level.
1885    ///
1886    /// The level indication is often related to the size of the batch, but it
1887    /// can also be used to artificially fuel the computation by supplying empty
1888    /// batches at non-trivial indices, to move merges along.
1889    fn introduce_batch(
1890        &mut self,
1891        batch: SpineBatch<T>,
1892        batch_index: usize,
1893        log: &mut SpineLog<'_, T>,
1894    ) {
1895        // Step 0.  Determine an amount of fuel to use for the computation.
1896        //
1897        //          Fuel is used to drive maintenance of the data structure,
1898        //          and in particular are used to make progress through merges
1899        //          that are in progress. The amount of fuel to use should be
1900        //          proportional to the number of records introduced, so that
1901        //          we are guaranteed to complete all merges before they are
1902        //          required as arguments to merges again.
1903        //
1904        //          The fuel use policy is negotiable, in that we might aim
1905        //          to use relatively less when we can, so that we return
1906        //          control promptly, or we might account more work to larger
1907        //          batches. Not clear to me which are best, of if there
1908        //          should be a configuration knob controlling this.
1909
1910        // The amount of fuel to use is proportional to 2^batch_index, scaled by
1911        // a factor of self.effort which determines how eager we are in
1912        // performing maintenance work. We need to ensure that each merge in
1913        // progress receives fuel for each introduced batch, and so multiply by
1914        // that as well.
1915        if batch_index > 32 {
1916            println!("Large batch index: {}", batch_index);
1917        }
1918
1919        // We believe that eight units of fuel is sufficient for each introduced
1920        // record, accounted as four for each record, and a potential four more
1921        // for each virtual record associated with promoting existing smaller
1922        // batches. We could try and make this be less, or be scaled to merges
1923        // based on their deficit at time of instantiation. For now, we remain
1924        // conservative.
1925        let mut fuel = 8 << batch_index;
1926        // Scale up by the effort parameter, which is calibrated to one as the
1927        // minimum amount of effort.
1928        fuel *= self.effort;
1929        // Convert to an `isize` so we can observe any fuel shortfall.
1930        // TODO(benesch): avoid dangerous usage of `as`.
1931        #[allow(clippy::as_conversions)]
1932        let fuel = fuel as isize;
1933
1934        // Step 1.  Apply fuel to each in-progress merge.
1935        //
1936        //          Before we can introduce new updates, we must apply any
1937        //          fuel to in-progress merges, as this fuel is what ensures
1938        //          that the merges will be complete by the time we insert
1939        //          the updates.
1940        self.apply_fuel(&fuel, log);
1941
1942        // Step 2.  We must ensure the invariant that adjacent layers do not
1943        //          contain two batches will be satisfied when we insert the
1944        //          batch. We forcibly completing all merges at layers lower
1945        //          than and including `batch_index`, so that the new batch is
1946        //          inserted into an empty layer.
1947        //
1948        //          We could relax this to "strictly less than `batch_index`"
1949        //          if the layer above has only a single batch in it, which
1950        //          seems not implausible if it has been the focus of effort.
1951        //
1952        //          This should be interpreted as the introduction of some
1953        //          volume of fake updates, and we will need to fuel merges
1954        //          by a proportional amount to ensure that they are not
1955        //          surprised later on. The number of fake updates should
1956        //          correspond to the deficit for the layer, which perhaps
1957        //          we should track explicitly.
1958        self.roll_up(batch_index, log);
1959
1960        // Step 3. This insertion should be into an empty layer. It is a logical
1961        //         error otherwise, as we may be violating our invariant, from
1962        //         which all wonderment derives.
1963        self.insert_at(batch, batch_index);
1964
1965        // Step 4. Tidy the largest layers.
1966        //
1967        //         It is important that we not tidy only smaller layers,
1968        //         as their ascension is what ensures the merging and
1969        //         eventual compaction of the largest layers.
1970        self.tidy_layers();
1971    }
1972
1973    /// Ensures that an insertion at layer `index` will succeed.
1974    ///
1975    /// This method is subject to the constraint that all existing batches
1976    /// should occur at higher levels, which requires it to "roll up" batches
1977    /// present at lower levels before the method is called. In doing this, we
1978    /// should not introduce more virtual records than 2^index, as that is the
1979    /// amount of excess fuel we have budgeted for completing merges.
1980    fn roll_up(&mut self, index: usize, log: &mut SpineLog<'_, T>) {
1981        // Ensure entries sufficient for `index`.
1982        while self.merging.len() <= index {
1983            self.merging.push(MergeState::default());
1984        }
1985
1986        // We only need to roll up if there are non-vacant layers.
1987        if self.merging[..index].iter().any(|m| !m.is_vacant()) {
1988            // Collect and merge all batches at layers up to but not including
1989            // `index`.
1990            let mut merged = None;
1991            for i in 0..index {
1992                if let Some(merged) = merged.take() {
1993                    self.insert_at(merged, i);
1994                }
1995                merged = self.complete_at(i, log);
1996            }
1997
1998            // The merged results should be introduced at level `index`, which
1999            // should be ready to absorb them (possibly creating a new merge at
2000            // the time).
2001            if let Some(merged) = merged {
2002                self.insert_at(merged, index);
2003            }
2004
2005            // If the insertion results in a merge, we should complete it to
2006            // ensure the upcoming insertion at `index` does not panic.
2007            if self.merging[index].is_full() {
2008                let merged = self.complete_at(index, log).expect("double batch");
2009                self.insert_at(merged, index + 1);
2010            }
2011        }
2012    }
2013
2014    /// Applies an amount of fuel to merges in progress.
2015    ///
2016    /// The supplied `fuel` is for each in progress merge, and if we want to
2017    /// spend the fuel non-uniformly (e.g. prioritizing merges at low layers) we
2018    /// could do so in order to maintain fewer batches on average (at the risk
2019    /// of completing merges of large batches later, but tbh probably not much
2020    /// later).
2021    pub fn apply_fuel(&mut self, fuel: &isize, log: &mut SpineLog<'_, T>) {
2022        // For the moment our strategy is to apply fuel independently to each
2023        // merge in progress, rather than prioritizing small merges. This sounds
2024        // like a great idea, but we need better accounting in place to ensure
2025        // that merges that borrow against later layers but then complete still
2026        // "acquire" fuel to pay back their debts.
2027        for index in 0..self.merging.len() {
2028            // Give each level independent fuel, for now.
2029            let mut fuel = *fuel;
2030            // Pass along various logging stuffs, in case we need to report
2031            // success.
2032            self.merging[index].work(&mut fuel);
2033            // `fuel` could have a deficit at this point, meaning we over-spent
2034            // when we took a merge step. We could ignore this, or maintain the
2035            // deficit and account future fuel against it before spending again.
2036            // It isn't clear why that would be especially helpful to do; we
2037            // might want to avoid overspends at multiple layers in the same
2038            // invocation (to limit latencies), but there is probably a rich
2039            // policy space here.
2040
2041            // If a merge completes, we can immediately merge it in to the next
2042            // level, which is "guaranteed" to be complete at this point, by our
2043            // fueling discipline.
2044            if self.merging[index].is_complete() {
2045                let complete = self.complete_at(index, log).expect("complete batch");
2046                self.insert_at(complete, index + 1);
2047            }
2048        }
2049    }
2050
2051    /// Inserts a batch at a specific location.
2052    ///
2053    /// This is a non-public internal method that can panic if we try and insert
2054    /// into a layer which already contains two batches (and is still in the
2055    /// process of merging).
2056    fn insert_at(&mut self, batch: SpineBatch<T>, index: usize) {
2057        // Ensure the spine is large enough.
2058        while self.merging.len() <= index {
2059            self.merging.push(MergeState::default());
2060        }
2061
2062        // Insert the batch at the location.
2063        let merging = &mut self.merging[index];
2064        merging.push_batch(batch);
2065        if merging.batches.is_full() {
2066            let compaction_frontier = Some(self.since.borrow());
2067            merging.merge = SpineBatch::begin_merge(&merging.batches[..], compaction_frontier)
2068        }
2069    }
2070
2071    /// Completes and extracts what ever is at layer `index`, leaving this layer vacant.
2072    fn complete_at(&mut self, index: usize, log: &mut SpineLog<'_, T>) -> Option<SpineBatch<T>> {
2073        self.merging[index].complete(log)
2074    }
2075
2076    /// Attempts to draw down large layers to size appropriate layers.
2077    fn tidy_layers(&mut self) {
2078        // If the largest layer is complete (not merging), we can attempt to
2079        // draw it down to the next layer. This is permitted if we can maintain
2080        // our invariant that below each merge there are at most half the
2081        // records that would be required to invade the merge.
2082        if !self.merging.is_empty() {
2083            let mut length = self.merging.len();
2084            if self.merging[length - 1].is_single() {
2085                // To move a batch down, we require that it contain few enough
2086                // records that the lower level is appropriate, and that moving
2087                // the batch would not create a merge violating our invariant.
2088                let appropriate_level = usize::cast_from(
2089                    self.merging[length - 1]
2090                        .len()
2091                        .next_power_of_two()
2092                        .trailing_zeros(),
2093                );
2094
2095                // Continue only as far as is appropriate
2096                while appropriate_level < length - 1 {
2097                    let current = &mut self.merging[length - 2];
2098                    if current.is_vacant() {
2099                        // Vacant batches can be absorbed.
2100                        self.merging.remove(length - 2);
2101                        length = self.merging.len();
2102                    } else {
2103                        if !current.is_full() {
2104                            // Single batches may initiate a merge, if sizes are
2105                            // within bounds, but terminate the loop either way.
2106
2107                            // Determine the number of records that might lead
2108                            // to a merge. Importantly, this is not the number
2109                            // of actual records, but the sum of upper bounds
2110                            // based on indices.
2111                            let mut smaller = 0;
2112                            for (index, batch) in self.merging[..(length - 2)].iter().enumerate() {
2113                                smaller += batch.batches.len() << index;
2114                            }
2115
2116                            if smaller <= (1 << length) / 8 {
2117                                // Remove the batch under consideration (shifting the deeper batches up a level),
2118                                // then merge in the single batch at the current level.
2119                                let state = self.merging.remove(length - 2);
2120                                assert_eq!(state.batches.len(), 1);
2121                                for batch in state.batches {
2122                                    self.insert_at(batch, length - 2);
2123                                }
2124                            }
2125                        }
2126                        break;
2127                    }
2128                }
2129            }
2130        }
2131    }
2132
2133    /// Checks invariants:
2134    /// - The lowers and uppers of all batches "line up".
2135    /// - The lower of the "minimum" batch is `antichain[T::minimum]`.
2136    /// - The upper of the "maximum" batch is `== self.upper`.
2137    /// - The since of each batch is `less_equal self.since`.
2138    /// - The `SpineIds` all "line up" and cover from `0` to `self.next_id`.
2139    /// - TODO: Verify fuel and level invariants.
2140    fn validate(&self) -> Result<(), String> {
2141        let mut id = SpineId(0, 0);
2142        let mut frontier = Antichain::from_elem(T::minimum());
2143        for x in self.merging.iter().rev() {
2144            if x.is_full() != x.merge.is_some() {
2145                return Err(format!(
2146                    "all (and only) full batches should have fueling merges (full={}, merge={:?})",
2147                    x.is_full(),
2148                    x.merge,
2149                ));
2150            }
2151
2152            if let Some(m) = &x.merge {
2153                if !x.is_full() {
2154                    return Err(format!(
2155                        "merge should only exist for full batches (len={:?}, merge={:?})",
2156                        x.batches.len(),
2157                        m.id,
2158                    ));
2159                }
2160                if x.id() != Some(m.id) {
2161                    return Err(format!(
2162                        "merge id should match the range of the batch ids (batch={:?}, merge={:?})",
2163                        x.id(),
2164                        m.id,
2165                    ));
2166                }
2167            }
2168
2169            // TODO: Anything we can validate about x.merge? It'd
2170            // be nice to assert that it's bigger than the len of the
2171            // two batches, but apply_merge_res might swap those lengths
2172            // out from under us.
2173            for batch in &x.batches {
2174                if batch.id().0 != id.1 {
2175                    return Err(format!(
2176                        "batch id {:?} does not match the previous id {:?}: {:?}",
2177                        batch.id(),
2178                        id,
2179                        self
2180                    ));
2181                }
2182                id = batch.id();
2183                if batch.desc().lower() != &frontier {
2184                    return Err(format!(
2185                        "batch lower {:?} does not match the previous upper {:?}: {:?}",
2186                        batch.desc().lower(),
2187                        frontier,
2188                        self
2189                    ));
2190                }
2191                frontier.clone_from(batch.desc().upper());
2192                if !PartialOrder::less_equal(batch.desc().since(), &self.since) {
2193                    return Err(format!(
2194                        "since of batch {:?} past the spine since {:?}: {:?}",
2195                        batch.desc().since(),
2196                        self.since,
2197                        self
2198                    ));
2199                }
2200            }
2201        }
2202        if self.next_id != id.1 {
2203            return Err(format!(
2204                "spine next_id {:?} does not match the last batch's id {:?}: {:?}",
2205                self.next_id, id, self
2206            ));
2207        }
2208        if self.upper != frontier {
2209            return Err(format!(
2210                "spine upper {:?} does not match the last batch's upper {:?}: {:?}",
2211                self.upper, frontier, self
2212            ));
2213        }
2214        Ok(())
2215    }
2216}
2217
2218/// Describes the state of a layer.
2219///
2220/// A layer can be empty, contain a single batch, or contain a pair of batches
2221/// that are in the process of merging into a batch for the next layer.
2222#[derive(Debug, Clone)]
2223struct MergeState<T> {
2224    batches: ArrayVec<SpineBatch<T>, BATCHES_PER_LEVEL>,
2225    merge: Option<IdFuelingMerge<T>>,
2226}
2227
2228impl<T> Default for MergeState<T> {
2229    fn default() -> Self {
2230        Self {
2231            batches: ArrayVec::new(),
2232            merge: None,
2233        }
2234    }
2235}
2236
2237impl<T: Timestamp + Lattice> MergeState<T> {
2238    /// An id that covers all the batches in the given merge state, assuming there are any.
2239    fn id(&self) -> Option<SpineId> {
2240        if let (Some(first), Some(last)) = (self.batches.first(), self.batches.last()) {
2241            Some(SpineId(first.id().0, last.id().1))
2242        } else {
2243            None
2244        }
2245    }
2246
2247    /// A new single-batch merge state.
2248    fn single(batch: SpineBatch<T>) -> Self {
2249        let mut state = Self::default();
2250        state.push_batch(batch);
2251        state
2252    }
2253
2254    /// Push a new batch at this level, checking invariants.
2255    fn push_batch(&mut self, batch: SpineBatch<T>) {
2256        self.try_push_batch(batch)
2257            .unwrap_or_else(|err| panic!("invalid batch push: {err}"));
2258    }
2259
2260    /// Fallible version of [Self::push_batch], for [Trace::unflatten], where
2261    /// the batches were decoded from an untrusted blob and a violated
2262    /// invariant must be a decode error rather than a panic.
2263    fn try_push_batch(&mut self, batch: SpineBatch<T>) -> Result<(), String> {
2264        if let Some(last) = self.batches.last() {
2265            if last.id().1 != batch.id().0 {
2266                return Err(format!(
2267                    "batch id {:?} does not chain with the previous id {:?}",
2268                    batch.id(),
2269                    last.id()
2270                ));
2271            }
2272            if last.upper() != batch.lower() {
2273                return Err(format!(
2274                    "batch lower {:?} does not match the previous upper {:?}",
2275                    batch.lower(),
2276                    last.upper()
2277                ));
2278            }
2279        }
2280        if self.merge.is_some() {
2281            return Err(format!(
2282                "attempted to insert batch into incomplete merge! (batch={:?}, batch_count={})",
2283                batch.id,
2284                self.batches.len(),
2285            ));
2286        }
2287        if self.batches.try_push(batch).is_err() {
2288            return Err("attempted to insert batch into full layer!".to_string());
2289        }
2290        Ok(())
2291    }
2292
2293    /// The number of actual updates contained in the level.
2294    fn len(&self) -> usize {
2295        self.batches.iter().map(SpineBatch::len).sum()
2296    }
2297
2298    /// True if this merge state contains no updates.
2299    fn is_empty(&self) -> bool {
2300        self.batches.iter().all(SpineBatch::is_empty)
2301    }
2302
2303    /// True if this level contains no batches.
2304    fn is_vacant(&self) -> bool {
2305        self.batches.is_empty()
2306    }
2307
2308    /// True only for a single-batch state.
2309    fn is_single(&self) -> bool {
2310        self.batches.len() == 1
2311    }
2312
2313    /// True if this merge cannot hold any more batches.
2314    /// (i.e. for a binary merge tree, true if this layer holds two batches.)
2315    fn is_full(&self) -> bool {
2316        self.batches.is_full()
2317    }
2318
2319    /// Immediately complete any merge.
2320    ///
2321    /// The result is either a batch, if there is a non-trivial batch to return
2322    /// or `None` if there is no meaningful batch to return.
2323    ///
2324    /// There is the additional option of input batches.
2325    fn complete(&mut self, log: &mut SpineLog<'_, T>) -> Option<SpineBatch<T>> {
2326        let mut this = mem::take(self);
2327        if this.batches.len() <= 1 {
2328            this.batches.pop()
2329        } else {
2330            // Merge the remaining batches, regardless of whether we have a fully fueled merge.
2331            let id_merge = this
2332                .merge
2333                .or_else(|| SpineBatch::begin_merge(&self.batches[..], None))?;
2334            id_merge.merge.done(this.batches, log)
2335        }
2336    }
2337
2338    /// True iff the layer is a complete merge, ready for extraction.
2339    fn is_complete(&self) -> bool {
2340        match &self.merge {
2341            Some(IdFuelingMerge { merge, .. }) => merge.remaining_work == 0,
2342            None => false,
2343        }
2344    }
2345
2346    /// Performs a bounded amount of work towards a merge.
2347    fn work(&mut self, fuel: &mut isize) {
2348        // We only perform work for merges in progress.
2349        if let Some(IdFuelingMerge { merge, .. }) = &mut self.merge {
2350            merge.work(&self.batches[..], fuel)
2351        }
2352    }
2353}
2354
2355#[cfg(test)]
2356pub mod datadriven {
2357    use mz_ore::fmt::FormatBuffer;
2358
2359    use crate::internal::datadriven::DirectiveArgs;
2360
2361    use super::*;
2362
2363    /// Shared state for a single [crate::internal::trace] [datadriven::TestFile].
2364    #[derive(Debug, Default)]
2365    pub struct TraceState {
2366        pub trace: Trace<u64>,
2367        pub merge_reqs: Vec<FueledMergeReq<u64>>,
2368    }
2369
2370    pub fn since_upper(
2371        datadriven: &TraceState,
2372        _args: DirectiveArgs,
2373    ) -> Result<String, anyhow::Error> {
2374        Ok(format!(
2375            "{:?}{:?}\n",
2376            datadriven.trace.since().elements(),
2377            datadriven.trace.upper().elements()
2378        ))
2379    }
2380
2381    pub fn batches(datadriven: &TraceState, _args: DirectiveArgs) -> Result<String, anyhow::Error> {
2382        let mut s = String::new();
2383        for b in datadriven.trace.spine.spine_batches() {
2384            s.push_str(b.describe(true).as_str());
2385            s.push('\n');
2386        }
2387        Ok(s)
2388    }
2389
2390    pub fn insert(
2391        datadriven: &mut TraceState,
2392        args: DirectiveArgs,
2393    ) -> Result<String, anyhow::Error> {
2394        for x in args
2395            .input
2396            .trim()
2397            .split('\n')
2398            .map(DirectiveArgs::parse_hollow_batch)
2399        {
2400            datadriven
2401                .merge_reqs
2402                .append(&mut datadriven.trace.push_batch(x));
2403        }
2404        Ok("ok\n".to_owned())
2405    }
2406
2407    pub fn downgrade_since(
2408        datadriven: &mut TraceState,
2409        args: DirectiveArgs,
2410    ) -> Result<String, anyhow::Error> {
2411        let since = args.expect("since");
2412        datadriven
2413            .trace
2414            .downgrade_since(&Antichain::from_elem(since));
2415        Ok("ok\n".to_owned())
2416    }
2417
2418    pub fn take_merge_req(
2419        datadriven: &mut TraceState,
2420        _args: DirectiveArgs,
2421    ) -> Result<String, anyhow::Error> {
2422        let mut s = String::new();
2423        for merge_req in std::mem::take(&mut datadriven.merge_reqs) {
2424            write!(
2425                s,
2426                "{:?}{:?}{:?} {}\n",
2427                merge_req.desc.lower().elements(),
2428                merge_req.desc.upper().elements(),
2429                merge_req.desc.since().elements(),
2430                merge_req
2431                    .inputs
2432                    .iter()
2433                    .flat_map(|x| x.batch.parts.iter())
2434                    .map(|x| x.printable_name())
2435                    .collect::<Vec<_>>()
2436                    .join(" ")
2437            );
2438        }
2439        Ok(s)
2440    }
2441
2442    pub fn apply_merge_res(
2443        datadriven: &mut TraceState,
2444        args: DirectiveArgs,
2445    ) -> Result<String, anyhow::Error> {
2446        let res = FueledMergeRes {
2447            output: DirectiveArgs::parse_hollow_batch(args.input),
2448            input: CompactionInput::Legacy,
2449            new_active_compaction: None,
2450        };
2451        match datadriven.trace.apply_merge_res_unchecked(&res) {
2452            ApplyMergeResult::AppliedExact => Ok("applied exact\n".into()),
2453            ApplyMergeResult::AppliedSubset => Ok("applied subset\n".into()),
2454            ApplyMergeResult::NotAppliedNoMatch => Ok("no-op\n".into()),
2455            ApplyMergeResult::NotAppliedInvalidSince => Ok("no-op invalid since\n".into()),
2456            ApplyMergeResult::NotAppliedTooManyUpdates => Ok("no-op too many updates\n".into()),
2457        }
2458    }
2459}
2460
2461#[cfg(test)]
2462pub(crate) mod tests {
2463    use std::ops::Range;
2464
2465    use proptest::prelude::*;
2466    use semver::Version;
2467
2468    use crate::internal::state::tests::{any_hollow_batch, any_hollow_batch_with_exact_runs};
2469
2470    use super::*;
2471
2472    pub fn any_trace<T: Arbitrary + Timestamp + Lattice>(
2473        num_batches: Range<usize>,
2474    ) -> impl Strategy<Value = Trace<T>> {
2475        Strategy::prop_map(
2476            (
2477                any::<Option<T>>(),
2478                proptest::collection::vec(any_hollow_batch::<T>(), num_batches),
2479                any::<bool>(),
2480                any::<u64>(),
2481            ),
2482            |(since, mut batches, roundtrip_structure, timeout_ms)| {
2483                let mut trace = Trace::<T>::default();
2484                trace.downgrade_since(&since.map_or_else(Antichain::new, Antichain::from_elem));
2485
2486                // Fix up the arbitrary HollowBatches so the lowers and uppers
2487                // align.
2488                batches.sort_by(|x, y| x.desc.upper().elements().cmp(y.desc.upper().elements()));
2489                let mut lower = Antichain::from_elem(T::minimum());
2490                for mut batch in batches {
2491                    // Overall trace since has to be past each batch's since.
2492                    if PartialOrder::less_than(trace.since(), batch.desc.since()) {
2493                        trace.downgrade_since(batch.desc.since());
2494                    }
2495                    batch.desc = Description::new(
2496                        lower.clone(),
2497                        batch.desc.upper().clone(),
2498                        batch.desc.since().clone(),
2499                    );
2500                    lower.clone_from(batch.desc.upper());
2501                    let _merge_req = trace.push_batch(batch);
2502                }
2503                let reqs: Vec<_> = trace
2504                    .fueled_merge_reqs_before_ms(timeout_ms, None)
2505                    .collect();
2506                for req in reqs {
2507                    trace.claim_compaction(req.id, ActiveCompaction { start_ms: 0 })
2508                }
2509                trace.roundtrip_structure = roundtrip_structure;
2510                trace
2511            },
2512        )
2513    }
2514
2515    #[mz_ore::test]
2516    #[cfg_attr(miri, ignore)] // proptest is too heavy for miri!
2517    fn test_roundtrips() {
2518        fn check(trace: Trace<i64>) {
2519            trace.validate().unwrap();
2520            let flat = trace.flatten();
2521            let unflat = Trace::unflatten(flat).unwrap();
2522            assert_eq!(trace, unflat);
2523        }
2524
2525        proptest!(|(trace in any_trace::<i64>(1..10))| { check(trace) })
2526    }
2527
2528    #[mz_ore::test]
2529    fn fueled_merge_reqs() {
2530        let mut trace: Trace<u64> = Trace::default();
2531        let fueled_reqs = trace.push_batch(crate::internal::state::tests::hollow(
2532            0,
2533            10,
2534            &["n0011500/p3122e2a1-a0c7-429f-87aa-1019bf4f5f86"],
2535            1000,
2536        ));
2537
2538        assert!(fueled_reqs.is_empty());
2539        assert_eq!(
2540            trace.fueled_merge_reqs_before_ms(u64::MAX, None).count(),
2541            0,
2542            "no merge reqs when not filtering by version"
2543        );
2544        assert_eq!(
2545            trace
2546                .fueled_merge_reqs_before_ms(
2547                    u64::MAX,
2548                    Some(WriterKey::for_version(&Version::new(0, 50, 0)))
2549                )
2550                .count(),
2551            0,
2552            "zero batches are older than a past version"
2553        );
2554        assert_eq!(
2555            trace
2556                .fueled_merge_reqs_before_ms(
2557                    u64::MAX,
2558                    Some(WriterKey::for_version(&Version::new(99, 99, 0)))
2559                )
2560                .count(),
2561            1,
2562            "one batch is older than a future version"
2563        );
2564    }
2565
2566    #[mz_ore::test]
2567    fn remove_redundant_merge_reqs() {
2568        fn req(lower: u64, upper: u64) -> FueledMergeReq<u64> {
2569            FueledMergeReq {
2570                id: SpineId(usize::cast_from(lower), usize::cast_from(upper)),
2571                desc: Description::new(
2572                    Antichain::from_elem(lower),
2573                    Antichain::from_elem(upper),
2574                    Antichain::new(),
2575                ),
2576                inputs: vec![],
2577            }
2578        }
2579
2580        // Empty
2581        assert_eq!(Trace::<u64>::remove_redundant_merge_reqs(vec![]), vec![]);
2582
2583        // Single
2584        assert_eq!(
2585            Trace::remove_redundant_merge_reqs(vec![req(0, 1)]),
2586            vec![req(0, 1)]
2587        );
2588
2589        // Duplicate
2590        assert_eq!(
2591            Trace::remove_redundant_merge_reqs(vec![req(0, 1), req(0, 1)]),
2592            vec![req(0, 1)]
2593        );
2594
2595        // Nothing covered
2596        assert_eq!(
2597            Trace::remove_redundant_merge_reqs(vec![req(0, 1), req(1, 2)]),
2598            vec![req(1, 2), req(0, 1)]
2599        );
2600
2601        // Covered
2602        assert_eq!(
2603            Trace::remove_redundant_merge_reqs(vec![req(1, 2), req(0, 3)]),
2604            vec![req(0, 3)]
2605        );
2606
2607        // Covered, lower equal
2608        assert_eq!(
2609            Trace::remove_redundant_merge_reqs(vec![req(0, 2), req(0, 3)]),
2610            vec![req(0, 3)]
2611        );
2612
2613        // Covered, upper equal
2614        assert_eq!(
2615            Trace::remove_redundant_merge_reqs(vec![req(1, 3), req(0, 3)]),
2616            vec![req(0, 3)]
2617        );
2618
2619        // Covered, unexpected order (doesn't happen in practice)
2620        assert_eq!(
2621            Trace::remove_redundant_merge_reqs(vec![req(0, 3), req(1, 2)]),
2622            vec![req(0, 3)]
2623        );
2624
2625        // Partially overlapping
2626        assert_eq!(
2627            Trace::remove_redundant_merge_reqs(vec![req(0, 2), req(1, 3)]),
2628            vec![req(1, 3), req(0, 2)]
2629        );
2630
2631        // Partially overlapping, the other order
2632        assert_eq!(
2633            Trace::remove_redundant_merge_reqs(vec![req(1, 3), req(0, 2)]),
2634            vec![req(0, 2), req(1, 3)]
2635        );
2636
2637        // Different sinces (doesn't happen in practice)
2638        let req015 = FueledMergeReq {
2639            id: SpineId(0, 1),
2640            desc: Description::new(
2641                Antichain::from_elem(0),
2642                Antichain::from_elem(1),
2643                Antichain::from_elem(5),
2644            ),
2645            inputs: vec![],
2646        };
2647        assert_eq!(
2648            Trace::remove_redundant_merge_reqs(vec![req(0, 1), req015.clone()]),
2649            vec![req015, req(0, 1)]
2650        );
2651    }
2652
2653    #[mz_ore::test]
2654    #[cfg_attr(miri, ignore)] // proptest is too heavy for miri!
2655    fn construct_batch_with_runs_replaced_test() {
2656        let batch_strategy = any_hollow_batch::<u64>();
2657        let to_replace_strategy = any_hollow_batch_with_exact_runs::<u64>(1);
2658
2659        let combined_strategy = (batch_strategy, to_replace_strategy)
2660            .prop_filter("non-empty batch", |(batch, _)| batch.run_meta.len() >= 1);
2661
2662        let final_strategy = combined_strategy.prop_flat_map(|(batch, to_replace)| {
2663            let batch_len = batch.run_meta.len();
2664            let batch_clone = batch.clone();
2665            let to_replace_clone = to_replace.clone();
2666
2667            proptest::collection::vec(any::<bool>(), batch_len)
2668                .prop_filter("at least one run selected", |mask| mask.iter().any(|&x| x))
2669                .prop_map(move |mask| {
2670                    let indices: Vec<usize> = mask
2671                        .iter()
2672                        .enumerate()
2673                        .filter_map(|(i, &selected)| if selected { Some(i) } else { None })
2674                        .collect();
2675                    (batch_clone.clone(), to_replace_clone.clone(), indices)
2676                })
2677        });
2678
2679        proptest!(|(
2680            (batch, to_replace, runs) in final_strategy
2681        )| {
2682            let original_run_ids: Vec<_> = batch.run_meta.iter().map(|x|
2683                x.id.unwrap().clone()
2684            ).collect();
2685
2686            let run_ids = runs.iter().map(|&i| original_run_ids[i].clone()).collect::<Vec<_>>();
2687
2688            let new_batch = SpineBatch::construct_batch_with_runs_replaced(
2689                &batch,
2690                &run_ids,
2691                &to_replace,
2692            ).unwrap();
2693
2694            let expected_len = batch.run_meta.len() - runs.len()
2695                + to_replace.run_meta.len();
2696            prop_assert!(new_batch.run_meta.len() == expected_len);
2697        });
2698    }
2699
2700    #[mz_ore::test]
2701    fn test_perform_subset_replacement() {
2702        let batch1 = crate::internal::state::tests::hollow::<u64>(0, 10, &["a"], 10);
2703        let batch2 = crate::internal::state::tests::hollow::<u64>(10, 20, &["b"], 10);
2704        let batch3 = crate::internal::state::tests::hollow::<u64>(20, 30, &["c"], 10);
2705
2706        let id_batch1 = IdHollowBatch {
2707            id: SpineId(0, 1),
2708            batch: Arc::new(batch1.clone()),
2709        };
2710        let id_batch2 = IdHollowBatch {
2711            id: SpineId(1, 2),
2712            batch: Arc::new(batch2.clone()),
2713        };
2714        let id_batch3 = IdHollowBatch {
2715            id: SpineId(2, 3),
2716            batch: Arc::new(batch3.clone()),
2717        };
2718
2719        let spine_batch = SpineBatch {
2720            id: SpineId(0, 3),
2721            desc: Description::new(
2722                Antichain::from_elem(0),
2723                Antichain::from_elem(30),
2724                Antichain::from_elem(0),
2725            ),
2726            parts: vec![id_batch1, id_batch2, id_batch3],
2727            active_compaction: None,
2728            len: 30,
2729        };
2730
2731        let res_exact = crate::internal::state::tests::hollow::<u64>(0, 30, &["d"], 30);
2732        let mut sb_exact = spine_batch.clone();
2733        let result = sb_exact.perform_subset_replacement(&res_exact, SpineId(0, 3), 0..3, None);
2734        assert!(matches!(result, ApplyMergeResult::AppliedExact));
2735        assert_eq!(sb_exact.parts.len(), 1);
2736        assert_eq!(sb_exact.len(), 30);
2737
2738        let res_subset = crate::internal::state::tests::hollow::<u64>(0, 20, &["e"], 20);
2739        let mut sb_subset = spine_batch.clone();
2740        let result = sb_subset.perform_subset_replacement(&res_subset, SpineId(0, 2), 0..2, None);
2741        assert!(matches!(result, ApplyMergeResult::AppliedSubset));
2742        assert_eq!(sb_subset.parts.len(), 2); // One new part + one old part
2743        assert_eq!(sb_subset.len(), 30);
2744
2745        let res_too_big = crate::internal::state::tests::hollow::<u64>(0, 30, &["f"], 31);
2746        let mut sb_too_big = spine_batch.clone();
2747        let result = sb_too_big.perform_subset_replacement(&res_too_big, SpineId(0, 3), 0..3, None);
2748        assert!(matches!(result, ApplyMergeResult::NotAppliedTooManyUpdates));
2749        assert_eq!(sb_too_big.parts.len(), 3);
2750        assert_eq!(sb_too_big.len(), 30);
2751    }
2752}