Repository maintenance runs through one handle, repo.maintenance(), which returns a Maintenance. Its options and result types live in maintenance. Long-running operations (gc, gc_auto, repack, repack_all, fsck) take a ProgressSink and a CancelToken as their last two parameters; pass &mut NullProgress and &CancelToken::never() when neither matters.
use grit_lib::maintenance::GcOptions;
use grit_lib::progress::{CancelToken, NullProgress};
let stats = repo.maintenance().gc(
&GcOptions::full_run(false, now_unix),
&mut NullProgress,
&CancelToken::never(),
)?;
println!("packed {:?} objects", stats.repack.objects_packed);
Maintenance::write_commit_graph— atomic monolithicobjects/info/commit-graphwith optional changed-path Bloom filters (CommitGraphOptions,CommitGraphWriteReport). Shallow clones,info/graftsand enabled replace refs change commit parents, so no graph is written there and any existing one is deleted (Git ignores graphs in that state butgit fsckstill rejects them);CommitGraphWriteReport::skippedholds theCommitGraphSkipReason. Writing needs the files backend; a repository with a custom primary store getsRepositoryError::UnsupportedObjectStorewithFilesOnlyOperation::CommitGraphWrite.Maintenance::build_commit_graph— the same graph built in memory through any object store, custom primaries included, returned as aCommitGraphBuild. TheBuiltCommitGraphbytes match whatwrite_commit_graphinstalls; a custom store keeps them itself and attaches them withOdbBuilder::commit_graph(see Object stores).Maintenance::write_midx— writemulti-pack-index(MidxOptions,MidxWriteReport). The file is format version 1 by default, readable by every Git with multi-pack-index support;MidxOptions::version, thenmidx.versionin config, select version 2. Other values fail withMidxError::UnknownWriteVersionbefore anything is written, including in dry-run mode. Incremental repack follows the samemidx.versionsetting when it writes a multi-pack-index bitmap.Maintenance::pack_refs— pack loose refs intopacked-refsor compact reftable stacks (PackRefsOptions).Maintenance::repack_allandMaintenance::gcorchestrate repack and prune;Maintenance::prune_loose_objectsdeletes unreachable loose objects older thangc.pruneExpire;Maintenance::fsckvalidates the result. Indexing the new pack reportsProgressPhase::IndexingObjectsandResolvingDeltas, andcancelis checked between phases and before a new pack is published.Maintenance::gc_autoisgit gc --auto:Maintenance::auto_gc_neededappliesgc.auto(loose objects estimated fromobjects/17, two directory reads in total) andgc.autoPackLimitand returns anAutoGcReason. Too many loose objects packs the reachable ones into one new, self-contained pack without touching existing packs (unreachable ones stay loose forgc.pruneExpire), delta-compressed withpack.window/pack.depthlike a full repack; too many packs runs a full consolidating gc. The result is anAutoGcOutcome(not needed, already running, declined by thepre-auto-gchook, or ran withGcStats). Call it after writing objects; the library never forks, so an application that honorsgc.autoDetach(ConfigSet::gc_auto_detach) runs it on its own thread or process.gcandgc_autohold Git'sgc.pidlock (GcLock) while they run, so maintenance never overlaps another grit or Git gc. A held lock isError::MaintenanceRunningfromgcandAutoGcOutcome::AlreadyRunningfromgc_auto.Maintenance::try_locktakes the same lock for an operation of your own, andMaintenance::lock_holderreports a live holder without taking it. Duringgc,gc.writeCommitGraphandcore.commitGraphgate commit-graph generation (existing graphs are kept when skipped),gc.packRefsgates pack-refs (notbarepacks only when the repository has a work tree), and the last ofrepack.writeBitmaps/pack.writeBitmapsin config load order selects whether repack writes a bitmap (unset defaults to true on bare repos). Explicitwrite_commit_graphandpack_refsignore the gc-only keys.Maintenance::prune_loose_objectsandMaintenance::gcalso run on a custom primary that can delete objects (PrunableObjectStore); see Garbage collection on a custom store. Withextensions.preciousObjectsset,prune_loose_objectsfails withRepositoryError::PreciousObjectsRepositoryon any backend, andgcon a custom store skips its prune step.
Maintenance APIs split into repository fsck, object validation, and hook execution:
maintenance::repository_fsck— repository-wide integrity checks (loose/pack objects, connectivity fromMaintenance::reachability_roots— every ref tip, reflog entry, stash, linked-worktreeHEAD, and index including each non-bare worktree's index plusGIT_INDEX_FILEwhen set), dangling objects, refs, MIDX, commit-graph).reachability_rootsreturns that root set for embedders callingprune_loose_unreachable; ref tips alone are not enough for prune. Progress viaProgressSink; severity follows Git defaults andfsck.<msg-id>config (issue_severity). EachFsckIssuereports the object it concerns (FsckIssue::oid), the file or ref it was found in (FsckIssue::location), and a one-line description (FsckIssue::detail), so callers can render findings without matching every variant. Packs are memory-mapped and verified in one depth-first pass over their delta trees on worker threads: each object is inflated once, hashed against its index entry and checked, then its bytes are dropped. Peak memory therefore follows the delta chains being walked plus a few dozen bytes per object (commit and tag links, object kinds), not the uncompressed size of the pack. A delta whose base is corrupt, missing or fails its hash check is reported ascorruptObjectalong with every delta built on it. The connectivity walk re-reads trees from the object store, as Git does, instead of caching every tree entry.maintenance::fsck— validate loose object bytes before hashing (fsck_object,FsckErrorwith Git-compatible message ids). Connectivity walks for receive-pack and bundles live inmaintenance::repository_fsck.Maintenance::repack— all-into-one repack usingMaintenance::reachability_roots, optional.rev/.bitmapsidecars, pack pruning, and unreachable loose-object pruning viaRepackOptions/RepackReport.Repository::repackis a thin alias. Objects already in a pack keep their stored form (whole objects byte for byte, deltas with their base reference rewritten, chains capped atpack.depth); only loose objects and deltas whose base is dropped go through a streamingpack.windowdelta search, and the pack streams to disk. SetRepackOptions::force_recompressto recompute every delta, likegit repack -f. Incremental repack (RepackOptions::incremental) keeps existing packs; when combined withwrite_bitmapand multiple packs, grit writes a multi-pack-index reachability bitmap instead of a single-pack sidecar.hooks— resolve and run hook scripts through the repositoryCommandRunner(RepositoryHooks::run,HookResult). A hook that runs and exits non-zero isOk(HookResult::Failed { status, output })with its real exit status; a hook that cannot be started at all isHookError::Spawncarrying the program, theio::Error, and whatever earlier hooks for the event (configuredhook.<name>.*entries run first) already wrote. The library never prints hook output. By default (HookStdio::Capture) both streams are piped and returned as aHookOutputin the result, and inHookError::FailedwhenHookResult::checkorcommit_worktreeturns a failingpre-commitorcommit-msginto an error, so a TUI or GUI can show it in its own pane. TheDisplayof the error stays one line. A terminal front end that wants Git's live output opens the repository withRepositoryOptions::with_hook_stdio(HookStdio::Inherit): the hook then writes straight to the process's stderr (its stdout too, except forpre-push) and the returned output is empty. Output an injectedCommandRunnerreturns is only ever handed back, never re-emitted. Server-side hooks run by receive-pack are always captured and relayed to the client on the sideband. Scripts the OS refuses to execute run throughsh(/bin/shon Unix; on Windows the#!interpreter, resolved in the Git for Windows tree and then on the hook'sPATH). Apost-commithook that cannot start never fails the commit; it is reported asWarning::HookNotRun. The same holds for the hooks porcelain runs after an operation completes:switch_repositoryrunspost-checkout,Merge::integrate_into_branchrunspost-merge, an amendingcreate_commitrunspost-rewrite amend, andHistory::applyrunspost-checkoutandpost-rewrite rebase(pairs fromRewritePlan::rewritten_pairs). Each takes aPostOperationHooksoption (Skipto opt out) and reports what ran asHookNamevalues;RepositoryHooks::run_post_checkout,RepositoryHooks::run_post_mergeandRepositoryHooks::run_post_rewriterun one hook with Git's arguments. The hooks that run before an operation records anything can refuse it, withError::HookwrappingHookError::Failed:create_commitrunspre-commit,prepare-commit-msg <COMMIT_EDITMSG> <source>andcommit-msg;integrate_branch_withrunspre-merge-commit, thenprepare-commit-msg <MERGE_MSG> mergeandcommit-msgwithMERGE_HEADrecorded, and leaves the merge in progress when one refuses;History::start_rebaserunspre-rebaseasRebaseOntoOptions::pre_rebasesays, once the branch is known not to be up to date and before any commit is replayed, so a refusal comes before a replay conflict and writes nothing (History::plan_rebasedoes the same for callers that plan and apply a rebase themselves,RepositoryHooks::run_pre_rebaseruns the bare hook).HookPolicy::SkipVerify(CommitRequest::hooks,MergeOptions::verify) is--no-verify: it skipspre-commit,pre-merge-commitandcommit-msg, neverprepare-commit-msg. Hooks inherit every variable of the repositoryEnvironmentsnapshot.Repository::hookslists scripts viaRepositoryHooks::list(HookInfo,HookSource). Tests often installRecordingRunnerviaRepositoryOptions.patch_ids—Repository::patch_idandcompute_patch_idfor stable/unstable commit equivalence (merge commits returnNone). Text diffs use unified hunks with three context lines on each side, matchinggit show --format= --no-ext-diff -U3 <REV> | git patch-id --stablein stable mode. Nearby unchanged context is hashed; distant unchanged lines are excluded.compute_patch_id_for_pathsapplies the same rules to selected paths, whilecompute_patch_ids_from_texthashes the hunks supplied by its caller, including their chosen context.Repository::patch_ids_for_revstakes revision specs and expands ranges:A..Byields one(patch_id, commit)pair per commit inrev-listorder, andA...Byields both sides as one unlabelled sequence. To compare the two sides ofA...B(for example a branch before and after a force-push), setRevWalkListOptions::cherry_markand readRevListResult::cherry_matches: eachCherryMatchlists the left and right commits sharing one patch-id, and for a one-to-one pair says whether the commit message changed.
Maintenance::offload_blobs moves large blobs from a repository to a large-object promisor (LOP), the way git repack -a -d --filter=blob:limit=<n> --filter-to=<lop> does in Git's own LOP tests. OffloadOptions names the promisor remote and the filter: blob:limit=<n> selects blobs of at least n bytes, and the default is the remote's partialCloneFilter. The current time is passed in for the gc.pid lock. Nothing leaves the main repository before the LOP has it. Candidate blobs are copied into one new LOP pack, whole, and its .keep marker (IngestPackOptions::keep_message) is written before the pack appears, so a gc on the LOP cannot prune the unreferenced blobs. Only a copy the LOP itself holds in a .keep pack counts as already there: a loose or unkept copy may be pruned by the LOP's gc, and one reached through the LOP's alternates is not the LOP's, so those candidates are copied too. Every candidate is then checked to be in a .keep pack of the LOP, and the new pack is flushed to disk. Next remote.<name>.promisor is set (and partialCloneFilter, when the filter was given), along with repack.writeBitmaps = false, without which git gc fails on the repository once something is pushed, and the LOP's git directory is added to grit.lopGitDir (LOP_GIT_DIR_KEY). Finally the main repository's packs and loose objects are rewritten into one .promisor pack without the candidates, and that pack is flushed to disk before the old packs go. The blobs that stay go into it too, although only the main repository has them: Git treats every blob a promisor-pack tree names as promised, and its repack -a -d and gc keep a promised object only when it is in a promisor pack, so a kept blob in an ordinary pack would be deleted. A repository whose kept blobs are in an ordinary pack is folded back on the next run. That rewrite keeps unreachable objects and leaves .keep packs alone. It deletes only the packs it listed when it started, so a concurrent push survives. Blobs a worktree's index or HEAD needs, and blobs in .keep packs, stay. The OffloadReport counts what moved, describes each pack it wrote (OffloadPack: its role, path, object count and size), and lists the config it set (OffloadConfigChange). It also says whether the LOP can answer lazy fetches (LopReadiness) and whether promisor.advertise tells clients about it. Refusals are typed OffloadErrors inside Error::Offload. Running it again offloads blobs pushed since and folds objects pushed since into the promisor pack, even when no blob moves; it has nothing to do otherwise. Like every maintenance step except pack_refs, it takes a trailing ProgressSink and CancelToken; cancellation is honoured until the blobs are safely in the LOP, and once the main repository starts dropping its copies the run completes.
use grit_lib::maintenance::OffloadOptions;
use grit_lib::progress::{CancelToken, NullProgress};
use grit_lib::remote::partial_clone::ObjectFilterSpec;
let mut opts = OffloadOptions::new("lop", now_unix);
opts.filter = Some(ObjectFilterSpec::BlobLimit(1024 * 1024));
opts.configure_lop = true; // uploadpack.allowFilter + allowAnySHA1InWant in the LOP
let report = repo
.maintenance()
.offload_blobs(&opts, &mut NullProgress, &CancelToken::never())?;
println!("moved {} blobs, main {} -> {} bytes",
report.dropped_from_main, report.main_bytes_before, report.main_bytes_after);
Dropping promised large blobs
A partial clone keeps every large blob it ever fetched. Maintenance::drop_promised_blobs removes the ones the promisor remote can supply again and nothing has needed recently, so they come back through the ordinary lazy fetch the next time something reads them. DropPromisedBlobsOptions carries the size threshold (blob:limit semantics: at least min_size bytes), the recency cutoff and the current time, all passed in; DropPromisedBlobsOptions::from_config reads maintenance.drop-large-blobs.minSize and .expire, and lets a caller's own size or DropExpiry (parsed from never, now or a date) take the place of either key, which is then not read. An expire that is not a date is ConfigError::InvalidDate. drop_large_blobs_enabled says whether gc runs it as a phase (GcOptions::drop_large_blobs, GcStats::drop_large_blobs); gc checks that config before its first phase, and skips the phase (DropPromisedBlobsSkip::NoCurrentTime) when GcOptions::now_unix is 0 rather than read a clock.
Only blobs stored in .promisor packs are candidates, and one is dropped only when it is stored nowhere else locally, no pack holding it has a .keep marker, some tree or tag in a promisor pack names it (so Git still treats it as promised once it is gone), no worktree's index (nor a GIT_INDEX_FILE one) or HEAD tree uses it, no commit a worktree's HEAD reflog named since the cutoff uses it, no promisor pack holding it was written since the cutoff, and a promisor can supply it again. A blob in a promisor pack of a partial clone was fetched from the promisor, but offload's promisor pack also holds blobs only the main repository has, so promisors this machine can read (remotes with a local URL, and the LOP directories in grit.lopGitDir) are checked: a blob one of them stores in its own object directory can go. One none of them stores stays when every promisor remote was checked (KeptBlobCounts::not_in_promisor) or offload has run here, since a network promisor cannot be asked without fetching (KeptBlobCounts::unverified). A partial clone of network remotes only, with no grit.lopGitDir, trusts its promisor packs as Git does and reads nothing more. The DropPromisedBlobsReport lists the dropped blobs (DroppedBlob) and counts the rest by reason (KeptBlobCounts). Deciding reads pack headers, the trees of the protected commits and, until every remaining candidate is found, the trees in promisor packs; it never fetches. Packs holding only dropped blobs are deleted and other affected packs rewritten, keeping their .promisor contents and modification time. Refusals are typed: ObjectError::NoPromisorRemote, MergeError::OperationInProgress, RepositoryError::PreciousObjectsRepository and RepositoryError::MaintenanceRunning; inside gc the first three become DropPromisedBlobsSkip values instead.
use grit_lib::maintenance::DropPromisedBlobsOptions;
use grit_lib::progress::{CancelToken, NullProgress};
let two_weeks_ago = now - time::Duration::weeks(2);
let opts = DropPromisedBlobsOptions::new(now, 1024 * 1024, Some(two_weeks_ago));
let report = repo
.maintenance()
.drop_promised_blobs(&opts, &mut NullProgress, &CancelToken::never())?;
println!("dropped {} blobs, freed {} bytes ({} kept for a checkout)",
report.dropped.len(), report.bytes_reclaimed, report.kept.checked_out);
Like Git's, fsck never fetches: a promised object that is missing stays missing, even with a promisor fetcher installed.
Partial-clone maintenance works offline. Repack keeps existing .promisor packs and their sidecars intact, and writes local objects into a separate unmarked pack. GC, reflog expiry, pruning, incremental repack, and dry runs honor promises without hydrating missing history. Missing non-promised objects still fail validation. Bitmaps are omitted when the local pack cannot contain the complete closure; RepackStats::pack_path and pack_bytes refer to the newly written local pack even when other packs remain.
The grit CLI maps fsck and hook failures to its own exit codes and messages; the library returns typed results only.
Fsck diagnostic summaries
Call FsckReport::summary
with the configuration, fsck options, and an include_info boolean to classify a
report for display. The returned
FsckSummary keeps
all findings in discovery order as borrowed
FsckDiagnostic
values, each with its resolved severity and listing visibility. No objects are
read or changed by classification.
summary.ok is false if any finding has error severity. summary.has_warnings
records warnings independently of errors; visible informational findings do not
count as warnings. include_info changes visibility only. By default, most
informational findings are hidden, while missingTaggerEntry remains visible.
The CLI uses this policy for human listings and summary messages; JSON and
Markdown retain every finding, including hidden informational findings.
Benchmarking
The October 2026 diagnostic-summary extraction was checked against main
7cc7979535ce and system Git 2.55.0 on a Linux factory VM with four AMD EPYC 7763
vCPUs, using Rust 1.99.0 and the dist profile. Builds and tests were idle during
measurement. Times below are median milliseconds.
| Repository and operation | Git | Grit before | Grit after |
|---|---|---|---|
20,000 files, 50,000 commits: fsck --no-dangling |
267.38 | 221.36 | 221.76 |
1,001 warning trees and an informational tag finding: fsck --no-dangling |
23.75 | 15.72 | 15.37 |
The large-repository row uses 30 interleaved rounds with randomized tool order, after three warmups per tool. Maximum process RSS was 60,960 KiB before and 60,724 KiB after, versus 28,444 KiB for Git. The diagnostic-heavy row uses hyperfine with five warmups and at least 30 runs per tool; it exercises severity and visibility classification rather than an empty report.
The standard grit-bench fsck --warmup 3 --min-runs 10 scenario also ran on both
builds: 207.99 to 214.31 ms for grit, with Git at 265.00 and 261.92 ms respectively.
The subsequent interleaved comparison put grit's medians within 0.2%, with the
paired sample variability including no change. Summary classification performs
no additional object reads and resolves severity once per finding.