From b3d03d16bc6c803ac470bbe97b40fa115d83301f Mon Sep 17 00:00:00 2001 From: Beardthelion Date: Mon, 30 Nov 2026 05:23:37 +0000 Subject: [PATCH 1/4] perf: walk visibility history with one Git log --- .../twigpine-node/src/git/visibility_pack.rs | 490 ++++++++++++++---- 1 file changed, 392 insertions(+), 98 deletions(-) diff --git a/crates/twigpine-node/src/git/visibility_pack.rs b/crates/twigpine-node/src/git/visibility_pack.rs index 2da866efb..a509cc6af 100644 --- a/crates/twigpine-node/src/git/visibility_pack.rs +++ b/crates/twigpine-node/src/git/visibility_pack.rs @@ -944,7 +944,22 @@ fn walk_tree_oids_inner( } Ok(()) } -fn blob_paths(repo_path: &Path, git_bin: &str, timeout: Duration) -> Result> { +fn blob_paths(repo_path: &Path, git_bin: &str, timeout: Duration) -> Result> { + let deadline = Instant::now() + timeout; + let mut out = object_paths(repo_path, git_bin, deadline, false)?.blobs; + let mut budget = WalkBudget::unbounded(); + let nc = non_commit_ref_sets(repo_path, git_bin, deadline, &mut budget)?; + out.extend(nc.blobs); + out.extend(nc.trees); + Ok(out.into_iter().collect()) +} + +#[cfg(test)] +fn blob_paths_ls_tree( + repo_path: &Path, + git_bin: &str, + timeout: Duration, +) -> Result> { // One deadline spans the whole walk (the HEAD probe, rev-list, every // per-commit ls-tree, and the for-each-ref phase 2), so a slow or hung walk // is bounded as a unit rather than granting each git child a fresh timeout. @@ -1724,6 +1739,7 @@ fn pair_decision( /// tree (#173 P2). `run_bounded_git` drains stdout concurrently with the stdin /// write, so a large history cannot deadlock the pipes. A commit whose root tree git /// cannot resolve fails the pass (bail), failing closed. +#[cfg(test)] fn root_tree_pairs( repo_path: &Path, git_bin: &str, @@ -1760,13 +1776,9 @@ fn root_tree_pairs( /// `replication_withheld_set`: a blob-only set handed to [`replicable_objects`] /// reintroduces #172 (withheld trees pin to public IPFS). /// -/// Strict where [`tree_paths`] is lenient. This feeds a withheld filter, so -/// absence means replicate; a missed reachable tree would leak. The walk -/// therefore matches [`blob_paths`]: [`assert_all_refs_are_commits`] first, then -/// a failing `rev-list --all [HEAD]` is an error, then [`object_paths`] (already -/// fail-closed on ls-tree / non-UTF-8) plus [`root_tree_pairs`]. [`tree_paths`] -/// stays the lenient allow-list walk for GET /ipfs/{cid} and the full-scan -/// allowed-tree set, where absence withholds. +/// This feeds a withheld filter, so absence means replicate; a missed reachable +/// tree would leak. The walk requires [`assert_all_refs_are_commits`] first, then +/// [`object_paths`] (fail-closed on Git errors or non-UTF-8 paths). pub fn withheld_object_oids_bounded( repo_path: &Path, git_bin: &str, @@ -1778,31 +1790,8 @@ pub fn withheld_object_oids_bounded( ) -> Result> { let deadline = Instant::now() + timeout; assert_all_refs_are_commits(repo_path, git_bin, deadline)?; - let head_resolves = run_bounded_git( - git_bin, - &["rev-parse", "--verify", "HEAD"], - repo_path, - b"", - deadline, - ) - .is_ok(); - let mut rev_args = vec!["rev-list", "--all"]; - if head_resolves { - rev_args.push("HEAD"); - } - let commits_out = run_bounded_git(git_bin, &rev_args, repo_path, b"", deadline)?; - let commits: Vec = String::from_utf8_lossy(&commits_out) - .lines() - .map(|l| l.trim().to_string()) - .filter(|l| !l.is_empty()) - .collect(); - let triples = object_paths(repo_path, git_bin, &commits, deadline)?; - let mut pairs: Vec<(String, String)> = triples - .into_iter() - .filter(|(_, _, kind)| kind == "blob" || kind == "tree") - .map(|(oid, path, _)| (oid, path)) - .collect(); - pairs.extend(root_tree_pairs(repo_path, git_bin, &commits, deadline)?); + let history = object_paths(repo_path, git_bin, deadline, true)?; + let pairs: Vec<_> = history.blobs.into_iter().chain(history.trees).collect(); Ok(withheld_from_pairs( &pairs, rules, is_public, owner_did, caller, )) @@ -2011,6 +2000,7 @@ pub fn allowed_blob_set_for_caller_bounded( /// enumerates non-commit ref targets and inserts them with empty path /// (round-3 fix for the annotated-tag-of-blob leak; the previous `assert_all_refs_are_commits` /// guard was removed in commit 91d0578, leaving that path fail-open). +#[cfg(test)] fn reachable_commit_oids( repo_path: &Path, git_bin: &str, @@ -2039,20 +2029,210 @@ fn reachable_commit_oids( .collect()) } +#[derive(Default)] +struct HistoryPaths { + blobs: HashSet, + trees: HashSet, + #[cfg(test)] + gitlinks: HashSet, +} + +enum DiffKind { + Deleted, + Blob, + Tree, + Gitlink, +} + +fn full_oid(oid: &str) -> bool { + matches!(oid.len(), 40 | 64) && oid.bytes().all(|b| b.is_ascii_hexdigit()) +} + +#[derive(Default)] +struct RawHistory { + paths: HistoryPaths, + first_parents: HashMap, + pending_path: Option<(DiffKind, String)>, + partial_field: Vec, +} + +impl RawHistory { + fn field(&mut self, bytes: &[u8], include_trees: bool) -> Result<()> { + let field = std::str::from_utf8(bytes).context("git log --raw returned non-UTF-8 data")?; + if let Some((kind, oid)) = self.pending_path.take() { + anyhow::ensure!(!field.is_empty(), "git log --raw returned an empty path"); + match kind { + DiffKind::Blob => self.paths.blobs.insert((oid, format!("/{field}"))), + DiffKind::Tree if include_trees => { + self.paths.trees.insert((oid, format!("/{field}"))) + } + #[cfg(test)] + DiffKind::Gitlink if include_trees => { + self.paths.gitlinks.insert((oid, format!("/{field}"))) + } + _ => false, + }; + } else if let Some(header) = field.strip_prefix('R') { + let (commit, parents_and_tree) = + header.split_once(' ').context("invalid commit header")?; + let (parents, tree) = parents_and_tree + .rsplit_once(' ') + .context("invalid commit header")?; + let first_parent = parents.split(' ').next().unwrap_or_default(); + anyhow::ensure!( + full_oid(commit) + && full_oid(tree) + && (first_parent.is_empty() || full_oid(first_parent)), + "invalid commit header from git log --raw" + ); + self.first_parents + .insert(commit.to_owned(), first_parent.to_owned()); + if include_trees { + self.paths.trees.insert((tree.to_owned(), "/".to_owned())); + } + } else { + // Git inserts a LF between the pretty header and its first raw record. + let meta = field.strip_prefix('\n').unwrap_or(field); + let meta = meta + .strip_prefix(':') + .context("invalid git log --raw record")?; + let mut fields = meta.split(' '); + let (Some(_), Some(mode), Some(old_oid), Some(oid), Some(status), None) = ( + fields.next(), + fields.next(), + fields.next(), + fields.next(), + fields.next(), + fields.next(), + ) else { + anyhow::bail!("invalid git log --raw metadata"); + }; + anyhow::ensure!( + full_oid(old_oid) && full_oid(oid) && old_oid.len() == oid.len(), + "invalid object ID from git log --raw" + ); + let kind = match (status, mode) { + ("D", "000000") => DiffKind::Deleted, + ("A" | "M" | "T", "100644" | "100755" | "120000") => DiffKind::Blob, + ("A" | "M" | "T", "040000") => DiffKind::Tree, + ("A" | "M" | "T", "160000") => DiffKind::Gitlink, + _ => anyhow::bail!("unexpected status or mode from git log --raw: {status} {mode}"), + }; + self.pending_path = Some((kind, oid.to_owned())); + } + Ok(()) + } + + fn chunk(&mut self, chunk: &[u8], include_trees: bool) -> Result<()> { + let mut partial = std::mem::take(&mut self.partial_field); + for field in chunk.split_inclusive(|&byte| byte == 0) { + if let Some(field) = field.strip_suffix(&[0]) { + if partial.is_empty() { + self.field(field, include_trees)?; + } else { + partial.extend_from_slice(field); + self.field(&partial, include_trees)?; + partial.clear(); + } + } else { + partial.extend_from_slice(field); + } + } + self.partial_field = partial; + Ok(()) + } + + fn finish(self) -> Result { + anyhow::ensure!( + self.pending_path.is_none() && self.partial_field.is_empty(), + "git log --raw returned a partial record" + ); + // Replace refs or grafts can create a cycle in effective history. No diff + // would report paths that are unchanged around that cycle. + let mut rooted = HashSet::new(); + let mut chain = HashSet::new(); + for mut oid in self.first_parents.keys().map(String::as_str) { + while !oid.is_empty() && !rooted.contains(oid) { + anyhow::ensure!(chain.insert(oid), "cyclic first-parent history"); + oid = self + .first_parents + .get(oid) + .context("git log --raw omitted a first parent")?; + } + rooted.extend(chain.drain()); + } + Ok(self.paths) + } +} + +/// Walk all refs and detached HEAD. Every path/object pair is either new relative +/// to the first parent, or already exists in that parent's snapshot. Diff merges +/// against the first parent *without* restricting traversal to first parents, so +/// merge resolutions and pairs exclusive to a side branch are both covered. +/// Roots (including shallow boundaries) diff against the empty tree. +fn object_paths( + repo_path: &Path, + git_bin: &str, + deadline: Instant, + include_trees: bool, +) -> Result { + let mut args = vec![ + "log", + "--all", + "--raw", + "-r", + "-z", + "--root", + "--format=tformat:R%H %P %T", + "--no-abbrev", + "--diff-merges=first-parent", + "--no-renames", + "--ignore-submodules=none", + "--no-relative", + "--no-follow", + "--no-ext-diff", + "--no-textconv", + "--no-decorate", + "--no-notes", + "--no-show-signature", + "--no-color", + ]; + if include_trees { + args.push("-t"); + } + args.push("--"); + + let mut raw = RawHistory::default(); + let mut parse_result = Ok(()); + let (status, stderr, _) = + run_bounded_git_streaming(git_bin, &args, repo_path, b"", deadline, &mut |chunk| { + parse_result = raw.chunk(chunk, include_trees); + parse_result.is_ok() + })?; + parse_result?; + anyhow::ensure!( + status.success(), + "git log --raw failed: {}", + String::from_utf8_lossy(&stderr) + ); + raw.finish() +} + /// Every `(oid, "/repo/relative/path", kind)` triple reachable from the given /// `commits` — the shared ls-tree seam the tree walk filters (`kind == "tree"`). /// One bounded `git ls-tree -rzt` per commit under the caller's shared `deadline`: /// `-rzt` is byte-identical to `-rz` for blob records and additionally emits the /// tree object for each directory at its own path. `kind` is git's object-type /// string ("blob", "tree", or "commit" for a gitlink). The commit's ROOT tree is -/// not emitted by `ls-tree` (it lists entries *under* a tree); `tree_paths` adds -/// it. Triples are de-duplicated across commits and paths carry a leading "/" to +/// not emitted by `ls-tree` (it lists entries *under* a tree); [`root_tree_pairs`] +/// adds it. Triples are de-duplicated across commits and paths carry a leading "/" to /// match the glob form of visibility rules ("/secret/**"). /// /// Fails closed: if any tree walk fails — or a path is not valid UTF-8 — it /// returns an error so the caller aborts rather than producing a partial /// (under-withheld) set. -fn object_paths( +#[cfg(test)] +fn object_paths_ls_tree( repo_path: &Path, git_bin: &str, commits: &[String], @@ -2248,34 +2428,6 @@ fn tree_structurally_safe( Ok(true) } -/// Every `(tree_oid, "/path")` pair reachable in `repo_path`: the `kind == "tree"` -/// slice of [`object_paths`] (subtree trees at their directory paths) PLUS every -/// reachable commit's root tree at "/" (see [`root_tree_pairs`]). Computes the -/// reachable-commit set ONCE (leniently, see [`reachable_commit_oids`]; the tree -/// allowed-set feeds the `/ipfs/{cid}` tree gate AND the full-scan pin allow-list, -/// where absence = fail-closed) and drives both the ls-tree walk and the root-tree -/// pass from it, so the two cannot diverge and neither re-enumerates. The tree analog -/// of [`blob_paths`], bounded by the same shared `deadline`. Not for a withheld -/// filter: that path is [`withheld_object_oids_bounded`]. -fn tree_paths( - repo_path: &Path, - git_bin: &str, - deadline: Instant, -) -> Result> { - let commits = reachable_commit_oids(repo_path, git_bin, deadline)?; - // Subtree trees at their directory paths; the root tree is - // enumerated separately via `root_tree_oids` so the structural - // post-pass can apply without overlapping with the empty-path - // cat-file catch-all sentinel (#218 review P1b). - let mut out: HashSet<(String, String)> = HashSet::new(); - for (oid, path, kind) in object_paths(repo_path, git_bin, &commits, deadline)? { - if kind == "tree" { - out.insert((oid, path)); - } - } - Ok(out) -} - /// Reachable tree OIDs that visibility ALLOWS `caller` at some path — the tree /// analog of [`allowed_blob_set_for_caller`]. `GET /ipfs/{cid}` gates tree objects /// with this so the CID surface matches `get_tree`: a tree reachable only at a @@ -2305,8 +2457,7 @@ pub fn allowed_tree_set_for_caller( } /// [`allowed_tree_set_for_caller`] with an injectable `git_bin` and walk `timeout`, -/// for the `GET /ipfs/{cid}` tree gate. One deadline spans the whole walk (the HEAD -/// probe, rev-list, every per-commit ls-tree, and the root-tree pass), matching +/// for the `GET /ipfs/{cid}` tree gate. One deadline spans the whole walk, matching /// `blob_paths`, so a slow or hung walk is bounded as a unit while the handler holds /// its /ipfs walk permit (#174 F5). pub fn allowed_tree_set_for_caller_bounded( @@ -2330,7 +2481,7 @@ pub fn allowed_tree_set_for_caller_bounded( // on cycles and on the same tree reachable at multiple paths // (the "blob reachable at any allowed path" rule, applied to // trees). - let tree_pairs = tree_paths(repo_path, git_bin, deadline)?; + let tree_pairs = object_paths(repo_path, git_bin, deadline, true)?.trees; let ctx = TreeCheckCtx { repo_path, git_bin, @@ -2341,32 +2492,10 @@ pub fn allowed_tree_set_for_caller_bounded( }; let mut admitted: HashSet = HashSet::new(); for (oid, path) in &tree_pairs { - // `tree_paths` only emits non-empty paths (root trees are - // enumerated below), so the empty-path case is not reachable - // here. P3 (reviewer round 9): the previous comment described - // a caller-aware empty-path carve-out that the surrounding - // code never produced, so the call degenerated to the same - // decision `visibility_check` would make. Reverting the - // routing through `pair_decision` removes the dead code and - // its comment. `visibility_check` is still the policy surface - // for the root tree pass below. if visibility_check(rules, is_public, owner_did, caller, path) == Decision::Allow { tree_structurally_safe(&ctx, oid, path, &mut admitted, deadline)?; } } - // Root trees of reachable commits: they have no path in - // `tree_paths` (ls-tree emits descendants only), so evaluate - // them at "/" — the root tree is admitted iff every direct - // entry is safe at the root and (for tree entries) the child - // tree is itself structurally safe. The check is recursive, so - // a denied subtree propagates up to the root. - let commits = reachable_commit_oids(repo_path, git_bin, deadline)?; - for root_oid in root_tree_oids(repo_path, git_bin, &commits, deadline)? { - if visibility_check(rules, is_public, owner_did, caller, "/") != Decision::Allow { - continue; - } - tree_structurally_safe(&ctx, &root_oid, "/", &mut admitted, deadline)?; - } Ok(admitted) } @@ -3005,7 +3134,7 @@ mod tests { /// #174 U3: the withheld-blob walk is bounded at the shared `blob_paths` seam, so /// a hung git child cannot pin the caller's permit past the deadline. A fake git - /// that hangs on `rev-list` must make `blob_paths` return `GitServiceTimeout` + /// that hangs on `log` must make `blob_paths` return `GitServiceTimeout` /// within the watchdog budget (not block for the child's lifetime), and the /// child's process group must be reaped (its recorded leader PID gone). Every /// caller (upload-pack serve, receive-pack replication) funnels through @@ -3016,10 +3145,10 @@ mod tests { fn blob_paths_times_out_and_reaps_a_hung_walk() { use std::time::Duration; let tmp = TempDir::new().unwrap(); - // Fast on every stage except rev-list, which records its own (group-leader) + // Fast on every stage except log, which records its own (group-leader) // PID and then hangs. `sleep 30` bounds the worst case if the watchdog is // ever broken, so a regression cannot wedge the suite for 300s. - let body = "#!/bin/sh\ncase \"$1\" in\n rev-list) echo $$ > revlist.pid ; sleep 30 ;;\n rev-parse) echo deadbeef ;;\n *) : ;;\nesac\nexit 0\n"; + let body = "#!/bin/sh\ncase \"$1\" in\n log) echo $$ > log.pid ; sleep 30 ;;\n *) : ;;\nesac\nexit 0\n"; let git_bin = write_fake_git(tmp.path(), body); // Run the walk on a thread with a short budget; the recv_timeout succeeding @@ -3032,7 +3161,7 @@ mod tests { let result = rx.recv_timeout(Duration::from_secs(10)).expect( "blob_paths must return within the watchdog budget, not hang on a stuck git child", ); - let err = result.expect_err("a hung rev-list must abort the walk with an error"); + let err = result.expect_err("a hung log must abort the walk with an error"); assert!( err.downcast_ref::() .is_some(), @@ -3044,8 +3173,8 @@ mod tests { // The recorded process-group leader must be gone: the watchdog reaps the // whole group before blob_paths returns, so no orphaned git lingers. - let pid: i32 = std::fs::read_to_string(tmp.path().join("revlist.pid")) - .expect("the fake git must have recorded its rev-list PID") + let pid: i32 = std::fs::read_to_string(tmp.path().join("log.pid")) + .expect("the fake git must have recorded its log PID") .trim() .parse() .expect("recorded PID must parse"); @@ -3573,7 +3702,7 @@ esac\n"; let deadline = Instant::now() + WALK_TIMEOUT; // The lenient enumeration; on this clean fixture it matches the strict one. let commits = reachable_commit_oids(&bare, "git", deadline).unwrap(); - let objs = object_paths(&bare, "git", &commits, deadline).unwrap(); + let objs = object_paths_ls_tree(&bare, "git", &commits, deadline).unwrap(); // Blob records survive the `-rzt` change, at their paths (unchanged). assert!(objs.contains(&(secret_oid.clone(), "/secret/b.txt".into(), "blob".into()))); @@ -3606,6 +3735,171 @@ esac\n"; ); } + #[test] + fn raw_history_matches_ls_tree_snapshots() { + let repo = TempDir::new().unwrap(); + let path = repo.path(); + let git = |args: &[&str], input: &[u8]| { + let deadline = Instant::now() + WALK_TIMEOUT; + let result = run_bounded_git("git", args, path, input, deadline).unwrap(); + String::from_utf8(result).unwrap().trim_end().to_owned() + }; + git(&["init", "--bare", "-q"], b""); + git(&["config", "user.email", "t@t"], b""); + git(&["config", "user.name", "t"], b""); + git(&["config", "diff.renames", "copies"], b""); + git(&["config", "diff.ignoreSubmodules", "all"], b""); + git(&["config", "log.showRoot", "false"], b""); + let check = || { + let deadline = Instant::now() + WALK_TIMEOUT; + let commits = reachable_commit_oids(path, "git", deadline).unwrap(); + let old = object_paths_ls_tree(path, "git", &commits, deadline).unwrap(); + let pairs = |kind: &str| -> HashSet<_> { + old.iter() + .filter(|(_, _, k)| k == kind) + .map(|(oid, path, _)| (oid.clone(), path.clone())) + .collect() + }; + let mut old_trees = pairs("tree"); + old_trees.extend(root_tree_pairs(path, "git", &commits, deadline).unwrap()); + let new = object_paths(path, "git", deadline, true).unwrap(); + assert_eq!(new.blobs, pairs("blob")); + assert_eq!(new.trees, old_trees); + assert_eq!(new.gitlinks, pairs("commit")); + let old_blobs: HashSet<_> = blob_paths_ls_tree(path, "git", WALK_TIMEOUT) + .unwrap() + .into_iter() + .collect(); + let new_blobs: HashSet<_> = blob_paths(path, "git", WALK_TIMEOUT) + .unwrap() + .into_iter() + .collect(); + assert_eq!(new_blobs, old_blobs); + }; + check(); + + let tree = |entries: &[(&str, &str, &str)]| { + let mut input = Vec::new(); + for (mode_and_kind, oid, name) in entries { + input.extend_from_slice(format!("{mode_and_kind} {oid}\t{name}\0").as_bytes()); + } + git(&["mktree", "-z"], &input) + }; + let commit = |tree: &str, parents: &[&str], message: &str| { + let mut args = vec!["commit-tree", tree, "-m", message]; + for parent in parents { + args.extend(["-p", parent]); + } + git(&args, b"") + }; + let empty = tree(&[]); + let root = commit(&empty, &[], "empty root"); + let contents = make_blob(path, b"same file before and after rename"); + let other = make_blob(path, b"side branch only"); + let resolved = make_blob(path, b"merge-only conflict resolution"); + let inner = tree(&[("100644 blob", &contents, "- café \"quote\"\n\t ")]); + let nested = tree(&[("040000 tree", &inner, "child")]); + let name = "conflict"; + let common = tree(&[ + ("040000 tree", &nested, "nested"), + ("040000 tree", &empty, "empty-dir"), + ("100644 blob", &contents, name), + ("160000 commit", &root, "submodule"), + ]); + let base = commit(&common, &[&root], "nested files and submodule"); + let left_tree = tree(&[ + ("040000 tree", &nested, "renamed"), + ("100755 blob", &contents, "executable"), + ("100644 blob", &other, name), + ("160000 commit", &base, "submodule"), + ]); + let left = commit(&left_tree, &[&base], "rename and update gitlink"); + let right_tree = tree(&[ + ("100644 blob", &other, "side-only"), + ("120000 blob", &contents, name), + ("100644 blob", &contents, "submodule"), + ]); + let right = commit(&right_tree, &[&base], "delete trees and replace gitlink"); + let merged_tree = tree(&[ + ("040000 tree", &nested, "renamed"), + ("100644 blob", &resolved, name), + ("160000 commit", &right, "submodule"), + ]); + let merge = commit( + &merged_tree, + &[&left, &right], + "resolve against both parents", + ); + let tip = commit(&merged_tree, &[&merge], "empty commit on detached HEAD"); + git(&["update-ref", "--no-deref", "HEAD", &tip], b""); + git(&["update-ref", "refs/heads/other-root", &root], b""); + check(); + + // A shallow boundary with a nonempty tree must enumerate its snapshot. + std::fs::write(path.join("shallow"), format!("{merge}\n")).unwrap(); + check(); + + // A graft can make a tree identical to its only parent forever. Refuse + // a partial inventory rather than treating the unchanged paths as absent. + std::fs::remove_file(path.join("shallow")).unwrap(); + std::fs::write(path.join("info/grafts"), format!("{tip} {tip}\n")).unwrap(); + let err = blob_paths(path, "git", WALK_TIMEOUT).unwrap_err(); + assert!(err.to_string().contains("cyclic first-parent history")); + } + + #[test] + #[ignore = "times the paired walks over the developer checkout"] + fn benchmark_visibility_history_walk() { + use std::hint::black_box; + + let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + fn median_ms(mut walk: impl FnMut()) -> f64 { + walk(); + let mut samples = [Duration::ZERO; 5]; + for sample in &mut samples { + let start = Instant::now(); + walk(); + *sample = start.elapsed(); + } + samples.sort_unstable(); + samples[2].as_secs_f64() * 1_000.0 + } + + let before_blobs = median_ms(|| { + black_box(blob_paths_ls_tree(&repo, "git", WALK_TIMEOUT).unwrap()); + }); + let after_blobs = median_ms(|| { + black_box(blob_paths(&repo, "git", WALK_TIMEOUT).unwrap()); + }); + let before_objects = median_ms(|| { + let deadline = Instant::now() + WALK_TIMEOUT; + let commits = reachable_commit_oids(&repo, "git", deadline).unwrap(); + let mut pairs: Vec<_> = object_paths_ls_tree(&repo, "git", &commits, deadline) + .unwrap() + .into_iter() + .filter(|(_, _, kind)| kind == "blob" || kind == "tree") + .map(|(oid, path, _)| (oid, path)) + .collect(); + pairs.extend(root_tree_pairs(&repo, "git", &commits, deadline).unwrap()); + black_box(pairs); + }); + let after_objects = median_ms(|| { + let history = object_paths(&repo, "git", Instant::now() + WALK_TIMEOUT, true).unwrap(); + let pairs: Vec<_> = history.blobs.into_iter().chain(history.trees).collect(); + black_box(pairs); + }); + println!("| Rust walk | Before (median ms) | After (median ms) | Speedup |"); + println!("|---|---:|---:|---:|"); + println!( + "| Blob paths | {before_blobs:.2} | {after_blobs:.2} | {:.1}× |", + before_blobs / after_blobs + ); + println!( + "| Blob and tree paths | {before_objects:.2} | {after_objects:.2} | {:.1}× |", + before_objects / after_objects + ); + } + #[test] fn allowed_tree_set_gates_withheld_subtree_tree() { let (_td, bare, _s, _p) = fixture(); @@ -5891,7 +6185,7 @@ esac\n"; /// /// #218 review round 8 P2 (why this exists): the phase-2 ref tests used to /// hang the ref on `fixture()`'s `secret` blob, which is COMMITTED at - /// `secret/b.txt`. Phase 1's per-commit `ls-tree` therefore already yielded + /// `secret/b.txt`. The commit walk therefore already yields /// `(secret, "/secret/b.txt")`, the `/secret/**` rule already denied it, and /// the `withheld.contains(&secret)` assertion passed with phase 2 deleted /// outright — the tests bound nothing. A blob written straight to the object @@ -6378,7 +6672,7 @@ esac\n"; // * nested tag (tag-of-tag-of-blob) // The blob OID and tree OID are distinct so the consumers // can disambiguate. The blob is NOT committed anywhere, so - // phase 1 (`rev-list --all` + `ls-tree`) does not see it — + // the commit walk does not see it — // every entry in the `(oid, path)` set arrives through // phase 2 (`for-each-ref`) with an empty path. let td = TempDir::new().unwrap(); From 2937b9a829708ed5d3a075fb2af4884f74537329 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:26:58 -0600 Subject: [PATCH 2/4] docs(node): describe the log --raw history walk in the blob_paths doc comment --- .../twigpine-node/src/git/visibility_pack.rs | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/crates/twigpine-node/src/git/visibility_pack.rs b/crates/twigpine-node/src/git/visibility_pack.rs index a509cc6af..d59dff8cb 100644 --- a/crates/twigpine-node/src/git/visibility_pack.rs +++ b/crates/twigpine-node/src/git/visibility_pack.rs @@ -630,22 +630,22 @@ fn assert_all_refs_are_commits(repo_path: &Path, git_bin: &str, deadline: Instan /// including a blob that only ever existed /// in an older commit (a since-deleted file, a rotated secret whose previous version /// is still in history). Classifying only ref-tip trees would leave those blobs -/// unwithheld while pin/serve still hand them out in cleartext, so we enumerate all -/// reachable commits and walk each commit's tree. +/// unwithheld while pin/serve still hand them out in cleartext, so we walk the +/// whole reachable history with one `git log --raw` pass (`object_paths`). /// /// `--all` covers every ref namespace (a blob reachable only through `refs/notes/*` -/// must not escape withholding); HEAD is added explicitly for the detached case, -/// where HEAD reaches commits that no ref does. `git ls-tree -rz ` per commit -/// keeps every path a blob lives at (the same blob content can appear at several -/// paths, and the per-path visibility check needs all of them). This is why it is -/// not `git rev-list --objects`, which reports only one path per object. Pairs are -/// de-duplicated across commits. Paths carry a leading "/" to match the glob form -/// used by visibility rules ("/secret/**"). +/// must not escape withholding) and HEAD, so a detached HEAD that reaches commits no +/// ref does is walked too. The raw log reports every path a blob lives at (the same +/// blob content can appear at several paths, and the per-path visibility check needs +/// all of them). This is why it is not `git rev-list --objects`, which reports only +/// one path per object. Pairs are de-duplicated across commits. Paths carry a leading +/// "/" to match the glob form used by visibility rules ("/secret/**"). /// -/// Fails closed: if commit enumeration, the non-commit ref walk, or any tree walk +/// Fails closed: if the history walk, the non-commit ref walk, or any tree walk /// fails, returns an error so the caller aborts the serve/pin rather than producing -/// a partial (under-withheld) set. Two phases: -/// 1. `git rev-list --all` over commits + per-commit `ls-tree -rz` — captures every +/// a partial (under-withheld) set. A cyclic first-parent history (replace refs or +/// grafts) is such a failure. Two phases: +/// 1. `object_paths` (`git log --all --raw`) over history, capturing every /// commit-reachable blob with its path. /// 2. `git for-each-ref` over non-commit ref targets — captures every direct /// ref-to-blob / ref-to-tree with an EMPTY path (the deny-side caller From a510e844671787222b873cb081adace79e28e6cf Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:59:26 -0600 Subject: [PATCH 3/4] test(node): drive the ipfs walk shims through git log --raw --- crates/twigpine-node/src/api/ipfs.rs | 64 ++++++++++++++++++---------- 1 file changed, 41 insertions(+), 23 deletions(-) diff --git a/crates/twigpine-node/src/api/ipfs.rs b/crates/twigpine-node/src/api/ipfs.rs index f1e35ffbe..944fecf0d 100644 --- a/crates/twigpine-node/src/api/ipfs.rs +++ b/crates/twigpine-node/src/api/ipfs.rs @@ -3247,9 +3247,12 @@ mod tests { .to_string() } - /// Walk-counting shim that runs the REAL walk (`state.git_bin`): each `rev-list` - /// appends one line to `log`, then every invocation execs the real `git`, so the - /// allowed-set a walk produces is the repo's genuine one. + /// Walk-counting shim that runs the REAL walk (`state.git_bin`): each `log` (the + /// withheld walk's `git log --all --raw`) appends one line to `log`, then every + /// invocation execs the real `git`, so the allowed-set a walk produces is the + /// repo's genuine one. The `rev-list` arm stays for the commit/tag reachability + /// walk, which still enumerates with `git rev-list --all`; a walk is one or the + /// other, never both, so the tally stays one line per walk. /// /// `walk_logging_fake_git` below answers every subcommand with nothing, so under it /// EVERY walked repo yields an empty allowed set and no repo can ever authorize. The @@ -3261,8 +3264,10 @@ mod tests { "#!/bin/sh\n\ case \"$1\" in\n\ rev-list) echo walk >> \"{}\" ;;\n\ + log) echo walk >> \"{}\" ;;\n\ esac\n\ exec git \"$@\"\n", + log.display(), log.display() ); let git_path = dir.join("walkgit"); @@ -3285,9 +3290,11 @@ mod tests { } /// Fake git for the WALK only (`state.git_bin`): empty refs, `rev-parse` - /// resolves, and each `rev-list` appends one line to `log` and prints nothing — - /// every walked repo yields an EMPTY allowed-set (path-gate deny verdict) and - /// the log's line count == the number of expensive walks run. The probe and the + /// resolves, and each `log` (the withheld walk's `git log --all --raw`) appends + /// one line to `log` and prints nothing — every walked repo yields an EMPTY + /// allowed-set (path-gate deny verdict) and the log's line count == the number of + /// expensive walks run. The `rev-list` arm stays for the commit/tag reachability + /// walk, which still enumerates with `git rev-list --all`. The probe and the /// content read shell to the real `git`, so seeded objects must genuinely exist. #[cfg(unix)] fn walk_logging_fake_git(dir: &std::path::Path, log: &std::path::Path) -> String { @@ -3297,9 +3304,11 @@ mod tests { for-each-ref) : ;;\n\ rev-parse) echo deadbeef ;;\n\ rev-list) echo walk >> \"{}\" ;;\n\ + log) echo walk >> \"{}\" ;;\n\ *) : ;;\n\ esac\n\ exit 0\n", + log.display(), log.display() ); let git_path = dir.join("fakegit"); @@ -8447,16 +8456,17 @@ mod tests { let tmp = tempfile::TempDir::new().unwrap(); let walk_log = tmp.path().join("walks.log"); let revlist_pid = tmp.path().join("revlist.pid"); - // Fake git for the WALK only: `rev-list` records its pid and a start - // marker, sleeps far past the budget, then records a done marker. Under - // the clamped walk deadline the whole process group is torn down mid - // sleep, so "done" never appears. The 8s sleep also bounds a RED run. + // Fake git for the WALK only: the walk's `git log --all --raw` records its + // pid and a start marker, sleeps far past the budget, then records a done + // marker. Under the clamped walk deadline the whole process group is torn + // down mid sleep, so "done" never appears. The 8s sleep also bounds a RED run. let body = format!( "#!/bin/sh\n\ case \"$1\" in\n\ for-each-ref) : ;;\n\ rev-parse) echo deadbeef ;;\n\ rev-list) echo $$ > \"{pid}\"; echo start >> \"{log}\"; sleep 8; echo done >> \"{log}\" ;;\n\ + log) echo $$ > \"{pid}\"; echo start >> \"{log}\"; sleep 8; echo done >> \"{log}\" ;;\n\ *) : ;;\n\ esac\n\ exit 0\n", @@ -8514,7 +8524,7 @@ mod tests { let peer: SocketAddr = "203.0.113.71:5000".parse().unwrap(); let mut fut = Box::pin(router.oneshot(get_cid(&cid, Some(peer)))); - // Drive until the fake git's rev-list records its pid: the walk is now in + // Drive until the fake git's log records its pid: the walk is now in // the blocking pool and the request future is `.await`ing its join. Stop // polling the instant the future completes (re-polling would panic). let mut walk_pid: Option = None; @@ -8880,14 +8890,15 @@ mod tests { drop(held); } - /// Build the shared `/ipfs` TREE-walk fixture. A fake `git` whose `rev-list` records - /// its pid then sleeps ~6s (so the tree walk blocks deterministically inside + /// Build the shared `/ipfs` TREE-walk fixture. A fake `git` whose `log` (the + /// tree walk's `git log --all --raw`) records its pid then sleeps ~6s (so the + /// tree walk blocks deterministically inside /// `run_bounded_git`) and whose `cat-file -t` answers "tree" (so the bounded /// object-type probe, `object_type_bounded` on `state.git_bin`, routes into the /// tree-gate arm); a real SHA-256 bare repo with a committed `src/` tree pinned WITH /// provenance; and a path-scoped rule so the gate takes the tree-walk branch. Returns /// the tempdir (keep it alive for the whole test), the state (the caller sets the walk - /// semaphores), the requested CID, and the rev-list pidfile path. + /// semaphores), the requested CID, and the pidfile path. #[cfg(unix)] async fn seed_tree_walk_fixture( pool: sqlx::PgPool, @@ -8908,9 +8919,11 @@ mod tests { rev-parse) echo deadbeef ;;\n\ cat-file) if [ \"$2\" = \"-t\" ]; then echo tree; fi ;;\n\ rev-list) echo $$ > \"{}\"; sleep 6 ;;\n\ + log) echo $$ > \"{}\"; sleep 6 ;;\n\ *) : ;;\n\ esac\n\ exit 0\n", + revlist_pid.display(), revlist_pid.display() ); let git_path = tmp.path().join("fakegit"); @@ -9028,7 +9041,7 @@ mod tests { /// `allowed_tree_set_for_caller_bounded` — the walk this integration converts to /// `run_bounded_git` — rather than the blob walk #174 already proved. With the /// global pool at size 1, drive a request until its walk (a fake git that hangs on - /// `rev-list`) is in flight; the slot must stay held (`available_permits() == 0`) + /// `log`) is in flight; the slot must stay held (`available_permits() == 0`) /// and a replacement from a DIFFERENT source must shed 503 for as long as the /// blocking walk runs — even though the request future is only `.await`ing the /// blocking join. When the blocking walk ends the permit frees and a replacement @@ -9066,7 +9079,7 @@ mod tests { let peer: SocketAddr = "203.0.113.81:5000".parse().unwrap(); let mut fut = Box::pin(router.clone().oneshot(make_req(peer))); - // Drive until the fake git's rev-list records its pid — the TREE walk is now in + // Drive until the fake git's log records its pid — the TREE walk is now in // the blocking pool and the request future is `.await`ing its join, holding the // walk permit. Stop polling the instant the future completes (re-polling a // completed oneshot panics). @@ -9087,7 +9100,7 @@ mod tests { } } let pid = walk_pid - .unwrap_or_else(|| panic!("the fake git rev-list must have spawned; early: {early:?}")); + .unwrap_or_else(|| panic!("the fake git log must have spawned; early: {early:?}")); // Reap the sleeping child on drop so a RED run leaks no orphan. struct ReapOnDrop(i32); impl Drop for ReapOnDrop { @@ -9213,7 +9226,7 @@ mod tests { break; } } - let pid = walk_pid.expect("the fake git rev-list must have spawned"); + let pid = walk_pid.expect("the fake git log must have spawned"); struct ReapOnDrop(i32); impl Drop for ReapOnDrop { fn drop(&mut self) { @@ -9272,7 +9285,7 @@ mod tests { /// the object absent. With `ipfs_max_repos_walked = 1` and TWO public, path-scoped /// repos both carrying the blob, the first candidate is walked (empty allowed-set → /// a deny VERDICT) and the second is cut by the cap (no verdict), so the fake git's - /// `rev-list` runs exactly once and the request sheds a retryable 503 + Retry-After + /// `log` runs exactly once and the request sheds a retryable 503 + Retry-After /// — never the old false 404 (the blob genuinely sits in the second repo). /// This drives the TWIGPINE_IPFS_MAX_REPOS_WALKED knob specifically. The merge left /// two walk caps in play, this one and the branch's own history-walk ceiling, and @@ -9289,8 +9302,9 @@ mod tests { let tmp = tempfile::TempDir::new().unwrap(); let walk_log = tmp.path().join("walks.log"); - // Fake git for the WALK: empty refs, `rev-parse` resolves, and each `rev-list` - // appends one line to a log (so the number of walks == the line count) and exits + // Fake git for the WALK: empty refs, `rev-parse` resolves, and each `log` + // (the withheld walk's `git log --all --raw`) appends one line to a log (so + // the number of walks == the line count) and exits // with EMPTY output (the allowed-set is empty, so every repo path-gates to a // `continue` and the request 404s after walking). object_type uses the REAL git, // so the seeded blob below must genuinely exist. @@ -9300,9 +9314,11 @@ mod tests { for-each-ref) : ;;\n\ rev-parse) echo deadbeef ;;\n\ rev-list) echo walk >> \"{}\" ;;\n\ + log) echo walk >> \"{}\" ;;\n\ *) : ;;\n\ esac\n\ exit 0\n", + walk_log.display(), walk_log.display() ); let git_path = tmp.path().join("fakegit"); @@ -9864,8 +9880,9 @@ mod tests { /// in an admitted visibility walk is PROGRESSING, and shedding it would convert a /// slow-but-correct retrieval into a 503 on a box that is merely loaded. /// - /// The resolve budget is 1s while the walk sleeps ~2s per `rev-list`, so any - /// deadline that reaches past `oids_for_cid` ends this request before it can serve. + /// The resolve budget is 1s while the walk sleeps ~2s on its `git log --all --raw`, + /// so any deadline that reaches past `oids_for_cid` ends this request before it + /// can serve. /// The shim execs the REAL git after sleeping, so the allowed-set the walk produces /// is the repo's genuine one and the 200 is a real serve, not an artifact. /// @@ -9911,6 +9928,7 @@ mod tests { "#!/bin/sh\n\ case \"$1\" in\n\ rev-list) sleep 2 ;;\n\ + log) sleep 2 ;;\n\ esac\n\ exec git \"$@\"\n", ) From 46cae5dd6f28c234b9a574518eb7b6b92dbb346f Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:14:26 -0600 Subject: [PATCH 4/4] test(node): drive the repos walk shims through git log --raw --- crates/twigpine-node/src/api/repos.rs | 94 +++++++++++++-------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/crates/twigpine-node/src/api/repos.rs b/crates/twigpine-node/src/api/repos.rs index e128d2796..453c5f8b2 100644 --- a/crates/twigpine-node/src/api/repos.rs +++ b/crates/twigpine-node/src/api/repos.rs @@ -8374,7 +8374,7 @@ mod tests { async fn replication_walk_is_bounded_and_fails_closed_on_a_hung_git() { use std::time::Duration; let tmp = tempfile::TempDir::new().unwrap(); - let body = "#!/bin/sh\ncase \"$1\" in\n rev-list) sleep 30 ;;\n rev-parse) echo deadbeef ;;\n *) : ;;\nesac\nexit 0\n"; + let body = "#!/bin/sh\ncase \"$1\" in\n rev-list) sleep 30 ;;\n log) sleep 30 ;;\n rev-parse) echo deadbeef ;;\n *) : ;;\nesac\nexit 0\n"; let git_bin = write_fake_git(tmp.path(), body); // Public root (announceable) + a path-scoped rule, so the walk actually runs // rather than taking the has_path_scoped_rule short-circuit. @@ -8649,7 +8649,7 @@ mod tests { use tower::ServiceExt; let tmp = tempfile::TempDir::new().unwrap(); - let body = "#!/bin/sh\ncase \"$1\" in\n rev-list) sleep 30 ;;\n rev-parse) echo deadbeef ;;\n *) : ;;\nesac\nexit 0\n"; + let body = "#!/bin/sh\ncase \"$1\" in\n rev-list) sleep 30 ;;\n log) sleep 30 ;;\n rev-parse) echo deadbeef ;;\n *) : ;;\nesac\nexit 0\n"; let fake = write_fake_git(tmp.path(), body); let mut state = crate::test_support::test_state(pool).await; @@ -8724,7 +8724,7 @@ mod tests { // rev-list burns 1.2s of the 2s budget and lists no commits -> empty withheld. // Serve: upload-pack needs 1.2s, which does NOT fit the ~0.8s remainder but // WOULD fit a fresh 2s budget. - let body = "#!/bin/sh\ncase \"$1\" in\n rev-parse) exit 1 ;;\n rev-list) sleep 1.2 ;;\n upload-pack) sleep 1.2 ;;\n *) : ;;\nesac\nexit 0\n"; + let body = "#!/bin/sh\ncase \"$1\" in\n rev-parse) exit 1 ;;\n rev-list) sleep 1.2 ;;\n log) sleep 1.2 ;;\n upload-pack) sleep 1.2 ;;\n *) : ;;\nesac\nexit 0\n"; let fake = write_fake_git(tmp.path(), body); let mut state = crate::test_support::test_state(pool).await; @@ -8812,8 +8812,8 @@ mod tests { // repurposed this test from "the filtered serve shares the deadline" into // "the walk errors", losing the #174 guard while looking merely red. A // commit tip peels to nothing, so two columns is the whole line here; the - // 1.2s walk cost stays on `ls-tree` so walk and serve remain independently - // attributable. + // 1.2s walk cost stays on the walk's `log` arm so walk and serve remain + // independently attributable. let body = format!( "#!/bin/sh\ncase \"$1\" in\n \ for-each-ref) echo {commit} commit ;;\n \ @@ -8821,6 +8821,7 @@ mod tests { rev-parse) echo {commit} ;;\n \ rev-list) echo {commit} ;;\n \ ls-tree) printf '100644 blob {blob}\\tsecret/f.txt' ; sleep 1.2 ;;\n \ + log) printf 'R{commit} ffffffffffffffffffffffffffffffffffffffff\\0\\n:000000 100644 0000000000000000000000000000000000000000 {blob} A\\0secret/f.txt\\0' ; sleep 1.2 ;;\n \ pack-objects) sleep 1.2 ;;\n \ *) : ;;\nesac\nexit 0\n" ); @@ -11536,7 +11537,7 @@ mod tests { /// #174 U3 (P1-b, RED-before/GREEN-after): a client disconnect during the /// path-scoped withheld-blob walk must NOT release the read admission while the /// uncancellable `spawn_blocking` walk is still running. The handler takes the - /// global read permit, enters the walk (a fake git hangs on rev-list), then the + /// global read permit, enters the walk (a fake git hangs on `git log`), then the /// request future is dropped mid-walk. With both permits moved into the blocking /// task the global slot stays occupied until the walk finishes; on the pre-fix code /// the handler-local permits drop on future-drop and the slot frees instantly (RED), @@ -11563,7 +11564,8 @@ mod tests { // Fake git: resolve refs fast, hang on rev-list (recording its pid first). The // ~6s sleep bounds the walk so a broken fix cannot wedge the suite. let body = format!( - "#!/bin/sh\ncase \"$1\" in\n rev-list) echo $$ > \"{}\" ; sleep 6 ;;\n rev-parse) echo deadbeef ;;\n *) : ;;\nesac\nexit 0\n", + "#!/bin/sh\ncase \"$1\" in\n rev-list) echo $$ > \"{}\" ; sleep 6 ;;\n log) echo $$ > \"{}\" ; sleep 6 ;;\n rev-parse) echo deadbeef ;;\n *) : ;;\nesac\nexit 0\n", + revlist_pid.display(), revlist_pid.display() ); let git_path = tmp.path().join("fakegit"); @@ -11890,7 +11892,8 @@ mod tests { /// /// Same isolation as the plain-path test above: read pool = 1, per-source cap /// permissive, so only the global permit can shed a replacement. The fake git - /// serves the withheld walk (for-each-ref/rev-parse/rev-list/ls-tree) with a blob + /// serves the withheld walk (for-each-ref/rev-parse/rev-list/ls-tree, now one `git + /// log --all --raw`) with a blob /// under the denied `/src/**` subtree so the filtered branch is taken, answers /// the pack build's rev-list fast, and hangs pack-objects in a SIGTERM-trapping /// descendant. The descendant hang is first-invocation-only (keyed on the @@ -11918,6 +11921,7 @@ mod tests { rev-parse) echo {commit} ;;\n\ rev-list) echo {commit} ;;\n\ ls-tree) printf '100644 blob {blob}\\tsrc/x.txt' ;;\n\ + log) printf 'R{commit} ffffffffffffffffffffffffffffffffffffffff\\0\\n:000000 100644 0000000000000000000000000000000000000000 {blob} A\\0src/x.txt\\0' ;;\n\ pack-objects)\n\ if [ ! -e \"{desc}\" ]; then\n\ sh -c 'trap \"\" TERM; echo $$ > \"{desc}\"; i=0; while [ $i -lt 20 ]; do sleep 1; i=$((i+1)); done' &\n\ @@ -13072,7 +13076,8 @@ mod tests { let marker = tmp.path().join("revlist.ran"); // Fake git records when rev-list runs (the walk's first git call). let body = format!( - "#!/bin/sh\ncase \"$1\" in\n rev-list) echo ran > \"{}\" ;;\n *) : ;;\nesac\nexit 0\n", + "#!/bin/sh\ncase \"$1\" in\n rev-list) echo ran > \"{}\" ;;\n log) echo ran > \"{}\" ;;\n *) : ;;\nesac\nexit 0\n", + marker.display(), marker.display() ); let git_path = tmp.path().join("fakegit"); @@ -13323,11 +13328,11 @@ mod tests { use tokio::sync::Semaphore; let tmp = tempfile::TempDir::new().unwrap(); - // Phase 1 (ls-tree) sleeps 1.5s and succeeds (empty tree); phase 2 + // Phase 1 (`git log` without `-t`) sleeps 1.5s and succeeds (empty tree); phase 2 // (cat-file --batch-all-objects) sleeps 1.5s. With a 2s whole-scan budget the // shared deadline leaves phase 2 only ~0.5s, so it is reaped; a fresh 2s budget // would let it finish. - let body = "#!/bin/sh\ncase \"$1\" in\n rev-parse) echo deadbeef ;;\n rev-list) echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ;;\n ls-tree) case \"$*\" in *-rzt*) : ;; *) sleep 1.5 ;; esac ;;\n cat-file) case \"$*\" in *--batch-all-objects*) sleep 1.5 ;; *) : ;; esac ;;\n *) : ;;\nesac\nexit 0\n"; + let body = "#!/bin/sh\ncase \"$1\" in\n rev-parse) echo deadbeef ;;\n rev-list) echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ;;\n ls-tree) case \"$*\" in *-rzt*) : ;; *) sleep 1.5 ;; esac ;;\n log) case \"$*\" in *\" -t \"*) : ;; *) sleep 1.5 ;; esac ;;\n cat-file) case \"$*\" in *--batch-all-objects*) sleep 1.5 ;; *) : ;; esac ;;\n *) : ;;\nesac\nexit 0\n"; let git_bin = write_fake_git(tmp.path(), body); // A candidate that is NOT a blob (never appears in all_blob_oids): kept by // replicable_objects_fail_closed only if phase 2 actually ran to completion. @@ -13369,7 +13374,7 @@ mod tests { let tmp = tempfile::TempDir::new().unwrap(); // Blob ls-tree -rz sleeps 1.5s; tree ls-tree -rzt sleeps 1.5s; cat-file is // instant. With a 2s whole-scan budget the tree walk is reaped. - let body = "#!/bin/sh\ncase \"$1\" in\n rev-parse) echo deadbeef ;;\n rev-list) echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ;;\n ls-tree) case \"$*\" in *-rzt*) sleep 1.5 ;; *) sleep 1.5 ;; esac ;;\n cat-file) : ;;\n *) : ;;\nesac\nexit 0\n"; + let body = "#!/bin/sh\ncase \"$1\" in\n rev-parse) echo deadbeef ;;\n rev-list) echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ;;\n ls-tree) case \"$*\" in *-rzt*) sleep 1.5 ;; *) sleep 1.5 ;; esac ;;\n log) sleep 1.5 ;;\n cat-file) : ;;\n *) : ;;\nesac\nexit 0\n"; let git_bin = write_fake_git(tmp.path(), body); let candidates = vec!["cccccccccccccccccccccccccccccccccccccccc".to_string()]; @@ -14230,7 +14235,7 @@ mod tests { case \"$1\" in\n\ receive-pack) cat > /dev/null 2>/dev/null; printf '0022\\001unpack ok\\nok refs/heads/main\\n0000' ;;\n\ rev-parse) echo deadbeef ;;\n\ - cat-file|rev-list|ls-tree)\n\ + cat-file|rev-list|ls-tree|log)\n\ if mkdir \"{lock}\" 2>/dev/null; then\n\ echo 1 >> \"{ran}\"\n\ sleep 0.15\n\ @@ -14361,7 +14366,7 @@ mod tests { let tmp = tempfile::TempDir::new().unwrap(); let marker = tmp.path().join("scan.ran"); let body = format!( - "#!/bin/sh\ncase \"$1\" in\n receive-pack) cat > /dev/null 2>/dev/null ;;\n cat-file|rev-list|ls-tree) echo 1 >> \"{}\" ;;\n *) : ;;\nesac\nexit 0\n", + "#!/bin/sh\ncase \"$1\" in\n receive-pack) cat > /dev/null 2>/dev/null ;;\n cat-file|rev-list|ls-tree|log) echo 1 >> \"{}\" ;;\n *) : ;;\nesac\nexit 0\n", marker.display() ); let git_bin = write_fake_git(tmp.path(), &body); @@ -16626,14 +16631,16 @@ mod tests { std::fs::read_to_string(log).unwrap_or_default() } - /// Withheld-walk children run so far. `ls-tree` is the walk's signature child - /// (`blob_paths` lists every reachable commit's tree); the delta scan and the - /// full-scan fallback use `rev-list` / `cat-file` instead. + /// Withheld-walk children run so far. `log --all --raw` is the walk's signature + /// child (`blob_paths` enumerates history with one `git log --all --raw`); the + /// delta scan and the full-scan fallback use `rev-list` / `cat-file` instead, + /// and `root_tree_oids`'s `git log --no-walk` does not carry the `--all --raw` + /// prefix. #[cfg(unix)] fn f2a_walks(log: &std::path::Path) -> usize { f2a_log(log) .lines() - .filter(|l| l.starts_with("ls-tree")) + .filter(|l| l.starts_with("log --all --raw")) .count() } @@ -16825,7 +16832,7 @@ mod tests { /// A `rev-list --objects` line names the tips a DELTA scan was asked to resolve, /// so it attributes that scan to one push's tips. The withheld walk's own - /// `rev-list --all` / `ls-tree` lines never carry a tip as an argument this way. + /// the walk's `git log --all --raw` lines never carry a tip as an argument this way. #[cfg(unix)] fn f2a_delta_scanned(log: &std::path::Path, tip: &str) -> bool { f2a_log(log) @@ -16901,7 +16908,7 @@ mod tests { /// still spawn the task (with an empty snapshot) rather than let the guard go: /// dropping it discards the pending tips with a warn. /// - /// The git shim fails the FIRST `rev-list --all` (the withheld walk's commit + /// The git shim fails the FIRST `git log --all --raw` (the withheld walk's commit /// enumeration) after signalling that the walk has started and waiting for the /// test to inject the coalescing push, then behaves normally, so the drain that /// follows is a real one. @@ -16924,7 +16931,7 @@ mod tests { "#!/bin/sh\n\ printf '%s\\n' \"$*\" >> \"{log}\"\n\ case \"$*\" in\n\ - 'rev-list --all'*)\n\ + 'log --all --raw'*)\n\ if [ ! -f \"{once}\" ]; then\n\ : > \"{once}\"\n\ : > \"{started}\"\n\ @@ -17417,14 +17424,13 @@ mod tests { /// Round-3 P1: a successful receive-pack followed by a disconnect during /// `guard.release()` must still see its replication tail run. The tail is /// spawned above `release` (gated on `receive_result.is_ok()`), and the marker - /// polls for `rev-list` (the new tail's primary walk command) — the previous - /// `for-each-ref` marker is dead because commit 91d0578 removed the last - /// tail-path use of that command (it lived in `assert_all_refs_are_commits`, - /// which is now gone). The new marker points at a real command the tail still - /// executes, so a future reorder that drops the tail will be caught. + /// polls for `log --all --raw` (the tail's primary walk command, one + /// `git log --all --raw` per `object_paths` walk). The marker points at a real + /// command the tail still executes, so a future reorder that drops the tail + /// will be caught. /// - /// Load-bearing: with the spawn below `release` the walk's `rev-list` never - /// appears after the disconnect (RED). With it above, gated on + /// Load-bearing: with the spawn below `release` the walk's `log --all --raw` + /// never appears after the disconnect (RED). With it above, gated on /// `receive_result.is_ok()`, it does (GREEN). #[cfg(unix)] #[sqlx::test] @@ -17459,14 +17465,12 @@ mod tests { // The disconnect: drop the handler future while `release` is still awaiting. drop(fut); - // Round-3 P1: marker is `rev-list`, not `for-each-ref` — the - // tail's primary walk is `git rev-list --objects --all` (the - // same call as `smart_http::rev_list_keep`); a successful - // re-key on the cloned path emits it from the post-receive - // tail. Polling for `for-each-ref` was vacuous after 91d0578 - // removed the last tail-path use of that command. + // Round-3 P1: marker is the tail's primary walk. The withheld + // walk now enumerates history with one `git log --all --raw` + // (`object_paths`), so a successful re-key on the cloned path + // emits it from the post-receive tail. let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while !p2_logged(&log, "rev-list") { + while !p2_logged(&log, "log --all --raw") { assert!( std::time::Instant::now() < deadline, "RED: the pack landed but its replication tail never ran. A disconnect \ @@ -17535,14 +17539,12 @@ mod tests { drop(fut); tokio::time::sleep(std::time::Duration::from_millis(750)).await; - // Round-3 P1: the must-not twin also runs the `rev-list` - // command (the actual tail walk). `for-each-ref` is dead in - // the tail path; the previous marker made the assertion - // vacuous. The new marker pins the same command the + // Round-3 P1: the must-not twin also runs the `log --all --raw` + // command (the actual tail walk). The marker pins the same command the // positive-control sibling above uses, so a future change // that drops the tail leaves both tests red together. assert!( - !p2_logged(&log, "rev-list"), + !p2_logged(&log, "log --all --raw"), "a failed receive-pack must spawn no replication tail: pinning and \ announcing a half-applied repo is exactly what release(false) refuses \ to upload" @@ -18292,7 +18294,7 @@ exit 0 &format!( "#!/bin/sh\n\ printf '%s\\n' \"$*\" >> \"{log}\"\n\ - case \"$*\" in 'rev-list --all'*) exit 1 ;; esac\n\ + case \"$*\" in 'log --all --raw'*) exit 1 ;; esac\n\ exec git \"$@\"\n", log = log.display(), ), @@ -18330,7 +18332,7 @@ exit 0 || { f2a_log(&log) .lines() - .any(|l| l.starts_with("rev-list --all")) + .any(|l| l.starts_with("log --all --raw")) }, "the Pinata worker's fail-closed recomputation", ) @@ -18607,14 +18609,12 @@ exit 0 // ---- #174 F2b: a failed OWN walk does not buy a pin permit and a second walk ---- /// Withheld-walk commit-enumeration attempts so far. Each `replication_withheld_set` - /// runs exactly one `rev-list --all`, so this counts the walks that were attempted - /// (the `ls-tree` counter above cannot: a walk whose enumeration fails never gets - /// to `ls-tree`). + /// runs exactly one `git log --all --raw`, so this counts the walks that were attempted. #[cfg(unix)] fn f2b_walk_attempts(log: &std::path::Path) -> usize { f2a_log(log) .lines() - .filter(|l| l.starts_with("rev-list --all")) + .filter(|l| l.starts_with("log --all --raw")) .count() } @@ -18655,7 +18655,7 @@ exit 0 &format!( "#!/bin/sh\n\ printf '%s\\n' \"$*\" >> \"{log}\"\n\ - case \"$*\" in 'rev-list --all'*) exit 1 ;; esac\n\ + case \"$*\" in 'log --all --raw'*) exit 1 ;; esac\n\ exec git \"$@\"\n", log = log.display(), ),