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