Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(prewarm): faithful -vv traces and a universal git-config preload (#3705)

Maximilian Roos28a7c00448a6
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
index d3c746949..5c5a20db1 100644
--- a/benches/CLAUDE.md
+++ b/benches/CLAUDE.md
@@ -426,22 +426,24 @@ show — open the Chrome Trace JSON (`wt-perf timeline --chrome`, or `wt-perf
trace` on an existing `trace.jsonl`) in <https://ui.perfetto.dev> or
chrome://tracing.
-**A traced run has no prewarm, so it is not the run users get.** At `-vv`,
-`logging::init` opens the log sinks through `log_files::try_create`, which calls
-`Repository::current()` and so resolves the git common dir. `Repository::prewarm`
-treats a populated `GIT_COMMON_DIR_CACHE` as "prewarm already ran" and returns
-without doing anything — so in every `-vv` run (and therefore every
-`wt-perf timeline`), the rev-parse batch, the `git config --list -z` preload, and
-the user-config preload never happen concurrently. Their work still gets done, one
-serial on-demand fork at a time, which is what the trace shows.
-
-The trace is still right about what ran; it is wrong about what production
-overlaps. Two consequences when reading one:
-
-- Don't conclude a phase is serial because the trace shows it serial. Read
- `prewarm` / `prewarm_rev_parse` / `prewarm_git_config` spans first: if they're
- absent, the trace is a no-prewarm run and the startup calls are ordered
- differently than in production.
+**A traced run skips prewarm's rev-parse batch, so its startup ordering is
+not quite the run users get.** At `-vv`, `logging::init` opens the log sinks
+through `log_files::try_create`, which calls `Repository::current()` and so
+resolves the git common dir in a fork the trace never sees (the subscriber
+isn't installed yet). `Repository::prewarm` gates each of its threads on the
+cache it populates: the git-config and user-config preloads still run — their
+spans appear in the trace — but the rev-parse batch is skipped because its
+product is already cached, so the per-worktree discovery (`WORKTREE_ROOTS`,
+`GIT_DIRS`, `CURRENT_BRANCHES`) happens on demand via `prewarm_info` instead
+of overlapped at startup.
+
+Three consequences when reading one:
+
+- The run's first fork (the common-dir rev-parse) is invisible — it lands in
+ the untraced gap before the first span.
+- Don't conclude the per-worktree discovery is on-demand in production because
+ the trace shows a `prewarm_info` refork mid-command; in production the
+ rev-parse batch covers it at startup.
- Don't measure a startup change by trace alone. Time the real binary
(`hyperfine` on the shipped path) and, for a fork inventory that doesn't perturb
the run, put a logging shim named `git` at the front of `PATH` — a two-line
diff --git a/benches/completion.rs b/benches/completion.rs
index 66fbfecac..113fea4b9 100644
--- a/benches/completion.rs
+++ b/benches/completion.rs
@@ -13,8 +13,8 @@
//! over a series of deliberately lopsided repos and still can't say which call
//! moved, because the calls within a wave overlap. Localizing a regression is a
//! trace's job here, exactly as it is for `full` — see "Analyzing a trace" in
-//! benches/CLAUDE.md, and note that a `-vv` run has no prewarm and so is not
-//! the run users get.
+//! benches/CLAUDE.md, and note that a `-vv` run skips prewarm's rev-parse
+//! batch and so is not quite the run users get.
//!
//! `mixed-80-80-1400` is that one repo: 80 worktrees in four states, 80 more
//! branches forked across 200 commits of history, and 1400 remote-tracking
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 177c25410..5d2530f70 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -14,16 +14,16 @@
//!
//! A steady-state run reaches the skeleton through five `git` subprocess
//! forks (six in repos with `extensions.worktreeConfig=true` — see #3
-//! below). Fork *count* is O(1) — independent of worktree or branch
-//! count — because each batches as much as it can. Fork *work* scales with
-//! N (refs read, SHAs resolved); on a fast Linux system N=40 lands
-//! ~30–80 ms.
+//! below, where the sixth runs inside prewarm). Fork *count* is O(1) —
+//! independent of worktree or branch count — because each batches as much
+//! as it can. Fork *work* scales with N (refs read, SHAs resolved); on a
+//! fast Linux system N=40 lands ~30–80 ms.
//!
//! | # | Command | Source | Role |
//! |---|---------|--------|------|
//! | 1 | `git rev-parse --git-common-dir --is-inside-work-tree --show-toplevel --git-dir --symbolic-full-name HEAD` | [`Repository::prewarm`] (`prewarm_rev_parse`) | Five facts in one fork: shared `.git`, in-worktree gate, worktree root, per-worktree `.git/worktrees/<name>`, current branch. Populates process-global caches. Parallel with #2 at process startup. |
//! | 2 | `git config --list -z` (cwd = discovery path) | [`Repository::prewarm`] (`prewarm_git_config`) | Whole merged config (system + global + local) in one shot, NUL-delimited so values containing `\n` or `=` parse unambiguously. Stashed in `GIT_CONFIG_PRELOAD` keyed by discovery path; every later `config_last("…")` reads from memory. Parallel with #1. |
-//! | 3 | `git config --list -z` (cwd = `git_common_dir`) | [`Repository::all_config`] | **Conditional.** [`Repository::at`] consumes #2's preload into `cache.all_config`, so `all_config()` is a memory hit on a normal repo. This fork only fires when `prewarm_git_config` declined the preload because `extensions.worktreeConfig=true` — there `--list` from a linked worktree misses the main-worktree `config.worktree` overrides (most importantly `core.bare = true` for the `myproject/.git + sibling worktrees` layout), so `all_config` re-forks from the common dir to see the full merged set. See `prewarm_git_config` for the full reasoning. |
+//! | 3 | `git config --list -z` (cwd = `git_common_dir`) | [`Repository::prewarm`] post-pass (`prewarm_git_config_from_common_dir`) | **Conditional.** [`Repository::at`] consumes #2's preload into `cache.all_config`, so `all_config()` is a memory hit on a normal repo. In `extensions.worktreeConfig=true` repos, #2's read is declined — `--list` from a linked worktree misses the main-worktree `config.worktree` overrides (most importantly `core.bare = true` for the `myproject/.git + sibling worktrees` layout) — and prewarm re-forks from the common dir after its threads join, preloading the full merged set. [`Repository::all_config`] forks the same command on demand only when prewarm never ran for the path (a non-base `Repository::at`, tests). See `prewarm_git_config` for the full reasoning. |
//! | 4 | `git worktree list --porcelain` | [`Repository::list_worktrees`] | Path, HEAD SHA, branch, and flags per worktree — the row source for the skeleton. The picker prelude triggers this once for `num_items_estimate`; collect's rayon scope then hits the cache. |
//! | 5 | `git for-each-ref --format=… refs/heads/` | [`Repository::local_branches`] inside collect's `rayon::scope` | Local branch tips (name, SHA, committer date, upstream) for branch-only rows (`branches=true`) and for the stale-default-branch check. `remotes=true` adds a sibling `refs/remotes/` fork. The scope joins; this fork gates the skeleton. |
//! | 6 | `git log --no-walk --no-show-signature --format=… SHA₁ … SHA_N` | collect, after the scope | Batched commit metadata for every worktree HEAD + branch tip. See breakdown below. |
diff --git a/src/completion.rs b/src/completion.rs
index c0af681f7..ad992f29a 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -27,7 +27,7 @@
//! uses; see the call site. A change to any of this is measured against
//! `benches/completion.rs`, which runs one repo big enough in every dimension
//! to make the difference visible — and *not* against a `-vv` trace, which
-//! silently disables prewarm (benches/CLAUDE.md, "Analyzing a trace").
+//! skips prewarm's rev-parse batch (benches/CLAUDE.md, "Analyzing a trace").
use std::cell::RefCell;
use std::ffi::{OsStr, OsString};
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index a985f3b69..f9e32f9a1 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -430,11 +430,13 @@ pub(super) static CURRENT_BRANCHES: LazyLock<DashMap<PathBuf, Option<String>>> =
/// discovery path passed to [`Repository::prewarm`].
///
/// Populated on the cold path by the `git config --list -z` thread spawned
-/// from [`Repository::prewarm_at`]; consumed by [`Repository::at`] when it
-/// builds a fresh `RepoCache` for that discovery path. The point is to
-/// overlap the rev-parse and config reads — the two big git invocations on
-/// the alias-dispatch critical path — so a plain `wt <alias>` pays for one
-/// git startup instead of two in series.
+/// from [`Repository::prewarm_at`] (or, when that read declines under
+/// `extensions.worktreeConfig`, by the common-dir post-pass that follows
+/// it); consumed by [`Repository::at`] when it builds a fresh `RepoCache`
+/// for that discovery path. The point is to overlap the rev-parse and
+/// config reads — the two big git invocations on the alias-dispatch
+/// critical path — so a plain `wt <alias>` pays for one git startup
+/// instead of two in series.
///
/// Best-effort, like the rest of `prewarm`. A failed read leaves the entry
/// empty and the on-demand path inside [`Repository::all_config`] re-forks
@@ -726,7 +728,10 @@ impl Repository {
/// (`WORKTRUNK_USER_CONFIG_PRELOAD`) for the configured base path.
///
/// Called once from `main` after the logger is registered, before
- /// `init_command_log` and alias dispatch. Three threads run concurrently:
+ /// `init_command_log` and alias dispatch. Three threads run concurrently,
+ /// each gated on the cache it populates (a `Repository` constructed
+ /// before prewarm fills `GIT_COMMON_DIR_CACHE` but must not suppress the
+ /// config preloads — see `prewarm_at`):
///
/// - **rev-parse thread**: a single `git rev-parse` fork that folds the
/// two cold-path rev-parses (`--git-common-dir` from
@@ -734,7 +739,9 @@ impl Repository {
/// [`Repository::project_config_path`]) into one.
/// - **git-config thread**: a single `git config --list -z` fork that the
/// bulk config map (`Repository::all_config`) would otherwise spawn
- /// on first read.
+ /// on first read. When it declines (`extensions.worktreeConfig`), a
+ /// post-pass after the threads join re-reads from the resolved
+ /// `git_common_dir` so the preload still lands.
/// - **user-config thread**: pure file I/O on `$WORKTRUNK_CONFIG_PATH` /
/// XDG paths, parsing worktrunk's user `wt.toml`. No git or
/// `Repository` involvement, so it overlaps cleanly with both git
@@ -782,16 +789,19 @@ impl Repository {
/// drive prewarm against a specific repo without mutating the global
/// `BASE_PATH` `OnceLock`.
pub(super) fn prewarm_at(discovery_path: &Path) {
- // Fast path: another caller already ran prewarm (or `Repository::at`
- // populated GIT_COMMON_DIR_CACHE via the on-demand path). Skip the
- // fork — the per-worktree maps either have what we need from a prior
- // prewarm/prewarm_info run, or `prewarm_info` will refork on first use.
- // The config preloads are gated on the same key: if the rev-parse
- // result is already cached, the git-config read either ran in a prior
- // prewarm or will be re-forked on first `all_config` access, and the
- // user-config preload either landed in a prior prewarm or
- // `Repository::user_config` will reload it on demand.
- if GIT_COMMON_DIR_CACHE.contains_key(discovery_path) {
+ // Each thread is gated on the cache it populates, not on a shared
+ // key. A `Repository` constructed before prewarm (the `-vv` log-file
+ // sinks in `log_files::init` resolve one during `logging::init`)
+ // fills `GIT_COMMON_DIR_CACHE` without touching the config preloads;
+ // gating everything on that one key would silently skip them and
+ // every later construction would re-fork `git config --list -z` —
+ // which also made `-vv` traces overstate the fork pattern of a
+ // normal run. A skipped rev-parse leaves the per-worktree maps to
+ // `prewarm_info`, which reforks on first use.
+ let need_rev_parse = !GIT_COMMON_DIR_CACHE.contains_key(discovery_path);
+ let need_git_config = !GIT_CONFIG_PRELOAD.contains_key(discovery_path);
+ let need_user_config = WORKTRUNK_USER_CONFIG_PRELOAD.get().is_none();
+ if !need_rev_parse && !need_git_config && !need_user_config {
return;
}
@@ -807,19 +817,43 @@ impl Repository {
// caches empty and the on-demand callers re-fork — same
// best-effort contract `prewarm` always had.
std::thread::scope(|s| {
- s.spawn(|| {
- let _span = crate::trace::Span::new("prewarm_rev_parse");
- Self::prewarm_rev_parse(discovery_path);
- });
- s.spawn(|| {
- let _span = crate::trace::Span::new("prewarm_git_config");
- Self::prewarm_git_config(discovery_path);
- });
- s.spawn(|| {
- let _span = crate::trace::Span::new("prewarm_user_config");
- Self::prewarm_user_config();
- });
+ if need_rev_parse {
+ s.spawn(|| {
+ let _span = crate::trace::Span::new("prewarm_rev_parse");
+ Self::prewarm_rev_parse(discovery_path);
+ });
+ }
+ if need_git_config {
+ s.spawn(|| {
+ let _span = crate::trace::Span::new("prewarm_git_config");
+ Self::prewarm_git_config(discovery_path);
+ });
+ }
+ if need_user_config {
+ s.spawn(|| {
+ let _span = crate::trace::Span::new("prewarm_user_config");
+ Self::prewarm_user_config();
+ });
+ }
});
+
+ // `prewarm_git_config` declines the preload under
+ // `extensions.worktreeConfig` because its discovery-path read misses
+ // the main worktree's `config.worktree` overrides ([#2779]). Now that
+ // the rev-parse thread has landed the common dir, run the read
+ // [`Repository::all_config`] would otherwise fork on first access —
+ // `git config --list -z` from `git_common_dir` — and preload that
+ // merged map, so those repos get the same memory-hit constructions
+ // as everyone else. One serialized fork here replaces the on-demand
+ // one; a repo whose rev-parse failed (not a repo at all) skips this.
+ if !GIT_CONFIG_PRELOAD.contains_key(discovery_path)
+ && let Some(common_dir) = GIT_COMMON_DIR_CACHE
+ .get(discovery_path)
+ .map(|entry| entry.value().clone())
+ {
+ let _span = crate::trace::Span::new("prewarm_git_config_common_dir");
+ Self::prewarm_git_config_from_common_dir(discovery_path, &common_dir);
+ }
}
/// Rev-parse half of [`Self::prewarm_at`] — populates
@@ -943,11 +977,11 @@ impl Repository {
/// bare-style `myproject/.git + sibling worktrees` layout. Caching that
/// incomplete map would cause `is_bare()` to read `false`, and the
/// `repo_path()` fallback would walk one level too high. So when the
- /// parsed map contains `extensions.worktreeconfig=true`, we skip the
- /// preload entirely — [`Repository::all_config`] re-forks from
- /// `git_common_dir`, which sees the full merged set (one extra
- /// subprocess in this layout; the prewarm benefit is preserved for all
- /// other repos).
+ /// parsed map contains `extensions.worktreeconfig=true`, we decline the
+ /// preload here; the post-pass in [`Repository::prewarm_at`] re-reads
+ /// from `git_common_dir` — which sees the full merged set — via
+ /// [`Repository::prewarm_git_config_from_common_dir`] once the
+ /// rev-parse thread has resolved it.
///
/// Failures (non-repo directory, corrupted config) are swallowed; the
/// on-demand path inside `all_config` re-forks the same subprocess and
@@ -973,6 +1007,34 @@ impl Repository {
GIT_CONFIG_PRELOAD.insert(discovery_path.to_path_buf(), parsed);
}
+ /// Fallback half of the git-config preload: `git config --list -z` run
+ /// from `git_common_dir` — byte-for-byte the invocation
+ /// [`Repository::all_config`] forks on first access — parsed and stashed
+ /// under `discovery_path` for [`Repository::at`] to consume. Called from
+ /// the [`Repository::prewarm_at`] post-pass when
+ /// [`Repository::prewarm_git_config`] declined (the
+ /// `extensions.worktreeConfig` case, or a failed discovery-path read in
+ /// a repo the rev-parse thread still resolved). The common-dir read is
+ /// safe to cache in both cases because it produces exactly the map the
+ /// on-demand path would at this moment — like every preload it is a
+ /// startup snapshot, never invalidated by later `set_config` writes
+ /// (which update only the writing instance's `cache.all_config`).
+ fn prewarm_git_config_from_common_dir(discovery_path: &Path, common_dir: &Path) {
+ let Ok(output) = Cmd::new("git")
+ .args(["config", "--list", "-z"])
+ .current_dir(common_dir)
+ .context(path_to_logging_context(common_dir))
+ .run()
+ else {
+ return;
+ };
+ if !output.status.success() {
+ return;
+ }
+ let parsed = parse_config_list_z(&output.stdout);
+ GIT_CONFIG_PRELOAD.insert(discovery_path.to_path_buf(), parsed);
+ }
+
/// User-config half of [`Self::prewarm_at`] — loads worktrunk's user
/// `wt.toml` (and system + env-var layers) and stashes the result in
/// [`WORKTRUNK_USER_CONFIG_PRELOAD`] for [`Repository::at`] to clone
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 584879bf0..63e233e81 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -541,8 +541,10 @@ fn parse_git_bool_variants() {
fn worktree_config_enabled_detects_extension() {
// The detector keys on the lowercased canonical form that git emits in
// `--list -z` output. Both git-bool truthy spellings and the absent/
- // explicitly-false cases must classify correctly — getting either wrong
- // breaks the prewarm-skip in `prewarm_git_config` (see issue #2779).
+ // explicitly-false cases must classify correctly. A false truthy costs
+ // one extra prewarm fork (the common-dir post-pass caches the same map);
+ // a false falsy caches the incomplete linked-worktree map and
+ // reintroduces the #2779 `is_bare=false` bug.
use indexmap::IndexMap;
let mut empty: IndexMap<String, Vec<String>> = IndexMap::new();
@@ -1101,9 +1103,9 @@ fn prewarm_from_linked_worktree_under_worktree_config_preserves_is_bare() {
// `all_config()` with the stale value, and `is_bare()` returned
// `false` from the linked worktree.
//
- // After the fix, the prewarm detects `extensions.worktreeconfig=true`
- // and skips the preload — `all_config()` re-forks from
- // `git_common_dir`, which sees the merged set.
+ // The prewarm detects `extensions.worktreeconfig=true`, declines the
+ // discovery-path map, and preloads the `git_common_dir` read instead —
+ // the merged set `all_config()` would fork for on demand.
use super::Repository;
let (_tmp, _project, _main, linked) = build_worktree_config_bare_layout();
@@ -1139,28 +1141,145 @@ fn repo_path_from_linked_worktree_under_worktree_config_is_git_common_dir() {
}
#[test]
-fn prewarm_skips_preload_when_worktree_config_enabled() {
- // Direct test of the prewarm skip: with the extension on, the preload
- // map for the linked worktree must stay empty so `all_config()`
- // re-forks from `git_common_dir` instead of consuming a stale map.
+fn prewarm_partial_warm_runs_only_the_cold_threads() {
+ // The gates are per-cache: with the git-config preload already present
+ // (and the process-wide user-config preload latched) but no resolved
+ // common dir, prewarm still runs the rev-parse thread, and neither the
+ // config thread nor the post-pass touches the existing preload.
+ use super::canonicalize;
+ use crate::shell_exec::Cmd;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let init_repo = |name: &str| {
+ let root = canonicalize(tmp.path()).unwrap().join(name);
+ std::fs::create_dir_all(&root).unwrap();
+ let out = crate::testing::configure_git_env(Cmd::new("git"))
+ .args(["init", "-b", "main", root.to_str().unwrap()])
+ .run()
+ .unwrap();
+ assert!(out.status.success(), "git init failed");
+ root
+ };
+
+ // A full prewarm on one repo latches the process-wide user-config
+ // preload (OnceLock), whichever test runs first.
+ super::Repository::prewarm_at(&init_repo("first"));
+ assert!(super::WORKTRUNK_USER_CONFIG_PRELOAD.get().is_some());
+
+ // Second repo: hand-populate the config preload, then prewarm. Only
+ // the rev-parse cache is cold.
+ let second = init_repo("second");
+ let sentinel: indexmap::IndexMap<String, Vec<String>> =
+ [("wt.sentinel".to_string(), vec!["1".to_string()])]
+ .into_iter()
+ .collect();
+ super::GIT_CONFIG_PRELOAD.insert(second.clone(), sentinel);
+
+ super::Repository::prewarm_at(&second);
+
+ assert!(
+ super::GIT_COMMON_DIR_CACHE.contains_key(&second),
+ "rev-parse thread must run when only its cache is cold"
+ );
+ let sentinel_value = |path: &std::path::Path| {
+ super::GIT_CONFIG_PRELOAD
+ .get(path)
+ .and_then(|e| e.value().get("wt.sentinel").and_then(|v| v.last()).cloned())
+ };
+ assert_eq!(
+ sentinel_value(&second),
+ Some("1".to_string()),
+ "an existing preload must not be re-read or overwritten"
+ );
+
+ // Fully warm: every gate is satisfied, so a repeat call early-returns
+ // without spawning anything or touching the preload.
+ super::Repository::prewarm_at(&second);
+ assert_eq!(sentinel_value(&second), Some("1".to_string()));
+}
+
+#[test]
+fn prewarm_post_pass_swallows_common_dir_read_failures() {
+ // Best-effort contract: when the declined preload's common-dir re-read
+ // fails — the directory is gone, or its config is corrupt — the post-pass
+ // leaves the preload empty and the on-demand `all_config()` surfaces the
+ // error. The rev-parse thread is skipped (its cache is hand-populated),
+ // so the bogus common-dir entries survive to the post-pass.
let (_tmp, _project, _main, linked) = build_worktree_config_bare_layout();
+ // Spawn failure: the cached common dir does not exist.
+ let missing = linked.join("no-such-dir");
+ super::GIT_COMMON_DIR_CACHE.insert(linked.clone(), missing);
super::Repository::prewarm_at(&linked);
assert!(
super::GIT_CONFIG_PRELOAD.get(&linked).is_none(),
- "prewarm must skip GIT_CONFIG_PRELOAD when extensions.worktreeConfig=true"
+ "a failed spawn must not populate the preload"
+ );
+
+ // Non-zero exit: the cached common dir is a git dir with corrupt config.
+ let (_tmp2, project2, _main2, linked2) = build_worktree_config_bare_layout();
+ let corrupt = project2.join("corrupt.git");
+ let out = crate::testing::configure_git_env(crate::shell_exec::Cmd::new("git"))
+ .args(["init", "--bare", corrupt.to_str().unwrap()])
+ .run()
+ .unwrap();
+ assert!(out.status.success(), "git init --bare failed");
+ std::fs::write(corrupt.join("config"), "[core\ngarbage").unwrap();
+ super::GIT_COMMON_DIR_CACHE.insert(linked2.clone(), corrupt);
+ super::Repository::prewarm_at(&linked2);
+ assert!(
+ super::GIT_CONFIG_PRELOAD.get(&linked2).is_none(),
+ "a non-zero config read must not populate the preload"
+ );
+}
+
+#[test]
+fn all_config_without_prewarm_reads_common_dir_under_worktree_config() {
+ // The on-demand branch: a `Repository::at` with no prewarm (a non-base
+ // discovery path in production) gets no preload, so `all_config()` forks
+ // — and it must fork from `git_common_dir`, not the discovery path, or
+ // the linked worktree's partial config map reintroduces the #2779
+ // `is_bare=false` bug. The prewarm post-pass caches the same read, so
+ // only this prewarm-less construction still exercises the fork.
+ use super::Repository;
+
+ let (_tmp, _project, _main, linked) = build_worktree_config_bare_layout();
+
+ let repo = Repository::at(&linked).unwrap();
+ assert!(
+ super::GIT_CONFIG_PRELOAD.get(&linked).is_none(),
+ "test setup: no preload may exist for this path"
+ );
+ assert!(
+ repo.is_bare().unwrap(),
+ "on-demand all_config must read core.bare=true from the common dir"
+ );
+}
+
+#[test]
+fn prewarm_preload_under_worktree_config_holds_common_dir_map() {
+ // With the extension on, the discovery-path read is declined (it misses
+ // the main worktree's `config.worktree`) and the post-pass re-reads from
+ // `git_common_dir`. The preload must land, and it must be the merged
+ // common-dir map — `core.bare = true` from `.git/config.worktree` is the
+ // #2779 poison pin: the declined linked-worktree read would say `false`.
+ let (_tmp, _project, _main, linked) = build_worktree_config_bare_layout();
+
+ super::Repository::prewarm_at(&linked);
+ let entry = super::GIT_CONFIG_PRELOAD
+ .get(&linked)
+ .expect("prewarm must preload the common-dir map under extensions.worktreeConfig");
+ assert_eq!(
+ entry.value().get("core.bare").and_then(|v| v.last()),
+ Some(&"true".to_string()),
+ "the preload must hold the merged common-dir map, not the linked worktree's partial one"
);
}
#[test]
fn prewarm_still_caches_preload_when_worktree_config_disabled() {
- // The skip is targeted: normal repos (no worktreeConfig extension)
- // still benefit from the prewarm preload. This guards against
- // regressing the optimization for the common case while fixing #2779.
- //
- // Build a fresh repo directly (bypass `TestRepo`, whose constructor
- // calls `Repository::at` and populates `GIT_COMMON_DIR_CACHE` — that
- // short-circuits `prewarm_at` before it can run the config preload).
+ // The #2779 decline is targeted: normal repos (no worktreeConfig
+ // extension) get the preload from the discovery-path read alone.
use super::canonicalize;
use crate::shell_exec::Cmd;
@@ -1181,6 +1300,42 @@ fn prewarm_still_caches_preload_when_worktree_config_disabled() {
);
}
+#[test]
+fn prewarm_after_early_repository_still_preloads_config() {
+ // A `Repository` constructed before prewarm — the `-vv` log-file sinks
+ // in `log_files::init` do this during `logging::init` — populates
+ // `GIT_COMMON_DIR_CACHE` on its own. Prewarm used to fast-path on that
+ // one key and silently skip the config preloads, so every `-vv` run
+ // lost them and its trace overstated the `git config --list -z` forks
+ // of a normal run. Each prewarm thread now gates on the cache it
+ // populates: the config preload must land even when the common dir is
+ // already resolved.
+ use super::canonicalize;
+ use crate::shell_exec::Cmd;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let root = canonicalize(tmp.path()).unwrap().join("early");
+ std::fs::create_dir_all(&root).unwrap();
+
+ let out = crate::testing::configure_git_env(Cmd::new("git"))
+ .args(["init", "-b", "main", root.to_str().unwrap()])
+ .run()
+ .unwrap();
+ assert!(out.status.success(), "git init failed");
+
+ super::Repository::at(&root).unwrap();
+ assert!(
+ super::GIT_COMMON_DIR_CACHE.contains_key(&root),
+ "Repository::at should have resolved the common dir"
+ );
+
+ super::Repository::prewarm_at(&root);
+ assert!(
+ super::GIT_CONFIG_PRELOAD.get(&root).is_some(),
+ "prewarm must still preload git config when GIT_COMMON_DIR_CACHE was populated first"
+ );
+}
+
/// A worktree answers to its branch and to its own path, and the branch wins.
///
/// Both spellings reaching the same worktree is the point of routing every