Skip to main content

aft/
root_cache.rs

1//! These files coordinate safe access to a project-root cache: a writer lease
2//! ensures only one process updates the cache at a time, and read-marker files
3//! let cleanup see which readers are still using the cache.
4//!
5//! Writer leases are stored at `<storage>/callgraph/<artifact_cache_key>/writer.lease`
6//! and `<storage>/inspect/<project_scope_key>/writer.lease`. They use the
7//! `fs_lock` JSON format with a `writer_epoch` nonce so a writer can detect if
8//! another process has taken over before publishing changes or starting SQLite
9//! write transactions.
10//!
11//! Read markers track active SQLite readers so cache cleanup can tell when it is
12//! safe to remove old data. They are stored under
13//! `<cache-domain>/readers/<generation-label>/<pid>.<hostname>.<created_at_ms>.<seq>.json`;
14//! the JSON records the process identity and creation time, mtime is used as a
15//! heartbeat for cleanup across hosts, and the PID is used for cleanup on the
16//! same host. Marker files are created `0600` so they do not expose checkout
17//! activity or let another local user delete a protected marker.
18
19use std::collections::{HashMap, HashSet};
20use std::ffi::OsStr;
21use std::fs::{self, File, OpenOptions};
22use std::io::{self, Write};
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
25use std::sync::{Arc, Mutex, OnceLock, Weak};
26use std::time::{Duration, SystemTime, UNIX_EPOCH};
27
28use serde::{Deserialize, Serialize};
29
30use crate::fs_lock;
31
32static MARKER_SEQ: AtomicU64 = AtomicU64::new(0);
33static LIVE_SCOPE_KEYS: OnceLock<Mutex<HashMap<(PathBuf, String), usize>>> = OnceLock::new();
34
35/// Read-marker heartbeats refresh no more often than the filesystem lock
36/// heartbeat. Active readers piggyback this on normal read paths instead of
37/// spawning a thread per connection.
38pub const READ_MARKER_TOUCH_INTERVAL_MS: u64 = fs_lock::HEARTBEAT_INTERVAL_MS;
39/// Cross-host markers cannot use local PID liveness, so they expire after the
40/// same conservative 5x stale-heartbeat window used by filesystem locks.
41pub const READ_MARKER_CROSS_HOST_STALE_MS: u64 = fs_lock::STALE_HEARTBEAT_MS * 5;
42// Process start timestamps are not always millisecond-precise across OS APIs.
43// A one-second grace keeps a marker created immediately after process launch
44// attached to that process while still identifying clear PID reuse.
45const PROCESS_START_TIME_GRACE_MS: u64 = 1_000;
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub enum RootCacheDomain {
49    Callgraph,
50    Inspect,
51}
52
53impl RootCacheDomain {
54    pub fn as_str(self) -> &'static str {
55        match self {
56            RootCacheDomain::Callgraph => "callgraph",
57            RootCacheDomain::Inspect => "inspect",
58        }
59    }
60}
61
62/// Serializes artifact supersession with the final disk publication step.
63/// Advancing an epoch either happens before a stale worker checks and prevents
64/// its publish, or after that worker has fully published the still-current
65/// generation. This closes the check-then-publish race of a bare atomic epoch.
66#[derive(Clone, Default)]
67pub struct ArtifactPublishEpoch {
68    current: Arc<parking_lot::Mutex<u64>>,
69}
70
71impl ArtifactPublishEpoch {
72    pub fn next(&self) -> u64 {
73        let mut current = self.current.lock();
74        *current = current.wrapping_add(1);
75        *current
76    }
77
78    pub fn current(&self) -> u64 {
79        *self.current.lock()
80    }
81
82    pub fn run_if_current<R>(&self, expected: u64, publish: impl FnOnce() -> R) -> Option<R> {
83        let current = self.current.lock();
84        if *current != expected {
85            return None;
86        }
87        Some(publish())
88    }
89}
90
91pub struct WriterLease {
92    domain: RootCacheDomain,
93    key: String,
94    path: PathBuf,
95    epoch: String,
96    guard: Mutex<fs_lock::LockGuard>,
97}
98
99#[derive(Clone, Debug, Eq, Hash, PartialEq)]
100struct ProcessLeaseKey {
101    domain: RootCacheDomain,
102    cache_dir: PathBuf,
103}
104
105#[derive(Clone, Debug, Eq, Hash, PartialEq)]
106struct WriterLeaseAcquisitionKey {
107    domain: RootCacheDomain,
108    key: String,
109    project_root: PathBuf,
110}
111
112static PROCESS_LEASES: OnceLock<Mutex<HashMap<ProcessLeaseKey, Weak<WriterLease>>>> =
113    OnceLock::new();
114// Same-root callers share this short-lived gate so only one thread performs the
115// filesystem lease attempt, while different roots do not wait on the registry
116// mutex during stat/probe/create/heartbeat work.
117static PROCESS_LEASE_ACQUISITIONS: OnceLock<Mutex<HashMap<ProcessLeaseKey, Weak<Mutex<()>>>>> =
118    OnceLock::new();
119static WRITER_LEASE_ACQUISITION_COUNTS: OnceLock<Mutex<HashMap<WriterLeaseAcquisitionKey, usize>>> =
120    OnceLock::new();
121static WRITER_LEASE_ACQUISITION_COUNTER_ENABLED: AtomicBool = AtomicBool::new(false);
122static CONFIGURED_ARTIFACT_ACCESS: OnceLock<Mutex<HashMap<PathBuf, ArtifactAccess>>> =
123    OnceLock::new();
124static WARNED_BORROW_ONLY_WRITES: OnceLock<Mutex<HashSet<(PathBuf, PathBuf)>>> = OnceLock::new();
125
126/// Root-scoped capability that distinguishes shared repository artifacts from
127/// mutable state private to one checkout.
128#[derive(Clone, Debug)]
129pub struct ArtifactAccess {
130    project_root: PathBuf,
131    shared_key: String,
132    private_key: String,
133    borrow_only_shared: bool,
134    registered: bool,
135}
136
137impl ArtifactAccess {
138    fn configured(project_root: &Path, shared_key: &str, borrow_only_shared: bool) -> Self {
139        let project_root = canonical_root(project_root);
140        Self {
141            private_key: crate::path_identity::project_scope_key(&project_root),
142            project_root,
143            shared_key: shared_key.to_string(),
144            borrow_only_shared,
145            registered: true,
146        }
147    }
148
149    /// Resolve the capability registered during configure. Unregistered roots
150    /// receive a borrow-only capability without probing Git on the store path.
151    pub fn for_root(project_root: &Path) -> Self {
152        let project_root = canonical_root(project_root);
153        if let Some(access) = configured_artifact_access()
154            .lock()
155            .ok()
156            .and_then(|access| access.get(&project_root).cloned())
157        {
158            return access;
159        }
160        // Unregistered root: fail closed without spawning git probes. Configure
161        // registers every bound root before any store acquisition, so landing
162        // here means a direct artifact-API caller on an unconfigured root —
163        // treating it as borrow-only keeps shared artifacts safe and keeps this
164        // path subprocess-free (a git probe here has unbounded latency and can
165        // run on latency-critical threads).
166        crate::slog_warn!(
167            "artifact access requested for unconfigured root {}; defaulting to borrow-only",
168            project_root.display()
169        );
170        let shared_key = crate::path_identity::project_scope_key(&project_root);
171        Self {
172            private_key: shared_key.clone(),
173            project_root,
174            shared_key,
175            borrow_only_shared: true,
176            registered: false,
177        }
178    }
179
180    /// Return whether this root may write the keyed artifact, logging the first
181    /// denial for each concrete path so read-only degradation stays observable.
182    pub fn allows_write(&self, artifact_key: &str, write_path: &Path) -> bool {
183        let writes_keyed_dir = write_path
184            .ancestors()
185            .any(|ancestor| ancestor.file_name() == Some(OsStr::new(artifact_key)));
186        if !self.borrow_only_shared
187            || artifact_key != self.shared_key
188            || artifact_key == self.private_key
189            || !writes_keyed_dir
190        {
191            return true;
192        }
193        self.warn_write_denied_once(write_path);
194        false
195    }
196
197    fn allows_writer_lease(
198        &self,
199        domain: RootCacheDomain,
200        artifact_key: &str,
201        write_path: &Path,
202    ) -> bool {
203        self.allows_writer_lease_inner(domain, artifact_key, write_path)
204    }
205
206    fn allows_writer_lease_inner(
207        &self,
208        domain: RootCacheDomain,
209        artifact_key: &str,
210        write_path: &Path,
211    ) -> bool {
212        // Classify the layout from a comparison-local canonical copy rather
213        // than trusting key equality. A key derived while the root's final
214        // component was absent can encode a symlink alias (for example,
215        // /var versus /private/var) that disappears after the root exists.
216        let comparison_cache_dir = write_path.parent().map(canonical_process_lease_dir);
217        let writes_keyed_dir = comparison_cache_dir.as_deref().and_then(Path::file_name)
218            == Some(OsStr::new(artifact_key));
219        let writes_root_keyed_dir = comparison_cache_dir
220            .as_deref()
221            .and_then(Path::parent)
222            .and_then(Path::file_name)
223            == Some(OsStr::new(domain.as_str()));
224        if !self.borrow_only_shared {
225            return true;
226        }
227        if domain != RootCacheDomain::Callgraph
228            && writes_keyed_dir
229            && artifact_key == self.private_key
230        {
231            return true;
232        }
233        if !self.registered && !writes_root_keyed_dir {
234            // Caller-owned scratch paths are outside the shared root-keyed
235            // cache layout, so this capability does not govern them.
236            return true;
237        }
238        self.warn_write_denied_once(write_path);
239        false
240    }
241
242    fn warn_write_denied_once(&self, write_path: &Path) {
243        let warning_key = (self.project_root.clone(), write_path.to_path_buf());
244        let should_warn = WARNED_BORROW_ONLY_WRITES
245            .get_or_init(|| Mutex::new(HashSet::new()))
246            .lock()
247            .map(|mut warned| {
248                if warned.len() >= 4_096 {
249                    warned.clear();
250                }
251                warned.insert(warning_key)
252            })
253            .unwrap_or(false);
254        if should_warn {
255            crate::slog_warn!(
256                "borrow-only root denied shared artifact write at {} (configured shared key {})",
257                write_path.display(),
258                self.shared_key
259            );
260        }
261    }
262}
263
264fn configured_artifact_access() -> &'static Mutex<HashMap<PathBuf, ArtifactAccess>> {
265    CONFIGURED_ARTIFACT_ACCESS.get_or_init(|| Mutex::new(HashMap::new()))
266}
267
268/// Track scope keys belonging to roots currently bound in this process. The
269/// inspect sweep snapshots this registry at publication time so a live actor's
270/// cache cannot be mistaken for a reclaimed worktree cache.
271fn live_scope_keys() -> &'static Mutex<HashMap<(PathBuf, String), usize>> {
272    LIVE_SCOPE_KEYS.get_or_init(|| Mutex::new(HashMap::new()))
273}
274
275pub(crate) fn register_live_scope(storage_root: &Path, project_root: &Path) {
276    let storage_root = canonical_root(storage_root);
277    let scope_key = crate::path_identity::project_scope_key(project_root);
278    let mut scopes = match live_scope_keys().lock() {
279        Ok(scopes) => scopes,
280        Err(poisoned) => poisoned.into_inner(),
281    };
282    *scopes.entry((storage_root, scope_key)).or_default() += 1;
283}
284
285pub(crate) fn unregister_live_scope(storage_root: &Path, project_root: &Path) {
286    let storage_root = canonical_root(storage_root);
287    let scope_key = crate::path_identity::project_scope_key(project_root);
288    let mut scopes = match live_scope_keys().lock() {
289        Ok(scopes) => scopes,
290        Err(poisoned) => poisoned.into_inner(),
291    };
292    let key = (storage_root, scope_key);
293    if let Some(count) = scopes.get_mut(&key) {
294        *count = count.saturating_sub(1);
295        if *count == 0 {
296            scopes.remove(&key);
297        }
298    }
299}
300
301pub(crate) fn live_scope_keys_for_storage(storage_root: &Path) -> HashSet<String> {
302    let storage_root = canonical_root(storage_root);
303    let scopes = match live_scope_keys().lock() {
304        Ok(scopes) => scopes,
305        Err(poisoned) => poisoned.into_inner(),
306    };
307    scopes
308        .iter()
309        .filter(|((root, _), count)| root == &storage_root && **count > 0)
310        .map(|((_, key), _)| key.clone())
311        .collect()
312}
313
314/// Register the worktree topology already detected by configure so artifact
315/// APIs can enforce it without repeating a Git subprocess on every write path.
316pub fn configure_artifact_access(project_root: &Path, shared_key: &str, borrow_only_shared: bool) {
317    let access = ArtifactAccess::configured(project_root, shared_key, borrow_only_shared);
318    if let Ok(mut configured) = configured_artifact_access().lock() {
319        // Bounded, but never a wholesale clear: dropping still-live roots'
320        // capabilities would silently flip them onto the fail-closed
321        // (borrow-only) fallback. Evict an arbitrary other entry instead —
322        // any evicted-but-live root re-registers on its next configure.
323        if configured.len() >= 4_096 && !configured.contains_key(&access.project_root) {
324            if let Some(evict) = configured.keys().next().cloned() {
325                configured.remove(&evict);
326            }
327        }
328        configured.insert(access.project_root.clone(), access);
329    }
330}
331
332fn canonical_root(project_root: &Path) -> PathBuf {
333    // Nearest-existing-ancestor canonicalization, not a raw-spelling fallback:
334    // registration can precede the directory's creation (and lookups can follow
335    // it), and on macOS the raw tempdir spelling (/var/...) differs from the
336    // canonical one (/private/var/...). Keying the access registry by whichever
337    // spelling happened to win the existence race made a registered root miss
338    // its own entry and fail closed.
339    canonical_process_lease_dir(project_root)
340}
341
342fn process_leases() -> &'static Mutex<HashMap<ProcessLeaseKey, Weak<WriterLease>>> {
343    PROCESS_LEASES.get_or_init(|| Mutex::new(HashMap::new()))
344}
345
346fn process_lease_acquisitions() -> &'static Mutex<HashMap<ProcessLeaseKey, Weak<Mutex<()>>>> {
347    PROCESS_LEASE_ACQUISITIONS.get_or_init(|| Mutex::new(HashMap::new()))
348}
349
350fn writer_lease_acquisition_counts() -> &'static Mutex<HashMap<WriterLeaseAcquisitionKey, usize>> {
351    WRITER_LEASE_ACQUISITION_COUNTS.get_or_init(|| Mutex::new(HashMap::new()))
352}
353
354fn record_writer_lease_acquisition(domain: RootCacheDomain, key: &str, project_root: &Path) {
355    if !WRITER_LEASE_ACQUISITION_COUNTER_ENABLED.load(Ordering::Relaxed) {
356        return;
357    }
358    let project_root =
359        std::fs::canonicalize(project_root).unwrap_or_else(|_| project_root.to_path_buf());
360    let acquisition_key = WriterLeaseAcquisitionKey {
361        domain,
362        key: key.to_string(),
363        project_root,
364    };
365    if let Ok(mut counts) = writer_lease_acquisition_counts().lock() {
366        *counts.entry(acquisition_key).or_default() += 1;
367    }
368}
369
370#[doc(hidden)]
371pub fn reset_writer_lease_acquisition_counts_for_test() {
372    WRITER_LEASE_ACQUISITION_COUNTER_ENABLED.store(true, Ordering::Relaxed);
373    if let Ok(mut counts) = writer_lease_acquisition_counts().lock() {
374        counts.clear();
375    }
376}
377
378#[doc(hidden)]
379pub fn writer_lease_acquisition_count_for_test(
380    domain: RootCacheDomain,
381    key: &str,
382    project_root: &Path,
383) -> usize {
384    let project_root =
385        std::fs::canonicalize(project_root).unwrap_or_else(|_| project_root.to_path_buf());
386    writer_lease_acquisition_counts()
387        .lock()
388        .ok()
389        .and_then(|counts| {
390            counts
391                .get(&WriterLeaseAcquisitionKey {
392                    domain,
393                    key: key.to_string(),
394                    project_root,
395                })
396                .copied()
397        })
398        .unwrap_or(0)
399}
400
401fn shared_process_lease(
402    registry_key: &ProcessLeaseKey,
403) -> Result<Option<Arc<WriterLease>>, fs_lock::AcquireError> {
404    let mut leases = process_leases().lock().map_err(|_| {
405        fs_lock::AcquireError::Io(io::Error::other("process lease registry poisoned"))
406    })?;
407    if let Some(existing) = leases.get(registry_key).and_then(Weak::upgrade) {
408        if existing.verify()? {
409            return Ok(Some(existing));
410        }
411        leases.remove(registry_key);
412    }
413    Ok(None)
414}
415
416fn process_lease_acquisition_lock(
417    registry_key: &ProcessLeaseKey,
418) -> Result<Arc<Mutex<()>>, fs_lock::AcquireError> {
419    let mut acquisitions = process_lease_acquisitions().lock().map_err(|_| {
420        fs_lock::AcquireError::Io(io::Error::other(
421            "process lease acquisition registry poisoned",
422        ))
423    })?;
424    if let Some(existing) = acquisitions.get(registry_key).and_then(Weak::upgrade) {
425        return Ok(existing);
426    }
427    if acquisitions.len() > 1024 {
428        acquisitions.retain(|_, lock| lock.strong_count() > 0);
429    }
430    let lock = Arc::new(Mutex::new(()));
431    acquisitions.insert(registry_key.clone(), Arc::downgrade(&lock));
432    Ok(lock)
433}
434
435#[cfg(test)]
436type AcquireSharedHook = Arc<dyn Fn(RootCacheDomain, &Path, &str) + Send + Sync + 'static>;
437
438#[cfg(test)]
439static ACQUIRE_SHARED_HOOK: OnceLock<Mutex<Option<AcquireSharedHook>>> = OnceLock::new();
440
441#[cfg(test)]
442fn set_acquire_shared_hook_for_test(hook: Option<AcquireSharedHook>) {
443    *ACQUIRE_SHARED_HOOK
444        .get_or_init(|| Mutex::new(None))
445        .lock()
446        .expect("acquire shared hook mutex") = hook;
447}
448
449#[cfg(test)]
450fn run_acquire_shared_hook_for_test(domain: RootCacheDomain, cache_dir: &Path, key: &str) {
451    let hook = ACQUIRE_SHARED_HOOK
452        .get_or_init(|| Mutex::new(None))
453        .lock()
454        .expect("acquire shared hook mutex")
455        .clone();
456    if let Some(hook) = hook {
457        hook(domain, cache_dir, key);
458    }
459}
460
461#[cfg(not(test))]
462fn run_acquire_shared_hook_for_test(_domain: RootCacheDomain, _cache_dir: &Path, _key: &str) {}
463
464impl std::fmt::Debug for WriterLease {
465    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466        formatter
467            .debug_struct("WriterLease")
468            .field("domain", &self.domain)
469            .field("key", &self.key)
470            .field("path", &self.path)
471            .field("epoch", &self.epoch)
472            .finish_non_exhaustive()
473    }
474}
475
476impl WriterLease {
477    pub fn acquire_shared(
478        domain: RootCacheDomain,
479        cache_dir: &Path,
480        key: &str,
481        project_root: &Path,
482    ) -> Result<Option<Arc<Self>>, fs_lock::AcquireError> {
483        let access = ArtifactAccess::for_root(project_root);
484        if !access.allows_writer_lease(domain, key, &writer_lease_path(cache_dir)) {
485            return Ok(None);
486        }
487        let registry_key = ProcessLeaseKey {
488            domain,
489            cache_dir: canonical_process_lease_dir(cache_dir),
490        };
491        if let Some(existing) = shared_process_lease(&registry_key)? {
492            record_writer_lease_acquisition(domain, key, project_root);
493            return Ok(Some(existing));
494        }
495
496        let acquisition_lock = process_lease_acquisition_lock(&registry_key)?;
497        let _acquisition_guard = acquisition_lock.lock().map_err(|_| {
498            fs_lock::AcquireError::Io(io::Error::other("process lease acquisition poisoned"))
499        })?;
500
501        if let Some(existing) = shared_process_lease(&registry_key)? {
502            record_writer_lease_acquisition(domain, key, project_root);
503            return Ok(Some(existing));
504        }
505
506        run_acquire_shared_hook_for_test(domain, cache_dir, key);
507
508        let lease = Arc::new(Self::acquire(domain, cache_dir, key, Duration::ZERO)?);
509        process_leases()
510            .lock()
511            .map_err(|_| {
512                fs_lock::AcquireError::Io(io::Error::other("process lease registry poisoned"))
513            })?
514            .insert(registry_key, Arc::downgrade(&lease));
515        record_writer_lease_acquisition(domain, key, project_root);
516        Ok(Some(lease))
517    }
518
519    fn acquire(
520        domain: RootCacheDomain,
521        cache_dir: &Path,
522        key: &str,
523        timeout: Duration,
524    ) -> Result<Self, fs_lock::AcquireError> {
525        if !storage_allows_root_keyed(cache_dir)? {
526            return Err(fs_lock::AcquireError::Io(io::Error::new(
527                io::ErrorKind::PermissionDenied,
528                format!(
529                    "refusing root-keyed {} writer lease on a network filesystem at {}",
530                    domain.as_str(),
531                    cache_dir.display()
532                ),
533            )));
534        }
535        if let Some(storage_root) = cache_dir.parent().and_then(Path::parent) {
536            crate::legacy_partitions::guard_new_layout_write_path(
537                storage_root,
538                cache_dir,
539                "root-keyed writer lease",
540            )?;
541        }
542        fs::create_dir_all(cache_dir)?;
543        let guard = fs_lock::try_acquire(&writer_lease_path(cache_dir), timeout)?;
544        if !guard.verify_writer_epoch()? {
545            return Err(fs_lock::AcquireError::Io(io::Error::other(
546                "writer lease epoch changed immediately after acquisition",
547            )));
548        }
549        let path = guard.path().to_path_buf();
550        let epoch = guard.writer_epoch().to_string();
551        Ok(Self {
552            domain,
553            key: key.to_string(),
554            path,
555            epoch,
556            guard: Mutex::new(guard),
557        })
558    }
559
560    pub fn verify(&self) -> io::Result<bool> {
561        self.guard
562            .lock()
563            .map_err(|_| io::Error::other("writer lease mutex poisoned"))?
564            .verify_writer_epoch()
565    }
566
567    pub fn epoch(&self) -> &str {
568        &self.epoch
569    }
570
571    pub fn domain(&self) -> RootCacheDomain {
572        self.domain
573    }
574
575    pub fn key(&self) -> &str {
576        &self.key
577    }
578
579    pub fn path(&self) -> &Path {
580        &self.path
581    }
582}
583
584pub fn writer_lease_path(cache_dir: &Path) -> PathBuf {
585    cache_dir.join("writer.lease")
586}
587
588#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
589pub struct ReadMarkerMetadata {
590    pub pid: u32,
591    pub hostname: String,
592    pub created_at_ms: u64,
593}
594
595#[derive(Debug)]
596pub struct ReadMarker {
597    path: PathBuf,
598    metadata: ReadMarkerMetadata,
599    last_touched_at_ms: AtomicU64,
600}
601
602impl ReadMarker {
603    pub fn create(cache_dir: &Path, generation_label: &str) -> io::Result<Self> {
604        let metadata = ReadMarkerMetadata {
605            pid: std::process::id(),
606            hostname: current_hostname(),
607            created_at_ms: now_ms(),
608        };
609        let dir = read_marker_dir(cache_dir, generation_label);
610        fs::create_dir_all(&dir)?;
611        let seq = MARKER_SEQ.fetch_add(1, Ordering::Relaxed);
612        let path = dir.join(format!(
613            "{}.{}.{}.{}.json",
614            metadata.pid,
615            sanitize_marker_component(&metadata.hostname),
616            metadata.created_at_ms,
617            seq
618        ));
619        write_marker_file(&path, &metadata)?;
620        let last_touched_at_ms = AtomicU64::new(metadata.created_at_ms);
621        Ok(Self {
622            path,
623            metadata,
624            last_touched_at_ms,
625        })
626    }
627
628    pub fn touch(&self) -> io::Result<()> {
629        write_marker_file(&self.path, &self.metadata)?;
630        self.last_touched_at_ms.store(now_ms(), Ordering::Relaxed);
631        Ok(())
632    }
633
634    pub fn touch_if_due(&self) -> io::Result<()> {
635        let now = now_ms();
636        let last = self.last_touched_at_ms.load(Ordering::Relaxed);
637        if now.saturating_sub(last) < READ_MARKER_TOUCH_INTERVAL_MS {
638            return Ok(());
639        }
640        self.touch()
641    }
642
643    pub fn path(&self) -> &Path {
644        &self.path
645    }
646
647    pub fn metadata(&self) -> &ReadMarkerMetadata {
648        &self.metadata
649    }
650}
651
652impl Drop for ReadMarker {
653    fn drop(&mut self) {
654        let _ = fs::remove_file(&self.path);
655        fs_lock::sync_parent(&self.path);
656    }
657}
658
659pub fn read_marker_dir(cache_dir: &Path, generation_label: &str) -> PathBuf {
660    cache_dir.join("readers").join(generation_label)
661}
662
663/// Sweep every generation marker below a cache directory, reusing the same
664/// PID-authoritative and cross-host-TTL liveness rules as generation GC.
665pub(crate) fn sweep_all_read_markers(cache_dir: &Path) -> ReadMarkerSweep {
666    let readers = cache_dir.join("readers");
667    let entries = match fs::read_dir(&readers) {
668        Ok(entries) => entries,
669        Err(error) if error.kind() == io::ErrorKind::NotFound => return ReadMarkerSweep::default(),
670        Err(_) => {
671            return ReadMarkerSweep {
672                protected: true,
673                removed_stale: 0,
674            }
675        }
676    };
677
678    let mut sweep = ReadMarkerSweep::default();
679    for entry in entries {
680        let Ok(entry) = entry else {
681            sweep.protected = true;
682            continue;
683        };
684        let path = entry.path();
685        let file_type = match entry.file_type() {
686            Ok(file_type) => file_type,
687            Err(_) => {
688                sweep.protected = true;
689                continue;
690            }
691        };
692        if !file_type.is_dir() {
693            continue;
694        }
695        let Some(label) = path.file_name().and_then(|name| name.to_str()) else {
696            sweep.protected = true;
697            continue;
698        };
699        let generation = sweep_read_markers(cache_dir, label);
700        sweep.protected |= generation.protected;
701        sweep.removed_stale += generation.removed_stale;
702    }
703    sweep
704}
705
706#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
707pub struct ReadMarkerSweep {
708    pub protected: bool,
709    pub removed_stale: usize,
710}
711
712pub fn protected_read_marker_exists(cache_dir: &Path, generation_label: &str) -> bool {
713    read_marker_protection(cache_dir, generation_label, false).protected
714}
715
716pub fn sweep_read_markers(cache_dir: &Path, generation_label: &str) -> ReadMarkerSweep {
717    read_marker_protection(cache_dir, generation_label, true)
718}
719
720fn read_marker_protection(
721    cache_dir: &Path,
722    generation_label: &str,
723    remove_stale: bool,
724) -> ReadMarkerSweep {
725    let dir = read_marker_dir(cache_dir, generation_label);
726    let entries = match fs::read_dir(&dir) {
727        Ok(entries) => entries,
728        Err(error) if error.kind() == io::ErrorKind::NotFound => return ReadMarkerSweep::default(),
729        Err(_) => {
730            return ReadMarkerSweep {
731                protected: true,
732                removed_stale: 0,
733            };
734        }
735    };
736
737    let hostname = current_hostname();
738    let now = now_ms();
739    let mut sweep = ReadMarkerSweep::default();
740    for entry in entries.flatten() {
741        let path = entry.path();
742        match marker_file_is_protected(&path, now, &hostname) {
743            MarkerProtection::Protected => sweep.protected = true,
744            MarkerProtection::Stale | MarkerProtection::Malformed => {
745                if remove_stale && fs::remove_file(&path).is_ok() {
746                    fs_lock::sync_parent(&path);
747                    sweep.removed_stale += 1;
748                }
749            }
750        }
751    }
752    sweep
753}
754
755#[derive(Clone, Copy, Debug, PartialEq, Eq)]
756enum MarkerProtection {
757    Protected,
758    Stale,
759    Malformed,
760}
761
762fn marker_file_is_protected(path: &Path, now: u64, current_host: &str) -> MarkerProtection {
763    let bytes = match fs::read(path) {
764        Ok(bytes) => bytes,
765        Err(error) if error.kind() == io::ErrorKind::NotFound => return MarkerProtection::Stale,
766        Err(_) => return MarkerProtection::Protected,
767    };
768    let metadata: ReadMarkerMetadata = match serde_json::from_slice(&bytes) {
769        Ok(metadata) => metadata,
770        Err(_) => return MarkerProtection::Malformed,
771    };
772    if metadata.hostname != current_host {
773        let Ok(file_metadata) = fs::metadata(path) else {
774            return MarkerProtection::Protected;
775        };
776        let mtime_ms = file_metadata
777            .modified()
778            .ok()
779            .map(system_time_ms)
780            .unwrap_or(now);
781        let age_ms = now.saturating_sub(mtime_ms);
782        return if age_ms <= READ_MARKER_CROSS_HOST_STALE_MS {
783            MarkerProtection::Protected
784        } else {
785            MarkerProtection::Stale
786        };
787    }
788
789    if !fs_lock::process_alive(metadata.pid) {
790        return MarkerProtection::Stale;
791    }
792    if marker_matches_live_process_instance(&metadata) {
793        MarkerProtection::Protected
794    } else {
795        MarkerProtection::Stale
796    }
797}
798
799fn marker_matches_live_process_instance(metadata: &ReadMarkerMetadata) -> bool {
800    // Same-host PID liveness is authoritative for the process instance. When the
801    // OS can tell us the live PID started after this marker was created, the PID
802    // has been reused and the marker belongs to a dead prior process; otherwise
803    // a live PID protects the marker without consulting marker mtime.
804    process_start_time_ms(metadata.pid)
805        .map(|started_at_ms| {
806            started_at_ms
807                <= metadata
808                    .created_at_ms
809                    .saturating_add(PROCESS_START_TIME_GRACE_MS)
810        })
811        .unwrap_or(true)
812}
813
814fn write_marker_file(path: &Path, metadata: &ReadMarkerMetadata) -> io::Result<()> {
815    let tmp = path.with_file_name(format!(
816        ".{}.tmp.{}.{}",
817        path.file_name()
818            .and_then(|name| name.to_str())
819            .unwrap_or("reader"),
820        std::process::id(),
821        now_nanos()
822    ));
823    let result = (|| {
824        let mut file = open_private_file(&tmp)?;
825        serde_json::to_writer(&mut file, metadata).map_err(io::Error::other)?;
826        file.write_all(b"\n")?;
827        file.sync_all()?;
828        drop(file);
829        fs_lock::rename_over(&tmp, path)?;
830        fs_lock::sync_parent(path);
831        Ok(())
832    })();
833    if result.is_err() {
834        let _ = fs::remove_file(&tmp);
835    }
836    result
837}
838
839#[cfg(unix)]
840fn open_private_file(path: &Path) -> io::Result<File> {
841    use std::os::unix::fs::OpenOptionsExt;
842
843    OpenOptions::new()
844        .write(true)
845        .create_new(true)
846        .mode(0o600)
847        .open(path)
848}
849
850#[cfg(not(unix))]
851fn open_private_file(path: &Path) -> io::Result<File> {
852    OpenOptions::new().write(true).create_new(true).open(path)
853}
854
855fn sanitize_marker_component(value: &str) -> String {
856    value
857        .chars()
858        .map(|ch| {
859            if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_') {
860                ch
861            } else {
862                '_'
863            }
864        })
865        .collect()
866}
867
868#[cfg(test)]
869static FORCE_NETWORK_FS_FOR_TEST: AtomicBool = AtomicBool::new(false);
870
871#[cfg(test)]
872pub fn set_force_network_fs_for_test(enabled: bool) {
873    FORCE_NETWORK_FS_FOR_TEST.store(enabled, Ordering::SeqCst);
874}
875
876pub fn storage_allows_root_keyed(path: &Path) -> io::Result<bool> {
877    #[cfg(test)]
878    if FORCE_NETWORK_FS_FOR_TEST.load(Ordering::SeqCst) {
879        return Ok(false);
880    }
881
882    let probe = existing_ancestor(path);
883    filesystem_is_local(&probe)
884}
885
886fn canonical_process_lease_dir(path: &Path) -> PathBuf {
887    if let Ok(canonical) = std::fs::canonicalize(path) {
888        return canonical;
889    }
890
891    let normalized = lexical_normalize(path);
892    let mut missing_components = Vec::new();
893    let mut current = normalized.as_path();
894    while !current.exists() {
895        let Some(name) = current.file_name() else {
896            return normalized;
897        };
898        missing_components.push(name.to_os_string());
899        let Some(parent) = current.parent() else {
900            return normalized;
901        };
902        current = parent;
903    }
904
905    let mut canonical = std::fs::canonicalize(current).unwrap_or_else(|_| current.to_path_buf());
906    for component in missing_components.iter().rev() {
907        canonical.push(component);
908    }
909    canonical
910}
911
912fn lexical_normalize(path: &Path) -> PathBuf {
913    let mut normalized = PathBuf::new();
914    for component in path.components() {
915        match component {
916            std::path::Component::CurDir => {}
917            std::path::Component::ParentDir => {
918                normalized.pop();
919            }
920            other => normalized.push(other.as_os_str()),
921        }
922    }
923    normalized
924}
925
926fn existing_ancestor(path: &Path) -> PathBuf {
927    let mut current = path;
928    loop {
929        if current.exists() {
930            return current.to_path_buf();
931        }
932        let Some(parent) = current.parent() else {
933            return PathBuf::from(".");
934        };
935        current = parent;
936    }
937}
938
939#[cfg(target_os = "macos")]
940fn filesystem_is_local(path: &Path) -> io::Result<bool> {
941    use std::ffi::CString;
942    use std::os::unix::ffi::OsStrExt;
943
944    let c_path = CString::new(path.as_os_str().as_bytes())
945        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL byte"))?;
946    let mut stat: libc::statfs = unsafe { std::mem::zeroed() };
947    if unsafe { libc::statfs(c_path.as_ptr(), &mut stat) } != 0 {
948        return Err(io::Error::last_os_error());
949    }
950    let nul = stat
951        .f_fstypename
952        .iter()
953        .position(|byte| *byte == 0)
954        .unwrap_or(stat.f_fstypename.len());
955    let fs_type = String::from_utf8_lossy(
956        &stat.f_fstypename[..nul]
957            .iter()
958            .map(|byte| *byte as u8)
959            .collect::<Vec<_>>(),
960    )
961    .to_ascii_lowercase();
962    Ok(!matches!(
963        fs_type.as_str(),
964        "nfs" | "smbfs" | "afpfs" | "webdav" | "fusefs"
965    ))
966}
967
968#[cfg(all(unix, not(target_os = "macos")))]
969fn filesystem_is_local(path: &Path) -> io::Result<bool> {
970    use std::ffi::CString;
971    use std::os::unix::ffi::OsStrExt;
972
973    let c_path = CString::new(path.as_os_str().as_bytes())
974        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL byte"))?;
975    let mut stat: libc::statfs = unsafe { std::mem::zeroed() };
976    if unsafe { libc::statfs(c_path.as_ptr(), &mut stat) } != 0 {
977        return Err(io::Error::last_os_error());
978    }
979    let fs_type = stat.f_type as i64;
980    const NFS_SUPER_MAGIC: i64 = 0x6969;
981    const SMB_SUPER_MAGIC: i64 = 0x517B;
982    const CIFS_MAGIC_NUMBER: i64 = 0xFF534D42;
983    Ok(!matches!(
984        fs_type,
985        NFS_SUPER_MAGIC | SMB_SUPER_MAGIC | CIFS_MAGIC_NUMBER
986    ))
987}
988
989#[cfg(not(unix))]
990fn filesystem_is_local(_path: &Path) -> io::Result<bool> {
991    Ok(true)
992}
993
994fn now_ms() -> u64 {
995    system_time_ms(SystemTime::now())
996}
997
998fn system_time_ms(time: SystemTime) -> u64 {
999    time.duration_since(UNIX_EPOCH)
1000        .unwrap_or(Duration::ZERO)
1001        .as_millis() as u64
1002}
1003
1004fn now_nanos() -> u128 {
1005    SystemTime::now()
1006        .duration_since(UNIX_EPOCH)
1007        .unwrap_or(Duration::ZERO)
1008        .as_nanos()
1009}
1010
1011#[cfg(test)]
1012static PROCESS_START_TIME_OVERRIDES: OnceLock<Mutex<HashMap<u32, Option<u64>>>> = OnceLock::new();
1013
1014#[cfg(test)]
1015fn set_process_start_time_for_test(pid: u32, started_at_ms: Option<u64>) {
1016    PROCESS_START_TIME_OVERRIDES
1017        .get_or_init(|| Mutex::new(HashMap::new()))
1018        .lock()
1019        .expect("process start override mutex")
1020        .insert(pid, started_at_ms);
1021}
1022
1023#[cfg(test)]
1024fn clear_process_start_time_for_test(pid: u32) {
1025    if let Some(overrides) = PROCESS_START_TIME_OVERRIDES.get() {
1026        overrides
1027            .lock()
1028            .expect("process start override mutex")
1029            .remove(&pid);
1030    }
1031}
1032
1033#[cfg(test)]
1034fn process_start_time_override(pid: u32) -> Option<Option<u64>> {
1035    PROCESS_START_TIME_OVERRIDES
1036        .get()
1037        .and_then(|overrides| overrides.lock().ok()?.get(&pid).copied())
1038}
1039
1040#[cfg(target_os = "linux")]
1041fn process_start_time_ms(pid: u32) -> Option<u64> {
1042    #[cfg(test)]
1043    if let Some(override_value) = process_start_time_override(pid) {
1044        return override_value;
1045    }
1046
1047    let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1048    let after_comm = stat.rsplit_once(") ")?.1;
1049    let fields = after_comm.split_whitespace().collect::<Vec<_>>();
1050    let start_ticks = fields.get(19)?.parse::<u64>().ok()?;
1051    let boot_time_secs = fs::read_to_string("/proc/stat")
1052        .ok()?
1053        .lines()
1054        .find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())?;
1055    let ticks_per_second = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
1056    if ticks_per_second <= 0 {
1057        return None;
1058    }
1059    let ticks_per_second = ticks_per_second as u64;
1060    Some(
1061        boot_time_secs
1062            .saturating_mul(1_000)
1063            .saturating_add(start_ticks.saturating_mul(1_000) / ticks_per_second),
1064    )
1065}
1066
1067#[cfg(target_os = "macos")]
1068fn process_start_time_ms(pid: u32) -> Option<u64> {
1069    #[cfg(test)]
1070    if let Some(override_value) = process_start_time_override(pid) {
1071        return override_value;
1072    }
1073
1074    let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
1075    let info_size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
1076    let bytes = unsafe {
1077        libc::proc_pidinfo(
1078            pid as libc::c_int,
1079            libc::PROC_PIDTBSDINFO,
1080            0,
1081            (&mut info as *mut libc::proc_bsdinfo).cast(),
1082            info_size,
1083        )
1084    };
1085    if bytes != info_size {
1086        return None;
1087    }
1088    Some(
1089        info.pbi_start_tvsec
1090            .saturating_mul(1_000)
1091            .saturating_add(info.pbi_start_tvusec / 1_000),
1092    )
1093}
1094
1095#[cfg(not(any(target_os = "linux", target_os = "macos")))]
1096fn process_start_time_ms(pid: u32) -> Option<u64> {
1097    #[cfg(test)]
1098    if let Some(override_value) = process_start_time_override(pid) {
1099        return override_value;
1100    }
1101    let _ = pid;
1102    None
1103}
1104
1105#[cfg(unix)]
1106fn current_hostname() -> String {
1107    let mut buffer = [0u8; 256];
1108    let result = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) };
1109    if result == 0 {
1110        let len = buffer
1111            .iter()
1112            .position(|byte| *byte == 0)
1113            .unwrap_or(buffer.len());
1114        if len > 0 {
1115            return String::from_utf8_lossy(&buffer[..len]).into_owned();
1116        }
1117    }
1118    "unknown-host".to_string()
1119}
1120
1121#[cfg(windows)]
1122fn current_hostname() -> String {
1123    std::env::var("COMPUTERNAME").unwrap_or_else(|_| "unknown-host".to_string())
1124}
1125
1126#[cfg(all(not(unix), not(windows)))]
1127fn current_hostname() -> String {
1128    "unknown-host".to_string()
1129}
1130
1131#[cfg(test)]
1132mod tests {
1133    use super::*;
1134
1135    #[test]
1136    fn read_marker_file_is_private_and_touchable() {
1137        let dir = tempfile::tempdir().unwrap();
1138        let marker = ReadMarker::create(dir.path(), "current").unwrap();
1139        assert!(marker.path().is_file());
1140        marker.touch().unwrap();
1141        let bytes = fs::read(marker.path()).unwrap();
1142        let parsed: ReadMarkerMetadata = serde_json::from_slice(&bytes).unwrap();
1143        assert_eq!(parsed.pid, std::process::id());
1144        #[cfg(unix)]
1145        {
1146            use std::os::unix::fs::PermissionsExt;
1147            assert_eq!(
1148                fs::metadata(marker.path()).unwrap().permissions().mode() & 0o777,
1149                0o600
1150            );
1151        }
1152    }
1153
1154    #[test]
1155    fn same_host_live_marker_ignores_stale_mtime() {
1156        let dir = tempfile::tempdir().unwrap();
1157        let marker = ReadMarker::create(dir.path(), "current").unwrap();
1158        filetime::set_file_mtime(marker.path(), filetime::FileTime::from_unix_time(0, 0)).unwrap();
1159
1160        assert!(protected_read_marker_exists(dir.path(), "current"));
1161    }
1162
1163    #[test]
1164    fn sweep_removes_dead_same_host_marker() {
1165        let dir = tempfile::tempdir().unwrap();
1166        let marker_path = read_marker_dir(dir.path(), "old").join("dead.json");
1167        let metadata = ReadMarkerMetadata {
1168            pid: 0,
1169            hostname: current_hostname(),
1170            created_at_ms: now_ms(),
1171        };
1172        fs::create_dir_all(marker_path.parent().unwrap()).unwrap();
1173        write_marker_file(&marker_path, &metadata).unwrap();
1174
1175        let sweep = sweep_read_markers(dir.path(), "old");
1176
1177        assert!(!sweep.protected);
1178        assert_eq!(sweep.removed_stale, 1);
1179        assert!(!marker_path.exists());
1180    }
1181
1182    #[test]
1183    fn sweep_removes_reused_pid_marker_when_created_at_predates_process_start() {
1184        let dir = tempfile::tempdir().unwrap();
1185        let marker_path = read_marker_dir(dir.path(), "old").join("reused.json");
1186        let pid = std::process::id();
1187        let metadata = ReadMarkerMetadata {
1188            pid,
1189            hostname: current_hostname(),
1190            created_at_ms: 1_000,
1191        };
1192        fs::create_dir_all(marker_path.parent().unwrap()).unwrap();
1193        write_marker_file(&marker_path, &metadata).unwrap();
1194        set_process_start_time_for_test(pid, Some(10_000));
1195
1196        let sweep = sweep_read_markers(dir.path(), "old");
1197        clear_process_start_time_for_test(pid);
1198
1199        assert!(!sweep.protected);
1200        assert_eq!(sweep.removed_stale, 1);
1201        assert!(!marker_path.exists());
1202    }
1203
1204    #[test]
1205    fn sweep_removes_expired_cross_host_marker() {
1206        let dir = tempfile::tempdir().unwrap();
1207        let marker_path = read_marker_dir(dir.path(), "old").join("cross-host.json");
1208        let metadata = ReadMarkerMetadata {
1209            pid: 123,
1210            hostname: format!("other-{}", current_hostname()),
1211            created_at_ms: now_ms(),
1212        };
1213        fs::create_dir_all(marker_path.parent().unwrap()).unwrap();
1214        write_marker_file(&marker_path, &metadata).unwrap();
1215        let stale_time = SystemTime::now()
1216            .checked_sub(Duration::from_millis(
1217                READ_MARKER_CROSS_HOST_STALE_MS.saturating_add(1_000),
1218            ))
1219            .unwrap_or(UNIX_EPOCH);
1220        filetime::set_file_mtime(
1221            &marker_path,
1222            filetime::FileTime::from_system_time(stale_time),
1223        )
1224        .unwrap();
1225
1226        let sweep = sweep_read_markers(dir.path(), "old");
1227
1228        assert!(!sweep.protected);
1229        assert_eq!(sweep.removed_stale, 1);
1230        assert!(!marker_path.exists());
1231    }
1232
1233    #[cfg(unix)]
1234    #[test]
1235    fn process_lease_dir_canonicalizes_existing_ancestor_before_cache_dir_exists() {
1236        let dir = tempfile::tempdir().unwrap();
1237        let real = dir.path().join("real");
1238        let link = dir.path().join("link");
1239        fs::create_dir_all(&real).unwrap();
1240        std::os::unix::fs::symlink(&real, &link).unwrap();
1241
1242        let missing_cache_dir = link.join("inspect").join("project");
1243        let before_create = canonical_process_lease_dir(&missing_cache_dir);
1244        fs::create_dir_all(&missing_cache_dir).unwrap();
1245        let after_create = canonical_process_lease_dir(&missing_cache_dir);
1246
1247        assert_eq!(before_create, after_create);
1248        assert!(before_create.starts_with(std::fs::canonicalize(&real).unwrap()));
1249    }
1250
1251    #[test]
1252    fn borrow_only_root_never_receives_existing_shared_writer_capability() {
1253        let storage = tempfile::tempdir().unwrap();
1254        let parent_root = tempfile::tempdir().unwrap();
1255        let worktree_root = tempfile::tempdir().unwrap();
1256        let shared_key = "shared-artifact-key";
1257        let cache_dir = storage.path().join("callgraph").join(shared_key);
1258        configure_artifact_access(parent_root.path(), shared_key, false);
1259        configure_artifact_access(worktree_root.path(), shared_key, true);
1260
1261        let parent_lease = WriterLease::acquire_shared(
1262            RootCacheDomain::Callgraph,
1263            &cache_dir,
1264            shared_key,
1265            parent_root.path(),
1266        )
1267        .unwrap()
1268        .expect("parent writer lease");
1269        reset_writer_lease_acquisition_counts_for_test();
1270
1271        let worktree_lease = WriterLease::acquire_shared(
1272            RootCacheDomain::Callgraph,
1273            &cache_dir,
1274            shared_key,
1275            worktree_root.path(),
1276        )
1277        .unwrap();
1278        let unkeyed_worktree_lease = WriterLease::acquire_shared(
1279            RootCacheDomain::Callgraph,
1280            &storage.path().join("scratch"),
1281            shared_key,
1282            worktree_root.path(),
1283        )
1284        .unwrap();
1285
1286        assert!(worktree_lease.is_none());
1287        assert!(unkeyed_worktree_lease.is_none());
1288        assert!(parent_lease.verify().unwrap());
1289        assert_eq!(
1290            writer_lease_acquisition_count_for_test(
1291                RootCacheDomain::Callgraph,
1292                shared_key,
1293                worktree_root.path(),
1294            ),
1295            0
1296        );
1297    }
1298
1299    #[test]
1300    fn unregistered_root_cannot_acquire_keyed_shared_writer_lease() {
1301        let storage = tempfile::tempdir().unwrap();
1302        let root = tempfile::tempdir().unwrap();
1303        let shared_key = "unregistered-shared-key";
1304        let cache_dir = storage.path().join("callgraph").join(shared_key);
1305        reset_writer_lease_acquisition_counts_for_test();
1306
1307        let lease = WriterLease::acquire_shared(
1308            RootCacheDomain::Callgraph,
1309            &cache_dir,
1310            shared_key,
1311            root.path(),
1312        )
1313        .unwrap();
1314
1315        assert!(lease.is_none());
1316        assert_eq!(
1317            writer_lease_acquisition_count_for_test(
1318                RootCacheDomain::Callgraph,
1319                shared_key,
1320                root.path(),
1321            ),
1322            0
1323        );
1324        assert!(!writer_lease_path(&cache_dir).exists());
1325    }
1326
1327    #[cfg(unix)]
1328    #[test]
1329    fn unregistered_root_denies_symlink_aliased_stale_key() {
1330        let storage = tempfile::tempdir().unwrap();
1331        let roots = tempfile::tempdir().unwrap();
1332        let real_parent = roots.path().join("real");
1333        let alias_parent = roots.path().join("alias");
1334        fs::create_dir_all(&real_parent).unwrap();
1335        std::os::unix::fs::symlink(&real_parent, &alias_parent).unwrap();
1336
1337        let root = alias_parent.join("root");
1338        let stale_key = crate::search_index::artifact_cache_key(&root);
1339        fs::create_dir_all(&root).unwrap();
1340        let canonical_key = crate::search_index::artifact_cache_key(&root);
1341        assert_ne!(stale_key, canonical_key, "fixture must exercise the alias");
1342
1343        let cache_dir = storage.path().join("callgraph").join(&stale_key);
1344        reset_writer_lease_acquisition_counts_for_test();
1345        let lease = WriterLease::acquire_shared(
1346            RootCacheDomain::Callgraph,
1347            &cache_dir,
1348            &canonical_key,
1349            &root,
1350        )
1351        .unwrap();
1352
1353        assert!(lease.is_none());
1354        assert_eq!(
1355            writer_lease_acquisition_count_for_test(
1356                RootCacheDomain::Callgraph,
1357                &canonical_key,
1358                &root,
1359            ),
1360            0
1361        );
1362        assert!(!writer_lease_path(&cache_dir).exists());
1363    }
1364
1365    #[cfg(unix)]
1366    #[test]
1367    fn registration_before_directory_creation_survives_alias_canonicalization() {
1368        // Regression for the concurrent-acquire flake: configure registered the
1369        // root before its directory existed (raw alias spelling), the first
1370        // lease's create_dir_all made later lookups canonicalize to the real
1371        // spelling, and the registered root missed its own capability entry.
1372        let storage = tempfile::tempdir().unwrap();
1373        let roots = tempfile::tempdir().unwrap();
1374        let real_parent = roots.path().join("real");
1375        let alias_parent = roots.path().join("alias");
1376        fs::create_dir_all(&real_parent).unwrap();
1377        std::os::unix::fs::symlink(&real_parent, &alias_parent).unwrap();
1378
1379        let root = alias_parent.join("pre-registered");
1380        configure_artifact_access(&root, "pre-registered", false);
1381        fs::create_dir_all(&root).unwrap();
1382
1383        let cache_dir = storage.path().join("inspect").join("pre-registered");
1384        let lease = WriterLease::acquire_shared(
1385            RootCacheDomain::Inspect,
1386            &cache_dir,
1387            "pre-registered",
1388            &root,
1389        )
1390        .unwrap();
1391        assert!(
1392            lease.is_some(),
1393            "a root registered before its directory existed must keep its capability"
1394        );
1395    }
1396
1397    #[test]
1398    fn borrow_only_root_keeps_private_project_scope_writable() {
1399        let storage = tempfile::tempdir().unwrap();
1400        let worktree_root = tempfile::tempdir().unwrap();
1401        let shared_key = "shared-artifact-key";
1402        let private_key = crate::path_identity::project_scope_key(worktree_root.path());
1403        let cache_dir = storage.path().join("inspect").join(&private_key);
1404        configure_artifact_access(worktree_root.path(), shared_key, true);
1405
1406        let lease = WriterLease::acquire_shared(
1407            RootCacheDomain::Inspect,
1408            &cache_dir,
1409            &private_key,
1410            worktree_root.path(),
1411        )
1412        .unwrap()
1413        .expect("private inspect writer lease");
1414
1415        assert!(lease.verify().unwrap());
1416    }
1417
1418    #[test]
1419    fn writer_lease_acquire_shared_does_not_serialize_different_roots() {
1420        let dir = tempfile::tempdir().unwrap();
1421        let blocked_cache_dir = dir.path().join("callgraph").join("blocked");
1422        let free_cache_dir = dir.path().join("callgraph").join("free");
1423        configure_artifact_access(&blocked_cache_dir, "blocked", false);
1424        configure_artifact_access(&free_cache_dir, "free", false);
1425        let (blocked_tx, blocked_rx) = std::sync::mpsc::channel();
1426        let (release_tx, release_rx) = std::sync::mpsc::channel();
1427        let release_rx = Arc::new(Mutex::new(release_rx));
1428
1429        struct HookGuard;
1430        impl Drop for HookGuard {
1431            fn drop(&mut self) {
1432                set_acquire_shared_hook_for_test(None);
1433            }
1434        }
1435
1436        set_acquire_shared_hook_for_test(Some(Arc::new(move |_, _, key| {
1437            if key == "blocked" {
1438                blocked_tx.send(()).unwrap();
1439                release_rx.lock().unwrap().recv().unwrap();
1440            }
1441        })));
1442        let _hook_guard = HookGuard;
1443
1444        let blocked_handle = std::thread::spawn(move || {
1445            WriterLease::acquire_shared(
1446                RootCacheDomain::Callgraph,
1447                &blocked_cache_dir,
1448                "blocked",
1449                &blocked_cache_dir,
1450            )
1451            .map_err(|error| error.to_string())
1452            .and_then(|lease| lease.ok_or_else(|| "writer lease unexpectedly denied".to_string()))
1453        });
1454        blocked_rx
1455            .recv_timeout(Duration::from_secs(5))
1456            .expect("blocked root should reach acquisition hook");
1457
1458        let (free_tx, free_rx) = std::sync::mpsc::channel();
1459        let free_handle = std::thread::spawn(move || {
1460            let result = WriterLease::acquire_shared(
1461                RootCacheDomain::Callgraph,
1462                &free_cache_dir,
1463                "free",
1464                &free_cache_dir,
1465            )
1466            .map_err(|error| error.to_string())
1467            .and_then(|lease| lease.ok_or_else(|| "writer lease unexpectedly denied".to_string()));
1468            free_tx.send(result).unwrap();
1469        });
1470        let free_lease = free_rx
1471            .recv_timeout(Duration::from_secs(5))
1472            .expect("free root should not wait behind another root's acquisition")
1473            .expect("free root should acquire while another root is in acquisition");
1474        assert!(free_lease.verify().unwrap());
1475        free_handle
1476            .join()
1477            .expect("free root thread should not panic");
1478
1479        release_tx.send(()).unwrap();
1480        let blocked_lease = blocked_handle
1481            .join()
1482            .expect("blocked root thread should not panic")
1483            .expect("blocked root should acquire after release");
1484        assert!(blocked_lease.verify().unwrap());
1485    }
1486
1487    #[test]
1488    fn writer_lease_acquire_shared_reuses_single_process_lease_concurrently() {
1489        let dir = tempfile::tempdir().unwrap();
1490        let cache_dir = dir.path().join("inspect").join("project");
1491        configure_artifact_access(&cache_dir, "project", false);
1492        let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
1493        let mut handles = Vec::new();
1494        for _ in 0..8 {
1495            let barrier = std::sync::Arc::clone(&barrier);
1496            let cache_dir = cache_dir.clone();
1497            handles.push(std::thread::spawn(move || {
1498                barrier.wait();
1499                WriterLease::acquire_shared(
1500                    RootCacheDomain::Inspect,
1501                    &cache_dir,
1502                    "project",
1503                    &cache_dir,
1504                )
1505                .map_err(|error| error.to_string())
1506                .and_then(|lease| {
1507                    lease.ok_or_else(|| "writer lease unexpectedly denied".to_string())
1508                })
1509            }));
1510        }
1511
1512        let leases = handles
1513            .into_iter()
1514            .map(|handle| handle.join().unwrap().unwrap())
1515            .collect::<Vec<_>>();
1516        let epoch = leases[0].epoch().to_string();
1517        let path = leases[0].path().to_path_buf();
1518        for lease in &leases {
1519            assert_eq!(lease.epoch(), epoch);
1520            assert_eq!(lease.path(), path.as_path());
1521            assert!(lease.verify().unwrap());
1522        }
1523    }
1524
1525    #[test]
1526    fn nfs_guard_test_seam_fails_closed() {
1527        set_force_network_fs_for_test(true);
1528        assert!(!storage_allows_root_keyed(Path::new(".")).unwrap());
1529        set_force_network_fs_for_test(false);
1530    }
1531}