Skip to main content

itzma_core/compaction/
mod.rs

1//! Compaction: fold the WAL tail into a segment, or merge the segments.
2//!
3//! One run is: load the manifest, read the WAL tail, decide what to do, build
4//! the new segment, write it with put-if-absent, then publish it with one
5//! manifest compare-and-swap. Writers never touch the manifest, so they never
6//! conflict with a compactor. Two compactors that plan the same work build the
7//! same object (a segment is a pure function of its WAL range); at most one
8//! publish wins and the other reports [`Compaction::Superseded`].
9//!
10//! Compaction never deletes anything. A run that dies before publishing
11//! leaves an orphan segment that the next run verifies and reuses. Segments
12//! that a run supersedes are removed later, by an explicit
13//! [`Namespace::gc`](crate::Namespace::gc).
14
15use std::collections::HashSet;
16
17use futures::TryStreamExt;
18use object_store::path::Path;
19use object_store::{ObjectMeta, ObjectStore, ObjectStoreExt, PutMode, PutOptions, PutPayload};
20
21use crate::budget::ReadBudget;
22use crate::cpu::{self, Cost, Lane};
23use crate::document::Schema;
24use crate::error::{ItzmaError, Result};
25use crate::fetch::FetchPolicy;
26use crate::gc;
27use crate::layer;
28use crate::manifest::{self, Manifest};
29use crate::segment::SegmentWriter;
30use crate::sparse;
31use crate::{segment, wal};
32
33mod merge;
34
35/// The default for [`CompactionOptions::max_segments`].
36pub const DEFAULT_MAX_SEGMENTS: usize = 8;
37
38/// The default for [`CompactionOptions::max_segment_bytes`]: 128 MiB,
39/// comfortably under the 1 GiB default read budget so several
40/// segments plus a WAL tail can coexist in one query's budget.
41pub const DEFAULT_MAX_SEGMENT_BYTES: u64 = 128 * 1024 * 1024;
42
43/// Settings for [`Namespace::compact`](crate::Namespace::compact).
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct CompactionOptions {
46    /// The most live segments a namespace may end up with. When one more
47    /// fold would exceed it, every segment is merged into a single base
48    /// instead. Zero is treated as one.
49    pub max_segments: usize,
50    /// The most stored bytes one segment's `data.bin` may hold. A merge
51    /// produces as many size-balanced, contiguous segments as this cap
52    /// requires, instead of collapsing everything into one. Only the data object's size counts, never an
53    /// index object beside it. A merge needs it at or under the handle's
54    /// read budget, since it reads each group under a budget of its own;
55    /// see [`validate`](Self::validate).
56    pub max_segment_bytes: u64,
57}
58
59impl CompactionOptions {
60    /// Check the options against the read budget of the handle that will run
61    /// a merge with them. [`Namespace::compact`](crate::Namespace::compact)
62    /// calls this once it knows a merge is due, before any segment is read; a
63    /// fold does not need it.
64    ///
65    /// # Errors
66    ///
67    /// [`ItzmaError::InvalidConfig`] when `max_segment_bytes` is above
68    /// `read_budget`: a merge group that size could never be read.
69    ///
70    /// Passing is necessary, not sufficient: a group can exceed the cap, and
71    /// is also charged its `sparse.bin`, so keep the budget well above the cap
72    /// (the defaults are 1 GiB and 128 MiB).
73    pub fn validate(&self, read_budget: u64) -> Result<()> {
74        if self.max_segment_bytes > read_budget {
75            return Err(ItzmaError::InvalidConfig(
76                "max_segment_bytes is above the read budget, so a merge group could never be read",
77            ));
78        }
79        Ok(())
80    }
81}
82
83impl Default for CompactionOptions {
84    fn default() -> Self {
85        Self {
86            max_segments: DEFAULT_MAX_SEGMENTS,
87            max_segment_bytes: DEFAULT_MAX_SEGMENT_BYTES,
88        }
89    }
90}
91
92/// What a call to [`Namespace::compact`](crate::Namespace::compact) did.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum Compaction {
95    /// The WAL tail was empty and the segment count was within the limit.
96    Nothing,
97    /// A segment was written and the manifest now lists it.
98    Published {
99        /// Ids of the new segments, oldest first. Exactly one unless the
100        /// live segments and tail together exceeded `max_segment_bytes`, in
101        /// which case several balanced, contiguous segments are produced
102        /// (the segment size cap and merge policy).
103        segments: Vec<String>,
104        /// The new `wal_folded_through`.
105        folded_through: u64,
106        /// How many existing segments were merged into it: 0 for a fold.
107        merged_segments: usize,
108        /// Live documents in the new segment.
109        docs: usize,
110        /// Tombstones in the new segment. Always 0 for a base segment.
111        tombstones: usize,
112    },
113    /// Another compactor changed the manifest first, so this run published
114    /// nothing. The segment it wrote is either an orphan or the very object
115    /// the winner published.
116    Superseded,
117}
118
119#[derive(Clone, Copy, PartialEq, Eq, Debug)]
120enum Plan {
121    Nothing,
122    /// Turn the WAL tail into a new segment beside the existing ones.
123    Fold,
124    /// Merge into this many size-balanced, contiguous segments.
125    Merge {
126        target_count: usize,
127    },
128}
129
130fn plan(
131    segments: usize,
132    tail_is_empty: bool,
133    max_segments: usize,
134    oversized: bool,
135    total_bytes: u64,
136    max_segment_bytes: u64,
137) -> Plan {
138    let max = max_segments.max(1);
139    if tail_is_empty && segments <= max && !oversized {
140        Plan::Nothing
141    } else if segments + 1 > max || oversized {
142        let cap = max_segment_bytes.max(1);
143        let target_count = usize::try_from(total_bytes.div_ceil(cap))
144            .unwrap_or(usize::MAX)
145            .max(1);
146        Plan::Merge { target_count }
147    } else {
148        Plan::Fold
149    }
150}
151
152/// Partition `sizes` (one weight per unit, in order) into `target_count`
153/// contiguous groups whose boundaries land as close as possible to `i *
154/// total / target_count` for each cut `i`. Pure: no I/O, so two compactors
155/// planning the same live segments and tail compute identical groups
156/// (the "same range, same bytes" determinism). Returns the exclusive
157/// end index of each group; the last entry always equals `sizes.len()`.
158/// `target_count` is clamped to `1..=sizes.len().max(1)` — asking for more
159/// groups than there are units is impossible, and zero units always
160/// produces one (empty) group.
161fn partition(sizes: &[u64], target_count: usize) -> Vec<usize> {
162    let n = sizes.len();
163    let target_count = target_count.clamp(1, n.max(1));
164    if n == 0 || target_count <= 1 {
165        return vec![n];
166    }
167    let total: u64 = sizes.iter().sum();
168    let mut prefix = Vec::with_capacity(n);
169    let mut running = 0u64;
170    for &s in sizes {
171        running += s;
172        prefix.push(running);
173    }
174
175    let mut cuts = Vec::with_capacity(target_count);
176    let mut start = 0usize;
177    for i in 1..target_count {
178        let remaining_groups_after = target_count - i;
179        let max_idx = n - remaining_groups_after;
180        let ideal = (u128::from(total) * i as u128 / target_count as u128) as u64;
181        let mut best = start + 1;
182        let mut best_diff = prefix[start].abs_diff(ideal);
183        for idx in (start + 2)..=max_idx {
184            let diff = prefix[idx - 1].abs_diff(ideal);
185            if diff < best_diff {
186                best_diff = diff;
187                best = idx;
188            }
189        }
190        cuts.push(best);
191        start = best;
192    }
193    cuts.push(n);
194    cuts
195}
196
197/// The `data.bin` object's size in one segment's directory, from a listing
198/// (`gc::group`'s output), or 0 if the listing does not show it (a stale
199/// read against a manifest a merge or a GC has since moved past — the actual
200/// content fetch later either succeeds against a reloaded manifest or
201/// reports the same staleness `Namespace::compact` already handles, so this
202/// helper only needs to be a reasonable planning estimate, never a source of
203/// truth).
204fn data_size(found: &std::collections::BTreeMap<String, gc::Found>, id: &str) -> u64 {
205    found
206        .get(id)
207        .and_then(|f| {
208            f.objects
209                .iter()
210                .find(|(path, _)| path.filename() == Some("data.bin"))
211        })
212        .map(|(_, size)| *size)
213        .unwrap_or(0)
214}
215
216/// One compaction run against a manifest the caller has already loaded and
217/// validated. See the module docs and
218/// [`Namespace::compact`](crate::Namespace::compact).
219pub(crate) async fn run(
220    store: &dyn ObjectStore,
221    namespace: &str,
222    schema: Schema,
223    manifest: Manifest,
224    options: &CompactionOptions,
225    read_budget: u64,
226    policy: &FetchPolicy,
227) -> Result<Compaction> {
228    let folded = manifest.wal_folded_through;
229    let live = manifest.live_segments;
230
231    let segments_prefix = Path::from(format!("{namespace}/segments"));
232    let listing: Vec<ObjectMeta> = store.list(Some(&segments_prefix)).try_collect().await?;
233    let found = gc::group(&segments_prefix, listing);
234    let wal_objects = gc::list_wal_after(store, namespace, folded).await?;
235    let tail_size_estimate: u64 = wal_objects.iter().map(|o| o.size).sum();
236
237    // The cap is at least one byte, as `plan` takes it: a cap of zero would
238    // call an empty namespace oversized and plan a merge of nothing.
239    let cap = options.max_segment_bytes.max(1);
240    let oversized = live.iter().any(|id| data_size(&found, id) >= cap) || tail_size_estimate >= cap;
241
242    // The tail and each merge group get a budget of their own: the
243    // budget bounds what one step holds, not how big the namespace is.
244    let tail_budget = ReadBudget::new(read_budget);
245    let (tail, last) = layer::fold_log(
246        wal::stream_log(store, namespace, folded, &tail_budget, Lane::Maintenance).await?,
247    )
248    .await?;
249    let newest = last.unwrap_or(folded);
250
251    // Units in WAL order: each live segment, then the tail if it is
252    // non-empty. `Namespace::compact` already ran `segment::validate_chain`
253    // on this manifest before calling here (`load_manifest`), so every live
254    // id is guaranteed to parse.
255    struct Unit {
256        lo: u64,
257        hi: u64,
258        size: u64,
259    }
260    let mut units: Vec<Unit> = live
261        .iter()
262        .map(|id| {
263            let (lo, hi) = segment::parse_segment_id(id)
264                .expect("manifest invariant already validated by load_manifest");
265            Unit {
266                lo,
267                hi,
268                size: data_size(&found, id),
269            }
270        })
271        .collect();
272    if let Some(last_seq) = last {
273        units.push(Unit {
274            lo: folded + 1,
275            hi: last_seq,
276            size: tail_size_estimate,
277        });
278    }
279    let total_bytes: u64 = units.iter().map(|u| u.size).sum();
280
281    let plan = plan(
282        live.len(),
283        last.is_none(),
284        options.max_segments,
285        oversized,
286        total_bytes,
287        options.max_segment_bytes,
288    );
289
290    match plan {
291        Plan::Nothing => Ok(Compaction::Nothing),
292        Plan::Fold => {
293            let lo = folded + 1;
294            let id = segment::segment_id(lo, newest);
295            let mut layer = tail;
296            if lo == 1 {
297                layer.drop_tombstones();
298            }
299            let (docs, tombstones) = (layer.doc_count(), layer.tombstone_count());
300            let (_layer, data, sparse) = segment::encode_parts_on(
301                Lane::Maintenance,
302                layer,
303                schema.dim,
304                manifest.segment_format,
305                schema.attrs.clone(),
306            )
307            .await?;
308            write_segment(store, namespace, &id, data).await?;
309            write_sparse(store, namespace, &id, sparse).await?;
310
311            let published = manifest::update_if(store, namespace, |m| {
312                if m.wal_folded_through != folded || m.live_segments != live {
313                    return false;
314                }
315                m.live_segments.push(id.clone());
316                m.wal_folded_through = newest;
317                true
318            })
319            .await?;
320            Ok(match published {
321                Some(_) => Compaction::Published {
322                    segments: vec![id],
323                    folded_through: newest,
324                    merged_segments: 0,
325                    docs,
326                    tombstones,
327                },
328                None => Compaction::Superseded,
329            })
330        }
331        Plan::Merge { target_count } => {
332            options.validate(read_budget)?;
333            let sizes: Vec<u64> = units.iter().map(|u| u.size).collect();
334            let cuts = partition(&sizes, target_count);
335            let merged_segments = live.len();
336
337            let mut new_live = Vec::with_capacity(cuts.len());
338            let mut docs = 0usize;
339            let mut tombstones = 0usize;
340            let mut tail_left = Some(tail);
341            let mut start = 0usize;
342            for &end in &cuts {
343                let live_end = end.min(live.len());
344                let seg_ids = &live[start.min(live.len())..live_end];
345                let group_lo = units[start].lo;
346                let group_hi = units[end - 1].hi;
347
348                // Each input is read forward a window at a time and the
349                // output written as it is merged. Inputs are opened
350                // by index, not over `&String`s, for the `Send` reason in
351                // `segment::read_all`.
352                let group_budget = ReadBudget::new(read_budget);
353                let mut inputs = futures::future::try_join_all((0..seg_ids.len()).map(|i| {
354                    merge::Input::segment(
355                        store,
356                        namespace,
357                        &seg_ids[i],
358                        schema.dim,
359                        &group_budget,
360                        policy,
361                        data_size(&found, &seg_ids[i]),
362                        merge::MERGE_WINDOW,
363                    )
364                }))
365                .await?;
366                if end == units.len() {
367                    if let Some(t) = tail_left.take() {
368                        inputs.push(merge::Input::layer(t));
369                    }
370                }
371                let writer =
372                    SegmentWriter::new(schema.dim, manifest.segment_format, &schema.attrs)?;
373                let writer = merge::merge_into(inputs, group_lo == 1, writer).await?;
374                docs += writer.docs();
375                tombstones += writer.tombstones();
376                let id = segment::segment_id(group_lo, group_hi);
377                let (data, sparse) = finish_on(writer).await?;
378                write_segment(store, namespace, &id, data).await?;
379                write_sparse(store, namespace, &id, sparse).await?;
380                new_live.push(id);
381                start = end;
382            }
383
384            let published = manifest::update_if(store, namespace, |m| {
385                if m.wal_folded_through != folded || m.live_segments != live {
386                    return false;
387                }
388                m.live_segments = new_live.clone();
389                m.wal_folded_through = newest;
390                // An index belongs to the segment it was built for, so a
391                // merge takes the entries of the segments it retires with
392                // it. Every new segment starts without one.
393                let live_set: HashSet<&str> = m.live_segments.iter().map(String::as_str).collect();
394                m.indexes.retain(|id, _| live_set.contains(id.as_str()));
395                m.sparse_indexes
396                    .retain(|id, _| live_set.contains(id.as_str()));
397                true
398            })
399            .await?;
400            Ok(match published {
401                Some(_) => Compaction::Published {
402                    segments: new_live,
403                    folded_through: newest,
404                    merged_segments,
405                    docs,
406                    tombstones,
407                },
408                None => Compaction::Superseded,
409            })
410        }
411    }
412}
413
414/// [`SegmentWriter::finish`] on the maintenance lane: it builds the Bloom
415/// filter and the directory over every row.
416async fn finish_on(writer: SegmentWriter) -> Result<(PutPayload, Option<PutPayload>)> {
417    let cost = Cost::Bytes(writer.docs() * 64 + writer.tombstones() * 16);
418    cpu::run(Lane::Maintenance, cost, move || writer.finish()).await
419}
420
421/// Bytes compared per request when an object is already at a key.
422const COMPARE_PIECE: usize = 8 * 1024 * 1024;
423
424/// Put the segment at its final key with put-if-absent. An object already at
425/// that key is not trusted: it must be byte-identical to what this run built,
426/// or it is damaged (or came from an encoder that disagrees), and publishing
427/// it would poison the namespace. It is never overwritten.
428async fn write_segment(
429    store: &dyn ObjectStore,
430    namespace: &str,
431    id: &str,
432    data: PutPayload,
433) -> Result<()> {
434    let path = segment::segment_path(namespace, id);
435    put_or_reuse(
436        store,
437        &path,
438        data,
439        segment::missing,
440        "an object already at this key differs from the segment this range produces; if the \
441         manifest does not list it, delete it and rerun",
442    )
443    .await
444}
445
446/// Write the segment's sparse sidecar with the same put-if-absent,
447/// byte-compare-on-reuse rule [`write_segment`] uses for `data.bin` — only
448/// when the writer made one, which it does when at least one document has a
449/// sparse vector, since a segment with none legitimately has no `sparse.bin`.
450async fn write_sparse(
451    store: &dyn ObjectStore,
452    namespace: &str,
453    id: &str,
454    sparse: Option<PutPayload>,
455) -> Result<()> {
456    let Some(sparse) = sparse else {
457        return Ok(());
458    };
459    let path = sparse::sparse_path(namespace, id);
460    put_or_reuse(
461        store,
462        &path,
463        sparse,
464        sparse::missing,
465        "an object already at this key differs from the sparse sidecar this range produces; if \
466         the manifest's segment is not live, delete it and rerun",
467    )
468    .await
469}
470
471/// Put `payload` at `path` with put-if-absent, or accept an object already
472/// there only if it holds the same bytes, compared a piece at a time so the
473/// existing object is never held whole beside the new one. A dead
474/// orphan can be deleted by garbage collection between the refused put and
475/// the compare; that is `missing`, which `Namespace::compact` treats as a
476/// stale read.
477async fn put_or_reuse(
478    store: &dyn ObjectStore,
479    path: &Path,
480    payload: PutPayload,
481    missing: fn(&Path) -> ItzmaError,
482    differs: &str,
483) -> Result<()> {
484    match store
485        .put_opts(path, payload.clone(), PutOptions::from(PutMode::Create))
486        .await
487    {
488        Ok(_) => Ok(()),
489        Err(object_store::Error::AlreadyExists { .. }) => {
490            match same_object(store, path, &payload).await {
491                Ok(true) => Ok(()),
492                Ok(false) => Err(ItzmaError::CorruptSegment {
493                    path: path.to_string(),
494                    reason: differs.into(),
495                }),
496                Err(object_store::Error::NotFound { .. }) => Err(missing(path)),
497                Err(e) => Err(e.into()),
498            }
499        }
500        Err(e) => Err(e.into()),
501    }
502}
503
504/// Whether the object at `path` holds exactly `payload`'s bytes.
505async fn same_object(
506    store: &dyn ObjectStore,
507    path: &Path,
508    payload: &PutPayload,
509) -> object_store::Result<bool> {
510    if store.head(path).await?.size != payload.content_length() as u64 {
511        return Ok(false);
512    }
513    let mut at = 0u64;
514    for chunk in payload.iter() {
515        for piece in chunk.chunks(COMPARE_PIECE) {
516            let end = at + piece.len() as u64;
517            if store.get_range(path, at..end).await?.as_ref() != piece {
518                return Ok(false);
519            }
520            at = end;
521        }
522    }
523    Ok(true)
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529
530    #[test]
531    fn oversized_forces_a_merge_even_under_max_segments() {
532        // One segment, well under max_segments (8), but already over the
533        // cap: must merge, not sit there.
534        assert_eq!(
535            plan(1, true, 8, true, 200, 100),
536            Plan::Merge { target_count: 2 }
537        );
538        assert_eq!(plan(1, true, 8, false, 50, 100), Plan::Nothing);
539    }
540
541    #[test]
542    fn an_oversized_tail_also_forces_a_merge() {
543        // tail_is_empty is false here to represent a non-empty tail that is
544        // itself already over the cap; `oversized` is computed by the
545        // caller from the tail size estimate, `plan` itself just trusts the
546        // bool.
547        assert_eq!(
548            plan(1, false, 8, true, 150, 100),
549            Plan::Merge { target_count: 2 }
550        );
551    }
552
553    #[test]
554    fn the_existing_count_trigger_is_unchanged() {
555        assert_eq!(
556            plan(8, false, 8, false, 100, 100),
557            Plan::Merge { target_count: 1 }
558        ); // 8 + 1 > 8
559        assert_eq!(plan(7, false, 8, false, 100, 100), Plan::Fold);
560        assert_eq!(plan(3, true, 8, false, 100, 100), Plan::Nothing);
561    }
562
563    #[test]
564    fn a_cap_above_the_read_budget_is_refused() {
565        let options = CompactionOptions {
566            max_segments: 8,
567            max_segment_bytes: 1000,
568        };
569        assert!(options.validate(1000).is_ok());
570        assert!(matches!(
571            options.validate(999),
572            Err(ItzmaError::InvalidConfig(_))
573        ));
574    }
575
576    #[test]
577    fn target_count_is_the_ceiling_of_total_over_cap() {
578        assert_eq!(
579            plan(9, false, 8, false, 257, 100),
580            Plan::Merge { target_count: 3 }
581        );
582    }
583}
584
585#[cfg(test)]
586mod partition_tests {
587    use super::partition;
588
589    #[test]
590    fn below_the_cap_makes_one_group() {
591        assert_eq!(partition(&[10, 10, 10], 1), vec![3]);
592    }
593
594    #[test]
595    fn four_equal_sizes_split_evenly_in_two() {
596        assert_eq!(partition(&[10, 10, 10, 10], 2), vec![2, 4]);
597    }
598
599    #[test]
600    fn an_already_oversized_unit_gets_its_own_group() {
601        // One huge unit, three tiny ones: the balanced cut isolates the
602        // huge one rather than diluting it into a mixed group.
603        assert_eq!(partition(&[100, 1, 1, 1], 2), vec![1, 4]);
604    }
605
606    #[test]
607    fn target_count_is_clamped_to_the_unit_count() {
608        assert_eq!(partition(&[10, 10], 5), vec![1, 2]);
609    }
610
611    #[test]
612    fn zero_units_returns_one_empty_group() {
613        assert_eq!(partition(&[], 3), vec![0]);
614    }
615
616    #[test]
617    fn every_group_gets_at_least_one_unit() {
618        for target in 1..=6 {
619            let cuts = partition(&[1, 1, 1, 1, 1, 1], target);
620            assert_eq!(cuts.last(), Some(&6));
621            let mut prev = 0;
622            for &c in &cuts {
623                assert!(c > prev, "group must not be empty: {cuts:?}");
624                prev = c;
625            }
626        }
627    }
628}