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};
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::put::{self, Body, Uploader};
30use crate::segment::SegmentWriter;
31use crate::sparse;
32use crate::{segment, wal};
33
34mod merge;
35
36/// The default for [`CompactionOptions::max_segments`].
37pub const DEFAULT_MAX_SEGMENTS: usize = 8;
38
39/// The default for [`CompactionOptions::max_segment_bytes`]: 128 MiB,
40/// comfortably under the 1 GiB default read budget so several
41/// segments plus a WAL tail can coexist in one query's budget.
42pub const DEFAULT_MAX_SEGMENT_BYTES: u64 = 128 * 1024 * 1024;
43
44/// Settings for [`Namespace::compact`](crate::Namespace::compact).
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct CompactionOptions {
47    /// The most live segments a namespace may end up with. When one more
48    /// fold would exceed it, every segment is merged into a single base
49    /// instead. Zero is treated as one.
50    pub max_segments: usize,
51    /// The most stored bytes one segment's `data.bin` may hold. A merge
52    /// produces as many size-balanced, contiguous segments as this cap
53    /// requires, instead of collapsing everything into one. The trigger looks
54    /// at `data.bin` only, never an index object beside it; a merge sizes its
55    /// groups by what each segment charges its budget, `sparse.bin` included,
56    /// so with heavy sparse vectors the outputs come out smaller than the cap.
57    /// A merge needs it at or under the handle's read budget, since it reads
58    /// each group under a budget of its own; see
59    /// [`validate`](Self::validate).
60    pub max_segment_bytes: u64,
61}
62
63impl CompactionOptions {
64    /// Check the options against the read budget of the handle that will run
65    /// a merge with them. [`Namespace::compact`](crate::Namespace::compact)
66    /// calls this once it knows a merge is due, before any segment is read; a
67    /// fold does not need it.
68    ///
69    /// # Errors
70    ///
71    /// [`ItzmaError::InvalidConfig`] when `max_segment_bytes` is above
72    /// `read_budget`: a merge group that size could never be read.
73    ///
74    /// A merge sizes its groups by what each segment charges (`data.bin`,
75    /// `sparse.bin` and the guesses of a ranged open) and splits any group
76    /// over the cap, so once this passes every group fits the budget, unless
77    /// one segment alone charges more than it.
78    pub fn validate(&self, read_budget: u64) -> Result<()> {
79        if self.max_segment_bytes > read_budget {
80            return Err(ItzmaError::InvalidConfig(
81                "max_segment_bytes is above the read budget, so a merge group could never be read",
82            ));
83        }
84        Ok(())
85    }
86}
87
88impl Default for CompactionOptions {
89    fn default() -> Self {
90        Self {
91            max_segments: DEFAULT_MAX_SEGMENTS,
92            max_segment_bytes: DEFAULT_MAX_SEGMENT_BYTES,
93        }
94    }
95}
96
97/// What a call to [`Namespace::compact`](crate::Namespace::compact) did.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum Compaction {
100    /// The WAL tail was empty and the segment count was within the limit.
101    Nothing,
102    /// A segment was written and the manifest now lists it.
103    Published {
104        /// Ids of the new segments, oldest first. Exactly one unless the
105        /// live segments and tail together exceeded `max_segment_bytes`, in
106        /// which case several balanced, contiguous segments are produced
107        /// (the segment size cap and merge policy).
108        segments: Vec<String>,
109        /// The new `wal_folded_through`.
110        folded_through: u64,
111        /// How many existing segments were merged into it: 0 for a fold.
112        merged_segments: usize,
113        /// Live documents in the new segment.
114        docs: usize,
115        /// Tombstones in the new segment. Always 0 for a base segment.
116        tombstones: usize,
117    },
118    /// Another compactor changed the manifest first, so this run published
119    /// nothing. The segment it wrote is either an orphan or the very object
120    /// the winner published.
121    Superseded,
122}
123
124#[derive(Clone, Copy, PartialEq, Eq, Debug)]
125enum Plan {
126    Nothing,
127    /// Turn the WAL tail into a new segment beside the existing ones.
128    Fold,
129    /// Merge into this many size-balanced, contiguous segments.
130    Merge {
131        target_count: usize,
132    },
133}
134
135fn plan(
136    segments: usize,
137    tail_is_empty: bool,
138    max_segments: usize,
139    oversized: bool,
140    total_bytes: u64,
141    max_segment_bytes: u64,
142) -> Plan {
143    let max = max_segments.max(1);
144    if tail_is_empty && segments <= max && !oversized {
145        Plan::Nothing
146    } else if segments + 1 > max || oversized {
147        let cap = max_segment_bytes.max(1);
148        let target_count = usize::try_from(total_bytes.div_ceil(cap))
149            .unwrap_or(usize::MAX)
150            .max(1);
151        Plan::Merge { target_count }
152    } else {
153        Plan::Fold
154    }
155}
156
157/// Partition `sizes` (one weight per unit, in order) into `target_count`
158/// contiguous groups whose boundaries land as close as possible to `i *
159/// total / target_count` for each cut `i`. Pure: no I/O, so two compactors
160/// planning the same live segments and tail compute identical groups
161/// (the "same range, same bytes" determinism). Returns the exclusive
162/// end index of each group; the last entry always equals `sizes.len()`.
163/// `target_count` is clamped to `1..=sizes.len().max(1)` — asking for more
164/// groups than there are units is impossible, and zero units always
165/// produces one (empty) group.
166fn partition(sizes: &[u64], target_count: usize) -> Vec<usize> {
167    let n = sizes.len();
168    let target_count = target_count.clamp(1, n.max(1));
169    if n == 0 || target_count <= 1 {
170        return vec![n];
171    }
172    let total: u64 = sizes.iter().sum();
173    let mut prefix = Vec::with_capacity(n);
174    let mut running = 0u64;
175    for &s in sizes {
176        running += s;
177        prefix.push(running);
178    }
179
180    let mut cuts = Vec::with_capacity(target_count);
181    let mut start = 0usize;
182    for i in 1..target_count {
183        let remaining_groups_after = target_count - i;
184        let max_idx = n - remaining_groups_after;
185        let ideal = (u128::from(total) * i as u128 / target_count as u128) as u64;
186        let mut best = start + 1;
187        let mut best_diff = prefix[start].abs_diff(ideal);
188        for idx in (start + 2)..=max_idx {
189            let diff = prefix[idx - 1].abs_diff(ideal);
190            if diff < best_diff {
191                best_diff = diff;
192                best = idx;
193            }
194        }
195        cuts.push(best);
196        start = best;
197    }
198    cuts.push(n);
199    cuts
200}
201
202/// What the folded tail adds to an output segment: its listed size is
203/// compressed (ZSTD), so a tail that compresses well would look
204/// small and a merge mostly of tail would not spill. Its decoded
205/// rows are in hand, so they are counted: each document's id, vector and
206/// sparse terms, each tombstone's id, plus a little per row. Attributes are
207/// not serialized to be measured, so this is a lower bound of the segment;
208/// the listed size is too, and the larger is kept.
209fn tail_stored(listed: u64, tail: &layer::Layer, dim: usize) -> u64 {
210    let docs: u64 = tail
211        .docs()
212        .map(|doc| {
213            let sparse = doc.sparse.as_ref().map_or(0, Vec::len);
214            (doc.id.len() + dim * 4 + sparse * 8 + 16) as u64
215        })
216        .sum();
217    let tombstones: u64 = tail
218        .sorted_tombstones()
219        .iter()
220        .map(|id| id.len() as u64 + 8)
221        .sum();
222    listed.max(docs + tombstones)
223}
224
225/// The `data.bin` object's size in one segment's directory, from a listing
226/// (`gc::group`'s output), or 0 if the listing does not show it (a stale
227/// read against a manifest a merge or a GC has since moved past — the actual
228/// content fetch later either succeeds against a reloaded manifest or
229/// reports the same staleness `Namespace::compact` already handles, so this
230/// helper only needs to be a reasonable planning estimate, never a source of
231/// truth).
232fn data_size(found: &std::collections::BTreeMap<String, gc::Found>, id: &str) -> u64 {
233    object_size(found, id, "data.bin")
234}
235
236/// [`data_size`] for any object of the segment's directory, `sparse.bin` in
237/// particular (0 for a segment without one).
238fn object_size(found: &std::collections::BTreeMap<String, gc::Found>, id: &str, name: &str) -> u64 {
239    found
240        .get(id)
241        .and_then(|f| {
242            f.objects
243                .iter()
244                .find(|(path, _)| path.filename() == Some(name))
245        })
246        .map(|(_, size)| *size)
247        .unwrap_or(0)
248}
249
250/// `cuts` (from [`partition`]) with every group of more than one unit whose
251/// sizes add up to more than `limit` partitioned again, into as many groups
252/// as its sum over `limit` asks, until each fits or holds one unit. A merge
253/// charges each group to a budget of its own, so `limit` is that budget,
254/// not the cap: `partition` aims at the cap, and a group a little over it
255/// (each windowed segment adds its open's guesses) must still merge rather
256/// than fall apart into groups of one that rewrite the same ranges.
257/// Pure.
258fn fit(sizes: &[u64], cuts: Vec<usize>, limit: u64) -> Vec<usize> {
259    let cap = limit.max(1);
260    let mut out = Vec::with_capacity(cuts.len());
261    let mut start = 0;
262    for end in cuts {
263        let group = &sizes[start..end];
264        let sum: u64 = group.iter().sum();
265        if group.len() > 1 && sum > cap {
266            let count = usize::try_from(sum.div_ceil(cap))
267                .unwrap_or(usize::MAX)
268                .max(2);
269            let inner = fit(group, partition(group, count), cap);
270            out.extend(inner.into_iter().map(|cut| start + cut));
271        } else {
272            out.push(end);
273        }
274        start = end;
275    }
276    out
277}
278
279/// One compaction run against a manifest the caller has already loaded and
280/// validated. See the module docs and
281/// [`Namespace::compact`](crate::Namespace::compact).
282#[allow(clippy::too_many_arguments)]
283pub(crate) async fn run(
284    store: &dyn ObjectStore,
285    namespace: &str,
286    schema: Schema,
287    manifest: Manifest,
288    options: &CompactionOptions,
289    read_budget: u64,
290    policy: &FetchPolicy,
291    upload: &Uploader,
292) -> Result<Compaction> {
293    let folded = manifest.wal_folded_through;
294    let live = manifest.live_segments;
295
296    let segments_prefix = Path::from(format!("{namespace}/segments"));
297    let listing: Vec<ObjectMeta> = store.list(Some(&segments_prefix)).try_collect().await?;
298    let found = gc::group(&segments_prefix, listing);
299    let wal_objects = gc::list_wal_after(store, namespace, folded).await?;
300    let tail_size_estimate: u64 = wal_objects.iter().map(|o| o.size).sum();
301
302    // The cap is at least one byte, as `plan` takes it: a cap of zero would
303    // call an empty namespace oversized and plan a merge of nothing.
304    let cap = options.max_segment_bytes.max(1);
305    let oversized = live.iter().any(|id| data_size(&found, id) >= cap) || tail_size_estimate >= cap;
306
307    // The tail and each merge group get a budget of their own: the
308    // budget bounds what one step holds, not how big the namespace is.
309    let tail_budget = ReadBudget::new(read_budget);
310    let (tail, last) = layer::fold_log(
311        wal::stream_log(store, namespace, folded, &tail_budget, Lane::Maintenance).await?,
312    )
313    .await?;
314    let newest = last.unwrap_or(folded);
315
316    // Units in WAL order: each live segment, then the tail if it is
317    // non-empty. `Namespace::compact` already ran `segment::validate_chain`
318    // on this manifest before calling here (`load_manifest`), so every live
319    // id is guaranteed to parse.
320    struct Unit {
321        lo: u64,
322        hi: u64,
323        /// Its objects' bytes: what it adds to an output segment.
324        stored: u64,
325        /// What merging it charges its group's budget.
326        charge: u64,
327    }
328    let mut units: Vec<Unit> = live
329        .iter()
330        .map(|id| {
331            let (lo, hi) = segment::parse_segment_id(id)
332                .expect("manifest invariant already validated by load_manifest");
333            let (data, sparse) = (data_size(&found, id), object_size(&found, id, "sparse.bin"));
334            Unit {
335                lo,
336                hi,
337                stored: data.saturating_add(sparse),
338                charge: merge::charge_estimate(data, sparse, merge::MERGE_WINDOW),
339            }
340        })
341        .collect();
342    if let Some(last_seq) = last {
343        units.push(Unit {
344            lo: folded + 1,
345            hi: last_seq,
346            stored: tail_stored(tail_size_estimate, &tail, schema.dim),
347            charge: tail_size_estimate,
348        });
349    }
350    // The outputs' count comes from what they will hold; the charges only
351    // decide whether a group fits its budget.
352    let total_bytes: u64 = units.iter().map(|u| u.stored).sum();
353
354    let plan = plan(
355        live.len(),
356        last.is_none(),
357        options.max_segments,
358        oversized,
359        total_bytes,
360        options.max_segment_bytes,
361    );
362
363    match plan {
364        Plan::Nothing => Ok(Compaction::Nothing),
365        Plan::Fold => {
366            let lo = folded + 1;
367            let id = segment::segment_id(lo, newest);
368            let mut layer = tail;
369            if lo == 1 {
370                layer.drop_tombstones();
371            }
372            let (docs, tombstones) = (layer.doc_count(), layer.tombstone_count());
373            let (_layer, data, sparse) = segment::encode_parts_on(
374                Lane::Maintenance,
375                layer,
376                schema.dim,
377                manifest.segment_format,
378                schema.attrs.clone(),
379            )
380            .await?;
381            write_segment(store, namespace, &id, data.into(), upload).await?;
382            write_sparse(store, namespace, &id, sparse.map(Body::from), upload).await?;
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.push(id.clone());
389                m.wal_folded_through = newest;
390                true
391            })
392            .await?;
393            Ok(match published {
394                Some(_) => Compaction::Published {
395                    segments: vec![id],
396                    folded_through: newest,
397                    merged_segments: 0,
398                    docs,
399                    tombstones,
400                },
401                None => Compaction::Superseded,
402            })
403        }
404        Plan::Merge { target_count } => {
405            options.validate(read_budget)?;
406            let stored: Vec<u64> = units.iter().map(|u| u.stored).collect();
407            let charges: Vec<u64> = units.iter().map(|u| u.charge).collect();
408            let cuts = fit(&charges, partition(&stored, target_count), read_budget);
409            let merged_segments = live.len();
410
411            let mut new_live = Vec::with_capacity(cuts.len());
412            let mut docs = 0usize;
413            let mut tombstones = 0usize;
414            let mut tail_left = Some(tail);
415            let mut start = 0usize;
416            for &end in &cuts {
417                let live_end = end.min(live.len());
418                let seg_ids = &live[start.min(live.len())..live_end];
419                let group_lo = units[start].lo;
420                let group_hi = units[end - 1].hi;
421
422                // Each input is read forward a window at a time and the
423                // output written as it is merged. Inputs are opened
424                // by index, not over `&String`s, for the `Send` reason in
425                // `segment::read_all`.
426                let group_budget = ReadBudget::new(read_budget);
427                let mut inputs = futures::future::try_join_all((0..seg_ids.len()).map(|i| {
428                    merge::Input::segment(
429                        store,
430                        namespace,
431                        &seg_ids[i],
432                        schema.dim,
433                        &group_budget,
434                        policy,
435                        data_size(&found, &seg_ids[i])
436                            + object_size(&found, &seg_ids[i], "sparse.bin"),
437                        merge::MERGE_WINDOW,
438                    )
439                }))
440                .await?;
441                if end == units.len() {
442                    if let Some(t) = tail_left.take() {
443                        inputs.push(merge::Input::layer(t));
444                    }
445                }
446                let mut writer =
447                    SegmentWriter::new(schema.dim, manifest.segment_format, &schema.attrs)?;
448                // An output expected over the streaming threshold spills its
449                // sections to files as they fill, so the merge holds
450                // about a chunk per section instead of the whole segment.
451                let expected: u64 = units[start..end].iter().map(|u| u.stored).sum();
452                if expected > upload.options.stream_above {
453                    writer.spill_to(&upload.options.spill());
454                }
455                let writer = merge::merge_into(inputs, group_lo == 1, writer).await?;
456                docs += writer.docs();
457                tombstones += writer.tombstones();
458                let id = segment::segment_id(group_lo, group_hi);
459                let (data, sparse) = finish_on(writer).await?;
460                write_segment(store, namespace, &id, data, upload).await?;
461                write_sparse(store, namespace, &id, sparse, upload).await?;
462                new_live.push(id);
463                start = end;
464            }
465
466            let published = manifest::update_if(store, namespace, |m| {
467                if m.wal_folded_through != folded || m.live_segments != live {
468                    return false;
469                }
470                m.live_segments = new_live.clone();
471                m.wal_folded_through = newest;
472                // An index belongs to the segment it was built for, so a
473                // merge takes the entries of the segments it retires with
474                // it. Every new segment starts without one.
475                let live_set: HashSet<&str> = m.live_segments.iter().map(String::as_str).collect();
476                m.indexes.retain(|id, _| live_set.contains(id.as_str()));
477                m.sparse_indexes
478                    .retain(|id, _| live_set.contains(id.as_str()));
479                m.attr_indexes
480                    .retain(|id, _| live_set.contains(id.as_str()));
481                true
482            })
483            .await?;
484            Ok(match published {
485                Some(_) => Compaction::Published {
486                    segments: new_live,
487                    folded_through: newest,
488                    merged_segments,
489                    docs,
490                    tombstones,
491                },
492                None => Compaction::Superseded,
493            })
494        }
495    }
496}
497
498/// [`SegmentWriter::finish`] on the maintenance lane: it builds the Bloom
499/// filter and the directory over every row.
500async fn finish_on(writer: SegmentWriter) -> Result<(Body, Option<Body>)> {
501    let cost = Cost::Bytes(writer.docs() * 64 + writer.tombstones() * 16);
502    cpu::run(Lane::Maintenance, cost, move || writer.finish_body()).await
503}
504
505/// Write a segment's `data.bin` with put-if-absent, or reuse an identical
506/// object already at the key, streamed through a staging key when it is large.
507pub(crate) async fn write_segment(
508    store: &dyn ObjectStore,
509    namespace: &str,
510    id: &str,
511    data: Body,
512    upload: &Uploader,
513) -> Result<()> {
514    let path = segment::segment_path(namespace, id);
515    put::write(
516        store,
517        &path,
518        data,
519        upload,
520        &put::Refusal {
521            missing: segment::missing,
522            differs: "an object already at this key differs from the segment this range \
523                      produces; if the manifest does not list it, delete it and rerun",
524        },
525    )
526    .await
527}
528
529/// Write the segment's sparse sidecar with the same put-if-absent, when it
530/// has one.
531pub(crate) async fn write_sparse(
532    store: &dyn ObjectStore,
533    namespace: &str,
534    id: &str,
535    sparse: Option<Body>,
536    upload: &Uploader,
537) -> Result<()> {
538    let Some(sparse) = sparse else {
539        return Ok(());
540    };
541    let path = sparse::sparse_path(namespace, id);
542    put::write(
543        store,
544        &path,
545        sparse,
546        upload,
547        &put::Refusal {
548            missing: sparse::missing,
549            differs: "an object already at this key differs from the sparse sidecar this range \
550                      produces; if the manifest's segment is not live, delete it and rerun",
551        },
552    )
553    .await
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559
560    /// A tail that compresses well is counted by its rows, not by its
561    /// listed size, so a merge mostly of tail still spills.
562    #[test]
563    fn a_compressible_tail_is_counted_by_its_rows() {
564        let mut tail = layer::Layer::new();
565        for i in 0..1000 {
566            tail.apply(crate::document::WalOp::Upsert(crate::document::Document {
567                id: format!("d{i:04}"),
568                vector: vec![0.0; 128],
569                attrs: None,
570                sparse: None,
571            }));
572        }
573        tail.apply(crate::document::WalOp::Delete("gone".into()));
574        let rows = tail_stored(0, &tail, 128);
575        assert!(rows >= 1000 * 128 * 4, "{rows}");
576        assert_eq!(tail_stored(u64::MAX, &tail, 128), u64::MAX);
577    }
578
579    #[test]
580    fn oversized_forces_a_merge_even_under_max_segments() {
581        // One segment, well under max_segments (8), but already over the
582        // cap: must merge, not sit there.
583        assert_eq!(
584            plan(1, true, 8, true, 200, 100),
585            Plan::Merge { target_count: 2 }
586        );
587        assert_eq!(plan(1, true, 8, false, 50, 100), Plan::Nothing);
588    }
589
590    #[test]
591    fn an_oversized_tail_also_forces_a_merge() {
592        // tail_is_empty is false here to represent a non-empty tail that is
593        // itself already over the cap; `oversized` is computed by the
594        // caller from the tail size estimate, `plan` itself just trusts the
595        // bool.
596        assert_eq!(
597            plan(1, false, 8, true, 150, 100),
598            Plan::Merge { target_count: 2 }
599        );
600    }
601
602    #[test]
603    fn the_existing_count_trigger_is_unchanged() {
604        assert_eq!(
605            plan(8, false, 8, false, 100, 100),
606            Plan::Merge { target_count: 1 }
607        ); // 8 + 1 > 8
608        assert_eq!(plan(7, false, 8, false, 100, 100), Plan::Fold);
609        assert_eq!(plan(3, true, 8, false, 100, 100), Plan::Nothing);
610    }
611
612    #[test]
613    fn a_cap_above_the_read_budget_is_refused() {
614        let options = CompactionOptions {
615            max_segments: 8,
616            max_segment_bytes: 1000,
617        };
618        assert!(options.validate(1000).is_ok());
619        assert!(matches!(
620            options.validate(999),
621            Err(ItzmaError::InvalidConfig(_))
622        ));
623    }
624
625    #[test]
626    fn target_count_is_the_ceiling_of_total_over_cap() {
627        assert_eq!(
628            plan(9, false, 8, false, 257, 100),
629            Plan::Merge { target_count: 3 }
630        );
631    }
632}
633
634#[cfg(test)]
635mod partition_tests {
636    use super::{fit, partition};
637
638    #[test]
639    fn below_the_cap_makes_one_group() {
640        assert_eq!(partition(&[10, 10, 10], 1), vec![3]);
641    }
642
643    #[test]
644    fn four_equal_sizes_split_evenly_in_two() {
645        assert_eq!(partition(&[10, 10, 10, 10], 2), vec![2, 4]);
646    }
647
648    #[test]
649    fn an_already_oversized_unit_gets_its_own_group() {
650        // One huge unit, three tiny ones: the balanced cut isolates the
651        // huge one rather than diluting it into a mixed group.
652        assert_eq!(partition(&[100, 1, 1, 1], 2), vec![1, 4]);
653    }
654
655    #[test]
656    fn target_count_is_clamped_to_the_unit_count() {
657        assert_eq!(partition(&[10, 10], 5), vec![1, 2]);
658    }
659
660    #[test]
661    fn zero_units_returns_one_empty_group() {
662        assert_eq!(partition(&[], 3), vec![0]);
663    }
664
665    #[test]
666    fn a_group_over_the_cap_is_split_until_each_fits() {
667        // Balanced into three, the middle group is 80 under a cap of 60.
668        let sizes = [40, 40, 40, 40];
669        assert_eq!(partition(&sizes, 3), vec![1, 3, 4]);
670        assert_eq!(fit(&sizes, partition(&sizes, 3), 60), vec![1, 2, 3, 4]);
671        // A unit over the cap alone stays a group of one.
672        assert_eq!(fit(&[10, 90, 10], vec![3], 50), vec![1, 2, 3]);
673        // Groups already under the cap are kept as they are.
674        assert_eq!(fit(&[10, 10, 10, 10], vec![2, 4], 20), vec![2, 4]);
675        for cap in 1..=50 {
676            let sizes = [7, 3, 9, 1, 4, 12, 2, 8];
677            let cuts = fit(&sizes, partition(&sizes, 2), cap);
678            let mut start = 0;
679            for &end in &cuts {
680                let sum: u64 = sizes[start..end].iter().sum();
681                assert!(end - start == 1 || sum <= cap, "cap {cap}: {cuts:?}");
682                start = end;
683            }
684            assert_eq!(start, sizes.len());
685        }
686    }
687
688    #[test]
689    fn every_group_gets_at_least_one_unit() {
690        for target in 1..=6 {
691            let cuts = partition(&[1, 1, 1, 1, 1, 1], target);
692            assert_eq!(cuts.last(), Some(&6));
693            let mut prev = 0;
694            for &c in &cuts {
695                assert!(c > prev, "group must not be empty: {cuts:?}");
696                prev = c;
697            }
698        }
699    }
700}