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    fn work(&mut self, _: &[SpineBatch<T>], fuel: &mut isize) {
1585        // A negative `fuel` means a caller already overspent, so there is
1586        // nothing to spend here. Reading it as a `usize` instead would wrap to a
1587        // huge budget, spend `remaining_work` against it, and then underflow the
1588        // subtraction below.
1589        let available = usize::try_from(*fuel).unwrap_or(0);
1590        let used = std::cmp::min(available, self.remaining_work);
1591        self.remaining_work = self.remaining_work.saturating_sub(used);
1592        // `used <= available <= isize::MAX`, so neither conversion nor the
1593        // subtraction can overflow.
1594        *fuel -= isize::try_from(used).expect("used is bounded by fuel");
1595    }
1596
1597    /// Extracts merged results.
1598    ///
1599    /// This method should only be called after `work` has been called and has
1600    /// not brought `fuel` to zero. Otherwise, the merge is still in progress.
1601    fn done(
1602        self,
1603        bs: ArrayVec<SpineBatch<T>, BATCHES_PER_LEVEL>,
1604        log: &mut SpineLog<'_, T>,
1605    ) -> Option<SpineBatch<T>> {
1606        let first = bs.first()?;
1607        let last = bs.last()?;
1608        let id = SpineId(first.id().0, last.id().1);
1609        assert!(id.0 < id.1);
1610        let lower = first.desc().lower().clone();
1611        let upper = last.desc().upper().clone();
1612        let since = self.since;
1613
1614        // Special case empty batches.
1615        if bs.iter().all(SpineBatch::is_empty) {
1616            return Some(SpineBatch::empty(id, lower, upper, since));
1617        }
1618
1619        let desc = Description::new(lower, upper, since);
1620        let len = bs.iter().map(SpineBatch::len).sum();
1621
1622        // Pre-size the merged_parts Vec. Benchmarking has shown that, at least
1623        // in the worst case, the double iteration is absolutely worth having
1624        // merged_parts pre-sized.
1625        let mut merged_parts_len = 0;
1626        for b in &bs {
1627            merged_parts_len += b.parts.len();
1628        }
1629        let mut merged_parts = Vec::with_capacity(merged_parts_len);
1630        for b in bs {
1631            merged_parts.extend(b.parts)
1632        }
1633        // Sanity check the pre-size code.
1634        debug_assert_eq!(merged_parts.len(), merged_parts_len);
1635
1636        if let SpineLog::Enabled { merge_reqs } = log {
1637            merge_reqs.push(FueledMergeReq {
1638                id,
1639                desc: desc.clone(),
1640                inputs: merged_parts.clone(),
1641            });
1642        }
1643
1644        Some(SpineBatch {
1645            id,
1646            desc,
1647            len,
1648            parts: merged_parts,
1649            active_compaction: None,
1650        })
1651    }
1652}
1653
1654/// The maximum number of batches per level in the spine.
1655/// In practice, we probably want a larger max and a configurable soft cap, but using a
1656/// stack-friendly data structure and keeping this number low makes this safer during the
1657/// initial rollout.
1658const BATCHES_PER_LEVEL: usize = 2;
1659
1660/// An append-only collection of update batches.
1661///
1662/// The `Spine` is a general-purpose trace implementation based on collection
1663/// and merging immutable batches of updates. It is generic with respect to the
1664/// batch type, and can be instantiated for any implementor of `trace::Batch`.
1665///
1666/// ## Design
1667///
1668/// This spine is represented as a list of layers, where each element in the
1669/// list is either
1670///
1671///   1. MergeState::Vacant  empty
1672///   2. MergeState::Single  a single batch
1673///   3. MergeState::Double  a pair of batches
1674///
1675/// Each "batch" has the option to be `None`, indicating a non-batch that
1676/// nonetheless acts as a number of updates proportionate to the level at which
1677/// it exists (for bookkeeping).
1678///
1679/// Each of the batches at layer i contains at most 2^i elements. The sequence
1680/// of batches should have the upper bound of one match the lower bound of the
1681/// next. Batches may be logically empty, with matching upper and lower bounds,
1682/// as a bookkeeping mechanism.
1683///
1684/// Each batch at layer i is treated as if it contains exactly 2^i elements,
1685/// even though it may actually contain fewer elements. This allows us to
1686/// decouple the physical representation from logical amounts of effort invested
1687/// in each batch. It allows us to begin compaction and to reduce the number of
1688/// updates, without compromising our ability to continue to move updates along
1689/// the spine. We are explicitly making the trade-off that while some batches
1690/// might compact at lower levels, we want to treat them as if they contained
1691/// their full set of updates for accounting reasons (to apply work to higher
1692/// levels).
1693///
1694/// We maintain the invariant that for any in-progress merge at level k there
1695/// should be fewer than 2^k records at levels lower than k. That is, even if we
1696/// were to apply an unbounded amount of effort to those records, we would not
1697/// have enough records to prompt a merge into the in-progress merge. Ideally,
1698/// we maintain the extended invariant that for any in-progress merge at level
1699/// k, the remaining effort required (number of records minus applied effort) is
1700/// less than the number of records that would need to be added to reach 2^k
1701/// records in layers below.
1702///
1703/// ## Mathematics
1704///
1705/// When a merge is initiated, there should be a non-negative *deficit* of
1706/// updates before the layers below could plausibly produce a new batch for the
1707/// currently merging layer. We must determine a factor of proportionality, so
1708/// that newly arrived updates provide at least that amount of "fuel" towards
1709/// the merging layer, so that the merge completes before lower levels invade.
1710///
1711/// ### Deficit:
1712///
1713/// A new merge is initiated only in response to the completion of a prior
1714/// merge, or the introduction of new records from outside. The latter case is
1715/// special, and will maintain our invariant trivially, so we will focus on the
1716/// former case.
1717///
1718/// When a merge at level k completes, assuming we have maintained our invariant
1719/// then there should be fewer than 2^k records at lower levels. The newly
1720/// created merge at level k+1 will require up to 2^k+2 units of work, and
1721/// should not expect a new batch until strictly more than 2^k records are
1722/// added. This means that a factor of proportionality of four should be
1723/// sufficient to ensure that the merge completes before a new merge is
1724/// initiated.
1725///
1726/// When new records get introduced, we will need to roll up any batches at
1727/// lower levels, which we treat as the introduction of records. Each of these
1728/// virtual records introduced should either be accounted for the fuel it should
1729/// contribute, as it results in the promotion of batches closer to in-progress
1730/// merges.
1731///
1732/// ### Fuel sharing
1733///
1734/// We like the idea of applying fuel preferentially to merges at *lower*
1735/// levels, under the idea that they are easier to complete, and we benefit from
1736/// fewer total merges in progress. This does delay the completion of merges at
1737/// higher levels, and may not obviously be a total win. If we choose to do
1738/// this, we should make sure that we correctly account for completed merges at
1739/// low layers: they should still extract fuel from new updates even though they
1740/// have completed, at least until they have paid back any "debt" to higher
1741/// layers by continuing to provide fuel as updates arrive.
1742#[derive(Debug, Clone)]
1743struct Spine<T> {
1744    effort: usize,
1745    next_id: usize,
1746    since: Antichain<T>,
1747    upper: Antichain<T>,
1748    merging: Vec<MergeState<T>>,
1749}
1750
1751impl<T> Spine<T> {
1752    /// All batches in the spine, oldest to newest.
1753    pub fn spine_batches(&self) -> impl Iterator<Item = &SpineBatch<T>> {
1754        self.merging.iter().rev().flat_map(|m| &m.batches)
1755    }
1756
1757    /// All (mutable) batches in the spine, oldest to newest.
1758    pub fn spine_batches_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut SpineBatch<T>> {
1759        self.merging.iter_mut().rev().flat_map(|m| &mut m.batches)
1760    }
1761}
1762
1763impl<T: Timestamp + Lattice> Spine<T> {
1764    /// Allocates a fueled `Spine`.
1765    ///
1766    /// This trace will merge batches progressively, with each inserted batch
1767    /// applying a multiple of the batch's length in effort to each merge. The
1768    /// `effort` parameter is that multiplier. This value should be at least one
1769    /// for the merging to happen; a value of zero is not helpful.
1770    pub fn new() -> Self {
1771        Spine {
1772            effort: 1,
1773            next_id: 0,
1774            since: Antichain::from_elem(T::minimum()),
1775            upper: Antichain::from_elem(T::minimum()),
1776            merging: Vec::new(),
1777        }
1778    }
1779
1780    /// Apply some amount of effort to trace maintenance.
1781    ///
1782    /// The units of effort are updates, and the method should be thought of as
1783    /// analogous to inserting as many empty updates, where the trace is
1784    /// permitted to perform proportionate work.
1785    ///
1786    /// Returns true if this did work and false if it left the spine unchanged.
1787    fn exert(&mut self, effort: usize, log: &mut SpineLog<'_, T>) -> bool {
1788        self.tidy_layers();
1789        if self.reduced() {
1790            return false;
1791        }
1792
1793        if self.merging.iter().any(|b| b.merge.is_some()) {
1794            let fuel = isize::try_from(effort).unwrap_or(isize::MAX);
1795            // If any merges exist, we can directly call `apply_fuel`.
1796            self.apply_fuel(&fuel, log);
1797        } else {
1798            // Otherwise, we'll need to introduce fake updates to move merges
1799            // along.
1800
1801            // Introduce an empty batch with roughly *effort number of virtual updates.
1802            let level = usize::cast_from(effort.next_power_of_two().trailing_zeros());
1803            let id = self.next_id();
1804            self.introduce_batch(
1805                SpineBatch::empty(
1806                    id,
1807                    self.upper.clone(),
1808                    self.upper.clone(),
1809                    self.since.clone(),
1810                ),
1811                level,
1812                log,
1813            );
1814        }
1815        true
1816    }
1817
1818    pub fn next_id(&mut self) -> SpineId {
1819        let id = self.next_id;
1820        self.next_id += 1;
1821        SpineId(id, self.next_id)
1822    }
1823
1824    // Ideally, this method acts as insertion of `batch`, even if we are not yet
1825    // able to begin merging the batch. This means it is a good time to perform
1826    // amortized work proportional to the size of batch.
1827    pub fn insert(&mut self, batch: HollowBatch<T>, log: &mut SpineLog<'_, T>) {
1828        assert!(batch.desc.lower() != batch.desc.upper());
1829        assert_eq!(batch.desc.lower(), &self.upper);
1830
1831        let id = self.next_id();
1832        let batch = SpineBatch::merged(IdHollowBatch {
1833            id,
1834            batch: Arc::new(batch),
1835        });
1836
1837        self.upper.clone_from(batch.upper());
1838
1839        // If `batch` and the most recently inserted batch are both empty,
1840        // we can just fuse them.
1841        if batch.is_empty() {
1842            if let Some(position) = self.merging.iter().position(|m| !m.is_vacant()) {
1843                if self.merging[position].is_single() && self.merging[position].is_empty() {
1844                    self.insert_at(batch, position);
1845                    // Since we just inserted a batch, we should always have work to complete...
1846                    // but otherwise we just leave this layer vacant.
1847                    if let Some(merged) = self.complete_at(position, log) {
1848                        self.merging[position] = MergeState::single(merged);
1849                    }
1850                    return;
1851                }
1852            }
1853        }
1854
1855        // Normal insertion for the batch.
1856        let index = batch.len().next_power_of_two();
1857        self.introduce_batch(batch, usize::cast_from(index.trailing_zeros()), log);
1858    }
1859
1860    /// Returns true when the trace is considered *structurally reduced*.
1861    ///
1862    /// Reduced == the total number of runs (across every
1863    /// `SpineBatch` and all of their inner hollow batches) is < 2. In other
1864    /// words, there are either zero runs (fully empty) or exactly one logical
1865    /// run of data remaining.
1866    fn reduced(&self) -> bool {
1867        self.spine_batches()
1868            .map(|b| {
1869                b.parts
1870                    .iter()
1871                    .map(|p| p.batch.run_meta.len())
1872                    .sum::<usize>()
1873            })
1874            .sum::<usize>()
1875            < 2
1876    }
1877
1878    /// Describes the merge progress of layers in the trace.
1879    ///
1880    /// Intended for diagnostics rather than public consumption.
1881    #[allow(dead_code)]
1882    fn describe(&self) -> Vec<(usize, usize)> {
1883        self.merging
1884            .iter()
1885            .map(|b| (b.batches.len(), b.len()))
1886            .collect()
1887    }
1888
1889    /// Introduces a batch at an indicated level.
1890    ///
1891    /// The level indication is often related to the size of the batch, but it
1892    /// can also be used to artificially fuel the computation by supplying empty
1893    /// batches at non-trivial indices, to move merges along.
1894    fn introduce_batch(
1895        &mut self,
1896        batch: SpineBatch<T>,
1897        batch_index: usize,
1898        log: &mut SpineLog<'_, T>,
1899    ) {
1900        // Step 0.  Determine an amount of fuel to use for the computation.
1901        //
1902        //          Fuel is used to drive maintenance of the data structure,
1903        //          and in particular are used to make progress through merges
1904        //          that are in progress. The amount of fuel to use should be
1905        //          proportional to the number of records introduced, so that
1906        //          we are guaranteed to complete all merges before they are
1907        //          required as arguments to merges again.
1908        //
1909        //          The fuel use policy is negotiable, in that we might aim
1910        //          to use relatively less when we can, so that we return
1911        //          control promptly, or we might account more work to larger
1912        //          batches. Not clear to me which are best, of if there
1913        //          should be a configuration knob controlling this.
1914
1915        // The amount of fuel to use is proportional to 2^batch_index, scaled by
1916        // a factor of self.effort which determines how eager we are in
1917        // performing maintenance work. We need to ensure that each merge in
1918        // progress receives fuel for each introduced batch, and so multiply by
1919        // that as well.
1920        if batch_index > 32 {
1921            println!("Large batch index: {}", batch_index);
1922        }
1923
1924        // We believe that eight units of fuel is sufficient for each introduced
1925        // record, accounted as four for each record, and a potential four more
1926        // for each virtual record associated with promoting existing smaller
1927        // batches. We could try and make this be less, or be scaled to merges
1928        // based on their deficit at time of instantiation. For now, we remain
1929        // conservative.
1930        //
1931        // `batch_index` is derived from a batch's `len`, which for a trace
1932        // reconstructed from an untrusted blob can be large enough that
1933        // `8 << batch_index` overflows. Saturate at `isize::MAX` rather than
1934        // wrapping: fuel is a budget, so more of it only completes merges sooner,
1935        // whereas a wrapped value can land negative and starve them. The result
1936        // is an `isize` so a fuel shortfall stays observable.
1937        let fuel = u32::try_from(batch_index)
1938            .ok()
1939            .and_then(|shift| 8usize.checked_shl(shift))
1940            // Scale up by the effort parameter, which is calibrated to one as the
1941            // minimum amount of effort.
1942            .and_then(|fuel| fuel.checked_mul(self.effort))
1943            .and_then(|fuel| isize::try_from(fuel).ok())
1944            .unwrap_or(isize::MAX);
1945
1946        // Step 1.  Apply fuel to each in-progress merge.
1947        //
1948        //          Before we can introduce new updates, we must apply any
1949        //          fuel to in-progress merges, as this fuel is what ensures
1950        //          that the merges will be complete by the time we insert
1951        //          the updates.
1952        self.apply_fuel(&fuel, log);
1953
1954        // Step 2.  We must ensure the invariant that adjacent layers do not
1955        //          contain two batches will be satisfied when we insert the
1956        //          batch. We forcibly completing all merges at layers lower
1957        //          than and including `batch_index`, so that the new batch is
1958        //          inserted into an empty layer.
1959        //
1960        //          We could relax this to "strictly less than `batch_index`"
1961        //          if the layer above has only a single batch in it, which
1962        //          seems not implausible if it has been the focus of effort.
1963        //
1964        //          This should be interpreted as the introduction of some
1965        //          volume of fake updates, and we will need to fuel merges
1966        //          by a proportional amount to ensure that they are not
1967        //          surprised later on. The number of fake updates should
1968        //          correspond to the deficit for the layer, which perhaps
1969        //          we should track explicitly.
1970        self.roll_up(batch_index, log);
1971
1972        // Step 3. This insertion should be into an empty layer. It is a logical
1973        //         error otherwise, as we may be violating our invariant, from
1974        //         which all wonderment derives.
1975        self.insert_at(batch, batch_index);
1976
1977        // Step 4. Tidy the largest layers.
1978        //
1979        //         It is important that we not tidy only smaller layers,
1980        //         as their ascension is what ensures the merging and
1981        //         eventual compaction of the largest layers.
1982        self.tidy_layers();
1983    }
1984
1985    /// Ensures that an insertion at layer `index` will succeed.
1986    ///
1987    /// This method is subject to the constraint that all existing batches
1988    /// should occur at higher levels, which requires it to "roll up" batches
1989    /// present at lower levels before the method is called. In doing this, we
1990    /// should not introduce more virtual records than 2^index, as that is the
1991    /// amount of excess fuel we have budgeted for completing merges.
1992    fn roll_up(&mut self, index: usize, log: &mut SpineLog<'_, T>) {
1993        // Ensure entries sufficient for `index`.
1994        while self.merging.len() <= index {
1995            self.merging.push(MergeState::default());
1996        }
1997
1998        // We only need to roll up if there are non-vacant layers.
1999        if self.merging[..index].iter().any(|m| !m.is_vacant()) {
2000            // Collect and merge all batches at layers up to but not including
2001            // `index`.
2002            let mut merged = None;
2003            for i in 0..index {
2004                if let Some(merged) = merged.take() {
2005                    self.insert_at(merged, i);
2006                }
2007                merged = self.complete_at(i, log);
2008            }
2009
2010            // The merged results should be introduced at level `index`, which
2011            // should be ready to absorb them (possibly creating a new merge at
2012            // the time).
2013            if let Some(merged) = merged {
2014                self.insert_at(merged, index);
2015            }
2016
2017            // If the insertion results in a merge, we should complete it to
2018            // ensure the upcoming insertion at `index` does not panic.
2019            if self.merging[index].is_full() {
2020                let merged = self.complete_at(index, log).expect("double batch");
2021                self.insert_at(merged, index + 1);
2022            }
2023        }
2024    }
2025
2026    /// Applies an amount of fuel to merges in progress.
2027    ///
2028    /// The supplied `fuel` is for each in progress merge, and if we want to
2029    /// spend the fuel non-uniformly (e.g. prioritizing merges at low layers) we
2030    /// could do so in order to maintain fewer batches on average (at the risk
2031    /// of completing merges of large batches later, but tbh probably not much
2032    /// later).
2033    pub fn apply_fuel(&mut self, fuel: &isize, log: &mut SpineLog<'_, T>) {
2034        // For the moment our strategy is to apply fuel independently to each
2035        // merge in progress, rather than prioritizing small merges. This sounds
2036        // like a great idea, but we need better accounting in place to ensure
2037        // that merges that borrow against later layers but then complete still
2038        // "acquire" fuel to pay back their debts.
2039        for index in 0..self.merging.len() {
2040            // Give each level independent fuel, for now.
2041            let mut fuel = *fuel;
2042            // Pass along various logging stuffs, in case we need to report
2043            // success.
2044            self.merging[index].work(&mut fuel);
2045            // `fuel` could have a deficit at this point, meaning we over-spent
2046            // when we took a merge step. We could ignore this, or maintain the
2047            // deficit and account future fuel against it before spending again.
2048            // It isn't clear why that would be especially helpful to do; we
2049            // might want to avoid overspends at multiple layers in the same
2050            // invocation (to limit latencies), but there is probably a rich
2051            // policy space here.
2052
2053            // If a merge completes, we can immediately merge it in to the next
2054            // level, which is "guaranteed" to be complete at this point, by our
2055            // fueling discipline.
2056            if self.merging[index].is_complete() {
2057                let complete = self.complete_at(index, log).expect("complete batch");
2058                self.insert_at(complete, index + 1);
2059            }
2060        }
2061    }
2062
2063    /// Inserts a batch at a specific location.
2064    ///
2065    /// This is a non-public internal method that can panic if we try and insert
2066    /// into a layer which already contains two batches (and is still in the
2067    /// process of merging).
2068    fn insert_at(&mut self, batch: SpineBatch<T>, index: usize) {
2069        // Ensure the spine is large enough.
2070        while self.merging.len() <= index {
2071            self.merging.push(MergeState::default());
2072        }
2073
2074        // Insert the batch at the location.
2075        let merging = &mut self.merging[index];
2076        merging.push_batch(batch);
2077        if merging.batches.is_full() {
2078            let compaction_frontier = Some(self.since.borrow());
2079            merging.merge = SpineBatch::begin_merge(&merging.batches[..], compaction_frontier)
2080        }
2081    }
2082
2083    /// Completes and extracts what ever is at layer `index`, leaving this layer vacant.
2084    fn complete_at(&mut self, index: usize, log: &mut SpineLog<'_, T>) -> Option<SpineBatch<T>> {
2085        self.merging[index].complete(log)
2086    }
2087
2088    /// Attempts to draw down large layers to size appropriate layers.
2089    fn tidy_layers(&mut self) {
2090        // If the largest layer is complete (not merging), we can attempt to
2091        // draw it down to the next layer. This is permitted if we can maintain
2092        // our invariant that below each merge there are at most half the
2093        // records that would be required to invade the merge.
2094        if !self.merging.is_empty() {
2095            let mut length = self.merging.len();
2096            if self.merging[length - 1].is_single() {
2097                // To move a batch down, we require that it contain few enough
2098                // records that the lower level is appropriate, and that moving
2099                // the batch would not create a merge violating our invariant.
2100                let appropriate_level = usize::cast_from(
2101                    self.merging[length - 1]
2102                        .len()
2103                        .next_power_of_two()
2104                        .trailing_zeros(),
2105                );
2106
2107                // Continue only as far as is appropriate
2108                while appropriate_level < length - 1 {
2109                    let current = &mut self.merging[length - 2];
2110                    if current.is_vacant() {
2111                        // Vacant batches can be absorbed.
2112                        self.merging.remove(length - 2);
2113                        length = self.merging.len();
2114                    } else {
2115                        if !current.is_full() {
2116                            // Single batches may initiate a merge, if sizes are
2117                            // within bounds, but terminate the loop either way.
2118
2119                            // Determine the number of records that might lead
2120                            // to a merge. Importantly, this is not the number
2121                            // of actual records, but the sum of upper bounds
2122                            // based on indices.
2123                            let mut smaller = 0;
2124                            for (index, batch) in self.merging[..(length - 2)].iter().enumerate() {
2125                                smaller += batch.batches.len() << index;
2126                            }
2127
2128                            if smaller <= (1 << length) / 8 {
2129                                // Remove the batch under consideration (shifting the deeper batches up a level),
2130                                // then merge in the single batch at the current level.
2131                                let state = self.merging.remove(length - 2);
2132                                assert_eq!(state.batches.len(), 1);
2133                                for batch in state.batches {
2134                                    self.insert_at(batch, length - 2);
2135                                }
2136                            }
2137                        }
2138                        break;
2139                    }
2140                }
2141            }
2142        }
2143    }
2144
2145    /// Checks invariants:
2146    /// - The lowers and uppers of all batches "line up".
2147    /// - The lower of the "minimum" batch is `antichain[T::minimum]`.
2148    /// - The upper of the "maximum" batch is `== self.upper`.
2149    /// - The since of each batch is `less_equal self.since`.
2150    /// - The `SpineIds` all "line up" and cover from `0` to `self.next_id`.
2151    /// - TODO: Verify fuel and level invariants.
2152    fn validate(&self) -> Result<(), String> {
2153        let mut id = SpineId(0, 0);
2154        let mut frontier = Antichain::from_elem(T::minimum());
2155        for x in self.merging.iter().rev() {
2156            if x.is_full() != x.merge.is_some() {
2157                return Err(format!(
2158                    "all (and only) full batches should have fueling merges (full={}, merge={:?})",
2159                    x.is_full(),
2160                    x.merge,
2161                ));
2162            }
2163
2164            if let Some(m) = &x.merge {
2165                if !x.is_full() {
2166                    return Err(format!(
2167                        "merge should only exist for full batches (len={:?}, merge={:?})",
2168                        x.batches.len(),
2169                        m.id,
2170                    ));
2171                }
2172                if x.id() != Some(m.id) {
2173                    return Err(format!(
2174                        "merge id should match the range of the batch ids (batch={:?}, merge={:?})",
2175                        x.id(),
2176                        m.id,
2177                    ));
2178                }
2179            }
2180
2181            // TODO: Anything we can validate about x.merge? It'd
2182            // be nice to assert that it's bigger than the len of the
2183            // two batches, but apply_merge_res might swap those lengths
2184            // out from under us.
2185            for batch in &x.batches {
2186                if batch.id().0 != id.1 {
2187                    return Err(format!(
2188                        "batch id {:?} does not match the previous id {:?}: {:?}",
2189                        batch.id(),
2190                        id,
2191                        self
2192                    ));
2193                }
2194                id = batch.id();
2195                if batch.desc().lower() != &frontier {
2196                    return Err(format!(
2197                        "batch lower {:?} does not match the previous upper {:?}: {:?}",
2198                        batch.desc().lower(),
2199                        frontier,
2200                        self
2201                    ));
2202                }
2203                frontier.clone_from(batch.desc().upper());
2204                if !PartialOrder::less_equal(batch.desc().since(), &self.since) {
2205                    return Err(format!(
2206                        "since of batch {:?} past the spine since {:?}: {:?}",
2207                        batch.desc().since(),
2208                        self.since,
2209                        self
2210                    ));
2211                }
2212            }
2213        }
2214        if self.next_id != id.1 {
2215            return Err(format!(
2216                "spine next_id {:?} does not match the last batch's id {:?}: {:?}",
2217                self.next_id, id, self
2218            ));
2219        }
2220        if self.upper != frontier {
2221            return Err(format!(
2222                "spine upper {:?} does not match the last batch's upper {:?}: {:?}",
2223                self.upper, frontier, self
2224            ));
2225        }
2226        Ok(())
2227    }
2228}
2229
2230/// Describes the state of a layer.
2231///
2232/// A layer can be empty, contain a single batch, or contain a pair of batches
2233/// that are in the process of merging into a batch for the next layer.
2234#[derive(Debug, Clone)]
2235struct MergeState<T> {
2236    batches: ArrayVec<SpineBatch<T>, BATCHES_PER_LEVEL>,
2237    merge: Option<IdFuelingMerge<T>>,
2238}
2239
2240impl<T> Default for MergeState<T> {
2241    fn default() -> Self {
2242        Self {
2243            batches: ArrayVec::new(),
2244            merge: None,
2245        }
2246    }
2247}
2248
2249impl<T: Timestamp + Lattice> MergeState<T> {
2250    /// An id that covers all the batches in the given merge state, assuming there are any.
2251    fn id(&self) -> Option<SpineId> {
2252        if let (Some(first), Some(last)) = (self.batches.first(), self.batches.last()) {
2253            Some(SpineId(first.id().0, last.id().1))
2254        } else {
2255            None
2256        }
2257    }
2258
2259    /// A new single-batch merge state.
2260    fn single(batch: SpineBatch<T>) -> Self {
2261        let mut state = Self::default();
2262        state.push_batch(batch);
2263        state
2264    }
2265
2266    /// Push a new batch at this level, checking invariants.
2267    fn push_batch(&mut self, batch: SpineBatch<T>) {
2268        self.try_push_batch(batch)
2269            .unwrap_or_else(|err| panic!("invalid batch push: {err}"));
2270    }
2271
2272    /// Fallible version of [Self::push_batch], for [Trace::unflatten], where
2273    /// the batches were decoded from an untrusted blob and a violated
2274    /// invariant must be a decode error rather than a panic.
2275    fn try_push_batch(&mut self, batch: SpineBatch<T>) -> Result<(), String> {
2276        if let Some(last) = self.batches.last() {
2277            if last.id().1 != batch.id().0 {
2278                return Err(format!(
2279                    "batch id {:?} does not chain with the previous id {:?}",
2280                    batch.id(),
2281                    last.id()
2282                ));
2283            }
2284            if last.upper() != batch.lower() {
2285                return Err(format!(
2286                    "batch lower {:?} does not match the previous upper {:?}",
2287                    batch.lower(),
2288                    last.upper()
2289                ));
2290            }
2291        }
2292        if self.merge.is_some() {
2293            return Err(format!(
2294                "attempted to insert batch into incomplete merge! (batch={:?}, batch_count={})",
2295                batch.id,
2296                self.batches.len(),
2297            ));
2298        }
2299        if self.batches.try_push(batch).is_err() {
2300            return Err("attempted to insert batch into full layer!".to_string());
2301        }
2302        Ok(())
2303    }
2304
2305    /// The number of actual updates contained in the level.
2306    fn len(&self) -> usize {
2307        self.batches.iter().map(SpineBatch::len).sum()
2308    }
2309
2310    /// True if this merge state contains no updates.
2311    fn is_empty(&self) -> bool {
2312        self.batches.iter().all(SpineBatch::is_empty)
2313    }
2314
2315    /// True if this level contains no batches.
2316    fn is_vacant(&self) -> bool {
2317        self.batches.is_empty()
2318    }
2319
2320    /// True only for a single-batch state.
2321    fn is_single(&self) -> bool {
2322        self.batches.len() == 1
2323    }
2324
2325    /// True if this merge cannot hold any more batches.
2326    /// (i.e. for a binary merge tree, true if this layer holds two batches.)
2327    fn is_full(&self) -> bool {
2328        self.batches.is_full()
2329    }
2330
2331    /// Immediately complete any merge.
2332    ///
2333    /// The result is either a batch, if there is a non-trivial batch to return
2334    /// or `None` if there is no meaningful batch to return.
2335    ///
2336    /// There is the additional option of input batches.
2337    fn complete(&mut self, log: &mut SpineLog<'_, T>) -> Option<SpineBatch<T>> {
2338        let mut this = mem::take(self);
2339        if this.batches.len() <= 1 {
2340            this.batches.pop()
2341        } else {
2342            // Merge the remaining batches, regardless of whether we have a fully fueled merge.
2343            let id_merge = this
2344                .merge
2345                .or_else(|| SpineBatch::begin_merge(&self.batches[..], None))?;
2346            id_merge.merge.done(this.batches, log)
2347        }
2348    }
2349
2350    /// True iff the layer is a complete merge, ready for extraction.
2351    fn is_complete(&self) -> bool {
2352        match &self.merge {
2353            Some(IdFuelingMerge { merge, .. }) => merge.remaining_work == 0,
2354            None => false,
2355        }
2356    }
2357
2358    /// Performs a bounded amount of work towards a merge.
2359    fn work(&mut self, fuel: &mut isize) {
2360        // We only perform work for merges in progress.
2361        if let Some(IdFuelingMerge { merge, .. }) = &mut self.merge {
2362            merge.work(&self.batches[..], fuel)
2363        }
2364    }
2365}
2366
2367#[cfg(test)]
2368pub mod datadriven {
2369    use mz_ore::fmt::FormatBuffer;
2370
2371    use crate::internal::datadriven::DirectiveArgs;
2372
2373    use super::*;
2374
2375    /// Shared state for a single [crate::internal::trace] [datadriven::TestFile].
2376    #[derive(Debug, Default)]
2377    pub struct TraceState {
2378        pub trace: Trace<u64>,
2379        pub merge_reqs: Vec<FueledMergeReq<u64>>,
2380    }
2381
2382    pub fn since_upper(
2383        datadriven: &TraceState,
2384        _args: DirectiveArgs,
2385    ) -> Result<String, anyhow::Error> {
2386        Ok(format!(
2387            "{:?}{:?}\n",
2388            datadriven.trace.since().elements(),
2389            datadriven.trace.upper().elements()
2390        ))
2391    }
2392
2393    pub fn batches(datadriven: &TraceState, _args: DirectiveArgs) -> Result<String, anyhow::Error> {
2394        let mut s = String::new();
2395        for b in datadriven.trace.spine.spine_batches() {
2396            s.push_str(b.describe(true).as_str());
2397            s.push('\n');
2398        }
2399        Ok(s)
2400    }
2401
2402    pub fn insert(
2403        datadriven: &mut TraceState,
2404        args: DirectiveArgs,
2405    ) -> Result<String, anyhow::Error> {
2406        for x in args
2407            .input
2408            .trim()
2409            .split('\n')
2410            .map(DirectiveArgs::parse_hollow_batch)
2411        {
2412            datadriven
2413                .merge_reqs
2414                .append(&mut datadriven.trace.push_batch(x));
2415        }
2416        Ok("ok\n".to_owned())
2417    }
2418
2419    pub fn downgrade_since(
2420        datadriven: &mut TraceState,
2421        args: DirectiveArgs,
2422    ) -> Result<String, anyhow::Error> {
2423        let since = args.expect("since");
2424        datadriven
2425            .trace
2426            .downgrade_since(&Antichain::from_elem(since));
2427        Ok("ok\n".to_owned())
2428    }
2429
2430    pub fn take_merge_req(
2431        datadriven: &mut TraceState,
2432        _args: DirectiveArgs,
2433    ) -> Result<String, anyhow::Error> {
2434        let mut s = String::new();
2435        for merge_req in std::mem::take(&mut datadriven.merge_reqs) {
2436            write!(
2437                s,
2438                "{:?}{:?}{:?} {}\n",
2439                merge_req.desc.lower().elements(),
2440                merge_req.desc.upper().elements(),
2441                merge_req.desc.since().elements(),
2442                merge_req
2443                    .inputs
2444                    .iter()
2445                    .flat_map(|x| x.batch.parts.iter())
2446                    .map(|x| x.printable_name())
2447                    .collect::<Vec<_>>()
2448                    .join(" ")
2449            );
2450        }
2451        Ok(s)
2452    }
2453
2454    pub fn apply_merge_res(
2455        datadriven: &mut TraceState,
2456        args: DirectiveArgs,
2457    ) -> Result<String, anyhow::Error> {
2458        let res = FueledMergeRes {
2459            output: DirectiveArgs::parse_hollow_batch(args.input),
2460            input: CompactionInput::Legacy,
2461            new_active_compaction: None,
2462        };
2463        match datadriven.trace.apply_merge_res_unchecked(&res) {
2464            ApplyMergeResult::AppliedExact => Ok("applied exact\n".into()),
2465            ApplyMergeResult::AppliedSubset => Ok("applied subset\n".into()),
2466            ApplyMergeResult::NotAppliedNoMatch => Ok("no-op\n".into()),
2467            ApplyMergeResult::NotAppliedInvalidSince => Ok("no-op invalid since\n".into()),
2468            ApplyMergeResult::NotAppliedTooManyUpdates => Ok("no-op too many updates\n".into()),
2469        }
2470    }
2471}
2472
2473#[cfg(test)]
2474pub(crate) mod tests {
2475    use std::ops::Range;
2476
2477    use proptest::prelude::*;
2478    use semver::Version;
2479
2480    use crate::internal::state::tests::{any_hollow_batch, any_hollow_batch_with_exact_runs};
2481
2482    use super::*;
2483
2484    pub fn any_trace<T: Arbitrary + Timestamp + Lattice>(
2485        num_batches: Range<usize>,
2486    ) -> impl Strategy<Value = Trace<T>> {
2487        Strategy::prop_map(
2488            (
2489                any::<Option<T>>(),
2490                proptest::collection::vec(any_hollow_batch::<T>(), num_batches),
2491                any::<bool>(),
2492                any::<u64>(),
2493            ),
2494            |(since, mut batches, roundtrip_structure, timeout_ms)| {
2495                let mut trace = Trace::<T>::default();
2496                trace.downgrade_since(&since.map_or_else(Antichain::new, Antichain::from_elem));
2497
2498                // Fix up the arbitrary HollowBatches so the lowers and uppers
2499                // align.
2500                batches.sort_by(|x, y| x.desc.upper().elements().cmp(y.desc.upper().elements()));
2501                let mut lower = Antichain::from_elem(T::minimum());
2502                for mut batch in batches {
2503                    // Overall trace since has to be past each batch's since.
2504                    if PartialOrder::less_than(trace.since(), batch.desc.since()) {
2505                        trace.downgrade_since(batch.desc.since());
2506                    }
2507                    batch.desc = Description::new(
2508                        lower.clone(),
2509                        batch.desc.upper().clone(),
2510                        batch.desc.since().clone(),
2511                    );
2512                    lower.clone_from(batch.desc.upper());
2513                    let _merge_req = trace.push_batch(batch);
2514                }
2515                let reqs: Vec<_> = trace
2516                    .fueled_merge_reqs_before_ms(timeout_ms, None)
2517                    .collect();
2518                for req in reqs {
2519                    trace.claim_compaction(req.id, ActiveCompaction { start_ms: 0 })
2520                }
2521                trace.roundtrip_structure = roundtrip_structure;
2522                trace
2523            },
2524        )
2525    }
2526
2527    #[mz_ore::test]
2528    #[cfg_attr(miri, ignore)] // proptest is too heavy for miri!
2529    fn test_roundtrips() {
2530        fn check(trace: Trace<i64>) {
2531            trace.validate().unwrap();
2532            let flat = trace.flatten();
2533            let unflat = Trace::unflatten(flat).unwrap();
2534            assert_eq!(trace, unflat);
2535        }
2536
2537        proptest!(|(trace in any_trace::<i64>(1..10))| { check(trace) })
2538    }
2539
2540    #[mz_ore::test]
2541    fn fueled_merge_reqs() {
2542        let mut trace: Trace<u64> = Trace::default();
2543        let fueled_reqs = trace.push_batch(crate::internal::state::tests::hollow(
2544            0,
2545            10,
2546            &["n0011500/p3122e2a1-a0c7-429f-87aa-1019bf4f5f86"],
2547            1000,
2548        ));
2549
2550        assert!(fueled_reqs.is_empty());
2551        assert_eq!(
2552            trace.fueled_merge_reqs_before_ms(u64::MAX, None).count(),
2553            0,
2554            "no merge reqs when not filtering by version"
2555        );
2556        assert_eq!(
2557            trace
2558                .fueled_merge_reqs_before_ms(
2559                    u64::MAX,
2560                    Some(WriterKey::for_version(&Version::new(0, 50, 0)))
2561                )
2562                .count(),
2563            0,
2564            "zero batches are older than a past version"
2565        );
2566        assert_eq!(
2567            trace
2568                .fueled_merge_reqs_before_ms(
2569                    u64::MAX,
2570                    Some(WriterKey::for_version(&Version::new(99, 99, 0)))
2571                )
2572                .count(),
2573            1,
2574            "one batch is older than a future version"
2575        );
2576    }
2577
2578    #[mz_ore::test]
2579    fn remove_redundant_merge_reqs() {
2580        fn req(lower: u64, upper: u64) -> FueledMergeReq<u64> {
2581            FueledMergeReq {
2582                id: SpineId(usize::cast_from(lower), usize::cast_from(upper)),
2583                desc: Description::new(
2584                    Antichain::from_elem(lower),
2585                    Antichain::from_elem(upper),
2586                    Antichain::new(),
2587                ),
2588                inputs: vec![],
2589            }
2590        }
2591
2592        // Empty
2593        assert_eq!(Trace::<u64>::remove_redundant_merge_reqs(vec![]), vec![]);
2594
2595        // Single
2596        assert_eq!(
2597            Trace::remove_redundant_merge_reqs(vec![req(0, 1)]),
2598            vec![req(0, 1)]
2599        );
2600
2601        // Duplicate
2602        assert_eq!(
2603            Trace::remove_redundant_merge_reqs(vec![req(0, 1), req(0, 1)]),
2604            vec![req(0, 1)]
2605        );
2606
2607        // Nothing covered
2608        assert_eq!(
2609            Trace::remove_redundant_merge_reqs(vec![req(0, 1), req(1, 2)]),
2610            vec![req(1, 2), req(0, 1)]
2611        );
2612
2613        // Covered
2614        assert_eq!(
2615            Trace::remove_redundant_merge_reqs(vec![req(1, 2), req(0, 3)]),
2616            vec![req(0, 3)]
2617        );
2618
2619        // Covered, lower equal
2620        assert_eq!(
2621            Trace::remove_redundant_merge_reqs(vec![req(0, 2), req(0, 3)]),
2622            vec![req(0, 3)]
2623        );
2624
2625        // Covered, upper equal
2626        assert_eq!(
2627            Trace::remove_redundant_merge_reqs(vec![req(1, 3), req(0, 3)]),
2628            vec![req(0, 3)]
2629        );
2630
2631        // Covered, unexpected order (doesn't happen in practice)
2632        assert_eq!(
2633            Trace::remove_redundant_merge_reqs(vec![req(0, 3), req(1, 2)]),
2634            vec![req(0, 3)]
2635        );
2636
2637        // Partially overlapping
2638        assert_eq!(
2639            Trace::remove_redundant_merge_reqs(vec![req(0, 2), req(1, 3)]),
2640            vec![req(1, 3), req(0, 2)]
2641        );
2642
2643        // Partially overlapping, the other order
2644        assert_eq!(
2645            Trace::remove_redundant_merge_reqs(vec![req(1, 3), req(0, 2)]),
2646            vec![req(0, 2), req(1, 3)]
2647        );
2648
2649        // Different sinces (doesn't happen in practice)
2650        let req015 = FueledMergeReq {
2651            id: SpineId(0, 1),
2652            desc: Description::new(
2653                Antichain::from_elem(0),
2654                Antichain::from_elem(1),
2655                Antichain::from_elem(5),
2656            ),
2657            inputs: vec![],
2658        };
2659        assert_eq!(
2660            Trace::remove_redundant_merge_reqs(vec![req(0, 1), req015.clone()]),
2661            vec![req015, req(0, 1)]
2662        );
2663    }
2664
2665    #[mz_ore::test]
2666    #[cfg_attr(miri, ignore)] // proptest is too heavy for miri!
2667    fn construct_batch_with_runs_replaced_test() {
2668        let batch_strategy = any_hollow_batch::<u64>();
2669        let to_replace_strategy = any_hollow_batch_with_exact_runs::<u64>(1);
2670
2671        let combined_strategy = (batch_strategy, to_replace_strategy)
2672            .prop_filter("non-empty batch", |(batch, _)| batch.run_meta.len() >= 1);
2673
2674        let final_strategy = combined_strategy.prop_flat_map(|(batch, to_replace)| {
2675            let batch_len = batch.run_meta.len();
2676            let batch_clone = batch.clone();
2677            let to_replace_clone = to_replace.clone();
2678
2679            proptest::collection::vec(any::<bool>(), batch_len)
2680                .prop_filter("at least one run selected", |mask| mask.iter().any(|&x| x))
2681                .prop_map(move |mask| {
2682                    let indices: Vec<usize> = mask
2683                        .iter()
2684                        .enumerate()
2685                        .filter_map(|(i, &selected)| if selected { Some(i) } else { None })
2686                        .collect();
2687                    (batch_clone.clone(), to_replace_clone.clone(), indices)
2688                })
2689        });
2690
2691        proptest!(|(
2692            (batch, to_replace, runs) in final_strategy
2693        )| {
2694            let original_run_ids: Vec<_> = batch.run_meta.iter().map(|x|
2695                x.id.unwrap().clone()
2696            ).collect();
2697
2698            let run_ids = runs.iter().map(|&i| original_run_ids[i].clone()).collect::<Vec<_>>();
2699
2700            let new_batch = SpineBatch::construct_batch_with_runs_replaced(
2701                &batch,
2702                &run_ids,
2703                &to_replace,
2704            ).unwrap();
2705
2706            let expected_len = batch.run_meta.len() - runs.len()
2707                + to_replace.run_meta.len();
2708            prop_assert!(new_batch.run_meta.len() == expected_len);
2709        });
2710    }
2711
2712    #[mz_ore::test]
2713    fn test_perform_subset_replacement() {
2714        let batch1 = crate::internal::state::tests::hollow::<u64>(0, 10, &["a"], 10);
2715        let batch2 = crate::internal::state::tests::hollow::<u64>(10, 20, &["b"], 10);
2716        let batch3 = crate::internal::state::tests::hollow::<u64>(20, 30, &["c"], 10);
2717
2718        let id_batch1 = IdHollowBatch {
2719            id: SpineId(0, 1),
2720            batch: Arc::new(batch1.clone()),
2721        };
2722        let id_batch2 = IdHollowBatch {
2723            id: SpineId(1, 2),
2724            batch: Arc::new(batch2.clone()),
2725        };
2726        let id_batch3 = IdHollowBatch {
2727            id: SpineId(2, 3),
2728            batch: Arc::new(batch3.clone()),
2729        };
2730
2731        let spine_batch = SpineBatch {
2732            id: SpineId(0, 3),
2733            desc: Description::new(
2734                Antichain::from_elem(0),
2735                Antichain::from_elem(30),
2736                Antichain::from_elem(0),
2737            ),
2738            parts: vec![id_batch1, id_batch2, id_batch3],
2739            active_compaction: None,
2740            len: 30,
2741        };
2742
2743        let res_exact = crate::internal::state::tests::hollow::<u64>(0, 30, &["d"], 30);
2744        let mut sb_exact = spine_batch.clone();
2745        let result = sb_exact.perform_subset_replacement(&res_exact, SpineId(0, 3), 0..3, None);
2746        assert!(matches!(result, ApplyMergeResult::AppliedExact));
2747        assert_eq!(sb_exact.parts.len(), 1);
2748        assert_eq!(sb_exact.len(), 30);
2749
2750        let res_subset = crate::internal::state::tests::hollow::<u64>(0, 20, &["e"], 20);
2751        let mut sb_subset = spine_batch.clone();
2752        let result = sb_subset.perform_subset_replacement(&res_subset, SpineId(0, 2), 0..2, None);
2753        assert!(matches!(result, ApplyMergeResult::AppliedSubset));
2754        assert_eq!(sb_subset.parts.len(), 2); // One new part + one old part
2755        assert_eq!(sb_subset.len(), 30);
2756
2757        let res_too_big = crate::internal::state::tests::hollow::<u64>(0, 30, &["f"], 31);
2758        let mut sb_too_big = spine_batch.clone();
2759        let result = sb_too_big.perform_subset_replacement(&res_too_big, SpineId(0, 3), 0..3, None);
2760        assert!(matches!(result, ApplyMergeResult::NotAppliedTooManyUpdates));
2761        assert_eq!(sb_too_big.parts.len(), 3);
2762        assert_eq!(sb_too_big.len(), 30);
2763    }
2764
2765    /// Inserting a batch whose `len` is large enough to saturate the fuel
2766    /// computation must not disturb an in-progress merge's accounting.
2767    ///
2768    /// `introduce_batch` derives its fuel from `8 << batch_index`, where
2769    /// `batch_index` is `len.next_power_of_two().trailing_zeros()`. A `len` near
2770    /// `2^60` pushes that past what an `isize` holds, and `Trace::unflatten`
2771    /// accepts such a `len` from an untrusted blob: its `MAX_TOTAL_LEN` guard
2772    /// only caps the total at `usize::MAX >> 3`.
2773    #[mz_ore::test]
2774    fn spine_fuel_isize_overflow() {
2775        let mut trace = Trace::<u64>::default();
2776        let mut push = |lower, upper, key: &str, len| {
2777            trace.push_batch_no_merge_reqs(crate::internal::state::tests::hollow::<u64>(
2778                lower,
2779                upper,
2780                &[key],
2781                len,
2782            ));
2783        };
2784        // Two same-size batches fill a level and begin a merge whose
2785        // `remaining_work` (the sum of their lens) far exceeds the `8 << 0` fuel
2786        // that a subsequent len-1 batch delivers, so the merge is still in
2787        // progress when the saturating batch arrives.
2788        push(0, 1, "a", 100);
2789        push(1, 2, "b", 100);
2790        push(2, 3, "c", 1);
2791        push(3, 4, "d", 1 << 60);
2792    }
2793}