Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf: cache resolve_preferring_branch to eliminate redundant ref verification (#1948)
Maximilian Roos4e14483b929a
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex 62245afa9..9903d1fe9 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -31,15 +31,21 @@ impl Repository {/// qualified form to ensure we reference the branch, not a same-named tag./// Otherwise returns the original ref unchanged (for HEAD, SHAs, remote refs).fn resolve_preferring_branch(&self, r: &str) -> String {- let qualified = format!("refs/heads/{r}");- if self- .run_command(&["rev-parse", "--verify", "-q", &qualified])- .is_ok()- {- qualified- } else {- r.to_string()- }+ self.cache+ .resolved_refs+ .entry(r.to_string())+ .or_insert_with(|| {+ let qualified = format!("refs/heads/{r}");+ if self+ .run_command(&["rev-parse", "--verify", "-q", &qualified])+ .is_ok()+ {+ qualified+ } else {+ r.to_string()+ }+ })+ .clone()}/// Check if base is an ancestor of head (i.e., would be a fast-forward).diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 0353e6aa7..4365880f7 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -153,6 +153,9 @@ pub(super) struct RepoCache {/// Effective remote URLs: remote_name -> effective URL (with `url.insteadOf` applied)./// Cached because forge detection may query the same remote multiple times.pub(super) effective_remote_urls: DashMap<String, Option<String>>,+ /// Resolved refs: unresolved ref (e.g., "main") -> resolved form (e.g., "refs/heads/main")+ /// or original if not a local branch. Populated by `resolve_preferring_branch()`.+ pub(super) resolved_refs: DashMap<String, String>,// ========== Per-worktree values (keyed by path) ==========/// Worktree root paths: worktree_path -> canonicalized rootdiff --git a/tests/helpers/wt-perf/src/main.rs b/tests/helpers/wt-perf/src/main.rsindex ebf1cbc0d..f388992a9 100644--- a/tests/helpers/wt-perf/src/main.rs+++ b/tests/helpers/wt-perf/src/main.rs@@ -71,6 +71,24 @@ enum Commands {/// Path to trace log file (reads from stdin if omitted)file: Option<PathBuf>,},++ /// Analyze trace logs for duplicate commands (cache effectiveness)+ #[command(after_long_help = r#"EXAMPLES:+ # Check cache effectiveness for wt list+ RUST_LOG=debug wt list 2>&1 | grep wt-trace | wt-perf cache-check++ # From a file+ wt-perf cache-check trace.log++ # With a benchmark repo+ cargo run -p wt-perf -- setup typical-8 --persist+ RUST_LOG=debug wt -C /tmp/wt-perf-typical-8 list 2>&1 | \+ grep wt-trace | cargo run -p wt-perf -- cache-check+"#)]+ CacheCheck {+ /// Path to trace log file (reads from stdin if omitted)+ file: Option<PathBuf>,+ },}fn main() {@@ -174,49 +192,163 @@ fn main() {}Commands::Trace { file } => {- let input = match file {- Some(path) if path.as_os_str() != "-" => match std::fs::read_to_string(&path) {- Ok(content) => content,- Err(e) => {- eprintln!("Error reading {}: {}", path.display(), e);- std::process::exit(1);- }- },- _ => {- if std::io::stdin().is_terminal() {- eprintln!("Reading from stdin... (pipe trace data or use Ctrl+D to end)");- eprintln!();- eprintln!(- "Hint: RUST_LOG=debug wt list 2>&1 | grep wt-trace | wt-perf trace"- );- }-- let mut content = String::new();- std::io::stdin()- .lock()- .read_to_string(&mut content)- .expect("Failed to read stdin");- content- }- };+ let entries = read_trace_entries(file.as_deref());+ println!("{}", worktrunk::trace::to_chrome_trace(&entries));+ }- let entries = worktrunk::trace::parse_lines(&input);+ Commands::CacheCheck { file } => {+ let entries = read_trace_entries(file.as_deref());+ cache_check(&entries);+ }+ }+}- if entries.is_empty() {- eprintln!("No trace entries found in input.");- eprintln!();- eprintln!("Trace lines should look like:");+/// Read trace input from file or stdin, parse entries, and exit if empty.+fn read_trace_entries(file: Option<&std::path::Path>) -> Vec<worktrunk::trace::TraceEntry> {+ let input = match file {+ Some(path) if path.as_os_str() != "-" => match std::fs::read_to_string(path) {+ Ok(content) => content,+ Err(e) => {+ eprintln!("Error reading {}: {}", path.display(), e);+ std::process::exit(1);+ }+ },+ _ => {+ if std::io::stdin().is_terminal() {eprintln!(- " [wt-trace] ts=1234567890 tid=3 cmd=\"git status\" dur_us=12300 ok=true"+ "\+Reading from stdin... (pipe trace data or use Ctrl+D to end)++Hint: RUST_LOG=debug wt list 2>&1 | grep wt-trace | wt-perf <subcommand>");- eprintln!(" [wt-trace] ts=1234567890 tid=3 event=\"Showed skeleton\"");- eprintln!();- eprintln!("To capture traces, run with RUST_LOG=debug:");- eprintln!(" RUST_LOG=debug wt list 2>&1 | grep wt-trace | wt-perf trace");- std::process::exit(1);}- println!("{}", worktrunk::trace::to_chrome_trace(&entries));+ let mut content = String::new();+ std::io::stdin()+ .lock()+ .read_to_string(&mut content)+ .expect("Failed to read stdin");+ content}+ };++ let entries = worktrunk::trace::parse_lines(&input);++ if entries.is_empty() {+ eprintln!(+ "\+No trace entries found in input.++Trace lines should look like:+ [wt-trace] ts=1234567890 tid=3 cmd=\"git status\" dur_us=12300 ok=true+ [wt-trace] ts=1234567890 tid=3 event=\"Showed skeleton\"++To capture traces, run with RUST_LOG=debug:+ RUST_LOG=debug wt list 2>&1 | grep wt-trace | wt-perf <subcommand>"+ );+ std::process::exit(1);}++ entries+}++/// Truncate a string for display, respecting UTF-8 char boundaries.+fn truncate(s: &str, max: usize) -> String {+ if s.len() <= max {+ s.to_string()+ } else {+ let mut boundary = max - 3;+ while !s.is_char_boundary(boundary) {+ boundary -= 1;+ }+ format!("{}...", &s[..boundary])+ }+}++/// Analyze trace entries for cache effectiveness and report findings.+///+/// Two analyses:+/// 1. Same-context duplicates — commands that ran multiple times for the+/// same worktree, indicating missing or bypassed caches+/// 2. Summary — total commands, unique commands, duplicate counts+fn cache_check(entries: &[worktrunk::trace::TraceEntry]) {+ use std::collections::{BTreeMap, HashMap, HashSet};+ use worktrunk::trace::TraceEntryKind;++ let mut total_commands = 0;+ let mut cmd_counts: HashMap<&str, usize> = HashMap::new();+ let mut pair_counts: HashMap<(&str, &str), usize> = HashMap::new();+ let mut contexts: HashSet<&str> = HashSet::new();++ for entry in entries {+ if let TraceEntryKind::Command { command, .. } = &entry.kind {+ let ctx = entry.context.as_deref().unwrap_or("(none)");+ *cmd_counts.entry(command.as_str()).or_insert(0) += 1;+ *pair_counts.entry((command.as_str(), ctx)).or_insert(0) += 1;+ contexts.insert(ctx);+ total_commands += 1;+ }+ }++ // === Same-context duplicates ===+ let mut cmd_ctx_info: BTreeMap<&str, Vec<(&str, usize)>> = BTreeMap::new();+ for ((cmd, ctx), count) in &pair_counts {+ if *count > 1 {+ cmd_ctx_info.entry(cmd).or_default().push((ctx, *count));+ }+ }++ if !cmd_ctx_info.is_empty() {+ println!(+ "\+=== Same-context duplicates (potential cache misses) ===++Commands that ran multiple times for the SAME worktree.+These are the strongest signal of missing/bypassed caches.+"+ );++ let mut sorted: Vec<_> = cmd_ctx_info.iter().collect();+ sorted.sort_by(|a, b| {+ let max_a = a.1.iter().map(|(_, c)| c).max().unwrap();+ let max_b = b.1.iter().map(|(_, c)| c).max().unwrap();+ max_b.cmp(max_a)+ });++ let mut total_wasted = 0usize;+ for (cmd, ctx_list) in &sorted {+ let max_count = ctx_list.iter().map(|(_, c)| c).max().unwrap();+ let extra: usize = ctx_list.iter().map(|(_, c)| c - 1).sum();+ total_wasted += extra;+ println!(+ " {} (max {}x/context, {} extra calls)",+ truncate(cmd, 70),+ max_count,+ extra+ );+ let mut sorted_ctx: Vec<_> = ctx_list.to_vec();+ sorted_ctx.sort_by(|a, b| b.1.cmp(&a.1));+ for (ctx, count) in sorted_ctx.iter().take(3) {+ println!(" {}x in [{}]", count, ctx);+ }+ if sorted_ctx.len() > 3 {+ println!(" ... and {} more contexts", sorted_ctx.len() - 3);+ }+ }+ println!();+ println!(" Total extra calls from same-context duplicates: {total_wasted}");+ }++ // === Summary ===+ let dup_count: usize = cmd_counts.values().filter(|c| **c > 1).count();+ let dup_total: usize = cmd_counts.values().filter(|c| **c > 1).map(|c| c - 1).sum();+ println!(+ "\+\n=== Summary ===++ {total_commands} commands total, {} unique, {} contexts+ {dup_count} commands ran more than once ({dup_total} extra calls)",+ cmd_counts.len(),+ contexts.len()+ );}