# Object stores

> Pluggable ObjectStore backends, RepositoryOptions::with_object_store, OdbBuilder layers, and the odb_conformance test suite.

**Implementing a backend?** Start with [Writing storage backends](https://grit-scm.com/docs/library/object-stores/storage-backends.md/index.md) for traits, init, capabilities, conformance testing, and the SQLite walkthrough.

By default [`Repository`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) opens a files-backed [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) (loose objects, packs, and optional MIDX). Embedders swap the **primary** store with [`RepositoryOptions::with_object_store`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_object_store), and add read-only layers, an attached commit-graph or an alternates override with an [`OdbBuilder`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.OdbBuilder.html) passed to [`RepositoryOptions::with_odb_builder`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_odb_builder). Neither takes a path: [`Repository::open`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.open) resolves the `objects/` directory itself.

## Traits

| Trait | Role |
| ----- | ---- |
| [`ObjectStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.ObjectStore.html) | Read, metadata, streaming, enumeration |
| [`WritableObjectStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.WritableObjectStore.html) | Insert objects (idempotent writes) |
| [`PrunableObjectStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.PrunableObjectStore.html) | Optional: delete objects, so `gc` and `prune` work on the store (see [Garbage collection on a custom store](#garbage-collection-on-a-custom-store)) |

Built-in backends live under [`grit_lib::objects::odb::store`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/index.html) (`LooseStore`, `FilesSource`, `MemoryStore`, `CompositeStore`, and others).

## Lookup order

For a given [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) handle:

1. In-memory overlay (when enabled for merge-tree-style operations)
2. **Primary** store — files source by default, or your custom [`WritableObjectStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.WritableObjectStore.html)
3. Extra read sources from `OdbBuilder::push_read_source`
4. Alternate object directories (`info/alternates`, environment alternates, submodule object dirs). They are on for the files primary and off for a custom primary unless `OdbBuilder::alternates(true)` turns them on; `OdbBuilder::alternates(false)` turns them off for the files primary.

[`Odb::read_store`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.read_store) returns that whole chain as one `Arc<dyn ObjectStore>`, whatever the primary is. Hand it to another repository's `push_read_source` to layer one repository under another (a read-through cache or a mirror), or pass it as the `bases` of `ingest_pack_into`. A missing object is `Ok(None)` and never starts a promisor fetch. Its `open_stream` buffers the payload; for a large blob call [`Odb::with_stream`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.with_stream) on the `Odb` itself.

The narrower accessors keep their meaning: [`Odb::sources`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.sources) is the alternates alone (step 4), and [`Odb::primary`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.primary) returns the files-backed primary and fails with `UnsupportedObjectStore` (`files_source`) on a custom one. Use [`Odb::primary_writable`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.primary_writable) for the primary of any kind.

```rust
use std::path::Path;
use std::sync::Arc;

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::odb::store::MemoryStore;
use grit_lib::objects::odb::OdbBuilder;
use grit_lib::objects::{HashAlgo, ObjectKind};
use grit_lib::refs::store::MemoryRefStore;
use grit_lib::repo::Repository;

let in_memory = || {
    RepositoryOptions::empty()
        .with_object_store(Arc::new(MemoryStore::new(HashAlgo::Sha1)))
        .with_ref_store(Arc::new(MemoryRefStore::new()))
};
let upstream = Repository::open(Path::new("/nowhere/upstream.git"), &in_memory())?;
let mirror = Repository::open(
    Path::new("/nowhere/mirror.git"),
    &in_memory().with_odb_builder(OdbBuilder::new().push_read_source(upstream.odb().read_store())),
)?;
let oid = upstream.odb().write(ObjectKind::Blob, b"shared")?;
assert!(mirror.odb().contains(&oid)?);
# Ok::<(), grit_lib::error::Error>(())
```

`Arc<T>`, `Box<T>` and `&T` implement `ObjectStore` (and `WritableObjectStore` and `PrunableObjectStore`) whenever `T` does, `dyn` included, by forwarding every method, `as_prunable` among them. A decorator written as `struct Counted<S: ObjectStore>(S)` can therefore wrap a shared `Arc<dyn ObjectStore>` and still be passed on as `Arc<dyn ObjectStore>`, with no hand-written forwarding newtype.

## Where the primary store lives

A files-backed primary is `<git_dir>/objects` (the common directory's `objects/` for a linked worktree). When the [`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) passed in [`RepositoryOptions`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html) sets [`git_object_directory`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#structfield.git_object_directory) (`GIT_OBJECT_DIRECTORY`), that directory is the primary instead: reads and writes go there, and a relative path resolves against the environment's current directory. The directory must exist, and an empty value fails to open, as in Git. Also as in Git, `<git_dir>/objects` is then reachable only as an alternate, through [`git_alternate_object_directories`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#structfield.git_alternate_object_directories) or the new directory's `info/alternates`. This is how hooks and quarantines keep new objects out of the shared store. Fetch, pull and push through [`Repository::remotes`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.remotes) read and write through the repository's own store, and the git-dir based fetch functions open the repository with `FetchOptions::environment`.

## Backend failures

An error from your store's `read`, `read_info` or `contains` (a dropped connection, a locked database) reaches the caller as that error, not as a missing object. To test for an object, call [`Odb::contains`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.contains): it walks the lookup order like a read does and returns the first source failure, so it never reports an object as present that `Odb::read` cannot return. Fetch and push negotiation, write-tree, ref checks and rev-parse all use it, so an outage stops the operation with a retryable error instead of re-sending objects or reporting broken refs. [`Odb::exists`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.exists) is the infallible form: it treats a failing source as not having the object, so keep it for hints where a wrong answer is harmless.

A damaged copy ([`ObjectError::Zlib`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.Zlib) or [`ObjectError::Corrupt`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.Corrupt)) inside a [`CompositeStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/struct.CompositeStore.html), including the alternates chain, is treated differently from an outage: the read moves on to the next child and returns its good copy if it has one. When no child can return the object, the caller gets the first corruption error rather than a missing object, so bit rot in one replica is never mistaken for an absent object.

## Building a custom repository

Pass your store to [`RepositoryOptions::with_object_store`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_object_store) when calling [`Repository::open`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.open), or when creating the repository with [`Repository::init`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.init) (see [Creating a repository on your stores](#creating-a-repository-on-your-stores)). That is the only way to replace the files primary. The repository still resolves its `objects/` directory (`GIT_OBJECT_DIRECTORY` included) and the opened [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) reports its canonical path, but no object is read from or written to it and it need not exist. With `GIT_OBJECT_DIRECTORY` set, the custom store still wins and the environment's directory is left untouched. Add read sources, a commit-graph or an alternates override with an [`OdbBuilder`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.OdbBuilder.html) through [`RepositoryOptions::with_odb_builder`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_odb_builder); it works with the files primary as well.

The custom primary and every read source must hash with the repository's object format: the `extensions.objectformat` value in `<git_dir>/config`, or SHA-1 when that key or the config file is missing. Create the store with the same [`HashAlgo`](https://docs.rs/grit-lib/latest/grit_lib/objects/enum.HashAlgo.html) the repository was initialized with (`MemoryStore::new(HashAlgo::Sha256)` for a SHA-256 repository). A store that reports another algorithm through `ObjectStore::hash_algo` fails to open with [`RepositoryError::ObjectFormatMismatch`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.RepositoryError.html#variant.ObjectFormatMismatch), whose `repository` and `store` fields name the two algorithms, instead of writing object ids the repository's refs, index and config disagree with.

## Creating a repository on your stores

[`Repository::init`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.init) through [`InitOptions::with_repository_options`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.InitOptions.html#method.with_repository_options) seeds `HEAD` in an injected ref store and writes only the git-directory pieces your backends do not own (see the init table in [Writing storage backends](https://grit-scm.com/docs/library/object-stores/storage-backends.md/index.md#what-repositoryinit-writes)).

```rust
//! Create a repository whose primary object store is an in-memory [`MemoryStore`].
//!
//! Writes go to memory; [`Repository::init`] creates no `objects/` directory on disk.

use std::sync::Arc;

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::odb::store::{MemoryStore, ObjectStore};
use grit_lib::objects::{HashAlgo, ObjectKind};
use grit_lib::repo::{InitOptions, Repository};

fn main() -> grit_lib::error::Result<()> {
    let dir = tempfile::tempdir()?;
    let store = Arc::new(MemoryStore::new(HashAlgo::Sha1));
    let (repo, _) = Repository::init(
        dir.path(),
        &InitOptions::new()
            .with_repository_options(RepositoryOptions::empty().with_object_store(store.clone())),
    )?;

    let blob = repo.odb().write(ObjectKind::Blob, b"hello")?;
    println!("blob={blob}");
    println!("in_memory={}", store.contains(&blob)?);
    println!("objects_dir={}", repo.git_dir().join("objects").exists());
    Ok(())
}
```

```bash
cargo run -p grit-examples --bin memory_primary
```

## No git directory at all

When both the object store and the ref store are injected, [`Repository::open`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.open) reads nothing from the git directory's layout: it may be empty or missing. Repository config is still read from `<git_dir>/config` when that file exists; to keep config in memory instead, set it on the [`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) with [`Environment::push_config_override`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#method.push_config_override) (the `-c key=value` mechanism) and set [`git_config_nosystem`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#structfield.git_config_nosystem) so `/etc/gitconfig` stays out. Seed `HEAD` with [`RepositoryOptions::with_initial_branch`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_initial_branch), or create the repository with `Repository::init` as above, which seeds it for you:

```rust
use std::sync::Arc;

use grit_lib::config::environment::{ConfigOverride, Environment, RepositoryOptions};
use grit_lib::objects::HashAlgo;
use grit_lib::objects::odb::store::MemoryStore;
use grit_lib::refs::store::MemoryRefStore;

let mut env = Environment::empty();
env.git_config_nosystem = Some("1".to_owned());
env.push_config_override(&ConfigOverride::new("user.name", Some("Ada".to_owned()))?);
let git_dir = std::path::Path::new("/nowhere/in-memory.git");
let repo = Repository::open(
    git_dir,
    &RepositoryOptions::with_environment(env)
        .with_object_store(Arc::new(MemoryStore::new(HashAlgo::Sha1)))
        .with_ref_store(Arc::new(MemoryRefStore::new()))
        .with_initial_branch("main"),
)?;
# Ok::<(), grit_lib::error::Error>(())
```

A bare repository opened this way never creates its git directory. [`grit-lib/tests/repository_no_filesystem.rs`](https://github.com/gitbutlerapp/grit/blob/main/grit-lib/tests/repository_no_filesystem.rs) builds commits, moves refs, walks and diffs history, merges trees, blames, adds notes, writes a bundle into a `Vec`, rewrites history and fetches from a files repository, then checks that nothing was created on disk. What works and what still needs a `.git` directory on disk:

| Area | Without a git directory |
| ---- | ----------------------- |
| Objects, trees and commits (`repo.objects()`) | Work through the store. |
| Refs, reflogs, `HEAD` and ref transactions (`repo.references()`) | Work through the ref store. |
| Config (`repo.config()`) | Comes from the `Environment`. |
| Rev-parse, revwalk and log | Work. |
| Tree diff, [`write_merge_tree`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.WrittenMergeTree.html) and blame at a commit | Work. |
| Notes, and bundles written to any `Write` ([`RepositoryBundles::write_to`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryBundles.html#method.write_to)) | Work. |
| History edits ([`History::reword`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/history/struct.History.html#method.reword), [`History::apply`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/history/struct.History.html#method.apply)) | Work. |
| Fetch from a path or URL | Works. The pack is spooled in the system temp directory and removed after ingest, and `FETCH_HEAD` is not written. |
| Hooks | A missing hooks directory means no hooks. |
| The index, staging and worktree commits | Need the git directory: the index, `COMMIT_EDITMSG` and merge, revert and rebase state live there, and staging creates it. |
| Work-tree operations (checkout, switch, status, reset, stash) | Need a work tree and an index. |
| Linked worktrees | Need their admin directories under `worktrees/`. |
| rerere and sparse-checkout | Need their state files in the git directory. |
| Hooks that expect `GIT_DIR` on disk | Not supported: objects and refs held by the stores are invisible to other programs. |
| gc and prune | Work when the store implements `PrunableObjectStore` (see [Garbage collection on a custom store](#garbage-collection-on-a-custom-store)); refused with `UnsupportedObjectStore` otherwise. |
| Repack, commit-graph and multi-pack-index files | Refused with `UnsupportedObjectStore` (see below). |

The same table is on [`RepositoryOptions::with_object_store`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_object_store). With only the object store injected, refs, reflogs and `HEAD` stay in the git directory as usual.

Hooks still run, but there is nothing on disk for another program to open. They start in the work tree (the git directory when there is none), and `GIT_DIR` is exported only when the [`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) you passed sets [`git_dir`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#structfield.git_dir); opening a path through [`Repository::open`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.open) does not set it. Even when it is set, objects and refs held in memory are invisible to the system `git`, so a `pre-commit` hook that runs `git status` or `git rev-parse` fails with "not a git repository". Keep hooks for such repositories to work that only needs the work tree and the hook's arguments.

## What works with a custom primary

Object reads and writes go through your store, so commits, staging (`porcelain::add::stage` and auto-staging commits), log, diff, merge (including cherry-pick and revert), stash, notes, bundle creation and unbundling all work.

[`Maintenance::fsck`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.fsck) works too: it lists the store's objects with `ObjectStore::for_each_object`, re-hashes each one against its id and runs the usual object and connectivity checks. Read or hash failures are reported as `FsckIssue::BadObject`, since there is no loose file path to name.

[`Remote::fetch`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.Remote.html#method.fetch), [`Remote::push`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.Remote.html#method.push), pull, bundle fetch, [`clone_into`](https://docs.rs/grit-lib/latest/grit_lib/remote/clone/fn.clone_into.html), and smart HTTP serving ([`UploadPack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.UploadPack.html) / [`ReceivePack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePack.html)) read and write objects through the custom primary (pack bytes are resolved into the store with [`ingest_received_pack`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.ingest_received_pack.html) or the receive-pack overlay described below). Partial-clone filters are not supported yet.

An operation that needs the on-disk `objects/` layout refuses a custom primary with [`RepositoryError::UnsupportedObjectStore`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.RepositoryError.html#variant.UnsupportedObjectStore). Its `operation` field is a [`FilesOnlyOperation`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html), so match the variant rather than the message; `FilesOnlyOperation::as_str` gives the name below, which `grit --json` reports as `operation` with `kind` `unsupported_object_store` (see [Exit codes](https://grit-scm.com/docs/exit-codes/index.md)). The table is generated from the enum's rustdoc:

| Name | Variant | Description |
| --- | --- | --- |
| `gc` | [`Gc`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.Gc) | Garbage collection without a repository: [`Odb::gc`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.gc) on an `Odb` built standalone, with no git directory to find reachability roots in. |
| `prune` | [`Prune`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.Prune) | Deleting unreachable objects from a custom primary that cannot delete ([`WritableObjectStore::as_prunable`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/trait.WritableObjectStore.html#method.as_prunable) is `None`): [`Maintenance::prune_loose_objects`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.prune_loose_objects), [`refs::gc::prune_loose_unreachable`](https://docs.rs/grit-lib/latest/grit_lib/refs/gc/fn.prune_loose_unreachable.html), [`Odb::gc`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.gc), [`Maintenance::gc`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.gc). Implement [`PrunableObjectStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.PrunableObjectStore.html) to support them. |
| `repack` | [`Repack`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.Repack) | Repacking into `objects/pack/`: [`Maintenance::repack`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.repack) and [`Maintenance::repack_all`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.repack_all). |
| `commit_graph_write` | [`CommitGraphWrite`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.CommitGraphWrite) | Writing `objects/info/commit-graph`: [`Odb::write_commit_graph`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.write_commit_graph) and [`Maintenance::write_commit_graph`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.write_commit_graph). A custom store builds its graph in memory with [`Maintenance::build_commit_graph`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.build_commit_graph) instead. |
| `midx_write` | [`MidxWrite`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.MidxWrite) | Writing `objects/pack/multi-pack-index`: [`Maintenance::write_midx`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.write_midx). |
| `pack_store` | [`PackStore`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.PackStore) | The files backend’s pack and MIDX read cache: [`Odb::pack_store`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.pack_store). |
| `pack_install` | [`PackInstall`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.PackInstall) | Installing a pack file and its `.idx` under `objects/pack/`: [`index_pack::install_pack_bytes`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.install_pack_bytes.html) and [`index_pack::install_pack_path`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.install_pack_path.html). Use [`index_pack::ingest_received_pack`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.ingest_received_pack.html) to write a pack into any primary. |
| `largest_pack_index` | [`LargestPackIndex`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.LargestPackIndex) | Finding the largest pack index in `objects/pack/`: [`Odb::largest_pack_index_path`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.largest_pack_index_path). |
| `loose_write` | [`LooseWrite`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.LooseWrite) | Writing loose object files into `objects/`: [`Odb::write_local`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.write_local), [`Odb::write_raw_local`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.write_raw_local) and [`Odb::write_loose_materialize`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.write_loose_materialize). [`Odb::write`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.write) works with any primary. |
| `files_source` | [`FilesSource`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.FilesSource) | The files-backed primary source itself: [`Odb::primary`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.primary). Use [`Odb::primary_writable`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.primary_writable) for the primary of any kind. |
| `offload` | [`Offload`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.Offload) | Moving blobs to a large-object promisor: [`Maintenance::offload_blobs`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.offload_blobs), for the main repository and for the promisor repository. |
| `promisor_rewrite` | [`PromisorRewrite`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.PromisorRewrite) | Rewriting packs to leave out promised objects, as offload and dropping promised blobs do. |
| `partial_fetch` | [`PartialFetch`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.PartialFetch) | Fetching or cloning with an object filter (a partial clone) into a custom primary. |
| `receive_quarantine` | [`ReceiveQuarantine`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.ReceiveQuarantine) | The receive-pack quarantine directory under `objects/`. A custom primary receives pushes through an in-memory overlay instead. |
| `drop_large_blobs` | [`DropLargeBlobs`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.FilesOnlyOperation.html#variant.DropLargeBlobs) | Dropping promised blobs from promisor packs: [`Maintenance::drop_promised_blobs`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.drop_promised_blobs). |


Repack, multi-pack-index and commit-graph writes stay files-only by design: packs, `.idx`, multi-pack-index and commit-graph files are how the files backend stores objects, and a custom store owns its own layout. A custom store still gets a commit-graph, built in memory and kept in its own storage (see [Commit-graphs for a custom store](#commit-graphs-for-a-custom-store)), and garbage collection when it can delete objects (next section). Use `Odb::files_objects_dir` when you need the on-disk `objects/` path only for files-backed repos.

## Garbage collection on a custom store

A store that can delete objects implements [`PrunableObjectStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.PrunableObjectStore.html) and returns `Some(self)` from [`WritableObjectStore::as_prunable`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.WritableObjectStore.html#method.as_prunable). `MemoryStore` does. Then these work on a repository whose primary is that store:

| API | What it does on a custom store |
| --- | --- |
| [`Maintenance::prune_loose_objects`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.prune_loose_objects) | Deletes unreachable objects older than `gc.pruneExpire` (or `PruneOptions::older_than`) |
| [`Maintenance::gc`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.gc) | Pack-refs, reflog expiry, then the same prune; repack, drop-large-blobs and the commit-graph write are skipped |
| [`Odb::gc`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.gc) | Deletes every unreachable object, with no grace period |
| [`refs::gc::prune_loose_unreachable`](https://docs.rs/grit-lib/latest/grit_lib/refs/gc/fn.prune_loose_unreachable.html) | Deletes what your own root set does not reach |

Reachability is the same as for the files backend: every ref, every reflog entry (including linked worktrees' reflogs), `HEAD` and the index of each worktree, and the stash; walks stop at shallow boundaries. Grit lists your objects with `ObjectStore::for_each_object`, walks the graph once, passes the unreachable ids to `PrunableObjectStore::remove` in batches, and calls `WritableObjectStore::flush` at the end.

The grace period comes from [`PrunableObjectStore::object_mtime`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.PrunableObjectStore.html#method.object_mtime), which plays the part of a loose file's modification time. It defaults to `None`, and an object without a known time is kept whenever a grace period applies: with the default `gc.pruneExpire` of `2.weeks.ago`, a store that records no times (like `MemoryStore`) loses nothing until you prune with `now`. Record a time on `write` and `freshen` to get Git's behavior. The clock a relative expiry is measured from is passed in (`PruneOptions::with_now`, `GcOptions::now_unix`).

With `extensions.preciousObjects` set, `prune_loose_objects` and `Odb::gc` fail with `RepositoryError::PreciousObjectsRepository` (on the files backend too), and `maintenance::gc` on a custom store skips its prune step (`GcStats::prune_ran` stays false).

A store whose `as_prunable` is `None` is never pruned: those calls fail with `UnsupportedObjectStore` and `operation` `prune` before touching anything, and never fall back to the `objects/` directory.

## Filesystem-only by design

Some parts of grit-lib read or write `objects/` on disk directly, because what they work on is the files layout itself or a directory that only exists on disk. None of them runs against your store's objects:

| Area | Why it needs `objects/` on disk |
| ---- | ------------------------------- |
| The files backend | The files primary inside `Odb`, the loose, pack and multi-pack-index stores, and the pack readers and writers they are built from. |
| Maintenance | `gc`, repack, prune, offload, commit-graph, multi-pack-index and pack bitmap writing rewrite the files layout. On a custom primary they are refused (see the table above). |
| Pack install | Installing a received pack as `objects/pack/pack-*.pack` (index-pack, bundle install, fetch's pack spool) and receive-pack's on-disk quarantine. A custom primary takes the ingest path instead. |
| Repository layout | Opening a repository with the default files primary, discovering a repository from a directory, and creating the directories of a new repository. |
| Submodules and alternates | A submodule's git dir and `objects/info/alternates` name directories on disk. Alternates are read for the files primary unless `OdbBuilder::alternates(false)`, and for a custom primary only with `OdbBuilder::alternates(true)`. |
| Local-path transport | Fetch, push and clone from a peer repository given as a local path open that repository's own files store. |
| Gated fast paths | Rev-list, merge-base, fsck, bitmap walks, change-id lookup and author grouping (`log --group-by author`) read packs directly only after checking that the primary is the files backend, or that a pack bitmap exists. A custom primary takes the general path through `ObjectStore`. |
| Git-directory fallbacks | Functions that take only a git directory path, such as `refs::write_ref`, `refs::pack_remote_tracking_refs_for_clone`, `remote::list_refs_from_git_dir` without an `Odb`, and `promisor_pack_object_ids`, have no repository to ask, so they use that directory's files database. Called through a `Repository`, the same work (ref updates, `packed-refs` peel lines, ls-refs peeling) goes through your store. |
| Scratch databases | Throwaway, empty databases in a temporary directory, such as the one the thin-pack check indexes a received pack against. They never hold your objects. |

A source-scan test in grit-lib (`storage_backend_guard`) keeps this list honest: any new direct access to `objects/` outside these areas fails the build, and the places that still bypass a custom store are tracked there until they go through it.

## Fast history walks

Rev-list, merge-base and path-limited log read every commit they cross through [`ObjectStore::read_into`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.ObjectStore.html#method.read_into), into one buffer the walk reuses. Implement it to copy or decode your stored bytes straight into that buffer. The default goes through `read`, which allocates an owned `Object` per commit before copying it. Without a commit-graph, a store that implements `read_into` walks history about as fast as the files backend: on a 120,000-commit history, counting every commit takes the same time through a pass-through store as through the files backend.

## Change ids and author counts

A change id used as a revision (or passed to [`find_commits_by_change_id_prefix`](https://docs.rs/grit-lib/latest/grit_lib/change_id/fn.find_commits_by_change_id_prefix.html)) names a commit by the `change-id` header grit stamps into it, or by the id derived from its commit id when it has none. Finding a stored header means walking every commit reachable from your refs and reading its header. On the files backend grit records under `objects/info` whether any object holds a change-id header at all, so a repository without them (a clone of a project that never used grit) skips the header scan and matches derived ids from the walk alone. A custom primary has no such record and grit writes nothing to disk for it, so every lookup reads each reachable commit's header through `ObjectStore::read_into`, spread over the repository's worker threads.

On a git.git clone (86,000 commits, release build, 4-vCPU VM) a warm lookup takes about 72 ms on the files backend, which walks its commit-graph and skips the scan. Git's closest operation, `git rev-list --all --count`, takes 76 ms. With the same commits in a `MemoryStore` and no attached graph, a lookup takes about 243 ms: about 217 ms walking history through the store and about 26 ms scanning headers. Attaching a commit-graph (see [Commit-graphs for a custom store](#commit-graphs-for-a-custom-store)) shortens the walk, and implementing `read_into` (see [Fast history walks](#fast-history-walks)) keeps each header read down to one copy. A store that pays per call pays it once per commit, on every lookup.

Author counts (`log --group-by author`) read packs, the pack bitmap and commit-graph files directly on the files backend. On a custom primary they read each commit through the store instead, and walk parents through the commit-graph attached with `OdbBuilder::commit_graph`, if there is one. The counts are the same either way.

## Commit-graphs for a custom store

A commit-graph lets walks skip reading commit objects entirely. Parents, root trees, committer dates and generation numbers come from the graph, and so do changed-path Bloom filters for `log -- <path>`. On the 120,000-commit history above, counting commits drops from about 650 ms to about 40 ms.

Graph files under `objects/info/` describe the files layout, not your store, so grit never reads them for a custom primary: a stale or foreign graph there cannot make a walk report commits your store does not have. Instead:

1. Build the graph through any `Odb` with [`repo.maintenance().build_commit_graph`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.build_commit_graph). It walks every commit reachable from the repository's refs and returns a [`CommitGraphBuild`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/enum.CommitGraphBuild.html): either a [`BuiltCommitGraph`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.BuiltCommitGraph.html) or, in a shallow repository or one with grafts or replace refs, the [`CommitGraphSkipReason`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/enum.CommitGraphSkipReason.html) no graph may be built.
2. Store `BuiltCommitGraph::bytes` wherever your backend keeps its data. They are byte for byte the file Git writes to `objects/info/commit-graph`, and `git commit-graph verify` accepts them.
3. When you open the repository, turn stored bytes into a chain with [`BuiltCommitGraph::to_chain`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.BuiltCommitGraph.html#method.to_chain) (or build fresh from step 1 and call `to_chain` on the result) and attach it with [`OdbBuilder::commit_graph`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.OdbBuilder.html#method.commit_graph).

```rust
use std::sync::Arc;

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::maintenance::{CommitGraphBuild, CommitGraphOptions};
use grit_lib::objects::odb::store::WritableObjectStore;
use grit_lib::objects::odb::OdbBuilder;
use grit_lib::repo::{Repository};
use grit_lib::maintenance::BuiltCommitGraph;

fn open(
    git_dir: &std::path::Path,
    store: Arc<dyn WritableObjectStore>,
    graph: Option<Vec<u8>>,
) -> grit_lib::error::Result<Repository> {
    let mut layers = OdbBuilder::new();
    if let Some(bytes) = graph {
        let built = BuiltCommitGraph { bytes };
        layers = layers.commit_graph(Arc::new(built.to_chain()?));
    }
    Repository::open(
        git_dir,
        &RepositoryOptions::empty()
            .with_object_store(store)
            .with_odb_builder(layers),
    )
}

fn refresh_graph(repo: &Repository) -> grit_lib::error::Result<Option<Vec<u8>>> {
    match repo
        .maintenance()
        .build_commit_graph(&CommitGraphOptions::with_changed_paths(true))?
    {
        CommitGraphBuild::Built(graph) => Ok(Some(graph.bytes)),
        CommitGraphBuild::Skipped(_) => Ok(None),
    }
}
```

An attached graph is trusted, not checked against the store: every commit it lists must be in the store with the parents and tree it records, which holds for a graph built from the same repository. Commits written after the graph was built are not in it and are read from the store as usual, so rebuilding now and then (with your other maintenance) is enough. With changed paths on, a rebuild reuses the Bloom filters of the attached graph and only computes filters for new commits. The graph's hash algorithm must match the repository's object format, or opening fails with [`RepositoryError::ObjectFormatMismatch`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.RepositoryError.html#variant.ObjectFormatMismatch). `OdbBuilder::commit_graph` works for a files primary too, and takes the place of its on-disk graph.

### Benchmarks

A 120,000-commit linear history (350 files, 44 MB `.git`, one pack) on a 4-vCPU Linux VM, release build, best of three, in milliseconds. The custom store is a pass-through over the same repository's files backend, so only the cost of the store interface differs. Git 2.43 timings are hyperfine means of the matching commands.

| Operation | Git, no graph | Files backend | Custom store, before | Custom store | Git, graph | Custom store, attached graph |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| `rev-list --count HEAD` | 425 | 651 | 1129 | 682 | 75 | 41 |
| `rev-list --count HEAD~100000..HEAD` | 356 | 285 | 661 | 304 | 67 | 110 |
| `merge-base HEAD~60000 HEAD~10` | 196 | 161 | 381 | 163 | 36 | 40 |
| `log -n 20 -- dir7/f3.txt` | 53 | 43 | 95 | 52 | 10 | 8 |

"Before" is grit-lib before custom-store reads stopped installing the files backend's pack-read context on every object. The graph columns use changed-path Bloom filters. Peak memory for all four walks in one process is about 187 MB for the files backend and for the custom store without a graph, and 46 MB with the attached graph.

## Receiving packs into a custom store

Fetch, clone, push and bundles move objects as a pack stream. [`ingest_pack_into`](https://docs.rs/grit-lib/latest/grit_lib/objects/unpack_objects/fn.ingest_pack_into.html) applies one to any [`WritableObjectStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.WritableObjectStore.html): it inflates each object, resolves `OFS_DELTA` and `REF_DELTA` chains, verifies the pack checksum, and calls `write` for every object. A *thin* pack (one whose deltas name bases the sender knew you have) resolves those bases from the `bases` store you pass, after looking in the target store itself. Objects up to 1 MiB stay in memory until the pack is resolved; larger blobs are read back from your store when a delta needs them.

The repository-level entry points use it automatically. [`ingest_received_pack`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.ingest_received_pack.html) and [`ingest_received_pack_path`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.ingest_received_pack_path.html) write into a custom primary instead of installing `objects/pack/pack-*.pack`, reading thin bases through the whole `Odb`; the returned [`IngestedPack`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/struct.IngestedPack.html) has `pack_path: None`. Each successful ingest ends with one [`Odb::flush`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.flush) on the primary (one store round trip per new object during unpack, not a `contains` probe on read sources). [`Bundle::unbundle`](https://docs.rs/grit-lib/latest/grit_lib/bundle/struct.Bundle.html#method.unbundle) streams the bundle's pack straight from the file into your store, with no temporary copy.

[`ReceivePack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePack.html) uses the same quarantine contract on a custom primary: the pack is spooled to a system temp file, unpacked object-by-object into an in-memory overlay whose read side is the repository's [`Odb::read_store`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.read_store), and nothing is copied into your primary until pre-receive succeeds. Then the overlay objects are written through [`Odb::primary_writable`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.primary_writable) and [`Odb::flush_for_publish`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.flush_for_publish). A declined push or a corrupt pack drops the overlay with no primary writes. Shell hooks do not get `GIT_OBJECT_DIRECTORY` / `GIT_QUARANTINE_PATH` for a memory overlay (only the files quarantine sets them). Objects that were published and then lose a later ref update stay in the store, as on the files backend after the quarantine migrates, until garbage collection removes them: that needs a store with the prune capability (see [Garbage collection on a custom store](#garbage-collection-on-a-custom-store)).

```rust
//! Apply a pack stream to a custom object store.
//!
//! Builds a pack from a files-backed repository (as a fetch, push or bundle would
//! deliver it), then writes its objects into an in-memory store two ways: straight
//! through the [`WritableObjectStore`](https://grit-scm.com/docs/library/object-stores/grit_lib::objects::odb::store::WritableObjectStore/index.md)
//! trait, and through a repository whose primary is that store.

use grit_lib::objects::FileMode;
use std::io::Cursor;
use std::sync::Arc;

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::index_pack::{ingest_received_pack, IngestPackOptions};
use grit_lib::objects::odb::store::{MemoryStore, ObjectStore};
use grit_lib::objects::pack_objects::{build_pack, PackBuildOptions};
use grit_lib::objects::unpack_objects::{ingest_pack_into, UnpackOptions};
use grit_lib::objects::{serialize_tree, HashAlgo, ObjectId, ObjectKind, TreeEntry};
use grit_lib::refs::store::MemoryRefStore;
use grit_lib::repo::{InitOptions, Repository};

fn main() -> grit_lib::error::Result<()> {
    let dir = tempfile::tempdir()?;
    let (source, _) = Repository::init(&dir.path().join("source"), &InitOptions::default())?;
    let mut parent = None;
    let mut tip = ObjectId::zero();
    for version in 1..=2 {
        let blob = source
            .odb()
            .write(ObjectKind::Blob, format!("version {version}\n").as_bytes())?;
        let tree = source.odb().write(
            ObjectKind::Tree,
            &serialize_tree(&[TreeEntry::new(b"file.txt", FileMode::REGULAR, blob)]),
        )?;
        let parent_line = parent.map(|p| format!("parent {p}\n")).unwrap_or_default();
        let body = format!(
            "tree {tree}\n{parent_line}author A <a@example.com> 1 +0000\ncommitter A <a@example.com> 1 +0000\n\nv{version}\n"
        );
        tip = source.odb().write(ObjectKind::Commit, body.as_bytes())?;
        parent = Some(tip);
    }
    let pack = build_pack(source.odb(), &[tip], &[], &PackBuildOptions::default())?;
    println!("pack_bytes={}", pack.len());

    // Any WritableObjectStore: deltas are resolved and each object is written.
    let store = MemoryStore::new(HashAlgo::Sha1);
    let ingested = ingest_pack_into(
        &mut Cursor::new(&pack),
        &store,
        &store,
        &UnpackOptions::default(),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::CancelToken::never(),
    )?;
    println!("store_objects={}", ingested.object_ids.len());
    println!("store_has_tip={}", store.contains(&tip)?);

    // A repository whose primary is a custom store: the same entry point fetch and
    // clone use writes into that store instead of installing a pack under objects/.
    let git_dir = dir.path().join("custom.git");
    std::fs::create_dir_all(&git_dir)?;
    let primary = Arc::new(MemoryStore::new(HashAlgo::Sha1));
    let repo = Repository::open(
        &git_dir,
        &(RepositoryOptions::empty()
            .with_object_store(primary.clone())
            .with_ref_store(Arc::new(MemoryRefStore::new()))
            .with_initial_branch("main")),
    )?;
    let received = ingest_received_pack(
        pack,
        repo.odb(),
        &IngestPackOptions::default(),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::CancelToken::never(),
    )?;
    println!("repo_objects={}", received.object_ids.len());
    println!("repo_commits={}", received.object_counts.commits);
    println!("pack_installed={}", received.pack_path.is_some());
    println!("repo_reads_tip={}", repo.odb().read(&tip).is_ok());
    Ok(())
}
```

```bash
cargo run -p grit-examples --bin ingest_pack_into_store
```

For a lower-level hook, [`RepositoryRemotes::fetch_from`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.fetch_from) with [`TransferEndpoint::Connection`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/enum.TransferEndpoint.html#variant.Connection) drives wire negotiation on an open [`Connection`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport/trait.Connection.html) and ingests into the repository's primary store. With [`FetchOptions`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOptions.html) configured to spool the negotiated pack without index-pack, you receive a temp pack file and ingest it yourself with [`ingest_received_pack_path`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.ingest_received_pack_path.html) or [`ingest_pack_into`](https://docs.rs/grit-lib/latest/grit_lib/objects/unpack_objects/fn.ingest_pack_into.html). Going the other way, [`build_pack`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack_objects/fn.build_pack.html) on the custom repository's `Odb` produces a pack that `git index-pack --strict` accepts.

## Short ids and prefix lookup

Resolving a short id and abbreviating an id (for example [`RevWalk::abbreviate`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.abbreviate)) both call [`ObjectStore::lookup_prefix`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.ObjectStore.html#method.lookup_prefix) once per id. A backend only has to implement `for_each_object`: the default `lookup_prefix` parses the prefix once into an [`ObjectIdPrefix`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectIdPrefix.html) and compares raw id bytes without allocating, so each call is one pass over the whole store (about 1 ms per 200 000 ids on the factory VM).

For a label that does not need to resolve back to the id (log lines, conflict markers, status rows), [`ObjectId::to_short_hex`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectId.html#method.to_short_hex) returns the first seven hex digits without touching the store, and [`short_hex`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.short_hex.html) does the same for a hex string you already hold.

If your backend keeps ids sorted (a B-tree, an ordered key-value store, an SQL index on the raw id), override `lookup_prefix` with a range scan. Every id that starts with the prefix lies between [`ObjectIdPrefix::lowest`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectIdPrefix.html#method.lowest) and [`ObjectIdPrefix::highest`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectIdPrefix.html#method.highest), inclusive, and nothing else does:

```rust
use std::collections::BTreeSet;

use grit_lib::error::Result;
use grit_lib::objects::{HashAlgo, ObjectId, ObjectIdPrefix};

fn lookup_prefix(
    ids: &BTreeSet<ObjectId>,
    prefix: &str,
    limit: usize,
    out: &mut Vec<ObjectId>,
) -> Result<()> {
    let prefix = ObjectIdPrefix::from_hex(prefix, HashAlgo::Sha1)?;
    let matches = ids.range(prefix.lowest()..=prefix.highest());
    out.extend(matches.take(if limit == 0 { usize::MAX } else { limit }));
    Ok(())
}
```

## Batched existence checks

When grit needs to know whether many objects exist at once, it calls [`ObjectStore::contains_many`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.ObjectStore.html#method.contains_many) with the whole batch and expects one answer per id, in input order. Write-tree (and so every commit) uses it to confirm that the cached trees of unchanged directories still exist. Fetch and push negotiation use it to sort out which ids are already present. Local-path and `file://` clone or fetch into an empty custom primary does not probe existence at all (every reachable object is written once). An incremental local fetch or push into a non-empty custom primary asks `contains_many` once over the candidate send set. The default implementation calls `contains` once per id. A store that pays per call, such as a database or a network service, should override it to answer the batch in one query.

With an override, committing one changed file costs a handful of store calls however many directories the repository has: one batch for the reused trees, one for the changed directory's files, and one [`WritableObjectStore::write`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.WritableObjectStore.html#method.write) per new object (no Odb-level existence probe on a custom primary). Subtrees grit has just confirmed or written are not probed again. The reuse batch covers every layer of the database: the primary first, then each [`OdbBuilder::push_read_source`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.OdbBuilder.html#method.push_read_source) store and the alternates, each asked only about the trees earlier layers lack. An empty local cache in front of a slow read source therefore costs one batch to that source per commit, not one call per directory.

[`WritableObjectStore::flush`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.WritableObjectStore.html#method.flush) and [`WritableObjectStore::rollback`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.WritableObjectStore.html#method.rollback) let backends batch many writes (one transaction, one fsync). Pack ingest and [`Odb::flush`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.flush) before ref updates call flush on a custom primary; failed ingest calls rollback. Reads must observe successful writes before flush; flush is the durability barrier.

## Conformance tests

Object-store suites live in `grit_test_support::odb_conformance`; repository-level scenarios use `grit_test_support::repository_conformance`. See [Writing storage backends — Testing](https://grit-scm.com/docs/library/object-stores/storage-backends.md/index.md#testing) for `BackendFixture`, parity checks, and the SQLite example test.

## Example: append-only packfile KV store

`grit-examples` ships a single-file `PackfileKvStore` in `grit_examples::packfile_kv` (zlib records plus an in-memory index rebuilt on open) and a walkthrough that commits through a custom primary, walks history, and exports loose objects for system Git:

```rust
//! Custom append-only object store wired through [`RepositoryOptions::with_object_store`](https://grit-scm.com/docs/library/object-stores/grit_lib::config::environment::RepositoryOptions::with_object_store/index.md).
//!
//! Writes a small commit graph in the KV store, walks history with [`rev_list`],
//! then exports objects as loose files for interoperability with system Git.

use std::env;
use std::path::PathBuf;

use grit_examples::packfile_kv;

fn main() -> grit_lib::error::Result<()> {
    let (root, _tmpdir) = match env::args().nth(1) {
        Some(path) => (PathBuf::from(path), None),
        None => {
            let dir = tempfile::tempdir().map_err(grit_lib::error::Error::Io)?;
            let root = dir.path().to_path_buf();
            (root, Some(dir))
        }
    };
    let log = packfile_kv::run_custom_object_store_demo(&root)?;
    for oid in log {
        println!("{oid}");
    }
    Ok(())
}
```

## Example: SQLite object database

See [Writing storage backends — SQLite example](https://grit-scm.com/docs/library/object-stores/storage-backends.md/index.md#example-sqlite-object-database) for the walkthrough and conformance test. Implementation: [`grit_examples::sqlite_odb::SqliteOdbStore`](https://github.com/gitbutlerapp/grit/blob/main/grit-examples/src/sqlite_odb.rs).
