Skip to main content

grit_lib/maintenance/
drop_blobs.rs

1//! Reclaim space in a partial clone by dropping large promised blobs.
2//!
3//! A partial clone fetches blobs on demand, and over time keeps every large blob it
4//! ever needed. The promisor remote still has them, so the local copies can go once
5//! nothing needs them nearby: they come back through the ordinary lazy fetch the
6//! next time something reads them. [`Maintenance::drop_promised_blobs`](crate::maintenance::Maintenance::drop_promised_blobs) does that for blobs
7//! stored in promisor packs, at or above a size, and not needed recently.
8//!
9//! A blob is dropped only when all of these hold:
10//!
11//! - it is stored in a `.promisor` pack, and nowhere else in this repository (not
12//!   loose, not in an ordinary pack), and none of its packs has a `.keep` marker;
13//! - a promisor can supply it again (see below);
14//! - some tree or tag stored in a promisor pack names it, so it stays a promised
15//!   object once it is gone (Git's rule for an acceptable missing object);
16//! - no worktree's index (nor the `GIT_INDEX_FILE` one, when set) or `HEAD` tree
17//!   uses it;
18//! - no commit named by a worktree's `HEAD` reflog since the cutoff uses it;
19//! - none of the promisor packs holding it was written or freshened since the
20//!   cutoff (a lazy fetch writes a new pack, so this is when it was last fetched).
21//!
22//! In a partial clone, a blob in a promisor pack came from the promisor remote, so
23//! it can be fetched again. That stops being true once [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs) has run:
24//! the promisor pack it writes also holds the blobs only this repository has (Git
25//! would delete them anywhere else; see [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs)). So the promisors this
26//! machine can read are checked directly: promisor remotes with a local URL (a path
27//! or `file://`) and the LOP directories offload recorded in
28//! [`LOP_GIT_DIR_KEY`]. A blob one of them stores in its own object directory (not
29//! through its alternates) can go; in a recorded LOP, only a copy in a pack offload
30//! wrote there counts, since the LOP's own `gc` prunes any other (nothing in it
31//! reaches a blob). A promisor that stores its objects where this repository does
32//! (a linked worktree of it, say) holds nothing for this. A blob none of them
33//! stores stays when every promisor was read ([`KeptBlobCounts::not_in_promisor`]),
34//! and also ([`KeptBlobCounts::unverified`]) when offload has run here, since the
35//! network promisors left cannot be asked without fetching, or when a local
36//! promisor cannot be read (its directory is not a repository now, an unmounted
37//! disk say, or uses another object format). Otherwise, a partial clone of network
38//! remotes only, the promisor pack is trusted as Git does, and nothing extra is
39//! read.
40//!
41//! [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs): crate::maintenance::offload_blobs
42//!
43//! Git 2.56 has a manual version of the same operation,
44//! `git repack -a -d --filter=blob:limit=<n> --drop-filtered`: the same candidates,
45//! without the recency and promise checks, and refusing to run when the index
46//! names a candidate rather than keeping it.
47
48use crate::error::ObjectError;
49use std::collections::HashMap;
50use std::path::{Path, PathBuf};
51use std::sync::Arc;
52use std::time::SystemTime;
53
54use smallvec::SmallVec;
55use time::OffsetDateTime;
56
57use crate::config::ConfigSet;
58use crate::environment::RepositoryOptions;
59use crate::error::{BadNumericSource, ConfigError, Error, Result};
60use crate::git_date::approx::approxidate_careful_at;
61use crate::index_pack::{install_pack_path_with_progress, IngestPackOptions};
62use crate::objects::{
63    oid_hash_map, oid_hash_set, CommitRef, ObjectId, ObjectKind, OidHashMap, OidHashSet,
64    TreeRefIter,
65};
66use crate::odb::Odb;
67use crate::offload::LOP_GIT_DIR_KEY;
68use crate::pack::PackedType;
69use crate::pack_index::PackIndex;
70use crate::pack_objects::PackBuildOptions;
71use crate::porcelain::MergeError;
72use crate::repo::error::FilesOnlyOperation;
73use crate::repo::Repository;
74use crate::repo::RepositoryError;
75use crate::state::InProgressOperation;
76
77use super::{GcLock, GcLockAttempt};
78
79/// Name of the maintenance task, as used in its config keys
80/// (`maintenance.drop-large-blobs.*`) and in `grit gc drop-large-blobs`.
81pub const DROP_LARGE_BLOBS_TASK: &str = "drop-large-blobs";
82
83/// Size threshold used when neither `maintenance.drop-large-blobs.minSize` nor a
84/// promisor remote's `blob:limit` filter gives one: 1 MiB.
85pub const DEFAULT_DROP_MIN_SIZE: u64 = 1 << 20;
86
87/// Recency window used when `maintenance.drop-large-blobs.expire` is unset: blobs
88/// needed in the last two weeks stay.
89pub const DEFAULT_DROP_EXPIRE: &str = "2.weeks.ago";
90
91const ENABLED_KEY: &str = "maintenance.drop-large-blobs.enabled";
92const MIN_SIZE_KEY: &str = "maintenance.drop-large-blobs.minsize";
93const EXPIRE_KEY: &str = "maintenance.drop-large-blobs.expire";
94
95/// The operation name used in errors.
96const OPERATION: &str = "drop-large-blobs";
97
98/// Options for [`Maintenance::drop_promised_blobs`](crate::maintenance::Maintenance::drop_promised_blobs).
99#[derive(Debug, Clone, PartialEq, Eq)]
100#[non_exhaustive]
101pub struct DropPromisedBlobsOptions {
102    /// Current time: for the `gc.pid` maintenance lock. Cutoffs are given explicitly
103    /// in [`Self::keep_newer_than`].
104    pub now: OffsetDateTime,
105    /// Drop blobs of at least this many bytes (uncompressed), like a
106    /// `blob:limit=<n>` filter.
107    pub min_size: u64,
108    /// Keep blobs needed at or after this time (see the module documentation for
109    /// what counts as needed). `None` keeps nothing for recency.
110    pub keep_newer_than: Option<OffsetDateTime>,
111    /// Work out what would be dropped without changing anything (and without taking
112    /// the maintenance lock).
113    pub dry_run: bool,
114    /// Pack writing and indexing threads (`None` reads `pack.threads`).
115    pub threads: Option<usize>,
116}
117
118impl DropPromisedBlobsOptions {
119    /// Options that drop blobs of `min_size` bytes or more not needed since
120    /// `keep_newer_than`, at time `now`.
121    #[must_use]
122    pub fn new(
123        now: OffsetDateTime,
124        min_size: u64,
125        keep_newer_than: Option<OffsetDateTime>,
126    ) -> Self {
127        Self {
128            now,
129            min_size,
130            keep_newer_than,
131            dry_run: false,
132            threads: None,
133        }
134    }
135
136    /// Options from `maintenance.drop-large-blobs.minSize` and
137    /// `maintenance.drop-large-blobs.expire`, at time `now`, with values the caller gives
138    /// (a command line's `--min-size` and `--older-than`) in place of the config ones.
139    ///
140    /// `minSize` takes Git's `k`/`m`/`g` suffixes. When unset it is the smallest
141    /// `blob:limit` among the promisor remotes' `partialCloneFilter`, or
142    /// [`DEFAULT_DROP_MIN_SIZE`]. `expire` is read with [`DropExpiry::parse`]
143    /// ([`DEFAULT_DROP_EXPIRE`] when unset). A config key that is overridden is not read,
144    /// so an invalid value there does not matter.
145    ///
146    /// # Parameters
147    ///
148    /// - `min_size`: replaces `maintenance.drop-large-blobs.minSize` and its defaults.
149    /// - `expiry`: replaces `maintenance.drop-large-blobs.expire`.
150    ///
151    /// # Returns
152    ///
153    /// `None` when the expiry in effect is [`DropExpiry::Never`].
154    ///
155    /// # Errors
156    ///
157    /// [`ConfigError::BadNumericValue`] for a `minSize` that is not a non-negative
158    /// size, and [`ConfigError::InvalidDate`] for an `expire` that is not a date, for the
159    /// keys that are read.
160    pub fn from_config(
161        config: &ConfigSet,
162        now: OffsetDateTime,
163        min_size: Option<u64>,
164        expiry: Option<DropExpiry>,
165    ) -> Result<Option<Self>> {
166        let expiry = match expiry {
167            Some(expiry) => expiry,
168            None => configured_expiry(config, now)?,
169        };
170        let keep_newer_than = match expiry {
171            DropExpiry::Never => return Ok(None),
172            DropExpiry::Immediately => None,
173            DropExpiry::KeepNewerThan(cutoff) => Some(cutoff),
174        };
175        let min_size = match min_size {
176            Some(min_size) => min_size,
177            None => configured_min_size(config)?,
178        };
179        Ok(Some(Self::new(now, min_size, keep_newer_than)))
180    }
181}
182
183/// How long recently needed blobs are kept: the value of
184/// `maintenance.drop-large-blobs.expire`, or of a command line's `--older-than`.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum DropExpiry {
187    /// `never` or `false`: nothing is dropped, and `gc` skips the phase.
188    Never,
189    /// `now` or `all`: nothing is kept for recency.
190    Immediately,
191    /// A date: blobs needed at or after it are kept.
192    KeepNewerThan(OffsetDateTime),
193}
194
195impl DropExpiry {
196    /// Parse `spec` (case-insensitive keywords, else a Git approxidate such as
197    /// `2.weeks.ago` or `2026-01-01`) relative to `now`.
198    ///
199    /// # Returns
200    ///
201    /// `None` when `spec` is neither a keyword nor a date.
202    #[must_use]
203    pub fn parse(spec: &str, now: OffsetDateTime) -> Option<Self> {
204        let spec = spec.trim();
205        if spec.eq_ignore_ascii_case("never") || spec.eq_ignore_ascii_case("false") {
206            return Some(Self::Never);
207        }
208        if spec.eq_ignore_ascii_case("now") || spec.eq_ignore_ascii_case("all") {
209            return Some(Self::Immediately);
210        }
211        if spec.is_empty() {
212            return None;
213        }
214        let mut err = 0;
215        let secs = approxidate_careful_at(spec, now.unix_timestamp(), Some(&mut err));
216        if err != 0 {
217            return None;
218        }
219        let cutoff = i64::try_from(secs)
220            .ok()
221            .and_then(|secs| OffsetDateTime::from_unix_timestamp(secs).ok())?;
222        Some(Self::KeepNewerThan(cutoff))
223    }
224}
225
226/// `maintenance.drop-large-blobs.enabled` (default false): whether `gc` runs the
227/// drop phase. The `grit gc drop-large-blobs` command runs regardless.
228///
229/// # Errors
230///
231/// [`Error::Config`] when the value is not a boolean.
232pub fn drop_large_blobs_enabled(config: &ConfigSet) -> Result<bool> {
233    Ok(config.get_bool(ENABLED_KEY)?.unwrap_or(false))
234}
235
236/// `expire`, or [`DEFAULT_DROP_EXPIRE`] when unset or empty.
237fn configured_expiry(config: &ConfigSet, now: OffsetDateTime) -> Result<DropExpiry> {
238    let spec = config
239        .value(EXPIRE_KEY)
240        .map(|s| s.trim().to_owned())
241        .filter(|s| !s.is_empty())
242        .unwrap_or_else(|| DEFAULT_DROP_EXPIRE.to_owned());
243    DropExpiry::parse(&spec, now).ok_or_else(|| {
244        Error::Config(ConfigError::InvalidDate {
245            key: EXPIRE_KEY.to_owned(),
246            value: spec,
247        })
248    })
249}
250
251/// `minSize`, or the smallest promisor `blob:limit`, or [`DEFAULT_DROP_MIN_SIZE`].
252fn configured_min_size(config: &ConfigSet) -> Result<u64> {
253    if let Some(entry) = config.get_last_entry(MIN_SIZE_KEY) {
254        let raw = entry.value.as_deref().unwrap_or_default();
255        let bad = |reason| {
256            Error::Config(ConfigError::BadNumericValue {
257                key: MIN_SIZE_KEY.to_owned(),
258                value: raw.to_owned(),
259                reason,
260            })
261        };
262        let value = crate::config::parse_git_config_int_strict(raw).map_err(|e| {
263            bad(match e {
264                crate::config::GitConfigIntStrictError::InvalidUnit => {
265                    BadNumericSource::InvalidUnit
266                }
267                crate::config::GitConfigIntStrictError::OutOfRange => BadNumericSource::OutOfRange,
268            })
269        })?;
270        return u64::try_from(value).map_err(|_| bad(BadNumericSource::OutOfRange));
271    }
272    Ok(
273        crate::promisor_remote::configured_promisor_remotes(config, &[])
274            .iter()
275            .filter_map(|remote| {
276                crate::partial_clone::stored_remote_filter(config, &remote.name)
277                    .and_then(|filter| filter.blob_limit_bytes())
278            })
279            .min()
280            .unwrap_or(DEFAULT_DROP_MIN_SIZE),
281    )
282}
283
284/// One blob [`Maintenance::drop_promised_blobs`](crate::maintenance::Maintenance::drop_promised_blobs) dropped (or, on a dry run, would drop).
285#[derive(Debug, Clone, PartialEq, Eq)]
286#[non_exhaustive]
287pub struct DroppedBlob {
288    /// The blob.
289    pub oid: ObjectId,
290    /// Its size, uncompressed.
291    pub size: u64,
292    /// A promisor pack it was stored in (the first, when several held it).
293    pub pack: PathBuf,
294}
295
296/// Why candidate blobs stayed. Each candidate is counted once, under the first
297/// reason that applies, in the order of the fields.
298#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
299#[non_exhaustive]
300pub struct KeptBlobCounts {
301    /// A promisor pack holding it has a `.keep` marker.
302    pub kept_pack: usize,
303    /// It is also stored loose or in a pack without `.promisor`, so dropping the
304    /// promisor copy would free nothing (and Git would no longer treat it as
305    /// promised).
306    pub outside_promisor_packs: usize,
307    /// Every promisor is on this machine and was read, and none stores it, so
308    /// nothing could supply it again.
309    pub not_in_promisor: usize,
310    /// No promisor this machine could read stores it, and the rest cannot be asked:
311    /// network remotes, which cannot be asked without fetching (counted here once
312    /// offload has put blobs only this repository has into its promisor packs, so
313    /// being in one proves nothing), or a local promisor that does not open as a
314    /// repository of this object format (an unmounted disk, say).
315    pub unverified: usize,
316    /// A worktree's index (or the `GIT_INDEX_FILE` one) or `HEAD` tree uses it.
317    pub checked_out: usize,
318    /// The tree of a commit a worktree's `HEAD` reflog named since the cutoff uses
319    /// it.
320    pub recently_checked_out: usize,
321    /// A promisor pack holding it was written (or freshened) since the cutoff.
322    pub recently_fetched: usize,
323    /// No tree or tag in a promisor pack names it, so once gone it would be missing
324    /// rather than promised.
325    pub not_promised_elsewhere: usize,
326}
327
328impl KeptBlobCounts {
329    /// All candidates kept, for any reason.
330    #[must_use]
331    pub fn total(&self) -> usize {
332        self.kept_pack
333            + self.outside_promisor_packs
334            + self.checked_out
335            + self.recently_checked_out
336            + self.recently_fetched
337            + self.not_promised_elsewhere
338            + self.not_in_promisor
339            + self.unverified
340    }
341}
342
343/// Why `gc` did not run its drop phase ([`DropPromisedBlobsReport::skipped`]).
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345#[non_exhaustive]
346pub enum DropPromisedBlobsSkip {
347    /// `maintenance.drop-large-blobs.enabled` is not true, or `expire` is `never`.
348    Disabled,
349    /// The repository has no promisor remote, so there is nothing to fetch back from.
350    NoPromisorRemote,
351    /// A worktree is in the middle of this operation, which may need the blobs.
352    OperationInProgress(InProgressOperation),
353    /// `extensions.preciousObjects` is set: objects are never deleted.
354    PreciousObjects,
355    /// The `gc` options carry no current time ([`super::GcOptions::now_unix`] is 0,
356    /// or not a representable time), so there is no recency cutoff to apply.
357    NoCurrentTime,
358}
359
360/// What [`Maintenance::drop_promised_blobs`](crate::maintenance::Maintenance::drop_promised_blobs) did, or with [`DropPromisedBlobsOptions::dry_run`]
361/// would do.
362#[derive(Debug, Clone, Default, PartialEq, Eq)]
363#[non_exhaustive]
364pub struct DropPromisedBlobsReport {
365    /// The size threshold used.
366    pub min_size: u64,
367    /// The recency cutoff used (`None`: no recency protection).
368    pub keep_newer_than: Option<OffsetDateTime>,
369    /// Blobs stored in promisor packs at or above [`Self::min_size`].
370    pub candidates: usize,
371    /// The blobs dropped (on a dry run, those that would be), sorted by id.
372    pub dropped: Vec<DroppedBlob>,
373    /// The candidates that stayed, by reason.
374    pub kept: KeptBlobCounts,
375    /// Bytes freed: the old packs' size (with index and reverse index) minus the
376    /// new ones'. On a dry run, an estimate: the packed size of the dropped entries.
377    pub bytes_reclaimed: u64,
378    /// Promisor packs rewritten without the dropped blobs.
379    pub packs_rewritten: usize,
380    /// Promisor packs removed because they held only dropped blobs.
381    pub packs_removed: usize,
382    /// Set when `gc` skipped the phase; the counts are then zero.
383    pub skipped: Option<DropPromisedBlobsSkip>,
384}
385
386impl DropPromisedBlobsReport {
387    fn skipped_for(reason: DropPromisedBlobsSkip) -> Self {
388        Self {
389            skipped: Some(reason),
390            ..Self::default()
391        }
392    }
393}
394
395/// Drop large blobs a promisor remote can supply again from `repo`'s promisor
396/// packs, keeping those needed recently (see the module documentation for the
397/// exact rules).
398///
399/// A blob stays unless a promisor can supply it again: after
400/// [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs) has run, or when a promisor remote has a
401/// local URL, that is checked in the promisor's own object directory
402/// ([`KeptBlobCounts::not_in_promisor`], [`KeptBlobCounts::unverified`]).
403///
404/// Nothing is fetched while deciding. Unless [`DropPromisedBlobsOptions::dry_run`]
405/// is set, the repository's `gc.pid` lock is held throughout. A promisor pack that
406/// held only dropped blobs is removed; any other affected one is rewritten without
407/// them (deltas against a dropped blob are re-encoded) and keeps its `.promisor`
408/// contents and its modification time, so the recency of the blobs it still holds
409/// survives. The new pack is on disk before the old one is removed. A
410/// multi-pack-index is rewritten without a bitmap.
411///
412/// # Parameters
413///
414/// - `repo`: a partial clone (or any repository with a promisor remote), files-backed.
415/// - `opts`: threshold, cutoff and time.
416///
417/// # Errors
418///
419/// - [`RepositoryError::UnsupportedObjectStore`] without a files-backed object store;
420/// - [`RepositoryError::PreciousObjectsRepository`] when `extensions.preciousObjects` is set;
421/// - [`crate::error::ObjectError::NoPromisorRemote`] when no remote is a promisor and
422///   `extensions.partialClone` is unset;
423/// - [`MergeError::OperationInProgress`] when a worktree is in the middle of a merge,
424///   rebase, cherry-pick, revert, am or bisect;
425/// - [`crate::repo::RepositoryError::MaintenanceRunning`] when another process holds `gc.pid`;
426/// - pack read, write and removal failures.
427pub(crate) fn drop_promised_blobs(
428    repo: &Repository,
429    opts: &DropPromisedBlobsOptions,
430) -> Result<DropPromisedBlobsReport> {
431    repo.odb()
432        .primary_store()
433        .require_files_primary(FilesOnlyOperation::DropLargeBlobs)?;
434    let config = repo.config().snapshot()?;
435    if let Some(refusal) = gate(repo, &config)? {
436        return Err(refusal.into());
437    }
438    let _lock = if opts.dry_run {
439        None
440    } else {
441        match GcLock::try_acquire(repo, opts.now.unix_timestamp())? {
442            GcLockAttempt::Acquired(lock) => Some(lock),
443            GcLockAttempt::Held(holder) => {
444                return Err(Error::Repository(RepositoryError::MaintenanceRunning {
445                    holder,
446                }))
447            }
448        }
449    };
450    run(repo, &config, opts)
451}
452
453/// What the `gc` drop phase will do, settled from config before `gc` changes
454/// anything, so a bad value fails the run before its first phase.
455pub(crate) enum GcDropPlan {
456    /// The phase reports this skip.
457    Skip(DropPromisedBlobsSkip),
458    /// The phase runs with these options (`dry_run` and `threads` still to set).
459    Run(DropPromisedBlobsOptions),
460}
461
462/// Settle the `gc` phase: off unless `maintenance.drop-large-blobs.enabled` is
463/// true, options from config, and the current time from `now_unix` (0 means none
464/// was given, which skips the phase rather than read a clock here).
465///
466/// # Errors
467///
468/// [`Error::Config`] for an invalid `enabled`, `minSize` or `expire`.
469pub(crate) fn plan_drop_for_gc(config: &ConfigSet, now_unix: i64) -> Result<GcDropPlan> {
470    if !drop_large_blobs_enabled(config)? {
471        return Ok(GcDropPlan::Skip(DropPromisedBlobsSkip::Disabled));
472    }
473    let now = (now_unix != 0)
474        .then(|| OffsetDateTime::from_unix_timestamp(now_unix).ok())
475        .flatten();
476    let Some(now) = now else {
477        // `expire` is relative to the time, so only `minSize` can be checked.
478        configured_min_size(config)?;
479        return Ok(GcDropPlan::Skip(DropPromisedBlobsSkip::NoCurrentTime));
480    };
481    Ok(
482        match DropPromisedBlobsOptions::from_config(config, now, None, None)? {
483            Some(opts) => GcDropPlan::Run(opts),
484            None => GcDropPlan::Skip(DropPromisedBlobsSkip::Disabled),
485        },
486    )
487}
488
489/// The `gc` phase: runs a [`GcDropPlan::Run`], and reports a skip instead of
490/// failing on the gates. The caller holds the `gc.pid` lock (unless `dry_run`).
491pub(crate) fn run_drop_for_gc(
492    repo: &Repository,
493    config: &ConfigSet,
494    plan: GcDropPlan,
495    dry_run: bool,
496    threads: Option<usize>,
497) -> Result<DropPromisedBlobsReport> {
498    let mut opts = match plan {
499        GcDropPlan::Skip(reason) => return Ok(DropPromisedBlobsReport::skipped_for(reason)),
500        GcDropPlan::Run(opts) => opts,
501    };
502    if let Some(refusal) = gate(repo, config)? {
503        return Ok(DropPromisedBlobsReport::skipped_for(refusal.into()));
504    }
505    opts.dry_run = dry_run;
506    opts.threads = threads;
507    run(repo, config, &opts)
508}
509
510/// Why the repository is not in a state to drop anything.
511enum Refusal {
512    PreciousObjects,
513    NoPromisorRemote,
514    InProgress(InProgressOperation),
515}
516
517impl From<Refusal> for DropPromisedBlobsSkip {
518    fn from(refusal: Refusal) -> Self {
519        match refusal {
520            Refusal::PreciousObjects => Self::PreciousObjects,
521            Refusal::NoPromisorRemote => Self::NoPromisorRemote,
522            Refusal::InProgress(op) => Self::OperationInProgress(op),
523        }
524    }
525}
526
527impl From<Refusal> for Error {
528    fn from(refusal: Refusal) -> Self {
529        match refusal {
530            Refusal::PreciousObjects => RepositoryError::PreciousObjectsRepository {
531                operation: OPERATION,
532            }
533            .into(),
534            Refusal::NoPromisorRemote => Error::Object(ObjectError::NoPromisorRemote {
535                operation: OPERATION,
536            }),
537            Refusal::InProgress(op) => MergeError::OperationInProgress(op).into(),
538        }
539    }
540}
541
542/// The checks that must pass before anything is considered: `None` when they do.
543fn gate(repo: &Repository, config: &ConfigSet) -> Result<Option<Refusal>> {
544    if config.bool_with_default("extensions.preciousobjects", false) {
545        return Ok(Some(Refusal::PreciousObjects));
546    }
547    if !crate::promisor::repo_treats_promisor_packs(config) {
548        return Ok(Some(Refusal::NoPromisorRemote));
549    }
550    for wt in crate::worktree::list_worktrees(repo)? {
551        if wt.is_bare {
552            continue;
553        }
554        if let Some(op) = crate::state::detect_in_progress(&wt.admin_dir).first() {
555            return Ok(Some(Refusal::InProgress(*op)));
556        }
557    }
558    Ok(None)
559}
560
561/// A promisor pack in the local object directory.
562struct PromisorPack {
563    idx: Arc<PackIndex>,
564    mtime: Option<SystemTime>,
565    kept: bool,
566    /// Index rows of the trees and tags it stores.
567    referrers: Vec<u32>,
568    /// Index rows of the commits it stores.
569    commits: Vec<u32>,
570}
571
572/// A blob of at least the threshold stored in promisor packs.
573struct Candidate {
574    size: u64,
575    /// Indexes into the promisor pack list.
576    packs: SmallVec<[u32; 1]>,
577    /// Packed bytes of its entries (the dry-run estimate).
578    entry_bytes: u64,
579}
580
581fn run(
582    repo: &Repository,
583    config: &ConfigSet,
584    opts: &DropPromisedBlobsOptions,
585) -> Result<DropPromisedBlobsReport> {
586    let odb = repo.odb();
587    let pack_dir = odb.objects_dir().join("pack");
588    odb.reprepare_local_packs();
589    let (promisor, others): (Vec<_>, Vec<_>) = odb
590        .local_pack_indexes()?
591        .into_iter()
592        .partition(|idx| idx.is_promisor);
593    let mut packs: Vec<PromisorPack> = promisor
594        .into_iter()
595        .map(|idx| PromisorPack {
596            mtime: std::fs::metadata(&idx.pack_path)
597                .and_then(|m| m.modified())
598                .ok(),
599            kept: super::pack_has_keep_marker(&pack_dir, &idx.pack_path),
600            idx,
601            referrers: Vec::new(),
602            commits: Vec::new(),
603        })
604        .collect();
605    // Same order on every run, so the report's pack names are stable.
606    packs.sort_by(|a, b| a.idx.pack_path.cmp(&b.idx.pack_path));
607
608    let mut report = DropPromisedBlobsReport {
609        min_size: opts.min_size,
610        keep_newer_than: opts.keep_newer_than,
611        ..DropPromisedBlobsReport::default()
612    };
613    let mut candidates: OidHashMap<Candidate> = oid_hash_map();
614    for (pack_no, pack) in packs.iter_mut().enumerate() {
615        scan_pack(odb, pack, pack_no as u32, opts.min_size, &mut candidates)?;
616    }
617    report.candidates = candidates.len();
618    if candidates.is_empty() {
619        return Ok(report);
620    }
621
622    // Decide each candidate's fate; the first reason that applies wins.
623    let cutoff = opts.keep_newer_than.map(SystemTime::from);
624    let mut stored_only_here: OidHashSet = oid_hash_set();
625    for (oid, cand) in &candidates {
626        let holding = || cand.packs.iter().map(|&p| &packs[p as usize]);
627        if holding().any(|p| p.kept) {
628            report.kept.kept_pack += 1;
629        } else if odb.local_loose_file_size(oid).is_some()
630            || others.iter().any(|idx| idx.find_position(oid).is_some())
631        {
632            report.kept.outside_promisor_packs += 1;
633        } else {
634            stored_only_here.insert(*oid);
635        }
636    }
637    // Before the walks: in an offloaded repository most candidates stop here.
638    let mut undecided =
639        PromisorSupply::load(repo, config).suppliable(stored_only_here, &mut report.kept)?;
640    let mut walk = ProtectionWalk::new(odb, &undecided);
641    walk.mark_checkouts(repo)?;
642    let checked_out = std::mem::take(&mut walk.hits);
643    if let Some(cutoff) = opts.keep_newer_than {
644        walk.mark_recent_heads(repo, cutoff)?;
645    }
646    let recently_checked_out = std::mem::take(&mut walk.hits);
647    drop(walk);
648    report.kept.checked_out = checked_out.len();
649    report.kept.recently_checked_out = recently_checked_out.len();
650    undecided.retain(|oid| !checked_out.contains(oid) && !recently_checked_out.contains(oid));
651    undecided.retain(|oid| {
652        let fresh = cutoff.is_some_and(|cutoff| {
653            candidates[oid]
654                .packs
655                .iter()
656                .filter_map(|&p| packs[p as usize].mtime)
657                .any(|mtime| mtime >= cutoff)
658        });
659        if fresh {
660            report.kept.recently_fetched += 1;
661        }
662        !fresh
663    });
664    let promised = promised_by_promisor_packs(odb, &packs, &undecided)?;
665    report.kept.not_promised_elsewhere = undecided.len() - promised.len();
666    let drop_set = promised;
667
668    let mut dropped: Vec<DroppedBlob> = drop_set
669        .iter()
670        .map(|oid| {
671            let cand = &candidates[oid];
672            DroppedBlob {
673                oid: *oid,
674                size: cand.size,
675                pack: cand
676                    .packs
677                    .first()
678                    .map(|&p| packs[p as usize].idx.pack_path.clone())
679                    .unwrap_or_default(),
680            }
681        })
682        .collect();
683    dropped.sort_by_key(|d| d.oid);
684    report.dropped = dropped;
685    if drop_set.is_empty() {
686        return Ok(report);
687    }
688    if opts.dry_run {
689        report.bytes_reclaimed = drop_set.iter().map(|oid| candidates[oid].entry_bytes).sum();
690        return Ok(report);
691    }
692
693    let mut affected: Vec<u32> = drop_set
694        .iter()
695        .flat_map(|oid| candidates[oid].packs.iter().copied())
696        .collect();
697    affected.sort_unstable();
698    affected.dedup();
699    rewrite_packs(
700        repo,
701        config,
702        opts,
703        &packs,
704        &affected,
705        &drop_set,
706        &mut report,
707    )?;
708    Ok(report)
709}
710
711/// The promisors `drop-large-blobs` can check without fetching, and whether it
712/// must.
713struct PromisorSupply {
714    /// Promisors on this machine that opened: promisor remotes with a local URL,
715    /// and the LOPs offload recorded in [`LOP_GIT_DIR_KEY`].
716    local: Vec<LocalPromisor>,
717    /// Some promisor on this machine could not be read: its directory does not
718    /// open as a repository (an unmounted disk, say) or uses another object format.
719    /// What it holds is unknown, so blobs no readable promisor has are kept.
720    unreadable: bool,
721    /// Some promisor is on this machine (read or not, or `repo` itself).
722    any_local: bool,
723    /// Some promisor remote has a network URL.
724    network: bool,
725    /// [`LOP_GIT_DIR_KEY`] is set: offload has put blobs only this repository has
726    /// into its promisor packs.
727    offloaded: bool,
728}
729
730/// A promisor on this machine, and which of its copies count.
731struct LocalPromisor {
732    repo: Repository,
733    /// A LOP offload recorded: only its packs offload wrote count (see
734    /// [`crate::offload::lop_keep_packs`]). Nothing reaches a blob in a ref-less
735    /// LOP, so its own `gc` prunes any other copy.
736    lop: bool,
737}
738
739impl PromisorSupply {
740    /// The promisors of `repo` per `config`.
741    ///
742    /// A local promisor that stores its objects where `repo` does (`repo` itself, a
743    /// linked worktree of it, an `objects/` linked to its) supplies nothing. One
744    /// that does not open as a repository of the same object format is
745    /// [`Self::unreadable`].
746    fn load(repo: &Repository, config: &ConfigSet) -> Self {
747        let recorded: Vec<PathBuf> = config
748            .values_all(LOP_GIT_DIR_KEY)
749            .into_iter()
750            .filter(|v| !v.trim().is_empty())
751            .map(PathBuf::from)
752            .collect();
753        let mut dirs: Vec<(PathBuf, bool)> = recorded.iter().map(|d| (d.clone(), true)).collect();
754        let mut network = false;
755        for remote in crate::promisor_remote::configured_promisor_remotes(config, &[]) {
756            let Some(url) = remote.url else { continue };
757            if crate::transport_path::is_local_path_remote_url(&url) {
758                let dir = crate::transport_path::resolve_local_remote_git_dir(
759                    &url,
760                    repo.git_dir(),
761                    repo.work_tree(),
762                );
763                dirs.push((dir, false));
764            } else {
765                network = true;
766            }
767        }
768        let mut supply = Self {
769            local: Vec::new(),
770            unreadable: false,
771            any_local: !dirs.is_empty(),
772            network,
773            offloaded: !recorded.is_empty(),
774        };
775        for (dir, lop) in dirs {
776            let opened = Repository::open(
777                &dir,
778                &RepositoryOptions::with_environment(repo.environment().clone()),
779            );
780            let other = match opened {
781                Ok(other) if other.odb().hash_algo() == repo.odb().hash_algo() => other,
782                _ => {
783                    supply.unreadable = true;
784                    continue;
785                }
786            };
787            if crate::offload::same_object_store(&other, repo) {
788                continue;
789            }
790            // Listed twice (a recorded LOP that is also a remote): the first, LOP, rule.
791            if supply
792                .local
793                .iter()
794                .any(|p| crate::offload::same_object_store(&other, &p.repo))
795            {
796                continue;
797            }
798            supply.local.push(LocalPromisor { repo: other, lop });
799        }
800        supply
801    }
802
803    /// The blobs of `promised` a promisor can supply again; the rest are counted
804    /// in `kept`.
805    ///
806    /// A partial clone of network remotes only (no local promisor, no offload) is
807    /// trusted without reading anything. Otherwise a blob goes only if a local
808    /// promisor holds it, or, without offload and with every local promisor read,
809    /// a network one may.
810    fn suppliable(&self, promised: OidHashSet, kept: &mut KeptBlobCounts) -> Result<OidHashSet> {
811        if !self.any_local && !self.offloaded {
812            return Ok(promised);
813        }
814        if promised.is_empty() {
815            return Ok(promised);
816        }
817        let mut stores = Vec::with_capacity(self.local.len());
818        for promisor in &self.local {
819            let odb = promisor.repo.odb();
820            let indexes = if promisor.lop {
821                crate::offload::lop_keep_packs(odb)?
822            } else {
823                odb.local_pack_indexes()?
824            };
825            stores.push((odb, indexes, !promisor.lop));
826        }
827        let held = |oid: &ObjectId| {
828            stores.iter().any(|(odb, indexes, loose_counts)| {
829                indexes.iter().any(|idx| idx.find_position(oid).is_some())
830                    || (*loose_counts && odb.local_loose_file_size(oid).is_some())
831            })
832        };
833        let trust_network = self.network && !self.offloaded && !self.unreadable;
834        let mut out = oid_hash_set();
835        for oid in promised {
836            if held(&oid) || trust_network {
837                out.insert(oid);
838            } else if self.network || self.unreadable {
839                kept.unverified += 1;
840            } else {
841                kept.not_in_promisor += 1;
842            }
843        }
844        Ok(out)
845    }
846}
847
848/// Record `pack`'s blobs of at least `min_size` in `candidates`, and its trees and
849/// tags in [`PromisorPack::referrers`]. Only entry headers are decoded, plus the
850/// start of each blob delta for its size.
851fn scan_pack(
852    odb: &Odb,
853    pack: &mut PromisorPack,
854    pack_no: u32,
855    min_size: u64,
856    candidates: &mut OidHashMap<Candidate>,
857) -> Result<()> {
858    let idx = Arc::clone(&pack.idx);
859    let data = crate::pack::read_pack_bytes_cached(&idx.pack_path)?;
860    let bytes: &[u8] = &data;
861    let pack_end = (bytes.len() as u64).saturating_sub(idx.hash_bytes() as u64);
862    let mut kinds = EntryKinds::new(odb, &idx, bytes);
863    for pos in 0..idx.len() {
864        match kinds.kind(pos)? {
865            Some(ObjectKind::Blob) => {}
866            Some(ObjectKind::Tree | ObjectKind::Tag) => {
867                pack.referrers.push(pos as u32);
868                continue;
869            }
870            Some(ObjectKind::Commit) => {
871                pack.commits.push(pos as u32);
872                continue;
873            }
874            None => continue,
875        }
876        let offset = idx.offset_at(pos)?;
877        let size = entry_result_size(bytes, offset, idx.hash_bytes())?;
878        if size < min_size {
879            continue;
880        }
881        let oid = ObjectId::from_bytes(idx.oid_at(pos))?;
882        let entry_bytes = idx
883            .next_pack_offset_after(offset, pack_end)?
884            .saturating_sub(offset);
885        let cand = candidates.entry(oid).or_insert_with(|| Candidate {
886            size,
887            packs: SmallVec::new(),
888            entry_bytes: 0,
889        });
890        cand.packs.push(pack_no);
891        cand.entry_bytes += entry_bytes;
892    }
893    Ok(())
894}
895
896/// The uncompressed size of the entry at `offset`: its header size for a whole
897/// object, the result size recorded at the start of a delta.
898fn entry_result_size(bytes: &[u8], offset: u64, hash_bytes: usize) -> Result<u64> {
899    let mut pos = usize::try_from(offset).map_err(|_| {
900        Error::Object(ObjectError::Corrupt {
901            detail: "pack offset out of range".to_owned(),
902        })
903    })?;
904    let (packed, size) = crate::pack::parse_pack_object_header(bytes, &mut pos)?;
905    match packed {
906        PackedType::OfsDelta => {
907            crate::pack::parse_ofs_delta_base(bytes, &mut pos, offset)?;
908        }
909        PackedType::RefDelta => pos += hash_bytes,
910        _ => return Ok(size),
911    }
912    crate::pack::read_delta_result_size_from_pack_zlib(bytes, &mut pos)
913}
914
915/// Kinds of a pack's entries from their headers, following delta chains to their
916/// bases and remembering every entry resolved.
917struct EntryKinds<'a> {
918    odb: &'a Odb,
919    idx: &'a PackIndex,
920    bytes: &'a [u8],
921    /// Per index row: 0 unknown, 1-4 commit/tree/blob/tag, 5 unresolvable.
922    kinds: Vec<u8>,
923}
924
925/// Deepest delta chain followed before the pack is treated as corrupt.
926const MAX_CHAIN: usize = 10_000;
927
928impl<'a> EntryKinds<'a> {
929    fn new(odb: &'a Odb, idx: &'a PackIndex, bytes: &'a [u8]) -> Self {
930        Self {
931            odb,
932            idx,
933            bytes,
934            kinds: vec![0; idx.len()],
935        }
936    }
937
938    fn encode(kind: Option<ObjectKind>) -> u8 {
939        match kind {
940            Some(ObjectKind::Commit) => 1,
941            Some(ObjectKind::Tree) => 2,
942            Some(ObjectKind::Blob) => 3,
943            Some(ObjectKind::Tag) => 4,
944            None => 5,
945        }
946    }
947
948    fn decode(code: u8) -> Option<ObjectKind> {
949        match code {
950            1 => Some(ObjectKind::Commit),
951            2 => Some(ObjectKind::Tree),
952            3 => Some(ObjectKind::Blob),
953            4 => Some(ObjectKind::Tag),
954            _ => None,
955        }
956    }
957
958    /// The kind of the object at index row `pos`; `None` when its delta base is in
959    /// neither this pack nor the local object store.
960    fn kind(&mut self, pos: usize) -> Result<Option<ObjectKind>> {
961        let corrupt = |what: &str| {
962            Error::Object(ObjectError::Corrupt {
963                detail: format!("{what} in {}", self.idx.pack_path.display()),
964            })
965        };
966        let mut chain: Vec<usize> = Vec::new();
967        let mut cur = pos;
968        let kind = loop {
969            if self.kinds[cur] != 0 {
970                break Self::decode(self.kinds[cur]);
971            }
972            if chain.len() > MAX_CHAIN {
973                return Err(corrupt("delta chain too deep"));
974            }
975            chain.push(cur);
976            let offset = self.idx.offset_at(cur)?;
977            let mut at =
978                usize::try_from(offset).map_err(|_| corrupt("pack offset out of range"))?;
979            let (packed, _) = crate::pack::parse_pack_object_header(self.bytes, &mut at)?;
980            match packed {
981                PackedType::Commit => break Some(ObjectKind::Commit),
982                PackedType::Tree => break Some(ObjectKind::Tree),
983                PackedType::Blob => break Some(ObjectKind::Blob),
984                PackedType::Tag => break Some(ObjectKind::Tag),
985                PackedType::OfsDelta => {
986                    let base = crate::pack::parse_ofs_delta_base(self.bytes, &mut at, offset)?;
987                    cur = self
988                        .idx
989                        .find_position_by_offset_sorted(base)?
990                        .ok_or_else(|| corrupt("delta base offset not in index"))?;
991                }
992                PackedType::RefDelta => {
993                    let hash_bytes = self.idx.hash_bytes();
994                    let raw = self
995                        .bytes
996                        .get(at..at + hash_bytes)
997                        .ok_or_else(|| corrupt("truncated delta base id"))?;
998                    let base = ObjectId::from_bytes(raw)?;
999                    match self.idx.find_position(&base) {
1000                        Some(base_pos) => cur = base_pos,
1001                        None => match self.odb.read_info_without_fetch(&base) {
1002                            Ok(info) => break Some(info.kind),
1003                            Err(Error::Object(ObjectError::NotFound { .. })) => break None,
1004                            Err(err) => return Err(err),
1005                        },
1006                    }
1007                }
1008            }
1009        };
1010        let code = Self::encode(kind);
1011        for row in chain {
1012            self.kinds[row] = code;
1013        }
1014        Ok(kind)
1015    }
1016}
1017
1018/// The blobs of `wanted` some tree or tag stored in a promisor pack names: Git's
1019/// one-hop rule for a promised object. Stops reading once every one is found.
1020///
1021/// Trees are read breadth first from the root trees of the commits in promisor
1022/// packs, so the usual case, large files a few directories down the history the
1023/// clone fetched, is settled after reading the top levels. Promisor-pack trees and
1024/// tags that walk does not reach (a fetch by id, a tree only a non-promisor tree
1025/// names) are read afterwards, until every blob is found or none is left.
1026fn promised_by_promisor_packs(
1027    odb: &Odb,
1028    packs: &[PromisorPack],
1029    wanted: &OidHashSet,
1030) -> Result<OidHashSet> {
1031    let mut found = oid_hash_set();
1032    if wanted.is_empty() {
1033        return Ok(found);
1034    }
1035    let oid_len = odb.hash_algo().len();
1036    let mut read: Vec<Vec<bool>> = packs.iter().map(|_| Vec::new()).collect();
1037    let mut referrer = |pack_no: usize,
1038                        row: usize,
1039                        queue: Option<&mut std::collections::VecDeque<ObjectId>>,
1040                        found: &mut OidHashSet|
1041     -> Result<()> {
1042        let seen = &mut read[pack_no];
1043        if seen.is_empty() {
1044            *seen = vec![false; packs[pack_no].idx.len()];
1045        }
1046        if std::mem::replace(&mut seen[row], true) {
1047            return Ok(());
1048        }
1049        let idx = &packs[pack_no].idx;
1050        let obj = crate::pack::read_object_at(idx, idx.offset_at(row)?)?;
1051        match obj.kind {
1052            ObjectKind::Tree => {
1053                let mut queue = queue;
1054                for entry in TreeRefIter::with_oid_len(&obj.data, oid_len) {
1055                    let entry = entry?;
1056                    match entry.mode & 0o170000 {
1057                        0o040000 => {
1058                            if let Some(q) = queue.as_deref_mut() {
1059                                q.push_back(entry.oid);
1060                            }
1061                        }
1062                        0o160000 => {}
1063                        _ if wanted.contains(&entry.oid) => {
1064                            found.insert(entry.oid);
1065                        }
1066                        _ => {}
1067                    }
1068                }
1069            }
1070            ObjectKind::Tag => {
1071                if let Some(target) = crate::objects::tag_object_line_oid(&obj.data) {
1072                    if wanted.contains(&target) {
1073                        found.insert(target);
1074                    }
1075                }
1076            }
1077            ObjectKind::Blob | ObjectKind::Commit => {}
1078        }
1079        Ok(())
1080    };
1081    let locate = |oid: &ObjectId| {
1082        packs
1083            .iter()
1084            .enumerate()
1085            .find_map(|(n, p)| p.idx.find_position(oid).map(|row| (n, row)))
1086    };
1087
1088    let mut queue: std::collections::VecDeque<ObjectId> = std::collections::VecDeque::new();
1089    for pack in packs {
1090        for &row in &pack.commits {
1091            let obj = crate::pack::read_object_at(&pack.idx, pack.idx.offset_at(row as usize)?)?;
1092            if obj.kind == ObjectKind::Commit {
1093                queue.push_back(CommitRef::parse(&obj.data)?.tree());
1094            }
1095        }
1096    }
1097    let mut trees_seen = oid_hash_set();
1098    while let Some(tree) = queue.pop_front() {
1099        if found.len() == wanted.len() {
1100            return Ok(found);
1101        }
1102        if !trees_seen.insert(tree) {
1103            continue;
1104        }
1105        // A tree outside promisor packs names nothing promised; the scan below still
1106        // reads any promisor-pack trees under it.
1107        if let Some((pack_no, row)) = locate(&tree) {
1108            referrer(pack_no, row, Some(&mut queue), &mut found)?;
1109        }
1110    }
1111    drop(trees_seen);
1112    for (pack_no, pack) in packs.iter().enumerate() {
1113        for &row in &pack.referrers {
1114            if found.len() == wanted.len() {
1115                return Ok(found);
1116            }
1117            referrer(pack_no, row as usize, None, &mut found)?;
1118        }
1119    }
1120    Ok(found)
1121}
1122
1123/// Marks the candidate blobs checkouts and recent `HEAD`s use. Trees are read
1124/// once across all walks; missing objects are skipped, never fetched.
1125struct ProtectionWalk<'a> {
1126    odb: &'a Odb,
1127    wanted: &'a OidHashSet,
1128    trees_seen: OidHashSet,
1129    hits: OidHashSet,
1130}
1131
1132impl<'a> ProtectionWalk<'a> {
1133    fn new(odb: &'a Odb, wanted: &'a OidHashSet) -> Self {
1134        Self {
1135            odb,
1136            wanted,
1137            trees_seen: oid_hash_set(),
1138            hits: oid_hash_set(),
1139        }
1140    }
1141
1142    fn mark(&mut self, oid: ObjectId) {
1143        if self.wanted.contains(&oid) {
1144            self.hits.insert(oid);
1145        }
1146    }
1147
1148    fn walk_tree(&mut self, root: ObjectId) -> Result<()> {
1149        let oid_len = self.odb.hash_algo().len();
1150        let mut stack = vec![root];
1151        while let Some(tree) = stack.pop() {
1152            if !self.trees_seen.insert(tree) {
1153                continue;
1154            }
1155            let Some(obj) = self.odb.try_read_once(&tree)? else {
1156                continue;
1157            };
1158            if obj.kind != ObjectKind::Tree {
1159                continue;
1160            }
1161            for entry in TreeRefIter::with_oid_len(&obj.data, oid_len) {
1162                let entry = entry?;
1163                match entry.mode & 0o170000 {
1164                    0o040000 => stack.push(entry.oid),
1165                    0o160000 => {}
1166                    _ => self.mark(entry.oid),
1167                }
1168            }
1169        }
1170        Ok(())
1171    }
1172
1173    fn walk_commit(&mut self, commit: ObjectId) -> Result<()> {
1174        if commit.is_zero() {
1175            return Ok(());
1176        }
1177        let Some(obj) = self.odb.try_read_once(&commit)? else {
1178            return Ok(());
1179        };
1180        if obj.kind != ObjectKind::Commit {
1181            return Ok(());
1182        }
1183        let tree = CommitRef::parse(&obj.data)?.tree();
1184        self.walk_tree(tree)
1185    }
1186
1187    /// Every non-bare worktree's own index (sparse directories included) and `HEAD`
1188    /// tree, plus the `GIT_INDEX_FILE` index when one is set.
1189    fn mark_checkouts(&mut self, repo: &Repository) -> Result<()> {
1190        use crate::state::HeadState;
1191        for wt in crate::worktree::list_worktrees(repo)? {
1192            if wt.is_bare {
1193                continue;
1194            }
1195            self.mark_index(repo, &wt.admin_dir.join("index"))?;
1196            if let HeadState::Detached { oid } | HeadState::Branch { oid: Some(oid), .. } = wt.head
1197            {
1198                self.walk_commit(oid)?;
1199            }
1200        }
1201        // A `GIT_INDEX_FILE` index is in use too, besides the worktree's own.
1202        if repo.environment().git_index_file.is_some() {
1203            self.mark_index(repo, &repo.index_path_for_env()?)?;
1204        }
1205        Ok(())
1206    }
1207
1208    /// The entries of the index at `path` (none when it does not exist), sparse
1209    /// directories walked as trees.
1210    fn mark_index(&mut self, repo: &Repository, path: &Path) -> Result<()> {
1211        let index = repo.load_index_at_preserving_sparse(
1212            path,
1213            crate::index::IndexParseContext::from_policy(repo.thread_policy()),
1214        )?;
1215        for entry in index.entries() {
1216            match entry.mode & 0o170000 {
1217                0o040000 => self.walk_tree(entry.oid)?,
1218                0o160000 => {}
1219                _ => self.mark(entry.oid),
1220            }
1221        }
1222        Ok(())
1223    }
1224
1225    /// The commits each non-bare worktree's `HEAD` reflog named at or after `cutoff`.
1226    fn mark_recent_heads(&mut self, repo: &Repository, cutoff: OffsetDateTime) -> Result<()> {
1227        for wt in crate::worktree::list_worktrees(repo)? {
1228            if wt.is_bare {
1229                continue;
1230            }
1231            for entry in crate::reflog::read_reflog(&wt.admin_dir, "HEAD")? {
1232                if entry.signature().is_some_and(|sig| sig.time >= cutoff) {
1233                    self.walk_commit(entry.old_oid)?;
1234                    self.walk_commit(entry.new_oid)?;
1235                }
1236            }
1237        }
1238        Ok(())
1239    }
1240}
1241
1242/// Remove `drop_set` from each `affected` pack: delete a pack that held nothing
1243/// else, rewrite the others. New packs are installed before old ones go.
1244#[allow(clippy::too_many_arguments)]
1245fn rewrite_packs(
1246    repo: &Repository,
1247    config: &ConfigSet,
1248    opts: &DropPromisedBlobsOptions,
1249    packs: &[PromisorPack],
1250    affected: &[u32],
1251    drop_set: &OidHashSet,
1252    report: &mut DropPromisedBlobsReport,
1253) -> Result<()> {
1254    let odb = repo.odb();
1255    let pack_dir = odb.objects_dir().join("pack");
1256    let had_midx =
1257        pack_dir.join("multi-pack-index").is_file() || pack_dir.join("multi-pack-index.d").is_dir();
1258    let env = repo.environment().clone();
1259    let pack_opts = PackBuildOptions::for_local_copy(Some(config));
1260    let mut bytes_before = 0u64;
1261    let mut bytes_after = 0u64;
1262    let mut stems: std::collections::HashSet<std::ffi::OsString> = std::collections::HashSet::new();
1263    for &p in affected {
1264        let pack = &packs[p as usize];
1265        let old = &pack.idx.pack_path;
1266        bytes_before += pack_files_size(old);
1267        let mut keep: Vec<(u64, ObjectId)> = Vec::new();
1268        for entry in pack.idx.iter() {
1269            let oid = ObjectId::from_bytes(entry.oid())?;
1270            if !drop_set.contains(&oid) {
1271                keep.push((entry.offset()?, oid));
1272            }
1273        }
1274        // An old pack is removed only once nothing in it is still needed or its
1275        // replacement is installed.
1276        let old_stem = old.file_stem().map(|stem| stem.to_os_string());
1277        if keep.is_empty() {
1278            stems.extend(old_stem);
1279            report.packs_removed += 1;
1280            continue;
1281        }
1282        keep.sort_unstable();
1283        let objects: Vec<ObjectId> = keep.into_iter().map(|(_, oid)| oid).collect();
1284        let built = super::write_staged_repack_pack(
1285            odb,
1286            &pack_dir,
1287            &objects,
1288            &HashMap::new(),
1289            &pack_opts,
1290            opts.threads,
1291            Some(config),
1292        )?;
1293        let Some(staging) = built.staging_path.as_ref() else {
1294            continue;
1295        };
1296        let trusted_rows = (!built.index_rows.is_empty()).then_some(built.index_rows);
1297        let ingested = install_pack_path_with_progress(
1298            staging,
1299            odb,
1300            &IngestPackOptions {
1301                threads: opts.threads,
1302                merged_config: Some(config.clone()),
1303                environment: env.clone(),
1304                skip_post_index_verify: trusted_rows.is_some(),
1305                trusted_index_rows: trusted_rows,
1306                mark_promisor_pack: true,
1307                ..IngestPackOptions::default()
1308            },
1309            None,
1310            None,
1311        )?;
1312        let Some(new_pack) = ingested.pack_path else {
1313            continue;
1314        };
1315        // Keep the ref lines fetch wrote, as Git's own repack does not.
1316        if let Ok(lines) = std::fs::read(old.with_extension("promisor")) {
1317            std::fs::write(new_pack.with_extension("promisor"), lines)?;
1318        }
1319        if config.pack_write_reverse_index_default() {
1320            crate::pack_rev::write_pack_rev_sidecar_for_index_path(
1321                &new_pack.with_extension("idx"),
1322            )?;
1323        }
1324        // The blobs that stay were fetched when the old pack was: keep that time.
1325        if let Some(mtime) = pack.mtime {
1326            filetime::set_file_mtime(&new_pack, filetime::FileTime::from_system_time(mtime))?;
1327        }
1328        crate::index_pack::sync_installed_pack(&new_pack)?;
1329        bytes_after += pack_files_size(&new_pack);
1330        if new_pack.file_stem() != old.file_stem() {
1331            stems.extend(old_stem);
1332        }
1333        report.packs_rewritten += 1;
1334    }
1335    if had_midx {
1336        crate::midx::clear_pack_midx_state(&pack_dir)?;
1337    }
1338    // Drop cached mappings before deleting pack files (Windows).
1339    odb.invalidate_packs();
1340    super::remove_pack_files_with_stems(&pack_dir, &stems)?;
1341    crate::pack::clear_pack_cache();
1342    odb.invalidate_packs();
1343    odb.reprepare_local_packs();
1344    let packs_left = odb.local_pack_indexes()?.len();
1345    if had_midx && packs_left > 0 {
1346        super::write_midx(repo, &super::MidxOptions::default())?;
1347    }
1348    report.bytes_reclaimed = bytes_before.saturating_sub(bytes_after);
1349    Ok(())
1350}
1351
1352/// Bytes of a pack with its index and reverse index.
1353fn pack_files_size(pack: &Path) -> u64 {
1354    ["pack", "idx", "rev"]
1355        .iter()
1356        .filter_map(|ext| std::fs::metadata(pack.with_extension(ext)).ok())
1357        .map(|m| m.len())
1358        .sum()
1359}
1360
1361#[cfg(test)]
1362#[allow(clippy::unwrap_used, clippy::expect_used)]
1363mod tests {
1364    use super::*;
1365    use crate::config::{ConfigFile, ConfigScope};
1366
1367    fn config(text: &str) -> ConfigSet {
1368        let file = ConfigFile::parse(Path::new("test.config"), text, ConfigScope::Local).unwrap();
1369        let mut set = ConfigSet::new();
1370        set.merge(&file);
1371        set
1372    }
1373
1374    fn now() -> OffsetDateTime {
1375        OffsetDateTime::from_unix_timestamp(1_700_000_000).unwrap()
1376    }
1377
1378    #[test]
1379    fn defaults_are_one_mebibyte_and_two_weeks() {
1380        let opts = DropPromisedBlobsOptions::from_config(&config(""), now(), None, None)
1381            .unwrap()
1382            .unwrap();
1383        assert_eq!(opts.min_size, DEFAULT_DROP_MIN_SIZE);
1384        assert_eq!(opts.keep_newer_than, Some(now() - time::Duration::weeks(2)));
1385        assert_eq!(opts.now, now());
1386        assert!(!opts.dry_run);
1387    }
1388
1389    #[test]
1390    fn min_size_takes_units_and_rejects_junk() {
1391        let min = |v: &str| {
1392            DropPromisedBlobsOptions::from_config(
1393                &config(&format!(
1394                    "[maintenance \"drop-large-blobs\"]\n\tminSize = {v}\n"
1395                )),
1396                now(),
1397                None,
1398                None,
1399            )
1400            .map(|o| o.unwrap().min_size)
1401        };
1402        assert_eq!(min("100k").unwrap(), 100 * 1024);
1403        assert_eq!(min("1m").unwrap(), 1 << 20);
1404        assert_eq!(min("0").unwrap(), 0);
1405        for bad in ["lots", "-1"] {
1406            assert!(
1407                matches!(
1408                    min(bad),
1409                    Err(Error::Config(ConfigError::BadNumericValue { .. }))
1410                ),
1411                "{bad}"
1412            );
1413        }
1414    }
1415
1416    #[test]
1417    fn min_size_follows_the_smallest_promisor_blob_limit() {
1418        let cfg = config(
1419            "[remote \"origin\"]\n\turl = /o\n\tpromisor = true\n\tpartialclonefilter = blob:limit=200k\n\
1420             [remote \"lop\"]\n\turl = /l\n\tpromisor = true\n\tpartialclonefilter = blob:limit=50k\n\
1421             [remote \"none\"]\n\turl = /n\n\tpromisor = true\n\tpartialclonefilter = blob:none\n",
1422        );
1423        let opts = DropPromisedBlobsOptions::from_config(&cfg, now(), None, None)
1424            .unwrap()
1425            .unwrap();
1426        assert_eq!(opts.min_size, 50 * 1024);
1427        let blobless = config(
1428            "[remote \"origin\"]\n\turl = /o\n\tpromisor = true\n\tpartialclonefilter = blob:none\n",
1429        );
1430        let opts = DropPromisedBlobsOptions::from_config(&blobless, now(), None, None)
1431            .unwrap()
1432            .unwrap();
1433        assert_eq!(opts.min_size, DEFAULT_DROP_MIN_SIZE);
1434    }
1435
1436    #[test]
1437    fn expire_values() {
1438        let expire = |v: &str| {
1439            DropPromisedBlobsOptions::from_config(
1440                &config(&format!(
1441                    "[maintenance \"drop-large-blobs\"]\n\texpire = {v}\n"
1442                )),
1443                now(),
1444                None,
1445                None,
1446            )
1447        };
1448        assert_eq!(expire("now").unwrap().unwrap().keep_newer_than, None);
1449        assert_eq!(expire("all").unwrap().unwrap().keep_newer_than, None);
1450        assert!(expire("never").unwrap().is_none());
1451        assert!(expire("false").unwrap().is_none());
1452        assert_eq!(
1453            expire("3.days.ago").unwrap().unwrap().keep_newer_than,
1454            Some(now() - time::Duration::days(3))
1455        );
1456        assert!(matches!(
1457            expire("not a date at all"),
1458            Err(Error::Config(ConfigError::InvalidDate { key, value }))
1459                if key == EXPIRE_KEY && value == "not a date at all"
1460        ));
1461    }
1462
1463    #[test]
1464    fn expiry_keywords_dates_and_junk() {
1465        assert_eq!(DropExpiry::parse(" Never ", now()), Some(DropExpiry::Never));
1466        assert_eq!(DropExpiry::parse("false", now()), Some(DropExpiry::Never));
1467        assert_eq!(
1468            DropExpiry::parse("NOW", now()),
1469            Some(DropExpiry::Immediately)
1470        );
1471        assert_eq!(
1472            DropExpiry::parse("all", now()),
1473            Some(DropExpiry::Immediately)
1474        );
1475        assert_eq!(
1476            DropExpiry::parse("1.week.ago", now()),
1477            Some(DropExpiry::KeepNewerThan(now() - time::Duration::weeks(1)))
1478        );
1479        for junk in ["", "   ", "not a date at all"] {
1480            assert_eq!(DropExpiry::parse(junk, now()), None, "{junk:?}");
1481        }
1482    }
1483
1484    #[test]
1485    fn overrides_replace_only_their_own_key() {
1486        let cfg = config("[maintenance \"drop-large-blobs\"]\n\texpire = never\n\tminSize = 10m\n");
1487        assert!(
1488            DropPromisedBlobsOptions::from_config(&cfg, now(), None, None)
1489                .unwrap()
1490                .is_none()
1491        );
1492        // An expiry override runs the task, and minSize still comes from config.
1493        let opts =
1494            DropPromisedBlobsOptions::from_config(&cfg, now(), None, Some(DropExpiry::Immediately))
1495                .unwrap()
1496                .unwrap();
1497        assert_eq!(opts.min_size, 10 << 20);
1498        assert_eq!(opts.keep_newer_than, None);
1499        let opts = DropPromisedBlobsOptions::from_config(
1500            &cfg,
1501            now(),
1502            Some(5),
1503            Some(DropExpiry::KeepNewerThan(now())),
1504        )
1505        .unwrap()
1506        .unwrap();
1507        assert_eq!((opts.min_size, opts.keep_newer_than), (5, Some(now())));
1508        assert!(DropPromisedBlobsOptions::from_config(
1509            &cfg,
1510            now(),
1511            Some(5),
1512            Some(DropExpiry::Never)
1513        )
1514        .unwrap()
1515        .is_none());
1516
1517        // An overridden key is not read, so its bad value does not matter.
1518        let bad =
1519            config("[maintenance \"drop-large-blobs\"]\n\texpire = bogus\n\tminSize = lots\n");
1520        let opts = DropPromisedBlobsOptions::from_config(
1521            &bad,
1522            now(),
1523            Some(7),
1524            Some(DropExpiry::Immediately),
1525        )
1526        .unwrap()
1527        .unwrap();
1528        assert_eq!(opts.min_size, 7);
1529        assert!(matches!(
1530            DropPromisedBlobsOptions::from_config(&bad, now(), None, Some(DropExpiry::Immediately)),
1531            Err(Error::Config(ConfigError::BadNumericValue { .. }))
1532        ));
1533        assert!(matches!(
1534            DropPromisedBlobsOptions::from_config(&bad, now(), Some(7), None),
1535            Err(Error::Config(ConfigError::InvalidDate { .. }))
1536        ));
1537    }
1538
1539    #[test]
1540    fn gc_plan_checks_config_and_needs_a_time() {
1541        let plan = |text: &str, now_unix: i64| plan_drop_for_gc(&config(text), now_unix);
1542        let on = "[maintenance \"drop-large-blobs\"]\n\tenabled = true\n";
1543        assert!(matches!(
1544            plan("", 0).unwrap(),
1545            GcDropPlan::Skip(DropPromisedBlobsSkip::Disabled)
1546        ));
1547        assert!(matches!(
1548            plan(&format!("{on}\texpire = never\n"), 1_700_000_000).unwrap(),
1549            GcDropPlan::Skip(DropPromisedBlobsSkip::Disabled)
1550        ));
1551        let GcDropPlan::Run(opts) = plan(on, 1_700_000_000).unwrap() else {
1552            panic!("runs with a time");
1553        };
1554        assert_eq!(opts.now, now());
1555        // No time: skipped, not measured against a clock read here or the epoch.
1556        for no_time in [0, i64::MAX] {
1557            assert!(matches!(
1558                plan(on, no_time).unwrap(),
1559                GcDropPlan::Skip(DropPromisedBlobsSkip::NoCurrentTime)
1560            ));
1561        }
1562        // Bad values fail before any phase; without a time only minSize is checked.
1563        for (bad, now_unix) in [
1564            ("\texpire = bogus\n", 1_700_000_000),
1565            ("\tminSize = lots\n", 1_700_000_000),
1566            ("\tminSize = lots\n", 0),
1567        ] {
1568            assert!(
1569                matches!(plan(&format!("{on}{bad}"), now_unix), Err(Error::Config(_))),
1570                "{bad}"
1571            );
1572        }
1573        assert!(matches!(
1574            plan("[maintenance \"drop-large-blobs\"]\n\tenabled = maybe\n", 1),
1575            Err(Error::Config(_))
1576        ));
1577    }
1578
1579    #[test]
1580    fn enabled_is_off_by_default_and_must_be_a_boolean() {
1581        assert!(!drop_large_blobs_enabled(&config("")).unwrap());
1582        let on = config("[maintenance \"drop-large-blobs\"]\n\tenabled = true\n");
1583        assert!(drop_large_blobs_enabled(&on).unwrap());
1584        let bad = config("[maintenance \"drop-large-blobs\"]\n\tenabled = sometimes\n");
1585        assert!(matches!(
1586            drop_large_blobs_enabled(&bad),
1587            Err(Error::Config(_))
1588        ));
1589    }
1590
1591    #[test]
1592    fn kept_counts_total() {
1593        let kept = KeptBlobCounts {
1594            kept_pack: 1,
1595            outside_promisor_packs: 2,
1596            checked_out: 3,
1597            recently_checked_out: 4,
1598            recently_fetched: 5,
1599            not_promised_elsewhere: 6,
1600            not_in_promisor: 7,
1601            unverified: 8,
1602        };
1603        assert_eq!(kept.total(), 36);
1604    }
1605}