Skip to content
Open
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
16 changes: 4 additions & 12 deletions src/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::git::cli_parser::{
ParsedGitInvocation, explicit_rebase_branch_arg, parse_git_cli_args, summarize_rebase_args,
};
use crate::git::find_repository_in_path;
use crate::git::repo_state::{common_dir_for_worktree, worktree_root_for_path};
use crate::git::repo_state::{canonical_family_key_for_worktree, worktree_root_for_path};
use crate::git::repository::{Repository, discover_repository_in_path_no_git_exec, exec_git};
use crate::git::sync_authorship::{fetch_authorship_notes, fetch_remote_from_args};
use crate::utils::LockFile;
Expand Down Expand Up @@ -2397,17 +2397,12 @@ impl ActorDaemonCoordinator {
let Some(worktree) = trace_payload_worktree_hint(payload) else {
return Ok(());
};
let Some(common_dir) = common_dir_for_worktree(&worktree) else {
let Some(family) = canonical_family_key_for_worktree(&worktree) else {
return Ok(());
};
let started_at_ns = trace_payload_root_started_at_ns(payload)
.or_else(|| trace_payload_time_ns(payload))
.unwrap_or_else(now_unix_nanos);
let family = common_dir
.canonicalize()
.unwrap_or(common_dir)
.to_string_lossy()
.to_string();
self.append_pending_root_entry(&family, root_sid, started_at_ns)
}

Expand Down Expand Up @@ -3193,11 +3188,8 @@ impl ActorDaemonCoordinator {
}

if let Some(worktree) = worktree_hint.clone() {
if let Some(common_dir) = common_dir_for_worktree(&worktree) {
let family = common_dir.canonicalize().unwrap_or(common_dir);
ingress
.root_families
.insert(root.clone(), family.to_string_lossy().to_string());
if let Some(family) = canonical_family_key_for_worktree(&worktree) {
ingress.root_families.insert(root.clone(), family);
}
ingress.root_worktrees.insert(root.clone(), worktree);
}
Expand Down
21 changes: 3 additions & 18 deletions src/daemon/trace_normalizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::daemon::git_backend::GitBackend;
use crate::error::GitAiError;
use crate::git::cli_parser::parse_git_cli_args;
use crate::git::repo_state::{
common_dir_for_repo_path, common_dir_for_worktree, worktree_root_for_path,
canonical_family_key_for_worktree, common_dir_for_repo_path, worktree_root_for_path,
};
use crate::observability;
use serde_json::Value;
Expand Down Expand Up @@ -277,14 +277,7 @@ impl<B: GitBackend> TraceNormalizer<B> {
.or_else(|| self.state.sid_to_worktree.get(root_sid).cloned());

let family_key = if let Some(worktree) = worktree.as_deref() {
if let Some(common_dir) = common_dir_for_worktree(worktree) {
let family = FamilyKey::new(
common_dir
.canonicalize()
.unwrap_or(common_dir)
.to_string_lossy()
.to_string(),
);
if let Some(family) = canonical_family_key_for_worktree(worktree).map(FamilyKey::new) {
self.state
.sid_to_family
.insert(root_sid.to_string(), family.clone());
Expand Down Expand Up @@ -577,15 +570,7 @@ impl<B: GitBackend> TraceNormalizer<B> {
if pending.family_key.is_none()
&& let Some(worktree) = pending.worktree.as_deref()
{
pending.family_key = common_dir_for_worktree(worktree).map(|common_dir| {
FamilyKey::new(
common_dir
.canonicalize()
.unwrap_or(common_dir)
.to_string_lossy()
.to_string(),
)
});
pending.family_key = canonical_family_key_for_worktree(worktree).map(FamilyKey::new);
}

let mut primary_command = self.resolve_primary_hint(
Expand Down
93 changes: 93 additions & 0 deletions src/git/repo_state.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,60 @@
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

pub fn is_valid_git_oid(value: &str) -> bool {
matches!(value.len(), 40 | 64) && value.chars().all(|c| c.is_ascii_hexdigit())
}

/// Upper bound on memoized worktree→family-key entries. A daemon session
/// touches a handful of repos, so this is never hit in practice; it only
/// guards against unbounded growth in a very long-lived daemon spanning
/// thousands of distinct worktrees. On overflow we clear and rebuild rather
/// than evict per-entry — the set is tiny, so a coarse reset is cheapest.
const FAMILY_KEY_CACHE_LIMIT: usize = 4096;

fn family_key_cache() -> &'static Mutex<HashMap<PathBuf, String>> {
static CACHE: OnceLock<Mutex<HashMap<PathBuf, String>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Resolve a worktree path to its canonical family key (the canonicalized
/// common dir, as a string), memoizing the result.
///
/// `common_dir_for_worktree` walks parent dirs stat-ing for `.git` (and reads
/// the `.git` file for linked worktrees), and `canonicalize` issues a
/// stat/readlink per path component. This runs per mutating command on the
/// trace-ingestion path, where the same worktree recurs constantly, so the
/// uncached cost is pure repeated syscalls. The mapping is a stable function
/// of the on-disk repo layout for a live worktree, so caching it is safe.
///
/// Only successful resolutions are cached: a path that is not yet a repository
/// (before `clone`/`init` completes) returns `None` and is re-resolved on the
/// next call, so a repo that appears later is still picked up.
pub fn canonical_family_key_for_worktree(worktree: &Path) -> Option<String> {
if let Ok(cache) = family_key_cache().lock()
&& let Some(key) = cache.get(worktree)
{
return Some(key.clone());
}

let common_dir = common_dir_for_worktree(worktree)?;
let key = common_dir
.canonicalize()
.unwrap_or(common_dir)
.to_string_lossy()
.to_string();

if let Ok(mut cache) = family_key_cache().lock() {
if cache.len() >= FAMILY_KEY_CACHE_LIMIT {
cache.clear();
}
cache.insert(worktree.to_path_buf(), key.clone());
}
Some(key)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadState {
pub head: Option<String>,
Expand Down Expand Up @@ -143,4 +193,47 @@ mod tests {
assert_eq!(state.branch.as_deref(), Some("main"));
assert!(!state.detached);
}

#[test]
fn canonical_family_key_matches_uncached_computation_and_is_stable() {
let temp = tempfile::tempdir().unwrap();
let worktree = temp.path();
write_file(&worktree.join(".git/HEAD"), "ref: refs/heads/main\n");

// The memoized helper must equal the original uncached derivation:
// common_dir_for_worktree → canonicalize → string.
let common_dir = common_dir_for_worktree(worktree).unwrap();
let expected = common_dir
.canonicalize()
.unwrap_or(common_dir)
.to_string_lossy()
.to_string();

let first = canonical_family_key_for_worktree(worktree).unwrap();
assert_eq!(first, expected);
// A second call (served from cache) must return the identical value.
let second = canonical_family_key_for_worktree(worktree).unwrap();
assert_eq!(second, expected);
}

#[test]
fn canonical_family_key_does_not_cache_misses() {
// A path that is not yet a repository must return None AND must not be
// cached, so that once it becomes a repo (e.g. after clone/init) the
// next call resolves correctly rather than returning a stale miss.
let temp = tempfile::tempdir().unwrap();
let worktree = temp.path().join("not-a-repo-yet");
fs::create_dir_all(&worktree).unwrap();

assert!(canonical_family_key_for_worktree(&worktree).is_none());

// The repo now appears at this path.
write_file(&worktree.join(".git/HEAD"), "ref: refs/heads/main\n");

let resolved = canonical_family_key_for_worktree(&worktree);
assert!(
resolved.is_some(),
"a worktree that becomes a repo after a miss must resolve on the next call"
);
}
}
Loading