From 37bfb7f4c621bbfd1c673b25318553fae1ba91ea Mon Sep 17 00:00:00 2001 From: hmirin Date: Sun, 15 Nov 2026 21:19:55 -0800 Subject: [PATCH 1/5] perf: trace carrier object lookup costs --- src/storage.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/storage.rs b/src/storage.rs index 6046e80..a8c7d38 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -728,6 +728,7 @@ struct GitChunkReader { impl GitChunkReader { fn new(repo: &Path, chunks: Vec<(String, String)>) -> Result { + let _timer = trace::Span::new("carrier_cat_file_start"); Ok(Self { cat: CatFile::batch(&GitRepository::owned_work_tree(repo))?, chunks, @@ -1700,6 +1701,7 @@ fn carrier_chunk_entries( kind: ObjectKind, id: &str, ) -> Result { + let _timer = trace::Span::new("carrier_chunk_listing"); validate_id(id)?; let directory = format!("{}/{}/{id}", kind.directory(), &id[..2]); let mut child = GitRepository::owned_work_tree(repo) From 6d742301f997951e99aebc4f36d40eccb2ab4bc8 Mon Sep 17 00:00:00 2001 From: hmirin Date: Sun, 15 Nov 2026 21:34:51 -0800 Subject: [PATCH 2/5] perf: reuse bounded carrier manifest listing --- src/storage.rs | 107 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 106 insertions(+), 1 deletion(-) diff --git a/src/storage.rs b/src/storage.rs index a8c7d38..f828d9d 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -1,4 +1,4 @@ -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::fs::{self, File, OpenOptions}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; @@ -653,6 +653,12 @@ pub struct GitStorage { /// starting a second storage beside it. format_4_branch: bool, state: Mutex, + manifest_listings: Mutex>, +} + +struct ManifestListingCache { + commit: String, + directories: HashMap>, } struct GitStorageState { @@ -985,6 +991,7 @@ impl GitStorage { branch: branch.to_owned(), format_4_branch, state: Mutex::new(GitStorageState { base_commit }), + manifest_listings: Mutex::new(None), }) } @@ -1133,9 +1140,106 @@ impl GitStorage { } fn chunk_entries_at(&self, commit: &str, kind: ObjectKind, id: &str) -> Result { + if matches!(kind, ObjectKind::Manifest) + && self + .state + .lock() + .map_err(|_| anyhow::anyhow!("carrier state lock poisoned"))? + .base_commit + .as_deref() + == Some(commit) + && let Some(listing) = self.cached_manifest_chunk_entries(commit, id)? + { + return Ok(listing); + } carrier_chunk_entries(self.root(), commit, kind, id) } + /// Read the bounded manifest subtree once for this immutable carrier + /// commit. Large trees keep the per-object path and its existing bounds. + fn cached_manifest_chunk_entries( + &self, + commit: &str, + id: &str, + ) -> Result> { + validate_id(id)?; + let mut cache = self + .manifest_listings + .lock() + .map_err(|_| anyhow::anyhow!("carrier manifest cache lock poisoned"))?; + if cache.as_ref().is_none_or(|cached| cached.commit != commit) { + let mut child = GitRepository::owned_work_tree(self.root()) + .git() + .args(["ls-tree", "-r", "-z", commit, "--", "manifests"]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + let mut listing = Vec::new(); + child + .stdout + .take() + .context("open manifest tree listing")? + .take(MAX_CARRIER_LISTING_BYTES + 1) + .read_to_end(&mut listing)?; + if listing.len() as u64 > MAX_CARRIER_LISTING_BYTES { + let _ = child.kill(); + let _ = child.wait(); + return Ok(None); + } + let output = child.wait_with_output()?; + if !output.status.success() { + return Ok(None); + } + let mut by_directory: HashMap> = HashMap::new(); + for entry in listing + .split(|byte| *byte == 0) + .filter(|entry| !entry.is_empty()) + { + let Some(tab) = entry.iter().position(|byte| *byte == b'\t') else { + return Ok(None); + }; + let path = &entry[tab + 1..]; + let mut parts = path.splitn(4, |byte| *byte == b'/'); + let (Some(b"manifests"), Some(prefix), Some(object)) = + (parts.next(), parts.next(), parts.next()) + else { + continue; + }; + let mut directory = Vec::with_capacity(11 + prefix.len() + object.len()); + directory.extend_from_slice(b"manifests/"); + directory.extend_from_slice(prefix); + directory.push(b'/'); + directory.extend_from_slice(object); + let Ok(directory) = String::from_utf8(directory) else { + return Ok(None); + }; + let grouped = by_directory.entry(directory).or_default(); + grouped.extend_from_slice(entry); + grouped.push(0); + } + *cache = Some(ManifestListingCache { + commit: commit.to_owned(), + directories: by_directory, + }); + } + let directory = format!("manifests/{}/{id}", &id[..2]); + let Some(raw) = cache + .as_ref() + .and_then(|cached| cached.directories.get(&directory)) + else { + return Ok(Some(CarrierListing::Absent)); + }; + if raw.len() as u64 > MAX_CARRIER_LISTING_BYTES { + return Ok(Some(CarrierListing::Malformed( + "carrier object listing exceeds its size budget", + ))); + } + Ok(Some(match parse_chunk_listing(raw, &directory) { + Ok(chunks) => CarrierListing::Chunks(chunks), + Err(reason) => CarrierListing::Malformed(reason), + })) + } + /// Commits in `window` whose tree changed the stored copy of `id`, newest /// first. Carrier history is linear, so each one starts a distinct copy. fn copy_commits(&self, window: &[String], kind: ObjectKind, id: &str) -> Result> { @@ -2738,6 +2842,7 @@ mod tests { branch: "main".to_owned(), format_4_branch: false, state: Mutex::new(GitStorageState { base_commit: None }), + manifest_listings: Mutex::new(None), }; let id = "ab".repeat(32); let read = From 23025835fe97e5d386a7a6ff03e13c7c010f630a Mon Sep 17 00:00:00 2001 From: hmirin Date: Sun, 15 Nov 2026 21:52:03 -0800 Subject: [PATCH 3/5] perf: reuse bounded carrier pack listings --- src/storage.rs | 77 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 27 deletions(-) diff --git a/src/storage.rs b/src/storage.rs index f828d9d..daadde0 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -653,12 +653,13 @@ pub struct GitStorage { /// starting a second storage beside it. format_4_branch: bool, state: Mutex, - manifest_listings: Mutex>, + manifest_listings: Mutex>, + pack_listings: Mutex>, } -struct ManifestListingCache { +struct CarrierListingCache { commit: String, - directories: HashMap>, + directories: Option>>, } struct GitStorageState { @@ -992,6 +993,7 @@ impl GitStorage { format_4_branch, state: Mutex::new(GitStorageState { base_commit }), manifest_listings: Mutex::new(None), + pack_listings: Mutex::new(None), }) } @@ -1140,37 +1142,45 @@ impl GitStorage { } fn chunk_entries_at(&self, commit: &str, kind: ObjectKind, id: &str) -> Result { - if matches!(kind, ObjectKind::Manifest) - && self - .state - .lock() - .map_err(|_| anyhow::anyhow!("carrier state lock poisoned"))? - .base_commit - .as_deref() - == Some(commit) - && let Some(listing) = self.cached_manifest_chunk_entries(commit, id)? + if self + .state + .lock() + .map_err(|_| anyhow::anyhow!("carrier state lock poisoned"))? + .base_commit + .as_deref() + == Some(commit) + && let Some(listing) = self.cached_chunk_entries(commit, kind, id)? { return Ok(listing); } carrier_chunk_entries(self.root(), commit, kind, id) } - /// Read the bounded manifest subtree once for this immutable carrier + /// Read a bounded object subtree once for this immutable carrier /// commit. Large trees keep the per-object path and its existing bounds. - fn cached_manifest_chunk_entries( + fn cached_chunk_entries( &self, commit: &str, + kind: ObjectKind, id: &str, ) -> Result> { validate_id(id)?; - let mut cache = self - .manifest_listings + let kind_directory = kind.directory(); + let listings = match kind { + ObjectKind::Manifest => &self.manifest_listings, + ObjectKind::Pack => &self.pack_listings, + }; + let mut cache = listings .lock() - .map_err(|_| anyhow::anyhow!("carrier manifest cache lock poisoned"))?; + .map_err(|_| anyhow::anyhow!("carrier object listing cache lock poisoned"))?; if cache.as_ref().is_none_or(|cached| cached.commit != commit) { + let disabled = || CarrierListingCache { + commit: commit.to_owned(), + directories: None, + }; let mut child = GitRepository::owned_work_tree(self.root()) .git() - .args(["ls-tree", "-r", "-z", commit, "--", "manifests"]) + .args(["ls-tree", "-r", "-z", commit, "--", kind_directory]) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; @@ -1178,16 +1188,18 @@ impl GitStorage { child .stdout .take() - .context("open manifest tree listing")? + .context("open carrier object tree listing")? .take(MAX_CARRIER_LISTING_BYTES + 1) .read_to_end(&mut listing)?; if listing.len() as u64 > MAX_CARRIER_LISTING_BYTES { let _ = child.kill(); let _ = child.wait(); + *cache = Some(disabled()); return Ok(None); } let output = child.wait_with_output()?; if !output.status.success() { + *cache = Some(disabled()); return Ok(None); } let mut by_directory: HashMap> = HashMap::new(); @@ -1196,37 +1208,47 @@ impl GitStorage { .filter(|entry| !entry.is_empty()) { let Some(tab) = entry.iter().position(|byte| *byte == b'\t') else { + *cache = Some(disabled()); return Ok(None); }; let path = &entry[tab + 1..]; let mut parts = path.splitn(4, |byte| *byte == b'/'); - let (Some(b"manifests"), Some(prefix), Some(object)) = + let (Some(listed_kind), Some(prefix), Some(object)) = (parts.next(), parts.next(), parts.next()) else { continue; }; - let mut directory = Vec::with_capacity(11 + prefix.len() + object.len()); - directory.extend_from_slice(b"manifests/"); + if listed_kind != kind_directory.as_bytes() { + continue; + } + let mut directory = + Vec::with_capacity(kind_directory.len() + 2 + prefix.len() + object.len()); + directory.extend_from_slice(kind_directory.as_bytes()); + directory.push(b'/'); directory.extend_from_slice(prefix); directory.push(b'/'); directory.extend_from_slice(object); let Ok(directory) = String::from_utf8(directory) else { + *cache = Some(disabled()); return Ok(None); }; let grouped = by_directory.entry(directory).or_default(); grouped.extend_from_slice(entry); grouped.push(0); } - *cache = Some(ManifestListingCache { + *cache = Some(CarrierListingCache { commit: commit.to_owned(), - directories: by_directory, + directories: Some(by_directory), }); } - let directory = format!("manifests/{}/{id}", &id[..2]); - let Some(raw) = cache + let Some(directories) = cache .as_ref() - .and_then(|cached| cached.directories.get(&directory)) + .and_then(|cached| cached.directories.as_ref()) else { + return Ok(None); + }; + let directory = format!("{kind_directory}/{}/{id}", &id[..2]); + let Some(raw) = directories.get(&directory) else { return Ok(Some(CarrierListing::Absent)); }; if raw.len() as u64 > MAX_CARRIER_LISTING_BYTES { @@ -2843,6 +2865,7 @@ mod tests { format_4_branch: false, state: Mutex::new(GitStorageState { base_commit: None }), manifest_listings: Mutex::new(None), + pack_listings: Mutex::new(None), }; let id = "ab".repeat(32); let read = From c7def8b06a676aedfba55d5a37c94ee84a3281f1 Mon Sep 17 00:00:00 2001 From: hmirin Date: Mon, 16 Nov 2026 01:02:21 -0800 Subject: [PATCH 4/5] bench: measure cold full-history fetch --- scripts/benchmark-cold-fetch.sh | 54 +++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100755 scripts/benchmark-cold-fetch.sh diff --git a/scripts/benchmark-cold-fetch.sh b/scripts/benchmark-cold-fetch.sh new file mode 100755 index 0000000..637ffde --- /dev/null +++ b/scripts/benchmark-cold-fetch.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Benchmark a cold full-history fetch without network or production data. +if [[ $# -ne 1 ]]; then + echo "usage: $0 BIN_DIR" >&2 + exit 2 +fi +bin_dir=$(cd "$1" && pwd -P) +for binary in git-e2ee git-remote-e2ee; do + [[ -x "$bin_dir/$binary" ]] || { echo "missing $bin_dir/$binary" >&2; exit 2; } +done +generations=${BENCH_GENERATIONS:-30} +rounds=${BENCH_ROUNDS:-5} +[[ $generations =~ ^[1-9][0-9]*$ && $rounds =~ ^[1-9][0-9]*$ ]] || { + echo "BENCH_GENERATIONS and BENCH_ROUNDS must be positive integers" >&2 + exit 2 +} +work=$(mktemp -d "${TMPDIR:-/tmp}/e2ee-cold-fetch.XXXXXX") +trap 'rm -rf -- "$work"' EXIT +export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null +export XDG_STATE_HOME="$work/setup-state" XDG_CACHE_HOME="$work/setup-cache" +git init --bare -q "$work/carrier.git" +"$bin_dir/git-e2ee" keygen --output "$work/key.json" >/dev/null +(cd "$work" && "$bin_dir/git-e2ee" init "e2ee::file://$work/carrier.git" --key "$work/key.json" >/dev/null) +git init -q "$work/source" +git -C "$work/source" config user.name Benchmark +git -C "$work/source" config user.email benchmark@example.invalid +git -C "$work/source" remote add origin "e2ee::file://$work/carrier.git" +git -C "$work/source" config remote.origin.e2ee-key "$work/key.json" +for ((generation = 1; generation <= generations; generation++)); do + printf '%s\n' "$generation" > "$work/source/value" + git -C "$work/source" add value + git -C "$work/source" commit -qm "generation $generation" + PATH="$bin_dir:$PATH" git -C "$work/source" push -q origin HEAD:refs/heads/main +done +expected=$(git -C "$work/source" rev-parse HEAD) +printf 'run\twall_seconds\tmanifest_ms\tref_id\n' +for ((run = 1; run <= rounds; run++)); do + git init -q "$work/fresh-$run" + git -C "$work/fresh-$run" remote add origin "e2ee::file://$work/carrier.git" + git -C "$work/fresh-$run" config remote.origin.e2ee-key "$work/key.json" + export XDG_STATE_HOME="$work/state-$run" XDG_CACHE_HOME="$work/cache-$run" + started=$(perl -MTime::HiRes=time -e 'print time') + GIT_REMOTE_E2EE_TRACE=1 PATH="$bin_dir:$PATH" git -C "$work/fresh-$run" fetch -q origin >/dev/null 2>"$work/trace-$run" + ended=$(perl -MTime::HiRes=time -e 'print time') + actual=$(git -C "$work/fresh-$run" rev-parse refs/remotes/origin/main) + [[ $actual == "$expected" ]] || { echo "wrong fetched ref" >&2; exit 1; } + git -C "$work/fresh-$run" fsck --no-reflogs --unreachable >/dev/null 2>"$work/fsck-$run" + manifest_ms=$(sed -n 's/.*phase=manifest_chain_authentication elapsed_ms=\([0-9]*\).*/\1/p' "$work/trace-$run" | tail -1) + [[ -n $manifest_ms ]] || { echo "missing manifest trace" >&2; exit 1; } + wall=$(awk -v start="$started" -v end="$ended" 'BEGIN {printf "%.3f", end-start}') + printf '%s\t%s\t%s\t%s\n' "$run" "$wall" "$manifest_ms" "$actual" +done From 609d33a281959309d738a67c082305611e6b6497 Mon Sep 17 00:00:00 2001 From: hmirin Date: Mon, 16 Nov 2026 01:08:36 -0800 Subject: [PATCH 5/5] test: verify cached carrier listings and cold timing --- scripts/benchmark-cold-fetch.sh | 10 ++++-- src/storage.rs | 56 +++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/scripts/benchmark-cold-fetch.sh b/scripts/benchmark-cold-fetch.sh index 637ffde..8b37956 100755 --- a/scripts/benchmark-cold-fetch.sh +++ b/scripts/benchmark-cold-fetch.sh @@ -19,6 +19,7 @@ rounds=${BENCH_ROUNDS:-5} work=$(mktemp -d "${TMPDIR:-/tmp}/e2ee-cold-fetch.XXXXXX") trap 'rm -rf -- "$work"' EXIT export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null +unset GIT_REMOTE_E2EE_CACHE_DIR export XDG_STATE_HOME="$work/setup-state" XDG_CACHE_HOME="$work/setup-cache" git init --bare -q "$work/carrier.git" "$bin_dir/git-e2ee" keygen --output "$work/key.json" >/dev/null @@ -35,7 +36,7 @@ for ((generation = 1; generation <= generations; generation++)); do PATH="$bin_dir:$PATH" git -C "$work/source" push -q origin HEAD:refs/heads/main done expected=$(git -C "$work/source" rev-parse HEAD) -printf 'run\twall_seconds\tmanifest_ms\tref_id\n' +printf 'run\twall_seconds\tmanifest_total_ms\tref_id\n' for ((run = 1; run <= rounds; run++)); do git init -q "$work/fresh-$run" git -C "$work/fresh-$run" remote add origin "e2ee::file://$work/carrier.git" @@ -47,7 +48,12 @@ for ((run = 1; run <= rounds; run++)); do actual=$(git -C "$work/fresh-$run" rev-parse refs/remotes/origin/main) [[ $actual == "$expected" ]] || { echo "wrong fetched ref" >&2; exit 1; } git -C "$work/fresh-$run" fsck --no-reflogs --unreachable >/dev/null 2>"$work/fsck-$run" - manifest_ms=$(sed -n 's/.*phase=manifest_chain_authentication elapsed_ms=\([0-9]*\).*/\1/p' "$work/trace-$run" | tail -1) + manifest_ms=$(awk '/phase=manifest_chain_authentication elapsed_ms=/ { + sub(/.*elapsed_ms=/, "") + sub(/[^0-9].*/, "") + total += $0 + found = 1 + } END { if (found) print total }' "$work/trace-$run") [[ -n $manifest_ms ]] || { echo "missing manifest trace" >&2; exit 1; } wall=$(awk -v start="$started" -v end="$ended" 'BEGIN {printf "%.3f", end-start}') printf '%s\t%s\t%s\t%s\n' "$run" "$wall" "$manifest_ms" "$actual" diff --git a/src/storage.rs b/src/storage.rs index daadde0..c327574 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -2878,4 +2878,60 @@ mod tests { "git ls-tree failing on an unreadable commit must not read as an absent copy" ); } + + #[test] + fn cached_carrier_listings_preserve_valid_malformed_and_absent_results() { + let checkout = tempfile::tempdir().unwrap(); + checkout_git(checkout.path(), &["init", "--quiet"]); + let id = "ab".repeat(32); + let manifest = checkout.path().join(format!("manifests/ab/{id}/00000000")); + let pack = checkout.path().join(format!("packs/ab/{id}/00000001")); + fs::create_dir_all(manifest.parent().unwrap()).unwrap(); + fs::create_dir_all(pack.parent().unwrap()).unwrap(); + fs::write(manifest, b"manifest").unwrap(); + fs::write(pack, b"pack").unwrap(); + checkout_git(checkout.path(), &["add", "manifests", "packs"]); + let tree = checkout_git(checkout.path(), &["write-tree"]); + let commit = checkout_git( + checkout.path(), + &[ + "-c", + "user.name=test", + "-c", + "user.email=test@invalid", + "commit-tree", + "-m", + "carrier", + &tree, + ], + ); + let storage = GitStorage { + checkout, + location: "unused".to_owned(), + remote: "unused".to_owned(), + branch: "main".to_owned(), + format_4_branch: false, + state: Mutex::new(GitStorageState { + base_commit: Some(commit.clone()), + }), + manifest_listings: Mutex::new(None), + pack_listings: Mutex::new(None), + }; + assert!(matches!( + storage.chunk_entries_at(&commit, ObjectKind::Manifest, &id).unwrap(), + CarrierListing::Chunks(chunks) if chunks.len() == 1 + )); + assert!(matches!( + storage + .chunk_entries_at(&commit, ObjectKind::Pack, &id) + .unwrap(), + CarrierListing::Malformed(_) + )); + assert!(matches!( + storage + .chunk_entries_at(&commit, ObjectKind::Pack, &"cd".repeat(32)) + .unwrap(), + CarrierListing::Absent + )); + } }