Skip to main content

grit_lib/
pack_objects.rs

1//! Negotiation-driven pack-objects: enumerate wants minus haves, delta search, stream PACK v2.
2//!
3//! Holds object metadata (not payloads) during planning; reads object bytes from the
4//! [`Odb`] on demand when encoding.
5
6#![allow(dead_code)]
7
8use crate::environment::RepositoryOptions;
9use crate::error::ObjectError;
10
11use std::collections::{HashMap, HashSet, VecDeque};
12use std::io::Write;
13use std::path::Path;
14
15use flate2::write::ZlibEncoder;
16use flate2::Compression;
17
18use crate::bitmap_walk::ReachableSet;
19use crate::delta_encode::{encode_prefix_extension_delta, DeltaIndex};
20use crate::error::{Error, Result};
21use crate::hash::HashingWriter;
22use crate::objects::{
23    empty_object_id_hash_set, oid_hash_map, oid_hash_set, oid_hash_set_from, parse_commit,
24    parse_tag, HashAlgo, ObjectId, ObjectInfo, ObjectKind, OidHashMap, OidHashSet, TreeRefIter,
25};
26use crate::odb::Odb;
27use crate::pack_object_select::{
28    append_included_tags, HaveBoundary, NameTrees, PackObjectSelection, TagCandidate,
29};
30use crate::parallel::{try_par_map_force, ParallelHashError};
31use crate::progress::CancelSignal;
32use crate::repo::Repository;
33use crate::rev_list::ObjectFilter;
34
35/// Options controlling pack-objects output (also used by [`build_pack`]).
36#[derive(Clone, Copy, Debug)]
37pub struct PackBuildOptions {
38    /// Build a thin pack: allow deltas whose base is reachable from the `haves`
39    /// but **not** emitted in the pack (`REF_DELTA` against a peer-held base).
40    pub thin: bool,
41    /// Emit delta-compressed objects instead of whole objects only.
42    pub delta: bool,
43    /// Candidate bases per object (Git `--window`). `0` disables new deltas.
44    pub window: usize,
45    /// Maximum delta chain depth (Git `--depth`). `0` stores whole objects.
46    pub max_depth: usize,
47    /// Prefer `OFS_DELTA` when the base precedes the target in the pack stream.
48    pub use_ofs_delta: bool,
49    /// Honor `pack.island` delta-island rules when selecting bases.
50    pub respect_islands: bool,
51    /// Reuse on-disk delta edges when both target and base are in this pack.
52    pub reuse_deltas: bool,
53    /// Reuse verbatim packed bytes for whole objects (CRC32-guarded v2 indexes).
54    pub reuse_objects: bool,
55    /// Use pack reachability bitmaps for object enumeration when present.
56    pub use_bitmaps: bool,
57    /// Soft cap, in bytes, on the payloads and delta indexes one delta-search
58    /// window holds (Git `--window-memory`; each search thread has a window).
59    /// `None` reads `pack.windowMemory`, which defaults to unlimited; `Some(0)`
60    /// is unlimited too.
61    pub window_memory: Option<u64>,
62}
63
64/// The delta-search window cap a served fetch uses when `pack.windowMemory`
65/// is not set: unlimited windows of large blobs would hold `window` of them,
66/// with their indexes, per search thread.
67pub const SERVE_WINDOW_MEMORY: u64 = 32 * 1024 * 1024;
68
69impl Default for PackBuildOptions {
70    fn default() -> Self {
71        Self {
72            thin: false,
73            delta: false,
74            window: 10,
75            max_depth: 50,
76            use_ofs_delta: true,
77            respect_islands: false,
78            reuse_deltas: true,
79            reuse_objects: true,
80            use_bitmaps: true,
81            window_memory: None,
82        }
83    }
84}
85
86impl PackBuildOptions {
87    /// `pack.window` and `pack.depth` from config, or Git defaults when unset.
88    #[must_use]
89    pub fn window_and_depth_from_config(cfg: Option<&crate::config::ConfigSet>) -> (usize, usize) {
90        cfg.map(|c| (c.pack_object_window(), c.pack_object_depth()))
91            .unwrap_or((10, crate::pack::DEFAULT_PACK_DEPTH))
92    }
93
94    fn window_memory_from_config(cfg: Option<&crate::config::ConfigSet>) -> u64 {
95        cfg.map(crate::config::ConfigSet::pack_window_memory_bytes)
96            .filter(|&bytes| bytes > 0)
97            .unwrap_or(SERVE_WINDOW_MEMORY)
98    }
99
100    /// Production pack settings for a local full copy (clone/fetch from disk).
101    #[must_use]
102    pub fn for_local_copy(cfg: Option<&crate::config::ConfigSet>) -> Self {
103        let (window, max_depth) = Self::window_and_depth_from_config(cfg);
104        Self {
105            thin: false,
106            delta: true,
107            window,
108            max_depth,
109            use_ofs_delta: true,
110            reuse_deltas: max_depth > 0,
111            reuse_objects: true,
112            use_bitmaps: true,
113            window_memory: Some(Self::window_memory_from_config(cfg)),
114            ..Default::default()
115        }
116    }
117
118    /// Copy stored pack entries (whole objects and deltas) without a new delta search
119    /// (`window` 0), for rebuilding a pack from objects that are already packed.
120    #[must_use]
121    pub fn for_repack_rewrite(cfg: Option<&crate::config::ConfigSet>) -> Self {
122        let max_depth = Self::window_and_depth_from_config(cfg).1;
123        Self {
124            thin: false,
125            delta: true,
126            window: 0,
127            max_depth,
128            use_ofs_delta: true,
129            reuse_deltas: max_depth > 0,
130            reuse_objects: true,
131            use_bitmaps: true,
132            ..Default::default()
133        }
134    }
135
136    /// Pack settings for answering a fetch (upload-pack).
137    ///
138    /// Window and depth follow `pack.window` / `pack.depth`. Whole objects and deltas
139    /// already in the repository's packs are copied as they are, and the delta search
140    /// only covers blobs that are not already stored as a delta, as Git does when serving.
141    /// Like Git, `pack.depth = 0` only disables new deltas: existing on-disk deltas are
142    /// still sent.
143    ///
144    /// The result is not thin and uses `OFS_DELTA`. Set [`Self::thin`] only when the client
145    /// negotiated `thin-pack` *and* holds objects (sent `have`s), since a thin pack against
146    /// nothing gains nothing, and clear [`Self::use_ofs_delta`] when the client did not
147    /// negotiate `ofs-delta`.
148    ///
149    /// # Parameters
150    /// - `cfg` — repository config, or `None` for Git's defaults.
151    #[must_use]
152    pub fn for_serve(cfg: Option<&crate::config::ConfigSet>) -> Self {
153        let (window, max_depth) = Self::window_and_depth_from_config(cfg);
154        let window_memory = cfg
155            .map(crate::config::ConfigSet::pack_window_memory_bytes)
156            .filter(|&bytes| bytes > 0)
157            .unwrap_or(SERVE_WINDOW_MEMORY);
158        Self {
159            thin: false,
160            delta: true,
161            window,
162            max_depth,
163            use_ofs_delta: true,
164            reuse_deltas: true,
165            reuse_objects: true,
166            use_bitmaps: true,
167            window_memory: Some(window_memory),
168            ..Default::default()
169        }
170    }
171
172    /// Production pack settings for an incremental in-process local push.
173    ///
174    /// Uses a thin pack when the remote already has objects to delta against.
175    /// Initial pushes into an empty bare repo should use [`Self::for_local_copy`].
176    #[must_use]
177    pub fn for_local_push(cfg: Option<&crate::config::ConfigSet>) -> Self {
178        let (window, max_depth) = Self::window_and_depth_from_config(cfg);
179        Self {
180            thin: true,
181            delta: true,
182            window,
183            max_depth,
184            use_ofs_delta: true,
185            reuse_deltas: true,
186            reuse_objects: true,
187            use_bitmaps: true,
188            window_memory: Some(Self::window_memory_from_config(cfg)),
189            ..Default::default()
190        }
191    }
192}
193
194/// Extended options for [`PackObjects`].
195#[derive(Clone, Copy, Debug, Default)]
196pub struct PackObjectsOptions {
197    /// Core pack-objects behaviour flags.
198    pub build: PackBuildOptions,
199    /// Override parallel delta-search workers (`None` = resolve [`crate::parallel::ParallelOp::PackDeltaSearch`] / `pack.threads`).
200    pub search_threads: Option<usize>,
201    /// Override parallel pack-write workers (`None` = resolve [`crate::parallel::ParallelOp::PackWrite`] / `pack.threads` from the repo config attached to the [`Odb`]).
202    pub write_threads: Option<usize>,
203}
204
205impl From<PackBuildOptions> for PackObjectsOptions {
206    fn from(build: PackBuildOptions) -> Self {
207        Self {
208            build,
209            search_threads: None,
210            write_threads: None,
211        }
212    }
213}
214
215/// Counters reported after a successful pack write.
216#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
217pub struct PackStats {
218    /// Number of objects in the pack header.
219    pub object_count: u32,
220    /// Total bytes written (including header and trailing hash).
221    pub pack_bytes: u64,
222    /// Objects written as `OFS_DELTA` or `REF_DELTA`.
223    pub delta_count: u32,
224    /// Pack body bytes copied verbatim from an existing on-disk pack (reuse path).
225    pub verbatim_reuse_bytes: u64,
226    /// Objects emitted via verbatim pack reuse (whole or delta copy/rewrite).
227    pub verbatim_reuse_objects: u32,
228    /// Delta entries whose OFS base distance was rewritten for the output pack.
229    pub pack_ofs_fixup_objects: u32,
230    /// OFS deltas converted to REF deltas for thin packs.
231    pub pack_ref_from_ofs_objects: u32,
232}
233
234/// Internal progress events while building a pack (forwarded to [`crate::progress::ProgressSink`]).
235#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub(crate) enum PackProgress {
237    /// Enumeration finished (`total` objects selected).
238    Enumerated {
239        /// Number of objects selected for packing.
240        total: usize,
241    },
242    /// Delta planning finished.
243    PlannedDeltas,
244    /// An object was written (`written` of `total`).
245    WroteObject {
246        /// Objects written so far.
247        written: usize,
248        /// Total objects to write in this pack.
249        total: usize,
250    },
251}
252
253/// Forwards [`PackProgress`] to a [`crate::progress::ProgressSink`] while building a pack.
254pub(crate) struct PackBuildProgress<'a> {
255    sink: &'a mut dyn crate::progress::ProgressSink,
256    copying_started: bool,
257    write_total: usize,
258    written: usize,
259}
260
261impl<'a> PackBuildProgress<'a> {
262    /// Create a reporter writing to `sink`.
263    pub fn new(sink: &'a mut dyn crate::progress::ProgressSink) -> Self {
264        Self {
265            sink,
266            copying_started: false,
267            write_total: 0,
268            written: 0,
269        }
270    }
271
272    /// Apply one pack-build event to the sink.
273    pub fn report(&mut self, ev: PackProgress) {
274        use crate::progress::ProgressPhase;
275        match ev {
276            PackProgress::Enumerated { total } => {
277                self.write_total = total;
278                self.sink
279                    .start(ProgressPhase::EnumeratingObjects, Some(total as u64));
280                self.sink.set(total as u64);
281                self.sink.finish();
282            }
283            PackProgress::PlannedDeltas => {
284                self.sink.start(ProgressPhase::CopyingObjects, None);
285                self.copying_started = true;
286            }
287            PackProgress::WroteObject { written, total } => {
288                if !self.copying_started {
289                    self.sink
290                        .start(ProgressPhase::CopyingObjects, Some(total as u64));
291                    self.copying_started = true;
292                }
293                self.written = written;
294                self.sink.set(written as u64);
295            }
296        }
297    }
298
299    /// End the copying phase when one was started.
300    pub fn finish_copying(&mut self) {
301        if self.copying_started {
302            self.sink.finish();
303            self.copying_started = false;
304        }
305    }
306}
307
308/// Streaming pack-objects builder over an [`Odb`].
309pub struct PackObjects<'a> {
310    odb: &'a Odb,
311    source_odb: &'a Odb,
312    opts: PackObjectsOptions,
313    wants: Vec<ObjectId>,
314    haves: Vec<ObjectId>,
315    have_shallow: OidHashSet,
316    source_shallow: OidHashSet,
317}
318
319impl<'a> PackObjects<'a> {
320    /// Create a builder reading objects from `odb`.
321    #[must_use]
322    pub fn new(odb: &'a Odb, opts: PackObjectsOptions) -> Self {
323        Self {
324            odb,
325            source_odb: odb,
326            opts,
327            wants: Vec::new(),
328            haves: Vec::new(),
329            have_shallow: oid_hash_set(),
330            source_shallow: oid_hash_set(),
331        }
332    }
333
334    /// Read object payloads from a different ODB (local fetch: remote source, local haves).
335    #[must_use]
336    pub fn with_source_odb(mut self, source: &'a Odb) -> Self {
337        self.source_odb = source;
338        self
339    }
340
341    /// Objects that must be included in the pack.
342    #[must_use]
343    pub fn wants(mut self, wants: &[ObjectId]) -> Self {
344        self.wants.extend_from_slice(wants);
345        self
346    }
347
348    /// Objects already held by the peer (negotiation boundary).
349    #[must_use]
350    pub fn haves(mut self, haves: &[ObjectId]) -> Self {
351        self.haves.extend_from_slice(haves);
352        self
353    }
354
355    /// Shallow grafts on the have side (local fetch).
356    #[must_use]
357    pub fn have_shallow_grafts(mut self, grafts: &HashSet<ObjectId>) -> Self {
358        self.have_shallow = grafts.iter().copied().collect();
359        self
360    }
361
362    /// Shallow grafts on the source side (do not walk past on source).
363    #[must_use]
364    pub fn source_shallow_grafts(mut self, grafts: &HashSet<ObjectId>) -> Self {
365        self.source_shallow = grafts.iter().copied().collect();
366        self
367    }
368
369    /// Write a PACK v2 stream to `w` and return statistics.
370    ///
371    /// # Errors
372    ///
373    /// Missing wants, corrupt objects, or I/O failures while writing.
374    pub fn write_to(
375        self,
376        w: &mut dyn Write,
377        progress: &mut dyn crate::progress::ProgressSink,
378    ) -> Result<PackStats> {
379        self.write_to_with_cancel(w, progress, &CancelSignal::never())
380    }
381
382    /// [`Self::write_to`], stopping with [`Error::Cancelled`] once `stop` fires.
383    pub(crate) fn write_to_with_cancel(
384        self,
385        w: &mut dyn Write,
386        progress: &mut dyn crate::progress::ProgressSink,
387        stop: &CancelSignal<'_>,
388    ) -> Result<PackStats> {
389        let mut reporter = PackBuildProgress::new(progress);
390        let opts = self.opts.build;
391        let have_shallow: HashSet<ObjectId> = self.have_shallow.iter().copied().collect();
392        let source_shallow: HashSet<ObjectId> = self.source_shallow.iter().copied().collect();
393        let peer_odb = (!std::ptr::eq(self.source_odb, self.odb)).then_some(self.odb);
394        let selection = crate::pack_object_select::enumerate_pack_objects_naming(
395            self.source_odb,
396            &self.wants,
397            &self.haves,
398            &crate::pack_object_select::PackEnumerateOptions {
399                filter: None,
400                shallow_grafts: &source_shallow,
401                have_shallow_grafts: Some(&have_shallow),
402                use_bitmaps: opts.use_bitmaps,
403                exclude_objects: None,
404                peer_odb,
405                have_boundary: HaveBoundary::CommitClosure,
406            },
407            NameTrees::for_delta_search(&opts),
408            false,
409            stop,
410        )?;
411        let send = selection.send;
412        reporter.report(PackProgress::Enumerated { total: send.len() });
413        if !opts.delta {
414            let bytes = serialize_pack(self.source_odb, &send, &opts)?;
415            stop.poll()?;
416            w.write_all(&bytes).map_err(Error::Io)?;
417            reporter.report(PackProgress::PlannedDeltas);
418            reporter.report(PackProgress::WroteObject {
419                written: send.len(),
420                total: send.len(),
421            });
422            reporter.finish_copying();
423            let count = u32::from_be_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
424            return Ok(PackStats {
425                object_count: count,
426                pack_bytes: bytes.len() as u64,
427                ..Default::default()
428            });
429        }
430        let plan = plan_deltas(
431            self.source_odb,
432            &send,
433            &selection.have_closure,
434            selection.peer_held.as_deref(),
435            &opts,
436            &selection.name_hashes,
437            self.opts.search_threads,
438            stop,
439        )?;
440        reporter.report(PackProgress::PlannedDeltas);
441        let total = send.len();
442        let mut on_objects = |batch: u64| {
443            reporter.written = reporter.written.saturating_add(batch as usize);
444            reporter.report(PackProgress::WroteObject {
445                written: reporter.written,
446                total,
447            });
448        };
449        let stats = crate::pack_delta::write_pack_with_deltas(
450            self.source_odb,
451            &plan.entries,
452            &opts,
453            self.opts.write_threads,
454            w,
455            None,
456            stop,
457            Some(&mut on_objects),
458        )?;
459        reporter.finish_copying();
460        Ok(stats)
461    }
462}
463
464/// Compute the full object closure reachable from `roots`, stopping descent into
465/// any object already present in `stop`.
466pub fn reachable_closure(
467    odb: &Odb,
468    roots: &[ObjectId],
469    stop: &HashSet<ObjectId>,
470    skip_missing: bool,
471    shallow_grafts: &HashSet<ObjectId>,
472) -> Result<HashSet<ObjectId>> {
473    let stop = oid_hash_set_from(stop);
474    let shallow_grafts = oid_hash_set_from(shallow_grafts);
475    let mut seen = oid_hash_set();
476    let order = collect_reachable_excluding(odb, roots, &stop, skip_missing, &shallow_grafts)?;
477    for oid in order {
478        seen.insert(oid);
479    }
480    Ok(seen.into_iter().collect())
481}
482
483/// Build a v2 packfile containing exactly the objects reachable from `wants`
484/// but **not** reachable from `haves`, de-duplicated.
485pub fn build_pack(
486    odb: &Odb,
487    wants: &[ObjectId],
488    haves: &[ObjectId],
489    opts: &PackBuildOptions,
490) -> Result<Vec<u8>> {
491    build_pack_with_shallow_filter_and_boundary(
492        odb,
493        wants,
494        haves,
495        empty_object_id_hash_set(),
496        empty_object_id_hash_set(),
497        None,
498        opts,
499        HaveBoundary::CommitClosure,
500    )
501}
502
503/// Like [`build_pack`], but uses [`HaveBoundary::TipsOnly`] for send-pack pushes.
504///
505/// Negotiated have tips bound the want-side walk lazily instead of pre-walking
506/// their full commit closure before enumeration. Collects
507/// [`write_pack_for_push`] into memory; pushes stream with that instead.
508///
509/// # Errors
510///
511/// Same as [`build_pack`]: missing wants, corrupt objects, or pack write failures.
512pub fn build_pack_for_push(
513    odb: &Odb,
514    wants: &[ObjectId],
515    haves: &[ObjectId],
516    opts: &PackBuildOptions,
517) -> Result<Vec<u8>> {
518    let mut pack = Vec::new();
519    write_pack_for_push(odb, wants, haves, opts, &mut pack)?;
520    Ok(pack)
521}
522
523/// Stream the pack a push sends to `w`: the objects reachable from `wants` but not
524/// from `haves`, bounded by the have tips as in [`build_pack_for_push`].
525///
526/// Memory stays bounded by the object list rather than the pack size: on-disk
527/// deltas and whole objects are copied from the source packs batch by batch, and
528/// every phase shares one mapping of each source pack.
529///
530/// # Parameters
531///
532/// - `odb`: the object database the objects are read from.
533/// - `wants`: the new tips the remote should end up with.
534/// - `haves`: objects the remote already holds (its tips and `.have`s), all present in `odb`.
535/// - `opts`: delta, thin-pack and offset-delta settings for the remote.
536/// - `w`: where the PACK v2 stream, trailer included, is written.
537///
538/// # Returns
539///
540/// Object and byte counts of the pack written.
541///
542/// # Errors
543///
544/// Missing wants, corrupt objects, or [`Error::Io`] when writing to `w` fails.
545pub fn write_pack_for_push(
546    odb: &Odb,
547    wants: &[ObjectId],
548    haves: &[ObjectId],
549    opts: &PackBuildOptions,
550    w: &mut dyn Write,
551) -> Result<PackStats> {
552    write_pack_for_push_with_cancel(
553        odb,
554        wants,
555        haves,
556        &HashSet::new(),
557        &HashSet::new(),
558        opts,
559        w,
560        &CancelSignal::never(),
561        None,
562    )
563}
564
565/// [`write_pack_for_push`], stopping with [`Error::Cancelled`] once `stop` fires.
566#[allow(clippy::too_many_arguments)]
567pub(crate) fn write_pack_for_push_with_cancel(
568    odb: &Odb,
569    wants: &[ObjectId],
570    haves: &[ObjectId],
571    have_shallow: &HashSet<ObjectId>,
572    source_shallow: &HashSet<ObjectId>,
573    opts: &PackBuildOptions,
574    w: &mut dyn Write,
575    stop: &CancelSignal<'_>,
576    progress: Option<&mut dyn crate::progress::ProgressSink>,
577) -> Result<PackStats> {
578    // One pack read context for the walk, the reuse scan and the write, so the
579    // source packs are mapped and indexed once rather than once per phase.
580    odb.with_pack_read_context(|| {
581        write_pack_with_shallow_and_filter(
582            odb,
583            wants,
584            haves,
585            have_shallow,
586            source_shallow,
587            None,
588            opts,
589            HaveBoundary::TipsOnly,
590            &[],
591            w,
592            stop,
593            progress,
594        )
595    })
596}
597
598#[allow(clippy::too_many_arguments)]
599fn build_pack_with_shallow_filter_and_boundary(
600    odb: &Odb,
601    wants: &[ObjectId],
602    haves: &[ObjectId],
603    have_shallow: &HashSet<ObjectId>,
604    source_shallow: &HashSet<ObjectId>,
605    filter: Option<&ObjectFilter>,
606    opts: &PackBuildOptions,
607    have_boundary: HaveBoundary,
608) -> Result<Vec<u8>> {
609    let mut pack = Vec::new();
610    write_pack_with_shallow_and_filter(
611        odb,
612        wants,
613        haves,
614        have_shallow,
615        source_shallow,
616        filter,
617        opts,
618        have_boundary,
619        &[],
620        &mut pack,
621        &CancelSignal::never(),
622        None,
623    )?;
624    Ok(pack)
625}
626
627/// Streaming form of [`UploadPackStream::build`]; `include_tags` are added
628/// when the objects they peel to are selected.
629#[allow(clippy::too_many_arguments)]
630fn write_pack_with_shallow_and_filter(
631    odb: &Odb,
632    wants: &[ObjectId],
633    haves: &[ObjectId],
634    have_shallow: &HashSet<ObjectId>,
635    source_shallow: &HashSet<ObjectId>,
636    filter: Option<&ObjectFilter>,
637    opts: &PackBuildOptions,
638    have_boundary: HaveBoundary,
639    include_tags: &[TagCandidate],
640    w: &mut dyn Write,
641    stop: &CancelSignal<'_>,
642    progress: Option<&mut dyn crate::progress::ProgressSink>,
643) -> Result<PackStats> {
644    let mut selection = crate::pack_object_select::enumerate_pack_objects_naming(
645        odb,
646        wants,
647        haves,
648        &crate::pack_object_select::PackEnumerateOptions {
649            filter,
650            shallow_grafts: source_shallow,
651            have_shallow_grafts: Some(have_shallow),
652            use_bitmaps: opts.use_bitmaps,
653            exclude_objects: None,
654            peer_odb: None,
655            have_boundary,
656        },
657        NameTrees::for_delta_search(opts),
658        false,
659        stop,
660    )?;
661    append_included_tags(odb, &mut selection.send, include_tags)?;
662    write_selected_pack(odb, &selection, opts, w, stop, progress)
663}
664
665/// Write a pack holding exactly `selection.send`, searching for deltas when `opts`
666/// asks for them (thin bases from `selection.have_closure`).
667fn write_selected_pack(
668    odb: &Odb,
669    selection: &PackObjectSelection,
670    opts: &PackBuildOptions,
671    w: &mut dyn Write,
672    stop: &CancelSignal<'_>,
673    progress: Option<&mut dyn crate::progress::ProgressSink>,
674) -> Result<PackStats> {
675    let mut reporter = progress.map(PackBuildProgress::new);
676    if let Some(r) = reporter.as_mut() {
677        r.report(PackProgress::Enumerated {
678            total: selection.send.len(),
679        });
680    }
681    if !opts.delta {
682        let bytes = serialize_pack(odb, &selection.send, opts)?;
683        stop.poll()?;
684        w.write_all(&bytes).map_err(Error::Io)?;
685        if let Some(r) = reporter.as_mut() {
686            r.report(PackProgress::PlannedDeltas);
687            r.report(PackProgress::WroteObject {
688                written: selection.send.len(),
689                total: selection.send.len(),
690            });
691            r.finish_copying();
692        }
693        return Ok(PackStats {
694            object_count: u32::try_from(selection.send.len()).unwrap_or(u32::MAX),
695            pack_bytes: bytes.len() as u64,
696            ..PackStats::default()
697        });
698    }
699    let plan = plan_deltas(
700        odb,
701        &selection.send,
702        &selection.have_closure,
703        selection.peer_held.as_deref(),
704        opts,
705        &selection.name_hashes,
706        None,
707        stop,
708    )?;
709    if let Some(r) = reporter.as_mut() {
710        r.report(PackProgress::PlannedDeltas);
711    }
712    let total = selection.send.len();
713    let stats = if reporter.is_some() {
714        let mut on_objects = |batch: u64| {
715            if let Some(r) = reporter.as_mut() {
716                r.written = r.written.saturating_add(batch as usize);
717                r.report(PackProgress::WroteObject {
718                    written: r.written,
719                    total,
720                });
721            }
722        };
723        crate::pack_delta::write_pack_with_deltas(
724            odb,
725            &plan.entries,
726            opts,
727            None,
728            w,
729            None,
730            stop,
731            Some(&mut on_objects),
732        )?
733    } else {
734        crate::pack_delta::write_pack_with_deltas(
735            odb,
736            &plan.entries,
737            opts,
738            None,
739            w,
740            None,
741            stop,
742            None,
743        )?
744    };
745    if let Some(r) = reporter.as_mut() {
746        r.finish_copying();
747    }
748    Ok(stats)
749}
750
751/// The pack one upload-pack response streams: the client's wants and haves, the shallow
752/// boundaries on either side, and an optional partial-clone filter.
753///
754/// Build it with [`UploadPackStream::new`] and the `with_*` setters, then
755/// [`UploadPackStream::write`] it. The pack is streamed with pack reuse when bitmaps allow,
756/// otherwise with pack-objects; filtered (partial clone) packs stream too.
757#[derive(Clone, Copy, Debug)]
758pub struct UploadPackStream<'a> {
759    wants: &'a [ObjectId],
760    haves: &'a [ObjectId],
761    source_shallow: Option<&'a HashSet<ObjectId>>,
762    have_shallow: Option<&'a HashSet<ObjectId>>,
763    filter: Option<&'a ObjectFilter>,
764    options: PackBuildOptions,
765}
766
767impl<'a> UploadPackStream<'a> {
768    /// A pack of everything reachable from `wants`, built with `options`.
769    #[must_use]
770    pub fn new(wants: &'a [ObjectId], options: PackBuildOptions) -> Self {
771        Self {
772            wants,
773            haves: &[],
774            source_shallow: None,
775            have_shallow: None,
776            filter: None,
777            options,
778        }
779    }
780
781    /// Leave out objects reachable from `haves`, which the client already has.
782    #[must_use]
783    pub fn with_haves(mut self, haves: &'a [ObjectId]) -> Self {
784        self.haves = haves;
785        self
786    }
787
788    /// Shallow boundaries of the serving repository: the walk stops at their parents.
789    #[must_use]
790    pub fn with_source_shallow(mut self, grafts: &'a HashSet<ObjectId>) -> Self {
791        self.source_shallow = Some(grafts);
792        self
793    }
794
795    /// Shallow boundaries of the client: history behind them counts as missing on its side.
796    #[must_use]
797    pub fn with_have_shallow(mut self, grafts: &'a HashSet<ObjectId>) -> Self {
798        self.have_shallow = Some(grafts);
799        self
800    }
801
802    /// Apply a partial-clone object filter (`blob:none`, `blob:limit=<n>`, ...).
803    #[must_use]
804    pub fn with_filter(mut self, filter: &'a ObjectFilter) -> Self {
805        self.filter = Some(filter);
806        self
807    }
808
809    /// Write the pack for `repo` to `out`, reporting progress through `progress`.
810    ///
811    /// The whole build runs in the odb's pack read context, so planning and the pack-write
812    /// workers share one set of pack caches.
813    ///
814    /// # Errors
815    ///
816    /// Missing wants, corrupt objects, or I/O failures while writing to `out`.
817    pub fn write(
818        &self,
819        repo: &Repository,
820        progress: &mut dyn crate::progress::ProgressSink,
821        out: &mut dyn Write,
822    ) -> Result<PackStats> {
823        let none = HashSet::new();
824        write_upload_pack_stream_with_cancel(
825            repo,
826            self.wants,
827            self.haves,
828            self.source_shallow.unwrap_or(&none),
829            self.have_shallow.unwrap_or(&none),
830            self.filter,
831            &[],
832            &self.options,
833            progress,
834            out,
835            &CancelSignal::never(),
836        )
837    }
838
839    /// Only the bitmap pack-reuse path of [`Self::write`]: `None` when reuse is not possible.
840    #[cfg(any(test, feature = "test-support"))]
841    pub(crate) fn write_reused_only(
842        &self,
843        repo: &Repository,
844        progress: &mut dyn crate::progress::ProgressSink,
845        out: &mut dyn Write,
846    ) -> Result<Option<PackStats>> {
847        let none = HashSet::new();
848        crate::pack_reuse::try_write_streaming_pack_including_tags(
849            repo,
850            self.wants,
851            self.haves,
852            self.source_shallow.unwrap_or(&none),
853            self.have_shallow.unwrap_or(&none),
854            self.filter,
855            &[],
856            &self.options,
857            progress,
858            out,
859            &CancelSignal::never(),
860        )
861    }
862
863    /// Build the same pack in memory from `odb` instead of streaming it.
864    ///
865    /// Objects are selected the way the streamed pack selects them (a filter keeps the wants
866    /// and the objects their tags point at), but without bitmap pack reuse.
867    ///
868    /// # Errors
869    ///
870    /// Missing wants, corrupt objects, or pack encoding failures.
871    pub fn build(&self, odb: &Odb) -> Result<Vec<u8>> {
872        let none = HashSet::new();
873        build_pack_with_shallow_filter_and_boundary(
874            odb,
875            self.wants,
876            self.haves,
877            self.have_shallow.unwrap_or(&none),
878            self.source_shallow.unwrap_or(&none),
879            self.filter,
880            &self.options,
881            HaveBoundary::CommitClosure,
882        )
883    }
884}
885
886/// [`UploadPackStream::write`], stopping object enumeration when `stop` fires, that
887/// also packs each of `include_tags` whose peeled object is among the objects sent
888/// (`include-tag`), on the walk and reuse paths alike.
889#[allow(clippy::too_many_arguments)]
890pub(crate) fn write_upload_pack_stream_with_cancel(
891    repo: &Repository,
892    wants: &[ObjectId],
893    haves: &[ObjectId],
894    source_shallow: &HashSet<ObjectId>,
895    have_shallow: &HashSet<ObjectId>,
896    filter: Option<&ObjectFilter>,
897    include_tags: &[TagCandidate],
898    opts: &PackBuildOptions,
899    progress: &mut dyn crate::progress::ProgressSink,
900    w: &mut dyn Write,
901    stop: &CancelSignal<'_>,
902) -> Result<PackStats> {
903    repo.odb().with_pack_read_context(|| {
904        write_upload_pack_stream_in_context(
905            repo,
906            wants,
907            haves,
908            source_shallow,
909            have_shallow,
910            filter,
911            include_tags,
912            opts,
913            progress,
914            w,
915            stop,
916        )
917    })
918}
919
920#[allow(clippy::too_many_arguments)]
921fn write_upload_pack_stream_in_context(
922    repo: &Repository,
923    wants: &[ObjectId],
924    haves: &[ObjectId],
925    source_shallow: &HashSet<ObjectId>,
926    have_shallow: &HashSet<ObjectId>,
927    filter: Option<&ObjectFilter>,
928    include_tags: &[TagCandidate],
929    opts: &PackBuildOptions,
930    progress: &mut dyn crate::progress::ProgressSink,
931    w: &mut dyn Write,
932    stop: &CancelSignal<'_>,
933) -> Result<PackStats> {
934    if opts.use_bitmaps && filter.is_none() {
935        if let Some(stats) = crate::pack_reuse::try_write_streaming_pack_including_tags(
936            repo,
937            wants,
938            haves,
939            source_shallow,
940            have_shallow,
941            filter,
942            include_tags,
943            opts,
944            progress,
945            w,
946            stop,
947        )? {
948            return Ok(stats);
949        }
950    }
951    // The client's history only has to be painted down to where the want walk meets
952    // it, not pre-walked to its roots.
953    write_pack_with_shallow_and_filter(
954        repo.odb(),
955        wants,
956        haves,
957        have_shallow,
958        source_shallow,
959        filter,
960        opts,
961        HaveBoundary::TipsOnly,
962        include_tags,
963        w,
964        stop,
965        Some(progress),
966    )
967}
968
969type PackIndexRows = Vec<(ObjectId, u64, u32)>;
970
971/// Objects selected for an upload-pack response from a repository with promisor
972/// remotes, with the blobs it does not store set aside.
973///
974/// Always uses the object walk: bitmaps and verbatim pack reuse cannot tell that a
975/// blob is missing. See [`write_upload_pack_selection`].
976#[allow(clippy::too_many_arguments)]
977pub(crate) fn select_upload_pack_objects_probing(
978    repo: &Repository,
979    wants: &[ObjectId],
980    haves: &[ObjectId],
981    source_shallow: &HashSet<ObjectId>,
982    have_shallow: &HashSet<ObjectId>,
983    filter: Option<&ObjectFilter>,
984    opts: &PackBuildOptions,
985) -> Result<(
986    PackObjectSelection,
987    Vec<crate::pack_object_select::MissingBlob>,
988)> {
989    repo.odb().with_pack_read_context(|| {
990        crate::pack_object_select::enumerate_pack_objects_probing(
991            repo.odb(),
992            wants,
993            haves,
994            &crate::pack_object_select::PackEnumerateOptions {
995                filter,
996                shallow_grafts: source_shallow,
997                have_shallow_grafts: Some(have_shallow),
998                use_bitmaps: false,
999                exclude_objects: None,
1000                peer_odb: None,
1001                have_boundary: HaveBoundary::TipsOnly,
1002            },
1003            NameTrees::for_delta_search(opts),
1004            &CancelSignal::never(),
1005        )
1006    })
1007}
1008
1009/// Stream the pack for a selection made by [`select_upload_pack_objects_probing`]
1010/// (after its missing blobs were omitted or fetched).
1011pub(crate) fn write_upload_pack_selection(
1012    repo: &Repository,
1013    selection: &PackObjectSelection,
1014    opts: &PackBuildOptions,
1015    w: &mut dyn Write,
1016    stop: &CancelSignal<'_>,
1017) -> Result<PackStats> {
1018    repo.odb()
1019        .with_pack_read_context(|| write_selected_pack(repo.odb(), selection, opts, w, stop, None))
1020}
1021
1022fn write_pack_header(w: &mut dyn Write, count: u32) -> Result<()> {
1023    w.write_all(b"PACK").map_err(Error::Io)?;
1024    w.write_all(&2u32.to_be_bytes()).map_err(Error::Io)?;
1025    w.write_all(&count.to_be_bytes()).map_err(Error::Io)?;
1026    Ok(())
1027}
1028
1029/// Stream a delta pack from a plan, optionally applying bitmap verbatim reuse.
1030pub(crate) fn write_delta_pack_stream(
1031    odb: &Odb,
1032    plan: &DeltaPlan,
1033    opts: &PackBuildOptions,
1034    w: &mut dyn Write,
1035    reuse: Option<&mut crate::pack_reuse::StreamingReuse>,
1036) -> Result<PackStats> {
1037    let algo = odb.hash_algo();
1038    let mut out = HashingWriter::new(algo, w);
1039    let reuse_stats = if let Some(reuse) = reuse {
1040        let (_, body_bytes) = write_delta_plan_stream_body(&mut out, odb, plan, opts, Some(reuse))?;
1041        out.finish().map_err(Error::Io)?;
1042        let pack_bytes = 12u64 + body_bytes + algo.len() as u64;
1043        let stats = reuse.take_stats();
1044        (pack_bytes, stats)
1045    } else {
1046        let (_, body_bytes) = write_delta_plan_stream_body(&mut out, odb, plan, opts, None)?;
1047        out.finish().map_err(Error::Io)?;
1048        (
1049            12u64 + body_bytes + algo.len() as u64,
1050            crate::pack_reuse::ReuseWriteStats::default(),
1051        )
1052    };
1053    let delta_count = plan.entries.iter().filter(|e| e.base.is_some()).count() as u32;
1054    Ok(PackStats {
1055        object_count: u32::try_from(plan.entries.len()).map_err(|_| {
1056            Error::Object(ObjectError::Corrupt {
1057                detail: "pack object count exceeds u32".to_owned(),
1058            })
1059        })?,
1060        pack_bytes: reuse_stats.0,
1061        delta_count,
1062        verbatim_reuse_bytes: reuse_stats.1.verbatim_reuse_bytes,
1063        verbatim_reuse_objects: reuse_stats.1.verbatim_reuse_objects,
1064        pack_ofs_fixup_objects: reuse_stats.1.pack_ofs_fixup_objects,
1065        pack_ref_from_ofs_objects: reuse_stats.1.pack_ref_from_ofs_objects,
1066    })
1067}
1068
1069fn write_delta_plan_stream_body(
1070    w: &mut dyn Write,
1071    odb: &Odb,
1072    plan: &DeltaPlan,
1073    opts: &PackBuildOptions,
1074    reuse: Option<&mut crate::pack_reuse::StreamingReuse>,
1075) -> Result<(PackIndexRows, u64)> {
1076    let count = u32::try_from(plan.entries.len()).map_err(|_| {
1077        Error::Object(ObjectError::Corrupt {
1078            detail: "pack object count exceeds u32".to_owned(),
1079        })
1080    })?;
1081    write_pack_header(w, count)?;
1082    let mut index_rows = Vec::with_capacity(plan.entries.len());
1083    let body_bytes = write_planned_entries(w, odb, plan, opts, 12, reuse, &mut index_rows)?;
1084    Ok((index_rows, body_bytes))
1085}
1086
1087pub(crate) const PACK_STREAM_COPY_CHUNK: usize = 64 * 1024;
1088
1089pub(crate) struct CrcWriter<'a, W: Write + ?Sized> {
1090    inner: &'a mut W,
1091    crc: crc32fast::Hasher,
1092}
1093
1094impl<'a, W: Write + ?Sized> CrcWriter<'a, W> {
1095    pub fn new(inner: &'a mut W, prefix: &[u8]) -> Self {
1096        let mut crc = crc32fast::Hasher::new();
1097        crc.update(prefix);
1098        Self { inner, crc }
1099    }
1100
1101    pub(crate) fn finalize(self) -> u32 {
1102        self.crc.finalize()
1103    }
1104}
1105
1106impl<W: Write + ?Sized> Write for CrcWriter<'_, W> {
1107    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1108        let n = self.inner.write(buf)?;
1109        self.crc.update(&buf[..n]);
1110        Ok(n)
1111    }
1112
1113    fn flush(&mut self) -> std::io::Result<()> {
1114        self.inner.flush()
1115    }
1116}
1117
1118struct ByteCounter<'a, W: Write + ?Sized> {
1119    inner: &'a mut W,
1120    n: u64,
1121}
1122
1123impl<W: Write + ?Sized> Write for ByteCounter<'_, W> {
1124    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1125        let n = self.inner.write(buf)?;
1126        self.n += n as u64;
1127        Ok(n)
1128    }
1129
1130    fn flush(&mut self) -> std::io::Result<()> {
1131        self.inner.flush()
1132    }
1133}
1134
1135pub(crate) fn write_all_chunked(w: &mut dyn Write, data: &[u8]) -> Result<()> {
1136    for chunk in data.chunks(PACK_STREAM_COPY_CHUNK) {
1137        w.write_all(chunk).map_err(Error::Io)?;
1138    }
1139    Ok(())
1140}
1141
1142fn write_planned_entries(
1143    w: &mut dyn Write,
1144    odb: &Odb,
1145    plan: &DeltaPlan,
1146    opts: &PackBuildOptions,
1147    pack_body_start: u64,
1148    mut reuse: Option<&mut crate::pack_reuse::StreamingReuse>,
1149    index_rows: &mut Vec<(ObjectId, u64, u32)>,
1150) -> Result<u64> {
1151    let algo = odb.hash_algo();
1152    let compression = odb.pack_compression()?;
1153    let mut oid_to_offset: OidHashMap<u64> = oid_hash_map();
1154    let mut body_written = 0u64;
1155
1156    for entry in &plan.entries {
1157        let start = pack_body_start + body_written;
1158        let mut chunk = Vec::new();
1159        if entry.base.is_none() {
1160            let mut crc_w = CrcWriter {
1161                inner: w,
1162                crc: crc32fast::Hasher::new(),
1163            };
1164            let wrote = {
1165                let mut counter = ByteCounter {
1166                    inner: &mut crc_w,
1167                    n: 0,
1168                };
1169                if let Some(reuse) = reuse.as_mut() {
1170                    if let Some(n) = reuse.try_write_whole(&mut counter, &entry.oid, opts)? {
1171                        n
1172                    } else {
1173                        write_whole_pack_object_to_odb(
1174                            &mut counter,
1175                            odb,
1176                            entry.oid,
1177                            entry.kind,
1178                            opts,
1179                            &CancelSignal::never(),
1180                        )?
1181                    }
1182                } else {
1183                    write_whole_pack_object_to_odb(
1184                        &mut counter,
1185                        odb,
1186                        entry.oid,
1187                        entry.kind,
1188                        opts,
1189                        &CancelSignal::never(),
1190                    )?
1191                }
1192            };
1193            let crc = crc_w.finalize();
1194            index_rows.push((entry.oid, start, crc));
1195            body_written += wrote;
1196            oid_to_offset.insert(entry.oid, start);
1197            continue;
1198        }
1199        let Some(base_oid) = entry.base else {
1200            continue;
1201        };
1202        let in_pack_offset = oid_to_offset.get(&base_oid).copied();
1203        if let Some((delta_size, pack_bytes, zlib_start, zlib_end)) = &entry.reused_delta_zlib {
1204            let delta_len = usize::try_from(*delta_size).map_err(|_| {
1205                Error::Object(ObjectError::Corrupt {
1206                    detail: "reused delta size exceeds usize".to_owned(),
1207                })
1208            })?;
1209            if let Some(base_off) = in_pack_offset.filter(|_| opts.use_ofs_delta) {
1210                let dist = start.checked_sub(base_off).ok_or_else(|| {
1211                    Error::Object(ObjectError::Corrupt {
1212                        detail: "ofs-delta distance underflow".to_owned(),
1213                    })
1214                })?;
1215                encode_pack_object_header(&mut chunk, 6, delta_len);
1216                encode_ofs_delta_distance(&mut chunk, dist);
1217                if let Some(reuse) = reuse.as_mut() {
1218                    reuse.record_ofs_fixup();
1219                }
1220            } else {
1221                encode_pack_object_header(&mut chunk, 7, delta_len);
1222                chunk.extend_from_slice(base_oid.as_bytes());
1223            }
1224            chunk.extend_from_slice(&pack_bytes[*zlib_start..*zlib_end]);
1225            if let Some(reuse) = reuse.as_mut() {
1226                reuse.record_verbatim_zlib((zlib_end - zlib_start) as u64);
1227            }
1228        } else {
1229            let computed;
1230            let (delta_len, zlib): (usize, &[u8]) = match &entry.searched_delta {
1231                Some((len, zlib)) => (*len, zlib),
1232                None => {
1233                    let target_data = odb.read(&entry.oid)?.data;
1234                    let base_data = odb.read(&base_oid)?.data;
1235                    let delta = if target_data.starts_with(&base_data)
1236                        && target_data.len() > base_data.len()
1237                    {
1238                        encode_prefix_extension_delta(&base_data, &target_data)?
1239                    } else {
1240                        DeltaIndex::new(&base_data)
1241                            .encode(&target_data, 0)
1242                            .ok_or_else(|| {
1243                                Error::Object(ObjectError::Corrupt {
1244                                    detail: "failed to encode pack delta for object".into(),
1245                                })
1246                            })?
1247                    };
1248                    let mut buf = Vec::new();
1249                    write_zlib(&mut buf, &delta, compression)?;
1250                    computed = buf;
1251                    (delta.len(), &computed)
1252                }
1253            };
1254            if let Some(base_off) = in_pack_offset.filter(|_| opts.use_ofs_delta) {
1255                let dist = start.checked_sub(base_off).ok_or_else(|| {
1256                    Error::Object(ObjectError::Corrupt {
1257                        detail: "ofs-delta distance underflow".to_owned(),
1258                    })
1259                })?;
1260                encode_pack_object_header(&mut chunk, 6, delta_len);
1261                encode_ofs_delta_distance(&mut chunk, dist);
1262            } else {
1263                encode_pack_object_header(&mut chunk, 7, delta_len);
1264                if base_oid.as_bytes().len() != algo.len() {
1265                    return Err(Error::Object(ObjectError::Corrupt {
1266                        detail: "ref-delta base oid width mismatch".to_owned(),
1267                    }));
1268                }
1269                chunk.extend_from_slice(base_oid.as_bytes());
1270            }
1271            chunk.extend_from_slice(zlib);
1272        }
1273        w.write_all(&chunk).map_err(Error::Io)?;
1274        index_rows.push((entry.oid, start, crc32fast::hash(&chunk)));
1275        body_written += chunk.len() as u64;
1276        oid_to_offset.insert(entry.oid, start);
1277    }
1278    Ok(body_written)
1279}
1280
1281/// Serialize a precomputed object list into a pack (used by [`build_pack`] and filtered bundles).
1282///
1283/// # Errors
1284///
1285/// Same as [`build_pack`].
1286pub fn build_pack_from_send_list(
1287    odb: &Odb,
1288    send: &[ObjectId],
1289    have_closure: &HashSet<ObjectId>,
1290    opts: &PackBuildOptions,
1291    blob_name_hashes: &HashMap<ObjectId, u32>,
1292) -> Result<Vec<u8>> {
1293    build_pack_from_send_list_with_parallel_threads(
1294        odb,
1295        send,
1296        have_closure,
1297        opts,
1298        blob_name_hashes,
1299        None,
1300        None,
1301    )
1302}
1303
1304/// Like [`build_pack`] with an explicit pack-write worker override for tests and embedders.
1305///
1306/// `write_threads` replaces config-derived `pack.threads` when set.
1307pub fn build_pack_with_write_threads(
1308    odb: &Odb,
1309    wants: &[ObjectId],
1310    haves: &[ObjectId],
1311    opts: &PackBuildOptions,
1312    write_threads: Option<usize>,
1313) -> Result<Vec<u8>> {
1314    build_pack_with_write_threads_full(odb, wants, haves, opts, write_threads)
1315        .map(|pack| pack.bytes)
1316}
1317
1318/// Like [`build_pack_with_write_threads`], retaining trusted pack index rows for local install.
1319pub(crate) fn build_pack_with_write_threads_full(
1320    odb: &Odb,
1321    wants: &[ObjectId],
1322    haves: &[ObjectId],
1323    opts: &PackBuildOptions,
1324    write_threads: Option<usize>,
1325) -> Result<SerializedDeltaPack> {
1326    let empty_shallow = empty_object_id_hash_set();
1327    let have_closure = reachable_closure(odb, haves, empty_shallow, true, empty_shallow)?;
1328    let selection = crate::pack_object_select::enumerate_pack_objects_naming(
1329        odb,
1330        wants,
1331        haves,
1332        &crate::pack_object_select::PackEnumerateOptions {
1333            filter: None,
1334            shallow_grafts: empty_shallow,
1335            have_shallow_grafts: Some(empty_shallow),
1336            use_bitmaps: opts.use_bitmaps,
1337            exclude_objects: Some(&have_closure),
1338            peer_odb: None,
1339            have_boundary: HaveBoundary::CommitClosure,
1340        },
1341        NameTrees::for_delta_search(opts),
1342        false,
1343        &CancelSignal::never(),
1344    )?;
1345    build_pack_from_send_list_full(
1346        odb,
1347        &selection.send,
1348        &selection.have_closure,
1349        opts,
1350        &selection.name_hashes,
1351        None,
1352        write_threads,
1353    )
1354}
1355
1356/// Like [`build_pack`] with explicit delta-search and pack-write worker overrides.
1357pub fn build_pack_with_parallel_threads(
1358    odb: &Odb,
1359    wants: &[ObjectId],
1360    haves: &[ObjectId],
1361    opts: &PackBuildOptions,
1362    search_threads: Option<usize>,
1363    write_threads: Option<usize>,
1364) -> Result<Vec<u8>> {
1365    let empty_shallow = empty_object_id_hash_set();
1366    let have_closure = reachable_closure(odb, haves, empty_shallow, true, empty_shallow)?;
1367    let selection = crate::pack_object_select::enumerate_pack_objects_naming(
1368        odb,
1369        wants,
1370        haves,
1371        &crate::pack_object_select::PackEnumerateOptions {
1372            filter: None,
1373            shallow_grafts: empty_shallow,
1374            have_shallow_grafts: Some(empty_shallow),
1375            use_bitmaps: opts.use_bitmaps,
1376            exclude_objects: Some(&have_closure),
1377            peer_odb: None,
1378            have_boundary: HaveBoundary::CommitClosure,
1379        },
1380        NameTrees::for_delta_search(opts),
1381        false,
1382        &CancelSignal::never(),
1383    )?;
1384    build_pack_from_send_list_with_parallel_threads(
1385        odb,
1386        &selection.send,
1387        &selection.have_closure,
1388        opts,
1389        &selection.name_hashes,
1390        search_threads,
1391        write_threads,
1392    )
1393}
1394
1395/// Serialize a precomputed object list with an explicit pack-write worker count.
1396pub fn build_pack_from_send_list_with_write_threads(
1397    odb: &Odb,
1398    send: &[ObjectId],
1399    have_closure: &HashSet<ObjectId>,
1400    opts: &PackBuildOptions,
1401    blob_name_hashes: &HashMap<ObjectId, u32>,
1402    write_threads: Option<usize>,
1403) -> Result<Vec<u8>> {
1404    build_pack_from_send_list_with_parallel_threads(
1405        odb,
1406        send,
1407        have_closure,
1408        opts,
1409        blob_name_hashes,
1410        None,
1411        write_threads,
1412    )
1413}
1414
1415/// Serialize a precomputed object list with explicit delta-search and write parallelism.
1416pub fn build_pack_from_send_list_with_parallel_threads(
1417    odb: &Odb,
1418    send: &[ObjectId],
1419    have_closure: &HashSet<ObjectId>,
1420    opts: &PackBuildOptions,
1421    blob_name_hashes: &HashMap<ObjectId, u32>,
1422    search_threads: Option<usize>,
1423    write_threads: Option<usize>,
1424) -> Result<Vec<u8>> {
1425    build_pack_from_send_list_full(
1426        odb,
1427        send,
1428        have_closure,
1429        opts,
1430        blob_name_hashes,
1431        search_threads,
1432        write_threads,
1433    )
1434    .map(|pack| pack.bytes)
1435}
1436
1437pub(crate) fn build_pack_from_send_list_full(
1438    odb: &Odb,
1439    send: &[ObjectId],
1440    have_closure: &HashSet<ObjectId>,
1441    opts: &PackBuildOptions,
1442    blob_name_hashes: &HashMap<ObjectId, u32>,
1443    search_threads: Option<usize>,
1444    write_threads: Option<usize>,
1445) -> Result<SerializedDeltaPack> {
1446    if !opts.delta {
1447        let bytes = serialize_pack(odb, send, opts)?;
1448        return Ok(SerializedDeltaPack {
1449            bytes,
1450            index_rows: Vec::new(),
1451            staging_path: None,
1452        });
1453    }
1454    let plan = plan_deltas(
1455        odb,
1456        send,
1457        have_closure,
1458        None,
1459        opts,
1460        blob_name_hashes,
1461        search_threads,
1462        &CancelSignal::never(),
1463    )?;
1464    crate::pack_delta::serialize_pack_with_deltas(odb, &plan.entries, opts, write_threads)
1465}
1466
1467/// Stream a pack of exactly `send` (objects the receiver lacks, none of which it
1468/// needs as a delta base) to `w`, stopping with [`Error::Cancelled`] once `stop` fires.
1469///
1470/// Reuses on-disk whole objects and deltas as `opts` allows, like
1471/// [`build_pack_from_send_list`], without holding the pack in memory.
1472pub(crate) fn write_pack_from_send_list(
1473    odb: &Odb,
1474    send: &[ObjectId],
1475    opts: &PackBuildOptions,
1476    name_hashes: &HashMap<ObjectId, u32>,
1477    stop: &CancelSignal<'_>,
1478    w: &mut dyn Write,
1479    mut on_objects: Option<&mut dyn FnMut(u64)>,
1480) -> Result<(PackStats, PackIndexRows)> {
1481    if !opts.delta {
1482        let bytes = serialize_pack(odb, send, opts)?;
1483        stop.poll()?;
1484        w.write_all(&bytes).map_err(Error::Io)?;
1485        if let Some(on) = on_objects.as_deref_mut() {
1486            on(send.len() as u64);
1487        }
1488        return Ok((
1489            PackStats {
1490                object_count: u32::try_from(send.len()).unwrap_or(u32::MAX),
1491                pack_bytes: bytes.len() as u64,
1492                ..PackStats::default()
1493            },
1494            Vec::new(),
1495        ));
1496    }
1497    odb.with_pack_read_context(|| {
1498        let plan = plan_deltas(
1499            odb,
1500            send,
1501            &HashSet::new(),
1502            None,
1503            opts,
1504            name_hashes,
1505            None,
1506            stop,
1507        )?;
1508        stop.poll()?;
1509        let mut index_rows = Vec::with_capacity(plan.entries.len());
1510        let stats = crate::pack_delta::write_pack_with_deltas(
1511            odb,
1512            &plan.entries,
1513            opts,
1514            None,
1515            w,
1516            Some(&mut index_rows),
1517            stop,
1518            on_objects,
1519        )?;
1520        Ok((stats, index_rows))
1521    })
1522}
1523
1524/// Stream a pack for a local transfer to `w`: enumerate haves on `have_odb`, read
1525/// payloads from `source_odb`, and stop with [`Error::Cancelled`] once `stop` fires.
1526#[allow(clippy::too_many_arguments)]
1527pub(crate) fn write_pack_for_local_fetch(
1528    source_odb: &Odb,
1529    wants: &[ObjectId],
1530    have_odb: &Odb,
1531    haves: &[ObjectId],
1532    source_shallow: &HashSet<ObjectId>,
1533    have_shallow: &HashSet<ObjectId>,
1534    opts: &PackBuildOptions,
1535    stop: &CancelSignal<'_>,
1536    w: &mut dyn Write,
1537) -> Result<PackStats> {
1538    PackObjects::new(have_odb, PackObjectsOptions::from(*opts))
1539        .with_source_odb(source_odb)
1540        .wants(wants)
1541        .haves(haves)
1542        .have_shallow_grafts(have_shallow)
1543        .source_shallow_grafts(source_shallow)
1544        .write_to_with_cancel(w, &mut crate::progress::NullProgress, stop)
1545}
1546
1547fn collect_reachable_excluding(
1548    odb: &Odb,
1549    roots: &[ObjectId],
1550    exclude: &OidHashSet,
1551    skip_missing: bool,
1552    shallow_grafts: &OidHashSet,
1553) -> Result<Vec<ObjectId>> {
1554    let mut visited: OidHashSet = oid_hash_set();
1555    let mut ordered: Vec<ObjectId> = Vec::new();
1556    let mut queue: VecDeque<ObjectId> = VecDeque::new();
1557
1558    let enqueue = |oid: ObjectId,
1559                   queue: &mut VecDeque<ObjectId>,
1560                   visited: &mut OidHashSet,
1561                   ordered: &mut Vec<ObjectId>|
1562     -> bool {
1563        if !visited.insert(oid) {
1564            return false;
1565        }
1566        if !exclude.contains(&oid) {
1567            ordered.push(oid);
1568        }
1569        queue.push_back(oid);
1570        true
1571    };
1572
1573    for &root in roots {
1574        enqueue(root, &mut queue, &mut visited, &mut ordered);
1575    }
1576
1577    let oid_len = odb.hash_algo().len();
1578
1579    while let Some(oid) = queue.pop_front() {
1580        let obj = match odb.read(&oid) {
1581            Ok(o) => o,
1582            // A root/have absent from this odb cannot be traversed; with
1583            // `skip_missing` it simply contributes nothing (no descent), instead
1584            // of failing the whole pack build.
1585            Err(_) if skip_missing => continue,
1586            Err(e) => return Err(e),
1587        };
1588        match obj.kind {
1589            ObjectKind::Commit => {
1590                let commit = parse_commit(&obj.data)?;
1591                if !shallow_grafts.contains(&oid) {
1592                    for parent in commit.parents {
1593                        enqueue(parent, &mut queue, &mut visited, &mut ordered);
1594                    }
1595                }
1596                enqueue(commit.tree, &mut queue, &mut visited, &mut ordered);
1597            }
1598            ObjectKind::Tree => {
1599                for entry in TreeRefIter::with_oid_len(&obj.data, oid_len) {
1600                    let entry = entry?;
1601                    // Skip submodule (gitlink) entries: the commit they name
1602                    // lives in another object store and is not part of this pack.
1603                    if entry.mode == 0o160000 {
1604                        continue;
1605                    }
1606                    enqueue(entry.oid, &mut queue, &mut visited, &mut ordered);
1607                }
1608            }
1609            ObjectKind::Tag => {
1610                let tag = parse_tag(&obj.data)?;
1611                enqueue(tag.object, &mut queue, &mut visited, &mut ordered);
1612            }
1613            ObjectKind::Blob => {}
1614        }
1615    }
1616
1617    Ok(ordered)
1618}
1619
1620/// The pack object type code for a Git object kind (PACK v2 base types).
1621pub(crate) fn pack_type_code(kind: ObjectKind) -> u8 {
1622    match kind {
1623        ObjectKind::Commit => 1,
1624        ObjectKind::Tree => 2,
1625        ObjectKind::Blob => 3,
1626        ObjectKind::Tag => 4,
1627    }
1628}
1629
1630/// Append a PACK object header: 3-bit type + variable-length size (little-endian
1631/// 7-bit groups, MSB = continuation). Lifted from the CLI pack writer.
1632pub(crate) fn encode_pack_object_header(buf: &mut Vec<u8>, type_code: u8, payload_len: usize) {
1633    let mut size = payload_len;
1634    let first = ((type_code & 0x7) << 4) | (size & 0x0f) as u8;
1635    size >>= 4;
1636    if size > 0 {
1637        buf.push(first | 0x80);
1638        while size > 0 {
1639            let b = (size & 0x7f) as u8;
1640            size >>= 7;
1641            buf.push(if size > 0 { b | 0x80 } else { b });
1642        }
1643    } else {
1644        buf.push(first);
1645    }
1646}
1647
1648/// Serialize `oids` as a PACK v2 stream of whole (non-delta) objects, terminated
1649/// by the trailing pack checksum at the repository hash width.
1650fn serialize_pack(odb: &Odb, oids: &[ObjectId], opts: &PackBuildOptions) -> Result<Vec<u8>> {
1651    let mut buf = Vec::new();
1652    buf.extend_from_slice(b"PACK");
1653    buf.extend_from_slice(&2u32.to_be_bytes());
1654    let count = u32::try_from(oids.len()).map_err(|_| {
1655        Error::Object(ObjectError::Corrupt {
1656            detail: "pack object count exceeds u32".to_owned(),
1657        })
1658    })?;
1659    buf.extend_from_slice(&count.to_be_bytes());
1660
1661    for oid in oids {
1662        let kind = odb.read_info(oid)?.kind;
1663        write_whole_pack_object_from_odb(&mut buf, odb, *oid, kind, opts)?;
1664    }
1665
1666    append_pack_trailer(&mut buf, odb.hash_algo());
1667    Ok(buf)
1668}
1669
1670/// Append one whole object from the ODB, streaming large blobs when needed.
1671fn write_whole_pack_object_from_odb(
1672    buf: &mut Vec<u8>,
1673    odb: &Odb,
1674    oid: ObjectId,
1675    kind: ObjectKind,
1676    opts: &PackBuildOptions,
1677) -> Result<()> {
1678    write_whole_pack_object_to_odb(buf, odb, oid, kind, opts, &CancelSignal::never()).map(|_| ())
1679}
1680
1681/// Write one whole object from the ODB to `w`, reusing on-disk pack bytes or streaming
1682/// blobs at or above [`Odb::big_file_threshold`].
1683pub(crate) fn write_whole_pack_object_to_odb(
1684    w: &mut dyn Write,
1685    odb: &Odb,
1686    oid: ObjectId,
1687    kind: ObjectKind,
1688    opts: &PackBuildOptions,
1689    stop: &CancelSignal<'_>,
1690) -> Result<u64> {
1691    if opts.reuse_objects && odb.hash_algo() == HashAlgo::Sha1 {
1692        if let Some((bytes, start, end)) =
1693            crate::pack::packed_full_object_range(odb.objects_dir(), &oid)?
1694        {
1695            write_all_chunked(w, &bytes[start..end])?;
1696            return Ok((end - start) as u64);
1697        }
1698    }
1699    let size = odb.read_info(&oid)?.size;
1700    let stream_from = odb.big_file_threshold()?;
1701    if kind == ObjectKind::Blob && size >= stream_from {
1702        let mut counter = ByteCounter { inner: w, n: 0 };
1703        odb.with_stream(&oid, |mut stream| {
1704            let payload_len = usize::try_from(stream.size).map_err(|_| {
1705                Error::Object(ObjectError::Corrupt {
1706                    detail: format!("object size overflow for {}", oid.to_hex()),
1707                })
1708            })?;
1709            encode_pack_object_header_to(&mut counter, pack_type_code(kind), payload_len)?;
1710            crate::odb::deflate_stream_to_writer(
1711                &mut stream.reader,
1712                stream.size,
1713                &mut counter,
1714                odb.pack_compression()?,
1715                stop,
1716            )?;
1717            Ok(())
1718        })?
1719        .ok_or_else(|| Error::Object(ObjectError::NotFound { name: oid.to_hex() }))?;
1720        return Ok(counter.n);
1721    }
1722    let obj = odb.read(&oid)?;
1723    stop.poll()?;
1724    write_whole_pack_object_to(w, odb, oid, kind, &obj.data, opts)
1725}
1726
1727fn encode_pack_object_header_to(w: &mut dyn Write, type_code: u8, size: usize) -> Result<()> {
1728    let mut header = Vec::new();
1729    encode_pack_object_header(&mut header, type_code, size);
1730    w.write_all(&header).map_err(Error::Io)?;
1731    Ok(())
1732}
1733
1734/// Write one whole (non-delta) pack object, reusing on-disk bytes when allowed.
1735fn write_whole_pack_object(
1736    buf: &mut Vec<u8>,
1737    odb: &Odb,
1738    oid: ObjectId,
1739    kind: ObjectKind,
1740    data: &[u8],
1741    opts: &PackBuildOptions,
1742) -> Result<()> {
1743    write_whole_pack_object_to(buf, odb, oid, kind, data, opts).map(|_| ())
1744}
1745
1746fn write_whole_pack_object_to(
1747    w: &mut dyn Write,
1748    odb: &Odb,
1749    oid: ObjectId,
1750    kind: ObjectKind,
1751    data: &[u8],
1752    opts: &PackBuildOptions,
1753) -> Result<u64> {
1754    let mut counter = ByteCounter { inner: w, n: 0 };
1755    if opts.reuse_objects && odb.hash_algo() == HashAlgo::Sha1 {
1756        if let Some((bytes, start, end)) =
1757            crate::pack::packed_full_object_range(odb.objects_dir(), &oid)?
1758        {
1759            write_all_chunked(&mut counter, &bytes[start..end])?;
1760            return Ok(counter.n);
1761        }
1762    }
1763    encode_pack_object_header_to(&mut counter, pack_type_code(kind), data.len())?;
1764    let compression = crate::pack_zlib::compression_for_payload(data, odb.pack_compression()?);
1765    write_zlib_to(&mut counter, data, compression)?;
1766    Ok(counter.n)
1767}
1768
1769/// Append the trailing pack checksum: the hash of everything written so far, at
1770/// the repository's hash width (SHA-1 → 20 bytes, SHA-256 → 32 bytes).
1771pub(crate) fn append_pack_trailer(buf: &mut Vec<u8>, algo: HashAlgo) {
1772    buf.extend_from_slice(&algo.checksum_digest(&*buf));
1773}
1774
1775/// Append `oid` from `odb` to an in-progress pack as one whole object (header + zlib body).
1776///
1777/// Returns the object's kind.
1778pub(crate) fn append_whole_object_from_odb(
1779    buf: &mut Vec<u8>,
1780    odb: &Odb,
1781    oid: ObjectId,
1782) -> Result<ObjectKind> {
1783    let obj = odb.read(&oid)?;
1784    write_whole_pack_object(
1785        buf,
1786        odb,
1787        oid,
1788        obj.kind,
1789        &obj.data,
1790        &PackBuildOptions::default(),
1791    )?;
1792    Ok(obj.kind)
1793}
1794
1795/// A single object to write, either whole or as a delta against a chosen base.
1796pub(crate) struct PlannedEntry {
1797    pub(crate) oid: ObjectId,
1798    pub(crate) kind: ObjectKind,
1799    /// `Some(base_oid)` when this entry is a delta against `base_oid`. The base may be
1800    /// an in-pack object or — for thin packs — an external base present only on the peer.
1801    pub(crate) base: Option<ObjectId>,
1802    /// Delta chosen by the delta search: uncompressed length and zlib-compressed
1803    /// instructions, ready to copy into the pack. When neither this nor
1804    /// [`Self::reused_delta_zlib`] is set for a delta, the writer computes it.
1805    pub(crate) searched_delta: Option<(usize, Vec<u8>)>,
1806    /// On-disk reuse: uncompressed size from the source pack header plus zlib
1807    /// bytes copied verbatim from a cached pack buffer (Git's `reuse_delta`).
1808    pub(crate) reused_delta_zlib:
1809        Option<(u64, std::sync::Arc<crate::pack::PackData>, usize, usize)>,
1810}
1811
1812/// The full delta plan: the ordered entries to emit. Payloads stay in the object
1813/// database and are read again when the pack is written.
1814pub(crate) struct DeltaPlan {
1815    pub(crate) entries: Vec<PlannedEntry>,
1816}
1817
1818/// A delta pack built in-process, with index rows that match the emitted stream.
1819pub(crate) struct SerializedDeltaPack {
1820    pub bytes: Vec<u8>,
1821    pub index_rows: Vec<(ObjectId, u64, u32)>,
1822    /// Pack bytes on disk when set ([`Self::bytes`] may be empty).
1823    pub staging_path: Option<std::path::PathBuf>,
1824}
1825
1826/// Kind and size of each of `oids`, in the same order, without inflating payloads.
1827fn read_object_infos(
1828    odb: &Odb,
1829    oids: &[ObjectId],
1830    search_threads: Option<usize>,
1831) -> Result<Vec<ObjectInfo>> {
1832    let mut none: Option<&mut dyn FnMut(u64)> = None;
1833    read_object_infos_with_progress(odb, oids, search_threads, &CancelSignal::never(), &mut none)
1834}
1835
1836fn read_object_infos_with_progress(
1837    odb: &Odb,
1838    oids: &[ObjectId],
1839    search_threads: Option<usize>,
1840    stop: &CancelSignal<'_>,
1841    on_objects: &mut Option<&mut dyn FnMut(u64)>,
1842) -> Result<Vec<ObjectInfo>> {
1843    let par = crate::pack_delta::pack_delta_search_parallel_options(odb, search_threads)?;
1844    let read = |oid: &ObjectId| odb.read_info(oid);
1845    let stride = crate::progress::OBJECT_PROGRESS_STRIDE as usize;
1846    if par.threads.get() <= 1 || oids.len() < 32 {
1847        let mut out = Vec::with_capacity(oids.len());
1848        for (i, oid) in oids.iter().enumerate() {
1849            stop.poll()?;
1850            out.push(read(oid)?);
1851            if (i + 1).is_multiple_of(stride) {
1852                if let Some(on) = on_objects.as_deref_mut() {
1853                    on(stride as u64);
1854                }
1855            }
1856        }
1857        let rem = oids.len() % stride;
1858        if rem != 0 {
1859            if let Some(on) = on_objects.as_deref_mut() {
1860                on(rem as u64);
1861            }
1862        }
1863        return Ok(out);
1864    }
1865    try_par_map_force(oids, par, read).map_err(|e| match e {
1866        ParallelHashError::Task(err) => err,
1867    })
1868}
1869
1870/// Reorder `entries` so every delta base that is in the pack precedes its targets.
1871///
1872/// Entries keep their relative order except that a not-yet-emitted base chain is
1873/// emitted, deepest base first, right before the first entry that needs it. Bases
1874/// outside the pack (thin-pack bases) are left alone. The entries are moved in place.
1875fn order_bases_first(entries: &mut [PlannedEntry]) {
1876    let n = entries.len();
1877    let bases: Vec<Option<usize>> = {
1878        let position: OidHashMap<usize> = entries
1879            .iter()
1880            .enumerate()
1881            .map(|(i, e)| (e.oid, i))
1882            .collect();
1883        entries
1884            .iter()
1885            .map(|e| e.base.and_then(|b| position.get(&b).copied()))
1886            .collect()
1887    };
1888    // `dest[i]`: the position entry `i` moves to.
1889    let mut dest = vec![usize::MAX; n];
1890    let mut next = 0usize;
1891    let mut chain = Vec::new();
1892    for i in 0..n {
1893        let mut cur = Some(i);
1894        while let Some(j) = cur {
1895            if dest[j] != usize::MAX || chain.len() > n {
1896                break;
1897            }
1898            chain.push(j);
1899            cur = bases[j];
1900        }
1901        while let Some(j) = chain.pop() {
1902            if dest[j] == usize::MAX {
1903                dest[j] = next;
1904                next += 1;
1905            }
1906        }
1907    }
1908    for i in 0..n {
1909        while dest[i] != i {
1910            let d = dest[i];
1911            entries.swap(i, d);
1912            dest.swap(i, d);
1913        }
1914    }
1915}
1916
1917/// Whether `objects_dir/pack` holds at least one `.pack` file.
1918pub(crate) fn objects_dir_has_local_packs(objects_dir: &Path) -> bool {
1919    let pack_dir = objects_dir.join("pack");
1920    if !pack_dir.is_dir() {
1921        return false;
1922    }
1923    std::fs::read_dir(&pack_dir)
1924        .ok()
1925        .into_iter()
1926        .flatten()
1927        .filter_map(|e| e.ok())
1928        .any(|e| e.path().extension().is_some_and(|ext| ext == "pack"))
1929}
1930
1931/// Select deltas for `send` and produce an ordered emit plan.
1932///
1933/// Only object kinds and sizes are read up front. New deltas come from the streaming
1934/// window search ([`crate::delta_search::search_deltas`]), which covers every object
1935/// kind, groups objects by kind, path name hash (`name_hashes`, for blobs and trees)
1936/// and size as Git does, and reads payloads from `odb` only while they are in the
1937/// window, so memory does not grow with the number or size of the objects packed.
1938/// Chains are depth-limited on [`crate::pack::apply_delta_depth_limit`]'s rule.
1939/// Correctness (re-indexability) is preserved because the chosen edges form no cycle,
1940/// even when on-disk deltas come from several packs, and every base is either in-pack
1941/// (emitted ahead of its targets) or, for thin packs, peer-held.
1942///
1943/// Two optional refinements:
1944///
1945/// * **Delta islands** (`opts.respect_islands`): when `pack.island` config marks
1946///   any ref, a target only deltas against a base in a compatible (superset)
1947///   island ([`crate::delta_islands::DeltaIslands::in_same_island`]). Islands
1948///   default to inactive (the prior behavior).
1949/// * **On-disk delta reuse** (`opts.reuse_deltas`): an existing
1950///   `REF_DELTA`/`OFS_DELTA` edge whose base is also in this pack is reused
1951///   verbatim ([`crate::pack::packed_ref_delta_reuse_slice`]) rather than
1952///   recomputed, still subject to island rules. Such objects and their bases are
1953///   neither targets nor bases of the search.
1954///
1955/// When `opts.thin`, trees and blobs may also delta against objects the receiver
1956/// holds, which are referenced via `REF_DELTA` and not emitted: the objects at the
1957/// same paths in the trees of the edge commits (Git's preferred bases, see
1958/// [`crate::pack_thin_bases::find_thin_bases`]), and for on-disk delta reuse any base
1959/// in `peer_held`. Edge commits are the parents of sent commits that `peer_commits`
1960/// (the selection's [`crate::pack_object_select::PackObjectSelection::have_closure`])
1961/// or `peer_held` contains.
1962#[allow(clippy::too_many_arguments)]
1963pub(crate) fn plan_deltas(
1964    odb: &Odb,
1965    send: &[ObjectId],
1966    peer_commits: &HashSet<ObjectId>,
1967    peer_held: Option<&ReachableSet>,
1968    opts: &PackBuildOptions,
1969    name_hashes: &HashMap<ObjectId, u32>,
1970    search_threads: Option<usize>,
1971    stop: &CancelSignal<'_>,
1972) -> Result<DeltaPlan> {
1973    crate::trace::trace_span!("grit.pack.plan_deltas");
1974    let has_local_packs = objects_dir_has_local_packs(odb.objects_dir());
1975    let reuse_on_disk = opts.reuse_deltas && odb.hash_algo() == HashAlgo::Sha1 && has_local_packs;
1976    let search = opts.window > 0 && opts.max_depth > 0;
1977    stop.poll()?;
1978    let infos = read_object_infos(odb, send, search_threads)?;
1979    stop.poll()?;
1980    let in_pack: HashSet<ObjectId> = if reuse_on_disk || opts.thin || opts.respect_islands {
1981        send.iter().copied().collect()
1982    } else {
1983        HashSet::new()
1984    };
1985
1986    // Delta islands (`--delta-islands`): only loaded when requested AND a git dir
1987    // is attached to the odb. An inactive island set (no `pack.island` config, or
1988    // no matched ref) imposes no restriction, so the common case is unaffected.
1989    let islands = load_islands_for_pack(odb, &in_pack, opts);
1990
1991    // A thin pack may delta against what the receiver holds at the paths it changes.
1992    let peer_has = |oid: &ObjectId| peer_held.is_some_and(|held| held.contains(oid));
1993    let thin_bases = if opts.thin && (reuse_on_disk || search) {
1994        crate::pack_thin_bases::find_thin_bases(
1995            odb,
1996            send,
1997            &infos,
1998            &|oid| in_pack.contains(oid),
1999            &|oid| peer_commits.contains(oid) || peer_has(oid),
2000            name_hashes,
2001            opts.window.max(1),
2002        )?
2003    } else {
2004        crate::pack_thin_bases::ThinBases::default()
2005    };
2006
2007    // target oid -> base oid (the object `target` deltas against).
2008    let mut delta_to_base: OidHashMap<ObjectId> = oid_hash_map();
2009    // Deltas whose instruction stream is reused verbatim from an existing pack.
2010    let mut reused_zlib: HashMap<ObjectId, crate::pack::OnDiskReuseZlibEntry> = HashMap::new();
2011
2012    // On-disk delta reuse runs even with `--window=0` (no new deltas), matching Git pack-objects.
2013    if reuse_on_disk {
2014        // A thin pack keeps an on-disk delta whose base the receiver already holds; it is
2015        // written as `REF_DELTA` and completed by the receiver.
2016        let reusable_base = |oid: &ObjectId| {
2017            in_pack.contains(oid) || (opts.thin && (thin_bases.oids.contains(oid) || peer_has(oid)))
2018        };
2019        reused_zlib = crate::pack::collect_packed_delta_reuse_for_send(
2020            odb.objects_dir(),
2021            &in_pack,
2022            &reusable_base,
2023        )?;
2024        stop.poll()?;
2025        reused_zlib.retain(|t, (base, ..)| {
2026            // A stored delta against some other object the receiver holds is kept only
2027            // when the search has no base at the object's own path to do better with.
2028            let far_peer_base = !in_pack.contains(base) && !thin_bases.oids.contains(base);
2029            !(far_peer_base && search && thin_bases.targets.contains(t))
2030                && *base != *t
2031                && islands.in_same_island(t, base)
2032        });
2033        delta_to_base.extend(reused_zlib.iter().map(|(t, (base, ..))| (*t, *base)));
2034        // An empty blob is always stored whole.
2035        for (oid, info) in send.iter().zip(&infos) {
2036            if info.kind == ObjectKind::Blob && info.size == 0 && reused_zlib.remove(oid).is_some()
2037            {
2038                delta_to_base.remove(oid);
2039            }
2040        }
2041    }
2042
2043    // An object that is the base of a reused on-disk delta keeps its content as it is:
2044    // it may only become a delta against something the receiver holds (which cannot
2045    // close a cycle), and only with room left for the chains that depend on it. With
2046    // no such bases it stays whole (or keeps its own on-disk delta).
2047    let reuse_dependents: OidHashMap<usize> = {
2048        let mut longest: OidHashMap<usize> = oid_hash_map();
2049        let ends = crate::pack::delta_chain_ends(
2050            delta_to_base.keys().copied(),
2051            delta_to_base.len(),
2052            |oid| delta_to_base.get(oid).copied(),
2053        );
2054        for target in reused_zlib.keys() {
2055            let (end, depth) = match ends.as_ref().and_then(|ends| ends.get(target)) {
2056                Some((end, depth)) => (end, depth as usize),
2057                None => {
2058                    let mut cur = *target;
2059                    let mut depth = 0usize;
2060                    while let Some(base) = delta_to_base.get(&cur) {
2061                        depth += 1;
2062                        cur = *base;
2063                        if depth > delta_to_base.len() {
2064                            break;
2065                        }
2066                    }
2067                    (cur, depth)
2068                }
2069            };
2070            let entry = longest.entry(end).or_insert(0);
2071            *entry = (*entry).max(depth);
2072        }
2073        longest
2074    };
2075
2076    let mut searched: OidHashMap<(usize, Vec<u8>)> = oid_hash_map();
2077    if search {
2078        let found = search_new_deltas(
2079            odb,
2080            send,
2081            &infos,
2082            &thin_bases,
2083            |oid| {
2084                delta_to_base.contains_key(oid)
2085                    || (thin_bases.oids.is_empty() && reuse_dependents.contains_key(oid))
2086            },
2087            &reuse_dependents,
2088            name_hashes,
2089            &islands,
2090            opts,
2091            search_threads,
2092            has_local_packs,
2093            stop.flag(),
2094        )?;
2095        stop.poll()?;
2096        for (target, base, delta) in found {
2097            delta_to_base.insert(target, base);
2098            searched.insert(target, delta);
2099        }
2100    }
2101    drop((in_pack, thin_bases));
2102
2103    if opts.max_depth > 0 && !delta_to_base.is_empty() {
2104        // Cap chain length. After snipping, any removed target reverts to whole. The
2105        // edges are acyclic: reused ones come without cycles, and the search neither
2106        // retargets a reused delta nor deltas the root of a reused chain against
2107        // anything in the pack.
2108        let cuts = crate::pack::delta_chain_cuts(
2109            delta_to_base.keys().copied(),
2110            delta_to_base.len(),
2111            |oid| delta_to_base.get(oid).copied(),
2112            opts.max_depth,
2113        );
2114        match cuts {
2115            Some(cuts) => {
2116                for target in cuts {
2117                    delta_to_base.remove(&target);
2118                }
2119            }
2120            None => {
2121                let mut delta_std: HashMap<ObjectId, ObjectId> = delta_to_base.drain().collect();
2122                crate::pack::cap_delta_chain_depth(&mut delta_std, opts.max_depth);
2123                delta_to_base.extend(delta_std);
2124            }
2125        }
2126    }
2127
2128    // Emit in discovery order (commits before their trees/blobs), pulling each in-pack
2129    // delta base ahead of its first target so deltas can use the compact OFS_DELTA.
2130    // A delta whose target was snipped reverts to a whole object.
2131    let mut entries: Vec<PlannedEntry> = send
2132        .iter()
2133        .zip(&infos)
2134        .map(|(&oid, info)| {
2135            let base = delta_to_base.remove(&oid);
2136            let (searched_delta, reused_delta_zlib) = match base {
2137                Some(_) => (
2138                    searched.remove(&oid),
2139                    reused_zlib
2140                        .remove(&oid)
2141                        .map(|(_, size, bytes, start, end)| (size, bytes, start, end)),
2142                ),
2143                None => (None, None),
2144            };
2145            PlannedEntry {
2146                oid,
2147                kind: info.kind,
2148                base,
2149                searched_delta,
2150                reused_delta_zlib,
2151            }
2152        })
2153        .collect();
2154    drop((infos, delta_to_base, searched, reused_zlib));
2155    order_bases_first(&mut entries);
2156    Ok(DeltaPlan { entries })
2157}
2158
2159/// A delta chosen by the search: target, base, and (delta length, zlib-compressed delta).
2160type SearchedDelta = (ObjectId, ObjectId, (usize, Vec<u8>));
2161
2162/// Run the windowed delta search over the objects of `send` (with `infos` in the same
2163/// order) that `skip` leaves, trying only pairs in compatible delta islands.
2164///
2165/// `thin_bases` join the search as bases only: they are never targets and never
2166/// written, so a delta found against one names an object the receiver holds. An
2167/// object in `reuse_dependents` (the base of reused on-disk deltas, with the longest
2168/// chain that depends on it) is only paired with those bases, leaving room for that
2169/// chain under the depth limit.
2170#[allow(clippy::too_many_arguments)]
2171fn search_new_deltas(
2172    odb: &Odb,
2173    send: &[ObjectId],
2174    infos: &[ObjectInfo],
2175    thin_bases: &crate::pack_thin_bases::ThinBases,
2176    skip: impl Fn(&ObjectId) -> bool,
2177    reuse_dependents: &OidHashMap<usize>,
2178    name_hashes: &HashMap<ObjectId, u32>,
2179    islands: &crate::delta_islands::DeltaIslands,
2180    opts: &PackBuildOptions,
2181    search_threads: Option<usize>,
2182    has_local_packs: bool,
2183    stop: &std::sync::atomic::AtomicBool,
2184) -> Result<Vec<SearchedDelta>> {
2185    u32::try_from(send.len() + thin_bases.bases.len()).map_err(|_| {
2186        Error::Object(ObjectError::Corrupt {
2187            detail: "too many objects for one pack".to_owned(),
2188        })
2189    })?;
2190    let ids: Vec<u32> = (0..send.len())
2191        .filter(|&i| infos[i].size > 0 && !skip(&send[i]))
2192        .map(|i| i as u32)
2193        .collect();
2194    // Pairs an earlier pack writer already compared inside one pack are skipped.
2195    let packed = if opts.reuse_deltas && has_local_packs {
2196        let oids: OidHashSet = ids.iter().map(|&i| send[i as usize]).collect();
2197        crate::pack::locate_packed_objects(odb.objects_dir(), &oids).ok()
2198    } else {
2199        None
2200    };
2201    let base_oids: Vec<ObjectId> = thin_bases.bases.iter().map(|b| b.oid).collect();
2202    let base_infos = read_object_infos(odb, &base_oids, search_threads)?;
2203    let mut candidates: Vec<crate::delta_search::DeltaCandidate> = ids
2204        .into_iter()
2205        .map(|id| {
2206            let oid = send[id as usize];
2207            let info = infos[id as usize];
2208            let slot = packed.as_ref().and_then(|p| p.get(&oid));
2209            crate::delta_search::DeltaCandidate {
2210                id,
2211                oid,
2212                kind: info.kind,
2213                size: info.size,
2214                name_hash: name_hashes.get(&oid).copied().unwrap_or(0),
2215                whole_in_pack: slot.filter(|s| s.whole).map(|s| s.pack),
2216                in_pack: slot.map(|s| s.pack),
2217                dependent_depth: reuse_dependents.get(&oid).copied().unwrap_or(0),
2218                base_only: false,
2219            }
2220        })
2221        .collect();
2222    drop(packed);
2223    candidates.extend(
2224        (send.len()..)
2225            .zip(thin_bases.bases.iter().zip(&base_infos))
2226            .filter(|(_, (base, info))| info.kind == base.kind && info.size > 0)
2227            .map(|(id, (base, info))| crate::delta_search::DeltaCandidate {
2228                id: id as u32,
2229                oid: base.oid,
2230                kind: info.kind,
2231                size: info.size,
2232                name_hash: base.name_hash,
2233                whole_in_pack: None,
2234                in_pack: None,
2235                dependent_depth: 0,
2236                base_only: true,
2237            }),
2238    );
2239    let oid_of = |id: u32| {
2240        let id = id as usize;
2241        send.get(id)
2242            .copied()
2243            .unwrap_or_else(|| base_oids[id - send.len()])
2244    };
2245    let window_memory = match opts.window_memory {
2246        Some(bytes) => bytes,
2247        None => crate::pack_delta::pack_config(odb)?.pack_window_memory_bytes(),
2248    };
2249    let threads = crate::pack_delta::pack_delta_search_parallel_options(odb, search_threads)?;
2250    let allowed = |target: &ObjectId, base: &ObjectId| {
2251        islands.in_same_island(target, base)
2252            && (!reuse_dependents.contains_key(target) || thin_bases.oids.contains(base))
2253    };
2254    let found = crate::delta_search::search_deltas(
2255        odb,
2256        candidates,
2257        crate::delta_search::DeltaSearchParams {
2258            window: opts.window,
2259            max_depth: opts.max_depth,
2260            window_memory,
2261            hash_len: odb.hash_algo().len(),
2262            compression: odb.pack_compression()?,
2263            threads: threads.threads.get(),
2264        },
2265        &allowed,
2266        stop,
2267    )?;
2268    Ok(found
2269        .into_iter()
2270        .map(|d| (oid_of(d.target), oid_of(d.base), (d.delta_len, d.zlib)))
2271        .collect())
2272}
2273
2274/// Load delta-island marks for the objects being packed, honoring
2275/// `opts.respect_islands`. Returns an inactive (no-op) island set when islands
2276/// are not requested, when the odb has no attached git directory, or when no
2277/// `pack.island` regex matches a ref — so callers can always consult the result
2278/// without a flag check.
2279fn load_islands_for_pack(
2280    odb: &Odb,
2281    in_pack: &HashSet<ObjectId>,
2282    opts: &PackBuildOptions,
2283) -> crate::delta_islands::DeltaIslands {
2284    if !opts.respect_islands {
2285        return crate::delta_islands::DeltaIslands::default();
2286    }
2287    let Some(git_dir) = odb.config_git_dir() else {
2288        return crate::delta_islands::DeltaIslands::default();
2289    };
2290    let Ok(repo) = crate::repo::Repository::open(git_dir, &RepositoryOptions::empty()) else {
2291        return crate::delta_islands::DeltaIslands::default();
2292    };
2293    crate::delta_islands::load_delta_islands(&repo, in_pack)
2294}
2295
2296/// zlib-deflate `data` and append it to `buf`.
2297fn write_zlib(buf: &mut Vec<u8>, data: &[u8], compression: Compression) -> Result<()> {
2298    write_zlib_to(buf, data, compression)
2299}
2300
2301fn write_zlib_to(w: &mut dyn Write, data: &[u8], compression: Compression) -> Result<()> {
2302    let mut enc = ZlibEncoder::new(w, compression);
2303    enc.write_all(data).map_err(Error::Io)?;
2304    enc.finish().map_err(Error::Io)?;
2305    Ok(())
2306}
2307
2308/// Encode an `OFS_DELTA` base distance (Git's offset varint). Lifted verbatim
2309/// from the CLI pack writer's `encode_git_ofs_delta_distance`.
2310pub(crate) fn encode_ofs_delta_distance(buf: &mut Vec<u8>, mut ofs: u64) {
2311    let mut dheader = [0u8; 32];
2312    let mut pos = dheader.len() - 1;
2313    dheader[pos] = (ofs & 0x7f) as u8;
2314    while {
2315        ofs >>= 7;
2316        ofs != 0
2317    } {
2318        pos -= 1;
2319        ofs -= 1;
2320        dheader[pos] = 0x80 | ((ofs & 0x7f) as u8);
2321    }
2322    buf.extend_from_slice(&dheader[pos..]);
2323}
2324
2325#[cfg(test)]
2326#[allow(clippy::unwrap_used, clippy::expect_used)]
2327pub(crate) mod tests {
2328    use super::*;
2329    use crate::pack_object_select::{enumerate_pack_objects, PackEnumerateOptions};
2330
2331    fn planned(n: u8, base: Option<u8>) -> PlannedEntry {
2332        let oid = |n: u8| ObjectId::from_bytes(&[n; 20]).unwrap();
2333        PlannedEntry {
2334            oid: oid(n),
2335            kind: ObjectKind::Blob,
2336            base: base.map(oid),
2337            searched_delta: None,
2338            reused_delta_zlib: None,
2339        }
2340    }
2341
2342    fn order_of(mut entries: Vec<PlannedEntry>) -> Vec<u8> {
2343        order_bases_first(&mut entries);
2344        entries.iter().map(|e| e.oid.as_bytes()[0]).collect()
2345    }
2346
2347    #[test]
2348    fn bases_are_ordered_before_their_targets() {
2349        // 1 -> 3 -> 5 chain discovered target-first; 9 is an out-of-pack (thin) base.
2350        let entries = vec![
2351            planned(1, Some(3)),
2352            planned(2, None),
2353            planned(3, Some(5)),
2354            planned(4, Some(9)),
2355            planned(5, None),
2356            planned(6, Some(2)),
2357        ];
2358        assert_eq!(order_of(entries), [5, 3, 1, 2, 4, 6]);
2359    }
2360
2361    #[test]
2362    fn base_cycles_do_not_hang_or_drop_entries() {
2363        let entries = vec![planned(1, Some(2)), planned(2, Some(1)), planned(3, None)];
2364        let mut order = order_of(entries);
2365        order.sort_unstable();
2366        assert_eq!(order, [1, 2, 3]);
2367    }
2368
2369    /// Enumerate everything reachable from `main` in a git-packed fixture.
2370    pub(crate) fn packed_selection(
2371        commits: usize,
2372    ) -> (
2373        tempfile::TempDir,
2374        Repository,
2375        crate::pack_object_select::PackObjectSelection,
2376    ) {
2377        let tmp = tempfile::tempdir().unwrap();
2378        let path = grit_test_support::git_packed_history(tmp.path(), commits);
2379        let tip = grit_test_support::git(&path, &["rev-parse", "main"]);
2380        let tip = ObjectId::from_hex(tip.trim()).unwrap();
2381        let repo = Repository::open(&path, &RepositoryOptions::empty()).unwrap();
2382        let empty = HashSet::new();
2383        let selection = enumerate_pack_objects(
2384            repo.odb(),
2385            &[tip],
2386            &[],
2387            &PackEnumerateOptions {
2388                filter: None,
2389                shallow_grafts: &empty,
2390                have_shallow_grafts: Some(&empty),
2391                use_bitmaps: false,
2392                exclude_objects: None,
2393                peer_odb: None,
2394                have_boundary: HaveBoundary::CommitClosure,
2395            },
2396        )
2397        .unwrap();
2398        (tmp, repo, selection)
2399    }
2400
2401    #[cfg_attr(
2402        not(feature = "full-tests"),
2403        ignore = "starts system git or is heavy; run with --features full-tests"
2404    )]
2405    #[test]
2406    fn serve_plan_reuses_on_disk_deltas() {
2407        let (_tmp, repo, selection) = packed_selection(80);
2408        let opts = PackBuildOptions::for_serve(None);
2409        let plan = plan_deltas(
2410            repo.odb(),
2411            &selection.send,
2412            &selection.have_closure,
2413            selection.peer_held.as_deref(),
2414            &opts,
2415            &selection.name_hashes,
2416            None,
2417            &CancelSignal::never(),
2418        )
2419        .unwrap();
2420
2421        let reused = plan
2422            .entries
2423            .iter()
2424            .filter(|e| e.reused_delta_zlib.is_some())
2425            .count();
2426        let trees_and_blobs = plan
2427            .entries
2428            .iter()
2429            .filter(|e| matches!(e.kind, ObjectKind::Tree | ObjectKind::Blob))
2430            .count();
2431        assert!(
2432            reused * 2 > trees_and_blobs,
2433            "most trees and blobs keep their on-disk delta ({reused} of {trees_and_blobs})"
2434        );
2435    }
2436
2437    /// A history of loose objects: a subdirectory of stable files plus two that change
2438    /// in every commit.
2439    fn loose_history(commits: usize) -> (tempfile::TempDir, Repository, ObjectId) {
2440        let tmp = tempfile::tempdir().unwrap();
2441        let dir = tmp.path();
2442        grit_test_support::git(dir, &["init", "-q", "-b", "main"]);
2443        std::fs::create_dir_all(dir.join("src")).unwrap();
2444        for i in 0..20 {
2445            std::fs::write(
2446                dir.join(format!("src/stable{i}.txt")),
2447                format!("stable {i}\n"),
2448            )
2449            .unwrap();
2450        }
2451        let mut lines: Vec<String> = (0..200).map(|i| format!("line {i} of the file")).collect();
2452        for c in 0..commits {
2453            lines[(c * 13) % 200] = format!("changed in commit {c}");
2454            std::fs::write(dir.join("src/file.txt"), lines.join("\n")).unwrap();
2455            std::fs::write(dir.join("src/other.txt"), format!("other {c}\n")).unwrap();
2456            grit_test_support::git(dir, &["add", "."]);
2457            grit_test_support::git(
2458                dir,
2459                &[
2460                    "-c",
2461                    "user.name=T",
2462                    "-c",
2463                    "user.email=t@e",
2464                    "commit",
2465                    "-qm",
2466                    "c",
2467                ],
2468            );
2469        }
2470        let tip = grit_test_support::git(dir, &["rev-parse", "main"]);
2471        let tip = ObjectId::from_hex(tip.trim()).unwrap();
2472        let repo = Repository::open(&dir.join(".git"), &RepositoryOptions::empty()).unwrap();
2473        (tmp, repo, tip)
2474    }
2475
2476    #[cfg_attr(
2477        not(feature = "full-tests"),
2478        ignore = "starts system git or is heavy; run with --features full-tests"
2479    )]
2480    #[test]
2481    fn loose_plan_deltifies_trees_and_blobs_with_compressed_search_output() {
2482        let (tmp, repo, tip) = loose_history(12);
2483        assert!(!objects_dir_has_local_packs(repo.odb().objects_dir()));
2484        let empty = HashSet::new();
2485        let opts = PackBuildOptions::for_local_copy(None);
2486        let selection = crate::pack_object_select::enumerate_pack_objects_naming(
2487            repo.odb(),
2488            &[tip],
2489            &[],
2490            &PackEnumerateOptions {
2491                filter: None,
2492                shallow_grafts: &empty,
2493                have_shallow_grafts: Some(&empty),
2494                use_bitmaps: false,
2495                exclude_objects: None,
2496                peer_odb: None,
2497                have_boundary: HaveBoundary::CommitClosure,
2498            },
2499            NameTrees::for_delta_search(&opts),
2500            false,
2501            &CancelSignal::never(),
2502        )
2503        .unwrap();
2504        let plan = plan_deltas(
2505            repo.odb(),
2506            &selection.send,
2507            &selection.have_closure,
2508            selection.peer_held.as_deref(),
2509            &opts,
2510            &selection.name_hashes,
2511            Some(1),
2512            &CancelSignal::never(),
2513        )
2514        .unwrap();
2515        let deltas_of = |kind| {
2516            plan.entries
2517                .iter()
2518                .filter(|e| e.kind == kind && e.base.is_some())
2519                .count()
2520        };
2521        assert!(deltas_of(ObjectKind::Blob) >= 10, "blob deltas");
2522        assert!(deltas_of(ObjectKind::Tree) >= 10, "subtree deltas");
2523        assert!(plan
2524            .entries
2525            .iter()
2526            .filter(|e| e.base.is_some())
2527            .all(|e| e.searched_delta.is_some()));
2528
2529        let pack = crate::pack_delta::serialize_pack_with_deltas(
2530            repo.odb(),
2531            &plan.entries,
2532            &opts,
2533            Some(2),
2534        )
2535        .unwrap();
2536        std::fs::write(tmp.path().join("plan.pack"), &pack.bytes).unwrap();
2537        grit_test_support::git(tmp.path(), &["index-pack", "--strict", "plan.pack"]);
2538    }
2539
2540    #[test]
2541    fn serve_options_follow_pack_config() {
2542        use crate::config::{ConfigFile, ConfigScope, ConfigSet};
2543        let file = ConfigFile::parse(
2544            Path::new(".git/config"),
2545            "[pack]\n\twindow = 4\n\tdepth = 0\n",
2546            ConfigScope::Local,
2547        )
2548        .unwrap();
2549        let mut cfg = ConfigSet::new();
2550        cfg.merge(&file);
2551        let opts = PackBuildOptions {
2552            thin: true,
2553            use_ofs_delta: false,
2554            ..PackBuildOptions::for_serve(Some(&cfg))
2555        };
2556        assert_eq!((opts.window, opts.max_depth), (4, 0));
2557        assert!(opts.thin && !opts.use_ofs_delta && opts.delta);
2558        assert!(
2559            opts.reuse_deltas,
2560            "like git upload-pack, depth 0 stops new deltas but still sends on-disk deltas"
2561        );
2562
2563        let defaults = PackBuildOptions::for_serve(None);
2564        assert_eq!(
2565            (defaults.window, defaults.max_depth),
2566            (10, crate::pack::DEFAULT_PACK_DEPTH)
2567        );
2568        assert!(defaults.reuse_deltas && defaults.reuse_objects && !defaults.thin);
2569    }
2570
2571    /// A merge being sent whose two receiver-held parents hold an old and the new
2572    /// `f.txt`; the new blob is also sent, so a held tree names a sent object at the
2573    /// path being changed.
2574    struct PeerHoldsSentBlob {
2575        dir: tempfile::TempDir,
2576        repo: Repository,
2577        old: ObjectId,
2578        new: ObjectId,
2579        /// The parents and everything they reach, in write order.
2580        peer_objects: Vec<ObjectId>,
2581        peer_commits: HashSet<ObjectId>,
2582        send: Vec<ObjectId>,
2583        name_hashes: HashMap<ObjectId, u32>,
2584    }
2585
2586    impl PeerHoldsSentBlob {
2587        fn new() -> Self {
2588            use crate::objects::{serialize_tree, TreeEntry};
2589            use crate::pack_name_hash::pack_name_hash;
2590            let dir = tempfile::TempDir::new().unwrap();
2591            let (repo, _) =
2592                Repository::init(dir.path(), &crate::repo::InitOptions::default()).expect("init");
2593            let odb = repo.odb();
2594            let tree = |entries: &[(&str, ObjectId)]| {
2595                let entries: Vec<TreeEntry> = entries
2596                    .iter()
2597                    .map(|&(name, oid)| TreeEntry {
2598                        mode: 0o100644,
2599                        name: name.as_bytes().to_vec(),
2600                        oid,
2601                    })
2602                    .collect();
2603                odb.write(ObjectKind::Tree, &serialize_tree(&entries))
2604                    .unwrap()
2605            };
2606            let commit = |tree: ObjectId, parents: &[ObjectId]| {
2607                let parents: String = parents
2608                    .iter()
2609                    .map(|p| format!("parent {}\n", p.to_hex()))
2610                    .collect();
2611                let body = format!(
2612                    "tree {}\n{parents}author A <a@example.com> 0 +0000\ncommitter A <a@example.com> 0 +0000\n\nc\n",
2613                    tree.to_hex()
2614                );
2615                odb.write(ObjectKind::Commit, body.as_bytes()).unwrap()
2616            };
2617            let lines: Vec<String> = (0..200).map(|i| format!("line {i} of f.txt")).collect();
2618            let old = odb
2619                .write(ObjectKind::Blob, lines.join("\n").as_bytes())
2620                .unwrap();
2621            let new = odb
2622                .write(
2623                    ObjectKind::Blob,
2624                    format!("{}\nmore\n", lines.join("\n")).as_bytes(),
2625                )
2626                .unwrap();
2627            let old_tree = tree(&[("f.txt", old)]);
2628            let new_tree = tree(&[("f.txt", new)]);
2629            let first = commit(old_tree, &[]);
2630            let second = commit(new_tree, &[]);
2631            let extra = odb.write(ObjectKind::Blob, b"extra\n").unwrap();
2632            let merge_tree = tree(&[("extra.txt", extra), ("f.txt", new)]);
2633            let merge = commit(merge_tree, &[first, second]);
2634            Self {
2635                dir,
2636                old,
2637                new,
2638                peer_objects: vec![old, new, old_tree, new_tree, first, second],
2639                peer_commits: HashSet::from([first, second]),
2640                send: vec![merge, merge_tree, new, extra],
2641                name_hashes: HashMap::from([
2642                    (new, pack_name_hash("f.txt")),
2643                    (extra, pack_name_hash("extra.txt")),
2644                ]),
2645                repo,
2646            }
2647        }
2648
2649        fn thin_plan(&self) -> DeltaPlan {
2650            plan_deltas(
2651                self.repo.odb(),
2652                &self.send,
2653                &self.peer_commits,
2654                None,
2655                &PackBuildOptions {
2656                    thin: true,
2657                    ..PackBuildOptions::for_serve(None)
2658                },
2659                &self.name_hashes,
2660                Some(1),
2661                &CancelSignal::never(),
2662            )
2663            .unwrap()
2664        }
2665    }
2666
2667    #[test]
2668    fn thin_pack_never_deltas_a_sent_blob_against_itself() {
2669        let fx = PeerHoldsSentBlob::new();
2670        let plan = fx.thin_plan();
2671        assert_eq!(plan.entries.len(), fx.send.len());
2672        for entry in &plan.entries {
2673            assert_ne!(
2674                entry.base,
2675                Some(entry.oid),
2676                "a delta against itself never resolves"
2677            );
2678        }
2679        let new = plan.entries.iter().find(|e| e.oid == fx.new).unwrap();
2680        assert_eq!(new.base, Some(fx.old), "the other held version is the base");
2681    }
2682
2683    #[cfg_attr(
2684        not(feature = "full-tests"),
2685        ignore = "starts system git or is heavy; run with --features full-tests"
2686    )]
2687    #[test]
2688    fn thin_pack_with_held_sent_blob_completes_in_git() {
2689        let fx = PeerHoldsSentBlob::new();
2690        let plan = fx.thin_plan();
2691        let opts = PackBuildOptions {
2692            thin: true,
2693            ..PackBuildOptions::for_serve(None)
2694        };
2695        let pack = crate::pack_delta::serialize_pack_with_deltas(
2696            fx.repo.odb(),
2697            &plan.entries,
2698            &opts,
2699            Some(1),
2700        )
2701        .unwrap();
2702
2703        let root = fx.dir.path();
2704        grit_test_support::git(root, &["init", "-q", "--bare", "peer"]);
2705        let peer = root.join("peer");
2706        for oid in &fx.peer_objects {
2707            let obj = fx.repo.odb().read(oid).unwrap();
2708            let written = grit_test_support::git_cmd(&[
2709                "hash-object",
2710                "-w",
2711                "--stdin",
2712                "-t",
2713                obj.kind.as_str(),
2714            ])
2715            .in_dir(&peer)
2716            .stdin(obj.data)
2717            .suc();
2718            assert_eq!(written.stdout.trim(), oid.to_hex());
2719        }
2720        grit_test_support::git_cmd(&["index-pack", "--strict", "--fix-thin", "--stdin"])
2721            .in_dir(&peer)
2722            .stdin(pack.bytes)
2723            .suc();
2724        let merge = fx.send[0].to_hex();
2725        grit_test_support::git(&peer, &["update-ref", "refs/heads/main", &merge]);
2726        grit_test_support::git(&peer, &["fsck", "--strict", "--no-dangling"]);
2727    }
2728}