Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions scripts/benchmark-cold-fetch.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#!/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
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
(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_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"
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=$(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"
done
188 changes: 187 additions & 1 deletion src/storage.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -653,6 +653,13 @@ pub struct GitStorage {
/// starting a second storage beside it.
format_4_branch: bool,
state: Mutex<GitStorageState>,
manifest_listings: Mutex<Option<CarrierListingCache>>,
pack_listings: Mutex<Option<CarrierListingCache>>,
}

struct CarrierListingCache {
commit: String,
directories: Option<HashMap<String, Vec<u8>>>,
}

struct GitStorageState {
Expand Down Expand Up @@ -728,6 +735,7 @@ struct GitChunkReader {

impl GitChunkReader {
fn new(repo: &Path, chunks: Vec<(String, String)>) -> Result<Self> {
let _timer = trace::Span::new("carrier_cat_file_start");
Ok(Self {
cat: CatFile::batch(&GitRepository::owned_work_tree(repo))?,
chunks,
Expand Down Expand Up @@ -984,6 +992,8 @@ impl GitStorage {
branch: branch.to_owned(),
format_4_branch,
state: Mutex::new(GitStorageState { base_commit }),
manifest_listings: Mutex::new(None),
pack_listings: Mutex::new(None),
})
}

Expand Down Expand Up @@ -1132,9 +1142,126 @@ impl GitStorage {
}

fn chunk_entries_at(&self, commit: &str, kind: ObjectKind, id: &str) -> Result<CarrierListing> {
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 a bounded object subtree once for this immutable carrier
/// commit. Large trees keep the per-object path and its existing bounds.
fn cached_chunk_entries(
&self,
commit: &str,
kind: ObjectKind,
id: &str,
) -> Result<Option<CarrierListing>> {
validate_id(id)?;
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 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, "--", kind_directory])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let mut listing = Vec::new();
child
.stdout
.take()
.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<String, Vec<u8>> = 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 {
*cache = Some(disabled());
return Ok(None);
};
let path = &entry[tab + 1..];
let mut parts = path.splitn(4, |byte| *byte == b'/');
let (Some(listed_kind), Some(prefix), Some(object)) =
(parts.next(), parts.next(), parts.next())
else {
continue;
};
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(CarrierListingCache {
commit: commit.to_owned(),
directories: Some(by_directory),
});
}
let Some(directories) = cache
.as_ref()
.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 {
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<Vec<String>> {
Expand Down Expand Up @@ -1700,6 +1827,7 @@ fn carrier_chunk_entries(
kind: ObjectKind,
id: &str,
) -> Result<CarrierListing> {
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)
Expand Down Expand Up @@ -2736,6 +2864,8 @@ mod tests {
branch: "main".to_owned(),
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 =
Expand All @@ -2748,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
));
}
}
Loading