Skip to main content

grit_lib/
offload.rs

1//! Offload large blobs from a repository to a large-object promisor (LOP).
2//!
3//! A server can keep its big binaries out of its main repository: the blobs live
4//! in a second repository, the LOP, and the main repository becomes a partial
5//! repository of it. The main repository's config names the LOP as a promisor
6//! remote (`remote.<lop>.promisor = true`), its remaining objects sit in a
7//! `.promisor` pack, and upload-pack leaves the offloaded blobs out for clients
8//! that accept the LOP through the `promisor-remote` capability. This is the
9//! layout Git's own large-object-promisor tests build with
10//! `git repack -a -d --filter=blob:limit=<n> --filter-to=<lop>`.
11//!
12//! The blobs that stay (smaller than the threshold, or needed by a checkout) are in
13//! that promisor pack too, although only the main repository has them. Git treats
14//! every object a tree in a promisor pack names as promised, and its `repack -a -d`
15//! and `gc` keep only the promised objects they find in promisor packs: a kept blob
16//! in an ordinary pack beside it would be deleted, with nothing to fetch it back
17//! from. The price is that a blob in a promisor pack no longer proves the promisor
18//! can supply it, so offload records the LOP's directory in `grit.lopGitDir`, and
19//! [`Maintenance::drop_promised_blobs`](crate::maintenance::Maintenance::drop_promised_blobs) drops a blob only once a promisor
20//! it can read is seen to hold it.
21//!
22//! [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs) moves the blobs a filter leaves out (`blob:limit=<n>`: every
23//! blob of `n` bytes or more) from the main repository to the LOP. It never removes
24//! anything from the main repository before the LOP holds it, and blobs any checkout
25//! of the main repository needs stay where they are. Running it again offloads blobs
26//! pushed since, and folds the main repository's packs back into one promisor pack.
27
28use crate::error::ObjectError;
29use std::path::{Path, PathBuf};
30
31use crate::config::{ConfigFile, ConfigScope, ConfigSet};
32use crate::environment::RepositoryOptions;
33use crate::error::{Error, Result};
34use crate::index_pack::{install_pack_path_with_progress, IngestPackOptions};
35use crate::maintenance::{GcLock, GcLockAttempt, GcLockHolder, RepackOptions};
36use crate::objects::{
37    oid_hash_set, CommitRef, HashAlgo, ObjectId, ObjectKind, OidHashMap, OidHashSet, TreeRefIter,
38};
39use crate::odb::Odb;
40use crate::pack_index::PackIndex;
41use crate::pack_objects::PackBuildOptions;
42use crate::partial_clone::{stored_remote_filter, ObjectFilterSpec};
43use crate::repo::error::FilesOnlyOperation;
44use crate::repo::Repository;
45
46/// Message written into the `.keep` marker of every pack offload adds to a LOP.
47pub const LOP_KEEP_MESSAGE: &str = "grit offload: large-object promisor pack";
48
49/// Multi-valued config key [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs) adds to the main repository: the
50/// absolute git directory of each LOP it moved blobs to.
51///
52/// Its presence marks a repository whose promisor pack holds blobs only it has, so
53/// [`Maintenance::drop_promised_blobs`](crate::maintenance::Maintenance::drop_promised_blobs) drops a blob there only after seeing
54/// it in a promisor it can read (one of these directories, or a promisor remote
55/// with a local URL).
56pub const LOP_GIT_DIR_KEY: &str = "grit.lopGitDir";
57
58/// Options for [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs).
59#[derive(Debug, Clone)]
60#[non_exhaustive]
61pub struct OffloadOptions {
62    /// The promisor remote the blobs move to; `remote.<name>.url` must be set in the
63    /// main repository.
64    pub remote: String,
65    /// Which blobs move: those this filter leaves out (`blob:limit=<n>`: blobs of `n`
66    /// bytes or more; `blob:none`: every blob). `None` uses
67    /// `remote.<name>.partialCloneFilter`, the same value clients receive through
68    /// `promisor.sendFields`.
69    pub filter: Option<ObjectFilterSpec>,
70    /// The LOP's git directory on this machine. Needed when `remote.<name>.url` is
71    /// not a local path, for example an `https://` URL advertised to clients for a
72    /// repository the server also has on disk.
73    pub lop_git_dir: Option<PathBuf>,
74    /// Also set `uploadpack.allowFilter` and `uploadpack.allowAnySHA1InWant` in the
75    /// LOP, so it can answer the lazy fetches clients send it.
76    pub configure_lop: bool,
77    /// Work out what would move without writing anything.
78    pub dry_run: bool,
79    /// Current time in Unix seconds, for the `gc.pid` maintenance lock.
80    pub now_unix: i64,
81    /// Pack writing and indexing threads (`None` reads `pack.threads`).
82    pub threads: Option<usize>,
83}
84
85impl OffloadOptions {
86    /// Options that offload to `remote` with its configured filter, at time `now_unix`.
87    #[must_use]
88    pub fn new(remote: impl Into<String>, now_unix: i64) -> Self {
89        Self {
90            remote: remote.into(),
91            filter: None,
92            lop_git_dir: None,
93            configure_lop: false,
94            dry_run: false,
95            now_unix,
96            threads: None,
97        }
98    }
99}
100
101/// Why [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs) refused to run.
102#[derive(Debug, thiserror::Error)]
103#[non_exhaustive]
104pub enum OffloadError {
105    /// `remote.<name>.url` is not set in the main repository.
106    #[error("remote '{remote}' has no url configured")]
107    RemoteNotConfigured {
108        /// The remote named in [`OffloadOptions::remote`].
109        remote: String,
110    },
111    /// The remote's URL is not a local path and no [`OffloadOptions::lop_git_dir`]
112    /// was given.
113    #[error("remote '{remote}' is not a local repository ({url}); give its git directory")]
114    LopNotLocal {
115        /// The remote name.
116        remote: String,
117        /// Its configured URL (credentials removed).
118        url: String,
119    },
120    /// The LOP location is not a Git repository.
121    #[error("{} is not a git repository", path.display())]
122    LopNotARepository {
123        /// Where the LOP was looked for.
124        path: PathBuf,
125    },
126    /// The LOP is the main repository itself, or stores its objects in the same
127    /// directory (a linked worktree of it, or an `objects/` linked to its).
128    #[error("the large-object promisor is this repository itself")]
129    LopIsMainRepository,
130    /// The two repositories use different object formats.
131    #[error(
132        "object formats differ: this repository uses {}, the promisor {}",
133        main.name(),
134        lop.name()
135    )]
136    HashAlgoMismatch {
137        /// The main repository's object format.
138        main: HashAlgo,
139        /// The LOP's object format.
140        lop: HashAlgo,
141    },
142    /// No filter was given and the remote has no `partialCloneFilter`.
143    #[error("no size threshold: give a filter or set remote.{remote}.partialCloneFilter")]
144    NoThreshold {
145        /// The remote name.
146        remote: String,
147    },
148    /// A blob copied to the LOP cannot be found there afterwards; nothing was
149    /// removed from the main repository.
150    #[error("blob {oid} is not in the promisor after copying it there")]
151    NotInLopAfterCopy {
152        /// The blob.
153        oid: ObjectId,
154    },
155    /// An ordinary `.keep` pack (one without `.promisor`) of the main repository
156    /// holds the only copy of an object that a commit, tree or tag going into the
157    /// promisor pack names. Git counts every object a promisor-pack object names as
158    /// promised, and its `repack -a -d` keeps a promised object only in a promisor
159    /// pack: once the marker goes, it would delete this one, which no promisor has.
160    /// Offload does not rewrite kept packs, and a copy in the promisor pack does
161    /// not help (Git's repack leaves out objects a kept pack holds), so it refuses
162    /// before changing anything. Removing the marker lets offload fold the pack
163    /// in; marking the pack `.promisor` keeps it as it is.
164    #[error(
165        "{oid} is only in kept pack {}, and {referrer} names it",
166        pack.display()
167    )]
168    KeptPackObjectPromised {
169        /// The kept pack holding the object.
170        pack: PathBuf,
171        /// The object.
172        oid: ObjectId,
173        /// An object going into the promisor pack that names it.
174        referrer: ObjectId,
175    },
176    /// Another maintenance run holds the main repository's `gc.pid` lock.
177    #[error("maintenance is already running on this repository")]
178    MaintenanceRunning {
179        /// Who holds the lock.
180        holder: GcLockHolder,
181    },
182}
183
184/// Which repository a [`OffloadConfigChange`] was made in.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186#[non_exhaustive]
187pub enum OffloadRepo {
188    /// The repository the blobs moved out of.
189    Main,
190    /// The large-object promisor.
191    Lop,
192}
193
194/// One config value [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs) set.
195#[derive(Debug, Clone, PartialEq, Eq)]
196#[non_exhaustive]
197pub struct OffloadConfigChange {
198    /// The repository whose local config changed.
199    pub repo: OffloadRepo,
200    /// The key, as written (for example `remote.lop.promisor`).
201    pub key: String,
202    /// The new value.
203    pub value: String,
204}
205
206/// Whether a LOP can answer the lazy fetches of Git clients.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
208#[non_exhaustive]
209pub struct LopReadiness {
210    /// `uploadpack.allowFilter` is true, so it accepts `filter blob:none`.
211    pub allow_filter: bool,
212    /// `uploadpack.allowAnySHA1InWant` is true, so it serves blobs no ref points at.
213    pub allow_any_sha1_in_want: bool,
214}
215
216impl LopReadiness {
217    /// Both settings are on.
218    #[must_use]
219    pub fn is_ready(&self) -> bool {
220        self.allow_filter && self.allow_any_sha1_in_want
221    }
222
223    fn from_config(config: &ConfigSet) -> Self {
224        let flag = |key: &str| config.bool_with_default(key, false);
225        Self {
226            allow_filter: flag("uploadpack.allowfilter"),
227            allow_any_sha1_in_want: flag("uploadpack.allowanysha1inwant"),
228        }
229    }
230}
231
232/// What [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs) did (or, with [`OffloadOptions::dry_run`], would do).
233#[derive(Debug, Clone, PartialEq, Eq)]
234#[non_exhaustive]
235pub struct OffloadReport {
236    /// The promisor remote the blobs moved to.
237    pub remote: String,
238    /// The LOP's git directory.
239    pub lop_git_dir: PathBuf,
240    /// The filter that chose the blobs.
241    pub filter: ObjectFilterSpec,
242    /// True when nothing was written.
243    pub dry_run: bool,
244    /// Blobs stored in the main repository that the filter selects and that may move.
245    pub candidates: usize,
246    /// Their total size, uncompressed.
247    pub candidate_bytes: u64,
248    /// Candidates copied into a new LOP pack.
249    pub copied_to_lop: usize,
250    /// Candidates the LOP already had in a pack an earlier offload wrote there (its
251    /// `.keep` marker holds [`LOP_KEEP_MESSAGE`]). A loose or unkept copy there
252    /// does not count (the LOP's `gc` may prune it), nor does one in a pack another
253    /// writer keeps for a while (`receive-pack`, `fetch-pack`), nor one it reaches
254    /// through alternates; those candidates are copied.
255    pub already_in_lop: usize,
256    /// Candidates no longer stored in the main repository afterwards.
257    pub dropped_from_main: usize,
258    /// Selected blobs kept because a checkout of the main repository needs them
259    /// (a worktree's index or `HEAD`).
260    pub skipped_checked_out: usize,
261    /// Selected blobs kept because they are in a `.keep` pack (or the only tree
262    /// naming them is), which offload does not rewrite.
263    pub skipped_kept_pack: usize,
264    /// The pack added to the LOP, holding the blobs copied there, if any.
265    pub lop_pack: Option<OffloadPack>,
266    /// The promisor pack the main repository's objects now live in (its commits,
267    /// trees, tags and the blobs it keeps), if rewritten.
268    pub main_pack: Option<OffloadPack>,
269    /// Bytes of the main repository's local packs and loose objects before.
270    pub main_bytes_before: u64,
271    /// The same afterwards (equal to the before value on a dry run).
272    pub main_bytes_after: u64,
273    /// Config values set, in the order they were written.
274    pub config_changes: Vec<OffloadConfigChange>,
275    /// The LOP's upload-pack settings after the run.
276    pub lop_ready: LopReadiness,
277    /// `promisor.advertise` is true in the main repository, so its upload-pack tells
278    /// clients about the LOP.
279    pub advertised: bool,
280}
281
282impl OffloadReport {
283    /// The packs the run wrote, in the order they were written: the LOP pack, then
284    /// the main repository's promisor pack.
285    pub fn packs(&self) -> impl Iterator<Item = &OffloadPack> {
286        [&self.lop_pack, &self.main_pack].into_iter().flatten()
287    }
288}
289
290/// Which of the packs [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs) writes an [`OffloadPack`] is.
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292#[non_exhaustive]
293pub enum OffloadPackRole {
294    /// The LOP's new pack of the blobs that moved, with a `.keep` marker.
295    Lop,
296    /// The main repository's `.promisor` pack of every object it keeps.
297    MainPromisor,
298}
299
300/// A pack [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs) wrote.
301#[derive(Debug, Clone, PartialEq, Eq)]
302#[non_exhaustive]
303pub struct OffloadPack {
304    /// Which pack this is.
305    pub role: OffloadPackRole,
306    /// The `.pack` file (its `.idx` and other sidecars are beside it).
307    pub path: PathBuf,
308    /// Objects in the pack.
309    pub objects: usize,
310    /// Size of the `.pack` file in bytes.
311    pub bytes: u64,
312}
313
314impl OffloadPack {
315    /// Describe the pack at `path`, reading its size from disk.
316    fn written(role: OffloadPackRole, path: PathBuf, objects: usize) -> Result<Self> {
317        let bytes = std::fs::metadata(&path)?.len();
318        Ok(Self {
319            role,
320            path,
321            objects,
322            bytes,
323        })
324    }
325}
326
327/// Move the blobs [`OffloadOptions::filter`] selects from `repo` to the large-object
328/// promisor [`OffloadOptions::remote`].
329///
330/// The steps run in an order that never loses an object:
331///
332/// 1. Blobs reachable from the refs, reflogs and `HEAD`s, stored in `repo`, and left
333///    out by the filter are the candidates. Those a checkout needs, and those in
334///    `.keep` packs, stay.
335/// 2. The candidates the LOP does not already hold in a pack an earlier offload
336///    wrote there are copied into one new pack there, whole (no deltas), with a
337///    `.keep` marker holding [`LOP_KEEP_MESSAGE`] written before the pack appears:
338///    nothing in the LOP refers to them, so an unprotected pack could be pruned.
339///    A pack another writer keeps only for a while (`receive-pack`, `fetch-pack`)
340///    does not count. Every candidate is then checked to be in such a pack of the
341///    LOP, and the new pack, index and marker are flushed to disk.
342/// 3. The main repository's config gets `remote.<name>.promisor = true`, when the
343///    filter came from `opts` `remote.<name>.partialCloneFilter`, and
344///    `repack.writeBitmaps = false`. A reachability bitmap (pack or multi-pack)
345///    needs every object its commits reach in the packs it covers, and the
346///    offloaded blobs are in none of them. Git's repack keeps promisor and other
347///    objects in separate packs, so once a push adds a commit outside the
348///    promisor pack, Git 2.50 and 2.56 fail with "Packfile doesn't have full
349///    closure": `git gc` exits 128 on a bare repository, where bitmaps are on by
350///    default, and `git repack -a -d -b --write-midx` fails too. Grit's own repack
351///    leaves the bitmap out in that case, so the setting is for Git.
352///    `promisor.advertise` and `extensions.partialClone` are left to the caller;
353///    the report says whether clients are told about the LOP.
354///    It also gets the LOP's git directory in `grit.lopGitDir` (once per LOP),
355///    which tells `drop-large-blobs` where to check that a blob it would drop
356///    exists in the LOP.
357/// 4. The main repository's local packs and loose objects are rewritten into one
358///    `.promisor` pack without the candidates; its trees keep the offloaded blobs
359///    promised. The blobs that stay go into it too: Git's repack and `gc` keep a
360///    promised object only when it is in a promisor pack (see the module
361///    documentation). This happens on every run, even when no blob moves, so
362///    objects pushed since the last run (trees naming offloaded blobs, new small
363///    blobs) join the promisor pack, and a repository whose kept blobs sit in an
364///    ordinary pack is folded back. The new pack is flushed to disk before the old
365///    packs are removed. `.keep` packs are not rewritten (see
366///    [`OffloadError::KeptPackObjectPromised`]).
367///
368/// # Parameters
369///
370/// - `repo`: the main repository (files-backed object store).
371/// - `opts`: what to move and where.
372///
373/// # Errors
374///
375/// [`crate::error::ObjectError::Offload`] for the [`OffloadError`] cases, [`RepositoryError::UnsupportedObjectStore`](crate::repo::RepositoryError::UnsupportedObjectStore)
376/// without a files-backed object store, and read, write and config failures.
377pub(crate) fn offload_blobs(repo: &Repository, opts: &OffloadOptions) -> Result<OffloadReport> {
378    let odb = repo.odb();
379    odb.primary_store()
380        .require_files_primary(FilesOnlyOperation::Offload)?;
381    let config = repo.config().snapshot()?;
382    let remote = opts.remote.as_str();
383    let url = config
384        .value(&format!("remote.{remote}.url"))
385        .filter(|u| !u.trim().is_empty())
386        .ok_or_else(|| OffloadError::RemoteNotConfigured {
387            remote: remote.to_owned(),
388        })?;
389    let filter = opts
390        .filter
391        .or_else(|| stored_remote_filter(&config, remote))
392        .ok_or_else(|| OffloadError::NoThreshold {
393            remote: remote.to_owned(),
394        })?;
395    let lop = open_lop(repo, opts, &url)?;
396
397    let _lock = if opts.dry_run {
398        None
399    } else {
400        match GcLock::try_acquire(repo, opts.now_unix)? {
401            GcLockAttempt::Acquired(lock) => Some(lock),
402            GcLockAttempt::Held(holder) => {
403                return Err(OffloadError::MaintenanceRunning { holder }.into())
404            }
405        }
406    };
407
408    let main_bytes_before = local_object_bytes(odb)?;
409    let selection = select_candidates(repo, filter)?;
410    let candidates: Vec<ObjectId> = selection.candidates.keys().copied().collect();
411    if let Some(refusal) = kept_object_the_promisor_pack_names(odb, &selection.candidates)? {
412        return Err(refusal.into());
413    }
414    let in_lop = held_in_lop_keep_packs(lop.odb(), &candidates)?;
415    let missing_in_lop: Vec<ObjectId> = candidates
416        .iter()
417        .zip(&in_lop)
418        .filter_map(|(oid, has)| (!has).then_some(*oid))
419        .collect();
420
421    let mut report = OffloadReport {
422        remote: remote.to_owned(),
423        lop_git_dir: lop.git_dir().to_path_buf(),
424        filter,
425        dry_run: opts.dry_run,
426        candidates: candidates.len(),
427        candidate_bytes: selection.candidates.values().sum(),
428        copied_to_lop: 0,
429        already_in_lop: candidates.len() - missing_in_lop.len(),
430        dropped_from_main: 0,
431        skipped_checked_out: selection.skipped_checked_out,
432        skipped_kept_pack: selection.skipped_kept_pack,
433        lop_pack: None,
434        main_pack: None,
435        main_bytes_before,
436        main_bytes_after: main_bytes_before,
437        config_changes: Vec::new(),
438        lop_ready: LopReadiness::from_config(&lop_config(&lop)?),
439        advertised: config.bool_with_default("promisor.advertise", false),
440    };
441    if opts.dry_run {
442        return Ok(report);
443    }
444
445    if !missing_in_lop.is_empty() {
446        report.lop_pack = copy_to_lop(repo, &lop, &missing_in_lop, opts)?
447            .map(|(path, objects)| OffloadPack::written(OffloadPackRole::Lop, path, objects))
448            .transpose()?;
449        report.copied_to_lop = missing_in_lop.len();
450    }
451    lop.odb().invalidate_packs();
452    let present = held_in_lop_keep_packs(lop.odb(), &candidates)?;
453    if let Some((oid, _)) = candidates.iter().zip(&present).find(|(_, has)| !**has) {
454        return Err(OffloadError::NotInLopAfterCopy { oid: *oid }.into());
455    }
456    if let Some(pack) = &report.lop_pack {
457        // The main repository is about to drop its copies: the LOP's must be on disk.
458        crate::index_pack::sync_installed_pack(&pack.path)?;
459    }
460
461    let mut wanted: Vec<(String, String)> = Vec::new();
462    let promisor_key = format!("remote.{remote}.promisor");
463    if !config.bool_with_default(&promisor_key, false) {
464        wanted.push((promisor_key, "true".to_owned()));
465    }
466    let filter_key = format!("remote.{remote}.partialCloneFilter");
467    if opts.filter.is_some() && config.value(&filter_key).is_none() {
468        wanted.push((filter_key, filter.to_config_value()));
469    }
470    // No pack or multi-pack-index holds the offloaded blobs, so no bitmap can have
471    // full closure; once a push lands outside the promisor pack, Git's `gc` fails
472    // trying (bitmaps are on by default in bare repositories).
473    let bitmaps_key = "repack.writeBitmaps";
474    if config.bool_with_default(bitmaps_key, true) {
475        wanted.push((bitmaps_key.to_owned(), "false".to_owned()));
476    }
477    // The promisor pack is about to hold blobs the LOP does not have; record where
478    // the LOP is, so dropping promised blobs can check it first.
479    let mut added: Vec<(String, String)> = Vec::new();
480    let lop_dir = lop_dir_value(lop.git_dir());
481    if !config
482        .values_all(LOP_GIT_DIR_KEY)
483        .iter()
484        .any(|v| same_dir(Path::new(v), lop.git_dir()))
485    {
486        added.push((LOP_GIT_DIR_KEY.to_owned(), lop_dir));
487    }
488    write_config(repo.git_dir(), &wanted, &added)?;
489    report
490        .config_changes
491        .extend(
492            wanted
493                .into_iter()
494                .chain(added)
495                .map(|(key, value)| OffloadConfigChange {
496                    repo: OffloadRepo::Main,
497                    key,
498                    value,
499                }),
500        );
501    if opts.configure_lop {
502        let lop_changes: Vec<(String, String)> = [
503            ("uploadpack.allowFilter", report.lop_ready.allow_filter),
504            (
505                "uploadpack.allowAnySHA1InWant",
506                report.lop_ready.allow_any_sha1_in_want,
507            ),
508        ]
509        .into_iter()
510        .filter(|(_, already)| !already)
511        .map(|(key, _)| (key.to_owned(), "true".to_owned()))
512        .collect();
513        write_config(lop.git_dir(), &lop_changes, &[])?;
514        report
515            .config_changes
516            .extend(
517                lop_changes
518                    .into_iter()
519                    .map(|(key, value)| OffloadConfigChange {
520                        repo: OffloadRepo::Lop,
521                        key,
522                        value,
523                    }),
524            );
525        report.lop_ready = LopReadiness::from_config(&lop_config(&lop)?);
526    }
527
528    let omit: OidHashSet = candidates.iter().copied().collect();
529    let repack = RepackOptions {
530        threads: opts.threads,
531        environment: repo.environment().clone(),
532        ..RepackOptions::default()
533    };
534    // Fold in what arrived since the last run even when nothing moves now: a
535    // pushed tree naming an offloaded blob outside the promisor pack makes every
536    // promise check for that blob scan all promisor packs.
537    let rewrite = crate::maintenance::rewrite_local_objects_without(
538        repo,
539        &omit,
540        &repack,
541        crate::maintenance::PromisorRewriteWhen::Always,
542    )?;
543    report.main_pack = rewrite
544        .pack_path
545        .map(|path| OffloadPack::written(OffloadPackRole::MainPromisor, path, rewrite.objects))
546        .transpose()?;
547    report.dropped_from_main = odb.missing_stored_oids(candidates.iter().copied())?.len();
548    report.main_bytes_after = local_object_bytes(odb)?;
549    Ok(report)
550}
551
552/// Open the LOP named by `opts` (or by the remote's local `url`) and check it can
553/// take the blobs.
554fn open_lop(repo: &Repository, opts: &OffloadOptions, url: &str) -> Result<Repository> {
555    let path = match &opts.lop_git_dir {
556        Some(path) => path.clone(),
557        None if crate::transport_path::is_local_path_remote_url(url) => {
558            crate::transport_path::resolve_local_remote_git_dir(
559                url,
560                repo.git_dir(),
561                repo.work_tree(),
562            )
563        }
564        None => {
565            return Err(OffloadError::LopNotLocal {
566                remote: opts.remote.clone(),
567                url: crate::transport_path::redact_url_for_display(url),
568            }
569            .into())
570        }
571    };
572    let lop = Repository::open(
573        &path,
574        &RepositoryOptions::with_environment(repo.environment().clone()),
575    )
576    .map_err(|_| OffloadError::LopNotARepository { path: path.clone() })?;
577    if same_object_store(repo, &lop) {
578        return Err(OffloadError::LopIsMainRepository.into());
579    }
580    let (main_algo, lop_algo) = (repo.odb().hash_algo(), lop.odb().hash_algo());
581    if main_algo != lop_algo {
582        return Err(OffloadError::HashAlgoMismatch {
583            main: main_algo,
584            lop: lop_algo,
585        }
586        .into());
587    }
588    lop.odb()
589        .primary_store()
590        .require_files_primary(FilesOnlyOperation::Offload)?;
591    Ok(lop)
592}
593
594/// The LOP's own config (system and global included, as its upload-pack sees it).
595fn lop_config(lop: &Repository) -> Result<ConfigSet> {
596    ConfigSet::load(
597        lop.environment(),
598        Some(lop.git_dir()),
599        &crate::config::LoadConfigOptions::standard(lop.environment(), Some(lop.git_dir())),
600    )
601}
602
603/// Blobs chosen by [`select_candidates`], with their sizes.
604struct Selection {
605    candidates: OidHashMap<u64>,
606    skipped_checked_out: usize,
607    skipped_kept_pack: usize,
608}
609
610/// Walk every commit, tag and tree reachable from the maintenance roots and pick the
611/// blobs `filter` leaves out that this repository stores and can drop.
612///
613/// A blob qualifies only when a tree naming it will be in the rewritten promisor
614/// pack (stored loose or in a pack without `.keep`): that is what makes it promised
615/// once it is gone. Nothing is fetched; unreadable objects are skipped.
616fn select_candidates(repo: &Repository, filter: ObjectFilterSpec) -> Result<Selection> {
617    let odb = repo.odb();
618    let pack_dir = odb.objects_dir().join("pack");
619    let (kept, rewritten): (Vec<_>, Vec<_>) = odb
620        .local_pack_indexes()?
621        .into_iter()
622        .partition(|idx| pack_dir.join(keep_name(&idx.pack_path)).is_file());
623    let in_any = |indexes: &[std::sync::Arc<PackIndex>], oid: &ObjectId| {
624        indexes.iter().any(|idx| idx.find_position(oid).is_some())
625    };
626    let will_be_rewritten =
627        |oid: &ObjectId| in_any(&rewritten, oid) || odb.local_loose_file_size(oid).is_some();
628    let checked_out = crate::promisor::blobs_needed_by_checkouts(repo)?;
629
630    let mut selection = Selection {
631        candidates: crate::objects::oid_hash_map(),
632        skipped_checked_out: 0,
633        skipped_kept_pack: 0,
634    };
635    // Selected blobs no rewritten tree names yet; settled when one does.
636    let mut unanchored: OidHashMap<u64> = crate::objects::oid_hash_map();
637    let mut blobs_seen = oid_hash_set();
638    let mut walked = oid_hash_set();
639    let mut queue: Vec<ObjectId> = crate::maintenance::collect_maintenance_object_roots(repo)?;
640    let oid_len = odb.hash_algo().len();
641    while let Some(oid) = queue.pop() {
642        if !walked.insert(oid) {
643            continue;
644        }
645        let Some(obj) = odb.try_read_once(&oid)? else {
646            continue;
647        };
648        match obj.kind {
649            ObjectKind::Commit => {
650                let commit = CommitRef::parse(&obj.data)?;
651                queue.push(commit.tree());
652                queue.extend(commit.parents().iter().copied());
653            }
654            ObjectKind::Tag => {
655                if let Some(target) = crate::objects::tag_object_line_oid(&obj.data) {
656                    queue.push(target);
657                }
658            }
659            ObjectKind::Tree => {
660                let anchors = will_be_rewritten(&oid);
661                for entry in TreeRefIter::with_oid_len(&obj.data, oid_len) {
662                    let entry = entry?;
663                    match entry.mode & 0o170000 {
664                        0o100000 | 0o120000 => {}
665                        0o040000 => {
666                            queue.push(entry.oid);
667                            continue;
668                        }
669                        // Submodule commits are not ours to move.
670                        _ => continue,
671                    }
672                    if anchors {
673                        if let Some(size) = unanchored.remove(&entry.oid) {
674                            selection.candidates.insert(entry.oid, size);
675                        }
676                    }
677                    if !blobs_seen.insert(entry.oid) {
678                        continue;
679                    }
680                    let Some(size) = selected_blob_size(odb, filter, &entry.oid)? else {
681                        continue;
682                    };
683                    if checked_out.contains(&entry.oid) {
684                        selection.skipped_checked_out += 1;
685                    } else if in_any(&kept, &entry.oid) {
686                        selection.skipped_kept_pack += 1;
687                    } else if anchors {
688                        selection.candidates.insert(entry.oid, size);
689                    } else {
690                        unanchored.insert(entry.oid, size);
691                    }
692                }
693            }
694            ObjectKind::Blob => {}
695        }
696    }
697    selection.skipped_kept_pack += unanchored.len();
698    Ok(selection)
699}
700
701/// The refusal [`OffloadError::KeptPackObjectPromised`] when an object going into
702/// the promisor pack (one of the unkept packs or loose objects, except `omit`)
703/// names an object only an ordinary `.keep` pack holds.
704///
705/// Free without such packs. With them, every commit, tree and tag to be rewritten
706/// is read, as the rewrite reads them anyway.
707fn kept_object_the_promisor_pack_names(
708    odb: &Odb,
709    omit: &OidHashMap<u64>,
710) -> Result<Option<OffloadError>> {
711    odb.reprepare_local_packs();
712    let (kept, rewritten): (Vec<_>, Vec<_>) = odb
713        .local_pack_indexes()?
714        .into_iter()
715        .partition(|idx| idx.pack_path.with_extension("keep").is_file());
716    let (kept_promisor, kept_ordinary): (Vec<_>, Vec<_>) =
717        kept.into_iter().partition(|idx| idx.is_promisor);
718    if kept_ordinary.is_empty() {
719        return Ok(None);
720    }
721    let loose: OidHashSet = odb
722        .enumerate_local_loose_objects()?
723        .into_iter()
724        .map(|(oid, _)| oid)
725        .collect();
726    let in_promisor_pack_after = |oid: &ObjectId| {
727        loose.contains(oid)
728            || [&rewritten, &kept_promisor]
729                .into_iter()
730                .flatten()
731                .any(|idx| idx.find_position(oid).is_some())
732    };
733    let mut only_kept: OidHashMap<usize> = crate::objects::oid_hash_map();
734    for (pack_no, idx) in kept_ordinary.iter().enumerate() {
735        for entry in idx.iter() {
736            let oid = ObjectId::from_bytes(entry.oid())?;
737            if !in_promisor_pack_after(&oid) {
738                only_kept.entry(oid).or_insert(pack_no);
739            }
740        }
741    }
742    if only_kept.is_empty() {
743        return Ok(None);
744    }
745    let mut referrers: Vec<ObjectId> = loose.iter().copied().collect();
746    for idx in &rewritten {
747        for entry in idx.iter() {
748            referrers.push(ObjectId::from_bytes(entry.oid())?);
749        }
750    }
751    let oid_len = odb.hash_algo().len();
752    let mut checked = oid_hash_set();
753    for referrer in referrers {
754        if omit.contains_key(&referrer) || !checked.insert(referrer) {
755            continue;
756        }
757        let kind = match odb.read_info_without_fetch(&referrer) {
758            Ok(info) => info.kind,
759            Err(Error::Object(ObjectError::NotFound { .. })) => continue,
760            Err(err) => return Err(err),
761        };
762        if kind == ObjectKind::Blob {
763            continue;
764        }
765        let obj = odb.read(&referrer)?;
766        let mut named: Vec<ObjectId> = Vec::new();
767        match kind {
768            ObjectKind::Commit => {
769                let commit = CommitRef::parse(&obj.data)?;
770                named.push(commit.tree());
771                named.extend(commit.parents().iter().copied());
772            }
773            ObjectKind::Tree => {
774                for entry in TreeRefIter::with_oid_len(&obj.data, oid_len) {
775                    let entry = entry?;
776                    if entry.mode & 0o170000 != 0o160000 {
777                        named.push(entry.oid);
778                    }
779                }
780            }
781            ObjectKind::Tag => named.extend(crate::objects::tag_object_line_oid(&obj.data)),
782            ObjectKind::Blob => {}
783        }
784        if let Some((oid, &pack_no)) = named.iter().find_map(|oid| only_kept.get_key_value(oid)) {
785            return Ok(Some(OffloadError::KeptPackObjectPromised {
786                pack: kept_ordinary[pack_no].pack_path.clone(),
787                oid: *oid,
788                referrer,
789            }));
790        }
791    }
792    Ok(None)
793}
794
795/// The size of `oid` when it is a blob stored locally that `filter` leaves out.
796fn selected_blob_size(odb: &Odb, filter: ObjectFilterSpec, oid: &ObjectId) -> Result<Option<u64>> {
797    if !odb.try_exists_stored(oid)? {
798        return Ok(None);
799    }
800    let info = match odb.read_info_without_fetch(oid) {
801        Ok(info) => info,
802        Err(Error::Object(ObjectError::NotFound { .. })) => return Ok(None),
803        Err(err) => return Err(err),
804    };
805    if info.kind != ObjectKind::Blob {
806        return Ok(None);
807    }
808    let selected = match filter {
809        ObjectFilterSpec::BlobNone => true,
810        ObjectFilterSpec::BlobLimit(limit) => info.size >= limit,
811    };
812    Ok(selected.then_some(info.size))
813}
814
815fn keep_name(pack_path: &Path) -> PathBuf {
816    PathBuf::from(pack_path.file_name().unwrap_or_default()).with_extension("keep")
817}
818
819/// Copy `blobs` from `repo` into one new `.keep` pack in `lop`; returns the pack and
820/// how many objects it holds.
821fn copy_to_lop(
822    repo: &Repository,
823    lop: &Repository,
824    blobs: &[ObjectId],
825    opts: &OffloadOptions,
826) -> Result<Option<(PathBuf, usize)>> {
827    let cfg = repo.config().snapshot().ok();
828    let pack_opts = PackBuildOptions {
829        delta: false,
830        window: 0,
831        max_depth: 0,
832        reuse_deltas: false,
833        reuse_objects: true,
834        use_bitmaps: false,
835        thin: false,
836        ..PackBuildOptions::for_local_copy(cfg.as_deref())
837    };
838    let lop_pack_dir = lop.odb().objects_dir().join("pack");
839    let built = crate::maintenance::write_staged_repack_pack(
840        repo.odb(),
841        &lop_pack_dir,
842        blobs,
843        &std::collections::HashMap::new(),
844        &pack_opts,
845        opts.threads,
846        cfg.as_deref(),
847    )?;
848    let Some(staging) = built.staging_path.as_ref() else {
849        return Ok(None);
850    };
851    let trusted_rows = (!built.index_rows.is_empty()).then_some(built.index_rows);
852    let ingested = install_pack_path_with_progress(
853        staging,
854        lop.odb(),
855        &IngestPackOptions {
856            threads: opts.threads,
857            environment: lop.environment().clone(),
858            skip_post_index_verify: trusted_rows.is_some(),
859            trusted_index_rows: trusted_rows,
860            keep_message: Some(LOP_KEEP_MESSAGE.to_owned()),
861            ..IngestPackOptions::default()
862        },
863        None,
864        None,
865    )?;
866    let objects = ingested.object_ids.len();
867    Ok(ingested.pack_path.map(|path| (path, objects)))
868}
869
870/// For each of `oids`, whether the LOP itself holds it in a pack offload wrote
871/// there (see [`lop_keep_packs`]).
872fn held_in_lop_keep_packs(lop: &Odb, oids: &[ObjectId]) -> Result<Vec<bool>> {
873    let kept = lop_keep_packs(lop)?;
874    Ok(oids
875        .iter()
876        .map(|oid| kept.iter().any(|idx| idx.find_position(oid).is_some()))
877        .collect())
878}
879
880/// The LOP's own packs whose `.keep` marker holds [`LOP_KEEP_MESSAGE`]: the packs
881/// offload wrote there.
882///
883/// Only a copy in one of those is safe to rely on before the main repository drops
884/// its own. Nothing in a ref-less LOP reaches a blob, so a loose object or one in
885/// an unkept pack goes at its next `gc`, and so does one in a pack kept only for a
886/// while: `receive-pack` and `fetch-pack` keep the pack they are writing until
887/// they have updated the refs, then remove the marker. A copy found through the
888/// LOP's alternates (possibly the main repository itself) is not the LOP's at all.
889///
890/// # Errors
891///
892/// Pack directory read failures.
893pub(crate) fn lop_keep_packs(lop: &Odb) -> Result<Vec<std::sync::Arc<PackIndex>>> {
894    Ok(lop
895        .local_pack_indexes()?
896        .into_iter()
897        .filter(|idx| has_lop_keep_marker(&idx.pack_path))
898        .collect())
899}
900
901/// Whether the `.keep` marker next to `pack_path` is one offload wrote.
902fn has_lop_keep_marker(pack_path: &Path) -> bool {
903    std::fs::read(pack_path.with_extension("keep"))
904        .is_ok_and(|contents| contents.trim_ascii_end() == LOP_KEEP_MESSAGE.as_bytes())
905}
906
907/// Set `changes` and add the values of `additions` (keeping earlier ones) in the
908/// local config of the repository at `git_dir`.
909fn write_config(
910    git_dir: &Path,
911    changes: &[(String, String)],
912    additions: &[(String, String)],
913) -> Result<()> {
914    if changes.is_empty() && additions.is_empty() {
915        return Ok(());
916    }
917    let path = git_dir.join("config");
918    let content = match std::fs::read_to_string(&path) {
919        Ok(content) => content,
920        Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
921        Err(err) => return Err(Error::Io(err)),
922    };
923    let mut config = ConfigFile::parse(&path, &content, ConfigScope::Local)?;
924    for (key, value) in changes {
925        config.set(key, value)?;
926    }
927    for (key, value) in additions {
928        config.add_value(key, value)?;
929    }
930    config.write()
931}
932
933/// `git_dir` as recorded in [`LOP_GIT_DIR_KEY`]: absolute, symlinks resolved when
934/// possible.
935fn lop_dir_value(git_dir: &Path) -> String {
936    use crate::git_path::CanonicalizeExt as _;
937    git_dir
938        .canonicalize_simplified()
939        .unwrap_or_else(|_| git_dir.to_path_buf())
940        .to_string_lossy()
941        .into_owned()
942}
943
944/// Whether two repositories store their objects in the same directory: one is the
945/// other, a linked worktree of it, or has its `objects/` linked to the other's.
946pub(crate) fn same_object_store(a: &Repository, b: &Repository) -> bool {
947    same_dir(a.odb().objects_dir(), b.odb().objects_dir())
948}
949
950/// Whether two paths name the same directory.
951pub(crate) fn same_dir(a: &Path, b: &Path) -> bool {
952    use crate::git_path::CanonicalizeExt as _;
953    match (a.canonicalize_simplified(), b.canonicalize_simplified()) {
954        (Ok(a), Ok(b)) => a == b,
955        _ => a == b,
956    }
957}
958
959/// Bytes of the repository's own packs (with indexes) and loose objects.
960fn local_object_bytes(odb: &Odb) -> Result<u64> {
961    odb.invalidate_packs();
962    let mut total = 0u64;
963    for idx in odb.local_pack_indexes()? {
964        for path in [&idx.pack_path, &idx.idx_path] {
965            total += std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
966        }
967    }
968    for (_, path) in odb.enumerate_local_loose_objects()? {
969        total += std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
970    }
971    Ok(total)
972}
973
974#[cfg(test)]
975#[allow(clippy::unwrap_used, clippy::expect_used)]
976mod tests {
977    use super::*;
978    use crate::repo::InitOptions;
979
980    const NOW: i64 = 1_700_000_000;
981
982    /// A bare main repository whose `main` commit holds one blob per entry of
983    /// `sizes` (file `f<i>`), a bare LOP next to it, and `remote.lop` in main.
984    struct Fixture {
985        dir: tempfile::TempDir,
986        blobs: Vec<ObjectId>,
987    }
988
989    /// `size` bytes that do not compress, different for each `seed`.
990    fn blob_data(seed: usize, size: usize) -> Vec<u8> {
991        let mut state = (seed as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15);
992        (0..size)
993            .map(|_| {
994                state ^= state << 13;
995                state ^= state >> 7;
996                state ^= state << 17;
997                state.to_le_bytes()[0]
998            })
999            .collect()
1000    }
1001
1002    impl Fixture {
1003        fn new(sizes: &[usize]) -> Self {
1004            let dir = tempfile::tempdir().unwrap();
1005            let init = InitOptions::new()
1006                .with_bare(true)
1007                .with_initial_branch("main");
1008            let (main, _) = Repository::init(&dir.path().join("main.git"), &init).unwrap();
1009            Repository::init(&dir.path().join("lop.git"), &init)
1010                .unwrap()
1011                .0;
1012            let odb = main.odb();
1013            let blobs: Vec<ObjectId> = sizes
1014                .iter()
1015                .enumerate()
1016                .map(|(i, &size)| odb.write(ObjectKind::Blob, &blob_data(i, size)).unwrap())
1017                .collect();
1018            let mut entries: Vec<crate::objects::TreeEntry> = blobs
1019                .iter()
1020                .enumerate()
1021                .map(|(i, oid)| crate::objects::TreeEntry {
1022                    mode: 0o100644,
1023                    name: format!("f{i}").into_bytes(),
1024                    oid: *oid,
1025                })
1026                .collect();
1027            entries.sort_by(|a, b| a.name.cmp(&b.name));
1028            let tree = odb
1029                .write(ObjectKind::Tree, &crate::objects::serialize_tree(&entries))
1030                .unwrap();
1031            let commit =
1032                format!("tree {tree}\nauthor A <a@e> 1 +0000\ncommitter A <a@e> 1 +0000\n\nseed\n");
1033            let commit = odb.write(ObjectKind::Commit, commit.as_bytes()).unwrap();
1034            std::fs::write(
1035                dir.path().join("main.git/refs/heads/main"),
1036                format!("{commit}\n"),
1037            )
1038            .unwrap();
1039            let fx = Self { dir, blobs };
1040            fx.append_main_config("[remote \"lop\"]\n\turl = ../lop.git\n");
1041            fx
1042        }
1043
1044        fn main_dir(&self) -> PathBuf {
1045            self.dir.path().join("main.git")
1046        }
1047
1048        fn lop_dir(&self) -> PathBuf {
1049            self.dir.path().join("lop.git")
1050        }
1051
1052        fn main(&self) -> Repository {
1053            Repository::open(&self.main_dir(), &RepositoryOptions::empty()).unwrap()
1054        }
1055
1056        fn lop(&self) -> Repository {
1057            Repository::open(&self.lop_dir(), &RepositoryOptions::empty()).unwrap()
1058        }
1059
1060        fn append_main_config(&self, text: &str) {
1061            let path = self.main_dir().join("config");
1062            let mut config = std::fs::read_to_string(&path).unwrap();
1063            config.push_str(text);
1064            std::fs::write(path, config).unwrap();
1065        }
1066
1067        fn offload(&self, limit: u64) -> OffloadReport {
1068            let mut opts = OffloadOptions::new("lop", NOW);
1069            opts.filter = Some(ObjectFilterSpec::BlobLimit(limit));
1070            offload_blobs(&self.main(), &opts).expect("offload")
1071        }
1072
1073        fn files(&self, dir: &Path, ext: &str) -> Vec<PathBuf> {
1074            std::fs::read_dir(dir.join("objects/pack"))
1075                .map(|entries| {
1076                    entries
1077                        .flatten()
1078                        .map(|e| e.path())
1079                        .filter(|p| p.extension().is_some_and(|e| e == ext))
1080                        .collect()
1081                })
1082                .unwrap_or_default()
1083        }
1084    }
1085
1086    #[test]
1087    fn blobs_at_the_limit_move_and_smaller_ones_stay() {
1088        let fx = Fixture::new(&[10_000, 9_999, 30_000]);
1089        let report = fx.offload(10_000);
1090        assert_eq!(report.candidates, 2);
1091        assert_eq!(report.candidate_bytes, 40_000);
1092        assert_eq!(report.copied_to_lop, 2);
1093        assert_eq!(report.dropped_from_main, 2);
1094        assert_eq!(report.filter, ObjectFilterSpec::BlobLimit(10_000));
1095
1096        let main = fx.main();
1097        let lop = fx.lop();
1098        for (i, moved) in [(0, true), (1, false), (2, true)] {
1099            let blob = fx.blobs[i];
1100            assert_eq!(!main.odb().exists_stored(&blob), moved, "main f{i}");
1101            assert_eq!(lop.odb().exists_stored(&blob), moved, "lop f{i}");
1102        }
1103        // The rest of main, the kept blob included, lives in one promisor pack; the
1104        // loose objects are gone.
1105        let promisor = fx.files(&fx.main_dir(), "promisor");
1106        assert_eq!(promisor.len(), 1);
1107        assert_eq!(
1108            report.main_pack.as_ref().and_then(|p| p.path.file_name()),
1109            promisor[0].with_extension("pack").file_name()
1110        );
1111        let indexes = main.odb().local_pack_indexes().unwrap();
1112        let promisor_idx = indexes
1113            .iter()
1114            .find(|i| i.is_promisor)
1115            .expect("promisor pack");
1116        assert_eq!(indexes.len(), 1);
1117        assert_eq!(promisor_idx.len(), 3, "the commit, its tree and f1");
1118        assert!(promisor_idx.find_position(&fx.blobs[1]).is_some());
1119        assert!(main
1120            .odb()
1121            .enumerate_local_loose_objects()
1122            .unwrap()
1123            .is_empty());
1124        assert!(report.main_bytes_after < report.main_bytes_before);
1125
1126        // The report describes each pack it wrote.
1127        let roles: Vec<_> = report.packs().map(|p| (p.role, p.objects)).collect();
1128        assert_eq!(
1129            roles,
1130            [
1131                (OffloadPackRole::Lop, 2),
1132                (OffloadPackRole::MainPromisor, 3),
1133            ]
1134        );
1135        for pack in report.packs() {
1136            assert_eq!(pack.bytes, std::fs::metadata(&pack.path).unwrap().len());
1137        }
1138        assert!(report
1139            .lop_pack
1140            .as_ref()
1141            .unwrap()
1142            .path
1143            .starts_with(fx.lop().git_dir()));
1144    }
1145
1146    #[test]
1147    fn lop_pack_is_kept_and_complete() {
1148        let fx = Fixture::new(&[4096]);
1149        let report = fx.offload(1024);
1150        let lop_pack = report.lop_pack.expect("lop pack").path;
1151        assert_eq!(
1152            std::fs::read_to_string(lop_pack.with_extension("keep")).unwrap(),
1153            format!("{LOP_KEEP_MESSAGE}\n")
1154        );
1155        let blob = fx.lop().odb().read(&fx.blobs[0]).unwrap();
1156        assert_eq!(blob.data, blob_data(0, 4096));
1157    }
1158
1159    #[test]
1160    fn config_is_set_in_main_and_optionally_in_the_lop() {
1161        let fx = Fixture::new(&[2048]);
1162        let mut opts = OffloadOptions::new("lop", NOW);
1163        opts.filter = Some(ObjectFilterSpec::BlobLimit(1024));
1164        opts.configure_lop = true;
1165        let report = offload_blobs(&fx.main(), &opts).unwrap();
1166        let lop_dir = lop_dir_value(fx.lop().git_dir());
1167        assert!(Path::new(&lop_dir).is_absolute());
1168        let keys: Vec<(OffloadRepo, &str, &str)> = report
1169            .config_changes
1170            .iter()
1171            .map(|c| (c.repo, c.key.as_str(), c.value.as_str()))
1172            .collect();
1173        assert_eq!(
1174            keys,
1175            [
1176                (OffloadRepo::Main, "remote.lop.promisor", "true"),
1177                (
1178                    OffloadRepo::Main,
1179                    "remote.lop.partialCloneFilter",
1180                    "blob:limit=1024"
1181                ),
1182                (OffloadRepo::Main, "repack.writeBitmaps", "false"),
1183                (OffloadRepo::Main, LOP_GIT_DIR_KEY, lop_dir.as_str()),
1184                (OffloadRepo::Lop, "uploadpack.allowFilter", "true"),
1185                (OffloadRepo::Lop, "uploadpack.allowAnySHA1InWant", "true"),
1186            ]
1187        );
1188        assert!(report.lop_ready.is_ready());
1189        assert!(!report.advertised);
1190        let config = fx.main().config().snapshot().unwrap();
1191        assert_eq!(config.value("remote.lop.promisor").as_deref(), Some("true"));
1192        assert!(config.value("extensions.partialclone").is_none());
1193        assert_eq!(
1194            crate::partial_clone::stored_remote_filter(&config, "lop"),
1195            Some(ObjectFilterSpec::BlobLimit(1024))
1196        );
1197        assert_eq!(config.values_all(LOP_GIT_DIR_KEY), [lop_dir.clone()]);
1198
1199        // The LOP is recorded once, however often offload runs.
1200        let again = offload_blobs(&fx.main(), &opts).unwrap();
1201        assert!(
1202            again.config_changes.is_empty(),
1203            "{:?}",
1204            again.config_changes
1205        );
1206        assert_eq!(
1207            fx.main()
1208                .config()
1209                .snapshot()
1210                .unwrap()
1211                .get_all(LOP_GIT_DIR_KEY)
1212                .unwrap(),
1213            vec![lop_dir]
1214        );
1215    }
1216
1217    #[test]
1218    fn stored_filter_is_used_and_lop_is_left_alone_by_default() {
1219        let fx = Fixture::new(&[2048, 10]);
1220        fx.append_main_config("\tpartialCloneFilter = blob:limit=1k\n");
1221        let report = offload_blobs(&fx.main(), &OffloadOptions::new("lop", NOW)).unwrap();
1222        assert_eq!(report.candidates, 1);
1223        assert_eq!(report.filter, ObjectFilterSpec::BlobLimit(1024));
1224        let keys: Vec<&str> = report
1225            .config_changes
1226            .iter()
1227            .map(|c| c.key.as_str())
1228            .collect();
1229        assert_eq!(
1230            keys,
1231            [
1232                "remote.lop.promisor",
1233                "repack.writeBitmaps",
1234                LOP_GIT_DIR_KEY
1235            ]
1236        );
1237        assert_eq!(report.lop_ready, LopReadiness::default());
1238    }
1239
1240    /// Every file under `dir` with its contents, sorted by path.
1241    fn tree_snapshot(dir: &Path) -> Vec<(PathBuf, Vec<u8>)> {
1242        let mut out = Vec::new();
1243        let mut stack = vec![dir.to_path_buf()];
1244        while let Some(path) = stack.pop() {
1245            if path.is_dir() {
1246                stack.extend(
1247                    std::fs::read_dir(&path)
1248                        .unwrap()
1249                        .flatten()
1250                        .map(|e| e.path()),
1251                );
1252            } else {
1253                out.push((path.clone(), std::fs::read(&path).unwrap()));
1254            }
1255        }
1256        out.sort();
1257        out
1258    }
1259
1260    #[test]
1261    fn dry_run_writes_nothing() {
1262        let fx = Fixture::new(&[2048]);
1263        let before = tree_snapshot(&fx.main_dir());
1264        let mut opts = OffloadOptions::new("lop", NOW);
1265        opts.filter = Some(ObjectFilterSpec::BlobNone);
1266        opts.dry_run = true;
1267        opts.configure_lop = true;
1268        let report = offload_blobs(&fx.main(), &opts).unwrap();
1269        assert!(report.dry_run);
1270        assert_eq!(report.candidates, 1);
1271        assert_eq!(report.copied_to_lop, 0);
1272        assert!(report.config_changes.is_empty());
1273        assert_eq!(tree_snapshot(&fx.main_dir()), before);
1274        assert!(fx.files(&fx.lop_dir(), "pack").is_empty());
1275        assert!(!fx.main_dir().join("gc.pid").exists());
1276    }
1277
1278    #[test]
1279    fn running_again_is_a_no_op_until_new_blobs_arrive() {
1280        let fx = Fixture::new(&[2048, 10]);
1281        fx.offload(1024);
1282        let again = fx.offload(1024);
1283        assert_eq!(again.candidates, 0);
1284        assert_eq!(again.copied_to_lop, 0);
1285        assert!(again.main_pack.is_none(), "nothing to rewrite");
1286        assert_eq!(fx.files(&fx.lop_dir(), "pack").len(), 1);
1287        assert_eq!(fx.files(&fx.main_dir(), "pack").len(), 1);
1288    }
1289
1290    /// Put `fx`'s first blob into a new LOP pack whose `.keep` marker says `message`.
1291    fn pack_into_lop(fx: &Fixture, message: &str) {
1292        let pack = crate::pack_objects::build_pack_from_send_list(
1293            fx.main().odb(),
1294            &[fx.blobs[0]],
1295            &std::collections::HashSet::new(),
1296            &PackBuildOptions::default(),
1297            &std::collections::HashMap::new(),
1298        )
1299        .unwrap();
1300        crate::index_pack::install_pack_bytes(
1301            pack,
1302            fx.lop().odb(),
1303            &IngestPackOptions {
1304                keep_message: Some(message.to_owned()),
1305                ..IngestPackOptions::default()
1306            },
1307        )
1308        .unwrap();
1309    }
1310
1311    #[test]
1312    fn blobs_the_lop_keeps_are_not_copied_again() {
1313        let fx = Fixture::new(&[2048]);
1314        pack_into_lop(&fx, LOP_KEEP_MESSAGE);
1315        let report = fx.offload(1024);
1316        assert_eq!(report.already_in_lop, 1);
1317        assert_eq!(report.copied_to_lop, 0);
1318        assert!(report.lop_pack.is_none());
1319        assert_eq!(report.dropped_from_main, 1);
1320    }
1321
1322    #[test]
1323    fn a_copy_another_writer_keeps_for_a_while_is_not_trusted() {
1324        // receive-pack and fetch-pack keep the pack they write until the refs are
1325        // updated, then remove the marker; an operator's marker is no promise either.
1326        for message in ["receive-pack 4242 on build-host", "pinned"] {
1327            let fx = Fixture::new(&[2048]);
1328            pack_into_lop(&fx, message);
1329            let report = fx.offload(1024);
1330            assert_eq!(report.already_in_lop, 0, "{message}");
1331            assert_eq!(report.copied_to_lop, 1, "{message}");
1332            let lop_pack = report.lop_pack.expect("copied").path;
1333            let keep = std::fs::read_to_string(lop_pack.with_extension("keep")).unwrap();
1334            assert_eq!(keep.trim_end(), LOP_KEEP_MESSAGE);
1335        }
1336    }
1337
1338    #[cfg(unix)]
1339    #[test]
1340    fn a_lop_sharing_main_objects_is_refused() {
1341        let fx = Fixture::new(&[2048]);
1342        let lop_objects = fx.lop_dir().join("objects");
1343        std::fs::remove_dir_all(&lop_objects).unwrap();
1344        std::os::unix::fs::symlink(fx.main_dir().join("objects"), &lop_objects).unwrap();
1345        let mut opts = OffloadOptions::new("lop", NOW);
1346        opts.filter = Some(ObjectFilterSpec::BlobLimit(1024));
1347        assert!(matches!(
1348            offload_err(&fx, &opts),
1349            OffloadError::LopIsMainRepository
1350        ));
1351        assert!(fx.main().odb().exists_stored(&fx.blobs[0]));
1352    }
1353
1354    /// Remove the LOP's loose objects, as its `gc --prune=now` would for blobs
1355    /// nothing in it references.
1356    fn prune_lop_loose(fx: &Fixture) {
1357        for (_, path) in fx.lop().odb().enumerate_local_loose_objects().unwrap() {
1358            std::fs::remove_file(path).unwrap();
1359        }
1360    }
1361
1362    #[test]
1363    fn a_loose_copy_in_the_lop_is_not_trusted() {
1364        let fx = Fixture::new(&[2048]);
1365        fx.lop()
1366            .odb()
1367            .write(ObjectKind::Blob, &blob_data(0, 2048))
1368            .unwrap();
1369        let report = fx.offload(1024);
1370        assert_eq!(report.already_in_lop, 0);
1371        assert_eq!(report.copied_to_lop, 1);
1372        assert!(report.lop_pack.is_some());
1373        assert_eq!(report.dropped_from_main, 1);
1374        prune_lop_loose(&fx);
1375        let lop = fx.lop();
1376        assert_eq!(
1377            lop.odb().read(&fx.blobs[0]).unwrap().data,
1378            blob_data(0, 2048),
1379            "the kept pack survives the LOP's prune"
1380        );
1381    }
1382
1383    #[test]
1384    fn a_copy_the_lop_borrows_from_main_is_not_trusted() {
1385        let fx = Fixture::new(&[2048]);
1386        let alternates = fx.lop_dir().join("objects/info/alternates");
1387        std::fs::create_dir_all(alternates.parent().unwrap()).unwrap();
1388        std::fs::write(
1389            &alternates,
1390            format!("{}\n", fx.main_dir().join("objects").display()),
1391        )
1392        .unwrap();
1393        let report = fx.offload(1024);
1394        assert_eq!(report.already_in_lop, 0);
1395        assert_eq!(report.copied_to_lop, 1);
1396        std::fs::remove_file(&alternates).unwrap();
1397        assert_eq!(
1398            fx.lop().odb().read(&fx.blobs[0]).unwrap().data,
1399            blob_data(0, 2048),
1400            "the LOP has its own copy"
1401        );
1402    }
1403
1404    #[test]
1405    fn running_again_folds_pushed_objects_into_the_promisor_pack() {
1406        let fx = Fixture::new(&[2048, 10]);
1407        fx.offload(1024);
1408        // A push since: a loose tree that still names the offloaded blob.
1409        let main = fx.main();
1410        let mut body = b"100644 big\0".to_vec();
1411        body.extend_from_slice(fx.blobs[0].as_bytes());
1412        let tree = main
1413            .odb()
1414            .write_loose_materialize(ObjectKind::Tree, &body)
1415            .unwrap();
1416        let again = fx.offload(1024);
1417        assert_eq!(again.candidates, 0);
1418        let pack = again.main_pack.expect("folded").path;
1419        let promisor: Vec<_> = fx
1420            .files(&fx.main_dir(), "promisor")
1421            .iter()
1422            .map(|p| p.file_name().map(|n| n.to_os_string()))
1423            .collect();
1424        assert_eq!(
1425            promisor,
1426            [pack
1427                .with_extension("promisor")
1428                .file_name()
1429                .map(|n| n.to_os_string())]
1430        );
1431        let main = fx.main();
1432        assert!(main
1433            .odb()
1434            .enumerate_local_loose_objects()
1435            .unwrap()
1436            .is_empty());
1437        assert!(main.odb().exists_stored(&tree));
1438        assert!(!main.odb().exists_stored(&fx.blobs[0]));
1439    }
1440
1441    #[test]
1442    fn blobs_in_kept_packs_stay() {
1443        let fx = Fixture::new(&[2048]);
1444        let main = fx.main();
1445        let pack = crate::pack_objects::build_pack_from_send_list(
1446            main.odb(),
1447            &[fx.blobs[0]],
1448            &std::collections::HashSet::new(),
1449            &PackBuildOptions::default(),
1450            &std::collections::HashMap::new(),
1451        )
1452        .unwrap();
1453        crate::index_pack::install_pack_bytes(
1454            pack,
1455            main.odb(),
1456            &IngestPackOptions {
1457                keep_message: Some("pinned".into()),
1458                ..IngestPackOptions::default()
1459            },
1460        )
1461        .unwrap();
1462        let report = fx.offload(1024);
1463        assert_eq!(report.candidates, 0);
1464        assert_eq!(report.skipped_kept_pack, 1);
1465        assert!(fx.main().odb().exists_stored(&fx.blobs[0]));
1466    }
1467
1468    /// Pack `oids` of main into a new pack with a `.keep` marker, dropping their
1469    /// loose copies.
1470    fn keep_in_main(fx: &Fixture, oids: &[ObjectId]) -> PathBuf {
1471        let main = fx.main();
1472        let pack = crate::pack_objects::build_pack_from_send_list(
1473            main.odb(),
1474            oids,
1475            &std::collections::HashSet::new(),
1476            &PackBuildOptions::default(),
1477            &std::collections::HashMap::new(),
1478        )
1479        .unwrap();
1480        let installed = crate::index_pack::install_pack_bytes(
1481            pack,
1482            main.odb(),
1483            &IngestPackOptions {
1484                keep_message: Some("pinned".into()),
1485                ..IngestPackOptions::default()
1486            },
1487        )
1488        .unwrap();
1489        crate::prune_packed::prune_packed_objects(main.odb().objects_dir(), Default::default())
1490            .unwrap();
1491        installed.pack_path.unwrap()
1492    }
1493
1494    #[test]
1495    fn a_kept_object_the_promisor_pack_would_name_stops_offload() {
1496        // f1 (small, staying) has its only copy in an operator's kept pack, and the
1497        // tree naming it is loose: in the promisor pack it would make f1 promised.
1498        let fx = Fixture::new(&[2048, 10]);
1499        let kept = keep_in_main(&fx, &[fx.blobs[1]]);
1500        let mut opts = OffloadOptions::new("lop", NOW);
1501        opts.filter = Some(ObjectFilterSpec::BlobLimit(1024));
1502        for dry_run in [true, false] {
1503            opts.dry_run = dry_run;
1504            match offload_err(&fx, &opts) {
1505                OffloadError::KeptPackObjectPromised { pack, oid, .. } => {
1506                    assert_eq!(pack, kept);
1507                    assert_eq!(oid, fx.blobs[1]);
1508                }
1509                other => panic!("got {other:?}"),
1510            }
1511        }
1512        assert!(fx.files(&fx.lop_dir(), "pack").is_empty(), "nothing copied");
1513        assert!(fx.files(&fx.main_dir(), "promisor").is_empty());
1514        assert!(fx.main().odb().exists_stored(&fx.blobs[0]));
1515
1516        // Without the marker the pack is folded in like any other.
1517        std::fs::remove_file(kept.with_extension("keep")).unwrap();
1518        let report = fx.offload(1024);
1519        assert_eq!(report.dropped_from_main, 1);
1520        let main = fx.main();
1521        let indexes = main.odb().local_pack_indexes().unwrap();
1522        assert_eq!(indexes.len(), 1);
1523        assert!(indexes[0].is_promisor);
1524        assert!(indexes[0].find_position(&fx.blobs[1]).is_some());
1525    }
1526
1527    #[test]
1528    fn a_kept_pack_nothing_names_does_not_stop_offload() {
1529        let fx = Fixture::new(&[2048]);
1530        let stray = fx
1531            .main()
1532            .odb()
1533            .write(ObjectKind::Blob, b"named by nothing")
1534            .unwrap();
1535        let kept = keep_in_main(&fx, &[stray]);
1536        let report = fx.offload(1024);
1537        assert_eq!(report.dropped_from_main, 1);
1538        assert!(kept.is_file() && kept.with_extension("keep").is_file());
1539        assert!(fx.main().odb().exists_stored(&stray));
1540    }
1541
1542    #[test]
1543    fn blobs_a_checkout_needs_stay() {
1544        let dir = tempfile::tempdir().unwrap();
1545        let work = dir.path().join("work");
1546        let (repo, _) =
1547            Repository::init(&work, &InitOptions::new().with_initial_branch("main")).unwrap();
1548        Repository::init(
1549            &dir.path().join("lop.git"),
1550            &InitOptions::new().with_bare(true),
1551        )
1552        .unwrap();
1553        std::fs::write(work.join("big"), vec![b'x'; 4096]).unwrap();
1554        crate::porcelain::add::stage_for_commit(
1555            &repo,
1556            &mut crate::progress::NullProgress,
1557            &crate::progress::CancelToken::never(),
1558        )
1559        .unwrap();
1560        let ident = "T <t@example.com> 1 +0000".to_string();
1561        let mut req = crate::porcelain::commit::CommitRequest::new("big");
1562        let sig: crate::ident::Signature = ident.parse().unwrap();
1563        req.author = Some(sig.clone());
1564        req.committer = Some(sig);
1565        crate::porcelain::commit::create_commit(
1566            &repo,
1567            &req,
1568            &mut crate::progress::NullProgress,
1569            &crate::progress::CancelToken::never(),
1570        )
1571        .unwrap();
1572        let config = repo.git_dir().join("config");
1573        let mut text = std::fs::read_to_string(&config).unwrap();
1574        text.push_str(&format!(
1575            "[remote \"lop\"]\n\turl = {}\n",
1576            dir.path().join("lop.git").display()
1577        ));
1578        std::fs::write(&config, text).unwrap();
1579        let repo = Repository::discover(Some(&work), &RepositoryOptions::empty()).unwrap();
1580        let mut opts = OffloadOptions::new("lop", NOW);
1581        opts.filter = Some(ObjectFilterSpec::BlobLimit(1024));
1582        let report = offload_blobs(&repo, &opts).unwrap();
1583        assert_eq!(report.candidates, 0);
1584        assert_eq!(report.skipped_checked_out, 1);
1585    }
1586
1587    fn offload_err(fx: &Fixture, opts: &OffloadOptions) -> OffloadError {
1588        match offload_blobs(&fx.main(), opts) {
1589            Err(Error::Object(ObjectError::Offload(err))) => err,
1590            other => panic!("expected an offload error, got {other:?}"),
1591        }
1592    }
1593
1594    #[test]
1595    fn refusals_are_typed() {
1596        let fx = Fixture::new(&[2048]);
1597        let with_filter = |remote: &str| {
1598            let mut opts = OffloadOptions::new(remote, NOW);
1599            opts.filter = Some(ObjectFilterSpec::BlobNone);
1600            opts
1601        };
1602        assert!(matches!(
1603            offload_err(&fx, &with_filter("nope")),
1604            OffloadError::RemoteNotConfigured { remote } if remote == "nope"
1605        ));
1606        assert!(matches!(
1607            offload_err(&fx, &OffloadOptions::new("lop", NOW)),
1608            OffloadError::NoThreshold { .. }
1609        ));
1610
1611        fx.append_main_config(
1612            "[remote \"web\"]\n\turl = https://user:secret@lop.example/r.git\n\
1613             [remote \"self\"]\n\turl = .\n\
1614             [remote \"gone\"]\n\turl = ../nothing-here.git\n",
1615        );
1616        match offload_err(&fx, &with_filter("web")) {
1617            OffloadError::LopNotLocal { url, .. } => assert!(!url.contains("secret")),
1618            other => panic!("got {other:?}"),
1619        }
1620        assert!(matches!(
1621            offload_err(&fx, &with_filter("self")),
1622            OffloadError::LopIsMainRepository
1623        ));
1624        assert!(matches!(
1625            offload_err(&fx, &with_filter("gone")),
1626            OffloadError::LopNotARepository { .. }
1627        ));
1628
1629        let sha256 = fx.dir.path().join("sha256.git");
1630        Repository::init(
1631            &sha256,
1632            &InitOptions::new()
1633                .with_bare(true)
1634                .with_object_format(HashAlgo::Sha256),
1635        )
1636        .unwrap();
1637        let mut opts = with_filter("web");
1638        opts.lop_git_dir = Some(sha256);
1639        assert!(matches!(
1640            offload_err(&fx, &opts),
1641            OffloadError::HashAlgoMismatch {
1642                main: HashAlgo::Sha1,
1643                lop: HashAlgo::Sha256
1644            }
1645        ));
1646
1647        std::fs::write(fx.main_dir().join("gc.pid"), "1 some-other-host").unwrap();
1648        assert!(matches!(
1649            offload_err(&fx, &with_filter("lop")),
1650            OffloadError::MaintenanceRunning { .. }
1651        ));
1652    }
1653}