Skip to main content

aft_base/cache_location/
markers.rs

1//! Reader markers and process-local root residency for cache cleanup.
2
3use super::{canonical_root, pin_cache_path};
4use crate::fs_lock;
5use crate::process_identity::process_start_time_ms;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8#[cfg(test)]
9use std::fs;
10use std::fs::File;
11use std::io;
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicU64, Ordering};
14#[cfg(test)]
15use std::sync::Arc;
16use std::sync::{Mutex, OnceLock};
17use std::time::{Duration, SystemTime, UNIX_EPOCH};
18
19static MARKER_SEQ: AtomicU64 = AtomicU64::new(0);
20struct LiveScope {
21    count: usize,
22    _marker: Option<ReadMarker>,
23}
24static LIVE_SCOPE_KEYS: OnceLock<Mutex<HashMap<(PathBuf, String), LiveScope>>> = OnceLock::new();
25
26/// Read-marker heartbeats refresh no more often than the filesystem lock
27/// heartbeat. Active readers piggyback this on normal read paths instead of
28/// spawning a thread per connection.
29pub const READ_MARKER_TOUCH_INTERVAL_MS: u64 = fs_lock::HEARTBEAT_INTERVAL_MS;
30/// Cross-host markers cannot use local PID liveness, so they expire after the
31/// same conservative 5x stale-heartbeat window used by filesystem locks.
32pub const READ_MARKER_CROSS_HOST_STALE_MS: u64 = fs_lock::STALE_HEARTBEAT_MS * 5;
33// Process start timestamps are not always millisecond-precise across OS APIs.
34// A one-second grace keeps a marker created immediately after process launch
35// attached to that process while still identifying clear PID reuse.
36const PROCESS_START_TIME_GRACE_MS: u64 = 1_000;
37
38/// Track scope keys belonging to roots currently bound in this process. The
39/// inspect sweep snapshots this registry at publication time so a live actor's
40/// cache cannot be mistaken for a reclaimed worktree cache.
41fn live_scope_keys() -> &'static Mutex<HashMap<(PathBuf, String), LiveScope>> {
42    LIVE_SCOPE_KEYS.get_or_init(|| Mutex::new(HashMap::new()))
43}
44
45pub(crate) fn register_live_scope(storage_root: &Path, project_root: &Path) {
46    let storage_root = canonical_root(storage_root);
47    let scope_key = crate::path_identity::project_scope_key(project_root);
48    let mut scopes = match live_scope_keys().lock() {
49        Ok(scopes) => scopes,
50        Err(poisoned) => poisoned.into_inner(),
51    };
52    let marker_root = storage_root.join("retention");
53    let entry = scopes
54        .entry((storage_root, scope_key.clone()))
55        .or_insert_with(|| LiveScope {
56            count: 0,
57            _marker: ReadMarker::create(&marker_root, &scope_key)
58                .map_err(|error| crate::slog_warn!("root residency marker unavailable: {error}"))
59                .ok(),
60        });
61    entry.count += 1;
62}
63
64pub(crate) fn unregister_live_scope(storage_root: &Path, project_root: &Path) {
65    let storage_root = canonical_root(storage_root);
66    let scope_key = crate::path_identity::project_scope_key(project_root);
67    let mut scopes = match live_scope_keys().lock() {
68        Ok(scopes) => scopes,
69        Err(poisoned) => poisoned.into_inner(),
70    };
71    let key = (storage_root, scope_key);
72    if let Some(scope) = scopes.get_mut(&key) {
73        scope.count = scope.count.saturating_sub(1);
74        if scope.count == 0 {
75            scopes.remove(&key);
76        }
77    }
78}
79
80#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
81pub struct ReadMarkerMetadata {
82    pub pid: u32,
83    pub hostname: String,
84    pub created_at_ms: u64,
85    /// Optional acquisition nonce. Ordinary readers leave it out, so their
86    /// serialized marker records are unchanged.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub nonce: Option<String>,
89}
90
91#[derive(Debug)]
92pub struct ReadMarker {
93    path: PathBuf,
94    generation: crate::pinned_dir::PinnedDir,
95    name: std::ffi::OsString,
96    metadata: ReadMarkerMetadata,
97    last_touched_at_ms: AtomicU64,
98}
99
100impl ReadMarker {
101    pub fn create(cache_dir: &Path, generation_label: &str) -> io::Result<Self> {
102        Self::create_inner(cache_dir, generation_label, None)
103    }
104
105    fn create_inner(
106        cache_dir: &Path,
107        generation_label: &str,
108        nonce: Option<String>,
109    ) -> io::Result<Self> {
110        let metadata = ReadMarkerMetadata {
111            pid: std::process::id(),
112            hostname: current_hostname(),
113            created_at_ms: now_ms(),
114            nonce,
115        };
116        let dir = read_marker_dir(cache_dir, generation_label);
117        crate::private_storage::open_dir(cache_dir, &dir).map_err(|error| {
118            crate::io_accounting::at("creating reader marker directory", &dir, error)
119        })?;
120        let seq = MARKER_SEQ.fetch_add(1, Ordering::Relaxed);
121        let path = dir.join(format!(
122            "{}.{}.{}.{}.json",
123            metadata.pid,
124            sanitize_marker_component(&metadata.hostname),
125            metadata.created_at_ms,
126            seq
127        ));
128        let generation = match pin_cache_path(&dir).map_err(|error| {
129            crate::io_accounting::at("pinning reader marker directory", &dir, error)
130        })? {
131            Some(access) => access.directory(false),
132            None => crate::pinned_dir::PinnedDir::repair_open_path(&dir),
133        }
134        .map_err(|error| {
135            crate::io_accounting::at("opening reader marker directory", &dir, error)
136        })?;
137        let name = path.file_name().unwrap().to_os_string();
138        write_marker_file_pinned(&generation, &name, &metadata)
139            .map_err(|error| crate::io_accounting::at("writing reader marker", &path, error))?;
140        let last_touched_at_ms = AtomicU64::new(metadata.created_at_ms);
141        Ok(Self {
142            path,
143            generation,
144            name,
145            metadata,
146            last_touched_at_ms,
147        })
148    }
149
150    pub fn touch(&self) -> io::Result<()> {
151        write_marker_file_pinned(&self.generation, &self.name, &self.metadata).map_err(
152            |error| crate::io_accounting::at("writing reader marker", &self.path, error),
153        )?;
154        self.last_touched_at_ms.store(now_ms(), Ordering::Relaxed);
155        Ok(())
156    }
157
158    pub fn touch_if_due(&self) -> io::Result<()> {
159        let now = now_ms();
160        let last = self.last_touched_at_ms.load(Ordering::Relaxed);
161        if now.saturating_sub(last) < READ_MARKER_TOUCH_INTERVAL_MS {
162            return Ok(());
163        }
164        self.touch()
165    }
166
167    pub fn path(&self) -> &Path {
168        &self.path
169    }
170
171    pub fn metadata(&self) -> &ReadMarkerMetadata {
172        &self.metadata
173    }
174}
175
176impl Drop for ReadMarker {
177    fn drop(&mut self) {
178        let _ = self.generation.repair_remove_file(&self.name);
179    }
180}
181
182#[cfg(unix)]
183#[test]
184fn reader_marker_drop_cannot_unlink_through_a_retargeted_generation_ancestor() {
185    let temp = tempfile::tempdir().unwrap();
186    let cache = temp.path().join("cache");
187    let marker = ReadMarker::create(&cache, "generation").unwrap();
188    let name = marker.path().file_name().unwrap().to_os_string();
189    let outside = temp.path().join("outside");
190    fs::create_dir_all(outside.join("generation")).unwrap();
191    let precious = outside.join("generation").join(&name);
192    fs::write(&precious, "precious").unwrap();
193    let parked = temp.path().join("parked-readers");
194    fs::rename(cache.join("readers"), &parked).unwrap();
195    std::os::unix::fs::symlink(&outside, cache.join("readers")).unwrap();
196    drop(marker);
197    assert_eq!(fs::read_to_string(&precious).unwrap(), "precious");
198    assert!(!parked.join("generation").join(name).exists());
199}
200
201fn read_marker_dir(cache_dir: &Path, generation_label: &str) -> PathBuf {
202    cache_dir.join("readers").join(generation_label)
203}
204
205/// Sweep generation markers through pinned handles without following links.
206#[cfg(any(test, feature = "test-support"))]
207pub fn sweep_all_read_markers(cache_dir: &Path) -> ReadMarkerSweep {
208    let result = crate::pinned_dir::PinnedDir::open(cache_dir).and_then(|dir| {
209        sweep_all_read_markers_pinned(&dir, &mut crate::pinned_dir::RepairBudget::new(), true)
210    });
211    result.unwrap_or(ReadMarkerSweep {
212        protected: true,
213        removed_stale: 0,
214    })
215}
216
217pub(crate) fn sweep_all_read_markers_pinned(
218    cache: &crate::pinned_dir::PinnedDir,
219    budget: &mut crate::pinned_dir::RepairBudget,
220    remove_stale: bool,
221) -> io::Result<ReadMarkerSweep> {
222    let readers = match cache.repair_child(std::ffi::OsStr::new("readers")) {
223        Ok(readers) => readers,
224        Err(error) if error.kind() == io::ErrorKind::NotFound => {
225            return Ok(ReadMarkerSweep::default())
226        }
227        Err(error) => {
228            return Err(io::Error::other(format!(
229                "readers is a symlink or non-directory: {error}"
230            )))
231        }
232    };
233    readers.repair_check_boundary(cache, &[])?;
234    let mut sweep = ReadMarkerSweep::default();
235    for name in readers.repair_names(budget)? {
236        let generation = readers.repair_child_same_mount(&name)?;
237        let result = sweep_marker_generation(&generation, budget, remove_stale)?;
238        sweep.protected |= result.protected;
239        sweep.removed_stale += result.removed_stale;
240    }
241    Ok(sweep)
242}
243
244fn sweep_marker_generation(
245    generation: &crate::pinned_dir::PinnedDir,
246    budget: &mut crate::pinned_dir::RepairBudget,
247    remove_stale: bool,
248) -> io::Result<ReadMarkerSweep> {
249    sweep_marker_generation_cached(
250        generation,
251        budget,
252        remove_stale,
253        now_ms(),
254        &current_hostname(),
255        &mut HashMap::new(),
256    )
257}
258
259/// [`sweep_marker_generation`] with the caller-supplied clock, hostname and
260/// process-start cache. The storage sweep visits many generations per pass
261/// and keeps all three in its pass context instead of re-reading the hostname
262/// and each live pid's start time once per generation.
263fn sweep_marker_generation_cached(
264    generation: &crate::pinned_dir::PinnedDir,
265    budget: &mut crate::pinned_dir::RepairBudget,
266    remove_stale: bool,
267    now: u64,
268    host: &str,
269    started: &mut HashMap<u32, Option<u64>>,
270) -> io::Result<ReadMarkerSweep> {
271    let mut sweep = ReadMarkerSweep::default();
272    let mut names = generation.repair_names(budget)?;
273    names.sort();
274    for name in names {
275        #[cfg(any(test, feature = "test-support"))]
276        BEFORE_MARKER_OPEN.with(|hook| {
277            if let Some(hook) = hook.borrow_mut().as_mut() {
278                hook(&name);
279            }
280        });
281        let file = match generation.repair_read_file(&name) {
282            Ok(file) => file,
283            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
284            Err(error) => return Err(error),
285        };
286        match marker_file_is_protected(file, now, host, started)? {
287            MarkerProtection::Protected => sweep.protected = true,
288            MarkerProtection::Stale | MarkerProtection::Malformed if remove_stale => {
289                match generation.repair_remove_file(&name) {
290                    Ok(()) => sweep.removed_stale += 1,
291                    Err(error) if error.kind() == io::ErrorKind::NotFound => {}
292                    Err(error) => return Err(error),
293                }
294            }
295            _ => {}
296        }
297    }
298    Ok(sweep)
299}
300
301#[cfg(any(test, feature = "test-support"))]
302thread_local! { static BEFORE_MARKER_OPEN: std::cell::RefCell<Option<Box<dyn FnMut(&std::ffi::OsStr)>>> = const { std::cell::RefCell::new(None) }; }
303
304#[test]
305fn reader_census_preserves_live_protection_when_another_marker_exits() {
306    let temp = tempfile::tempdir().unwrap();
307    let marker = ReadMarker::create(temp.path(), "generation").unwrap();
308    let generation = temp.path().join("readers/generation");
309    fs::copy(marker.path(), generation.join("000-live")).unwrap();
310    let departing = generation.join("zzz-exiting");
311    fs::write(&departing, "departing").unwrap();
312    let seen_live = Arc::new(std::sync::atomic::AtomicBool::new(false));
313    let seen = seen_live.clone();
314    BEFORE_MARKER_OPEN.with(|hook| {
315        *hook.borrow_mut() = Some(Box::new(move |name| {
316            if name == "000-live" {
317                seen.store(true, Ordering::SeqCst);
318            }
319            if name == "zzz-exiting" {
320                assert!(seen.load(Ordering::SeqCst));
321                fs::remove_file(&departing).unwrap();
322            }
323        }))
324    });
325    let sweep = read_marker_protection(temp.path(), "generation", false);
326    BEFORE_MARKER_OPEN.with(|hook| hook.borrow_mut().take());
327    assert!(seen_live.load(Ordering::SeqCst));
328    assert!(
329        sweep.protected,
330        "a vanished marker erased a surviving reader's protection: {sweep:?}"
331    );
332}
333
334#[test]
335fn reader_census_does_not_treat_an_unavailable_cache_root_as_empty() {
336    let temp = tempfile::tempdir().unwrap();
337    let missing = temp.path().join("missing-cache-root");
338    assert!(read_marker_protection(&missing, "generation", false).protected);
339}
340
341#[cfg(unix)]
342#[test]
343fn marker_sweep_stays_on_pinned_generation_after_ancestor_swap() {
344    use crate::pinned_dir::{PinnedDir, RepairBudget};
345    let temp = tempfile::tempdir().unwrap();
346    let readers = temp.path().join("readers");
347    let generation = readers.join("generation");
348    fs::create_dir_all(&generation).unwrap();
349    fs::write(generation.join("marker.json"), "malformed-own").unwrap();
350    let outside = temp.path().join("foreign");
351    fs::create_dir_all(outside.join("generation")).unwrap();
352    let precious = outside.join("generation/marker.json");
353    fs::write(&precious, "precious").unwrap();
354    let pinned = PinnedDir::open(&generation).unwrap();
355    let parked = temp.path().join("parked");
356    fs::rename(&readers, &parked).unwrap();
357    std::os::unix::fs::symlink(&outside, &readers).unwrap();
358    let result = sweep_marker_generation(&pinned, &mut RepairBudget::new(), true).unwrap();
359    assert_eq!(result.removed_stale, 1);
360    assert_eq!(fs::read_to_string(precious).unwrap(), "precious");
361    assert!(!parked.join("generation/marker.json").exists());
362}
363
364#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
365pub struct ReadMarkerSweep {
366    pub protected: bool,
367    pub removed_stale: usize,
368}
369
370#[cfg(any(test, feature = "test-support"))]
371pub fn protected_read_marker_exists(cache_dir: &Path, generation_label: &str) -> bool {
372    read_marker_protection(cache_dir, generation_label, false).protected
373}
374
375#[cfg(any(test, feature = "test-support"))]
376pub fn sweep_read_markers(cache_dir: &Path, generation_label: &str) -> ReadMarkerSweep {
377    read_marker_protection(cache_dir, generation_label, true)
378}
379
380// Test hook counting hostname resolutions on this thread. Reset before a
381// marker pass and read after it to prove the pass resolved the hostname
382// once instead of once per generation.
383#[cfg(any(test, feature = "test-support"))]
384thread_local! {
385    static HOSTNAME_RESOLUTIONS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
386}
387
388// Test hook counting process-start-time resolutions on this thread: cache
389// misses while attributing markers, not liveness probes (which are never
390// cached). Reset before a marker pass and read after it to prove repeated
391// markers from one process resolved its start time once.
392#[cfg(any(test, feature = "test-support"))]
393thread_local! {
394    static PROCESS_START_RESOLUTIONS: std::cell::Cell<u64> =
395        const { std::cell::Cell::new(0) };
396}
397
398#[cfg(any(test, feature = "test-support"))]
399fn read_marker_protection(
400    cache_dir: &Path,
401    generation_label: &str,
402    remove_stale: bool,
403) -> ReadMarkerSweep {
404    #[cfg(any(test, feature = "test-support"))]
405    READER_CENSUS.with(|reads| {
406        if let Some(reads) = reads.borrow_mut().as_mut() {
407            *reads
408                .entry((cache_dir.to_path_buf(), generation_label.to_owned()))
409                .or_default() += 1;
410        }
411    });
412    let result = (|| {
413        let cache = crate::pinned_dir::PinnedDir::open(cache_dir)?;
414        let readers = match cache.repair_child_same_mount(std::ffi::OsStr::new("readers")) {
415            Ok(readers) => readers,
416            Err(error) if error.kind() == io::ErrorKind::NotFound => {
417                return Ok(ReadMarkerSweep::default())
418            }
419            Err(error) => return Err(error),
420        };
421        let generation =
422            match readers.repair_child_same_mount(std::ffi::OsStr::new(generation_label)) {
423                Ok(generation) => generation,
424                Err(error) if error.kind() == io::ErrorKind::NotFound => {
425                    return Ok(ReadMarkerSweep::default())
426                }
427                Err(error) => return Err(error),
428            };
429        sweep_marker_generation(
430            &generation,
431            &mut crate::pinned_dir::RepairBudget::new(),
432            remove_stale,
433        )
434    })();
435    match result {
436        Ok(sweep) => sweep,
437        Err(_) => ReadMarkerSweep {
438            protected: true,
439            removed_stale: 0,
440        },
441    }
442}
443
444#[cfg(any(test, feature = "test-support"))]
445thread_local! {
446    static READER_CENSUS: std::cell::RefCell<Option<std::collections::BTreeMap<(PathBuf, String), usize>>> = const { std::cell::RefCell::new(None) };
447}
448
449#[derive(Clone, Copy, Debug, PartialEq, Eq)]
450enum MarkerProtection {
451    Protected,
452    Stale,
453    Malformed,
454}
455
456fn marker_file_is_protected(
457    file: File,
458    now: u64,
459    current_host: &str,
460    started: &mut HashMap<u32, Option<u64>>,
461) -> io::Result<MarkerProtection> {
462    use std::io::Read;
463    let file_metadata = file.metadata()?;
464    // Marker records are tiny. Refuse oversized input rather than allocating
465    // an unbounded buffer or interpreting a partial record as stale.
466    if file_metadata.len() > 32 * 1024 {
467        return Err(io::Error::other("read marker exceeds byte limit"));
468    }
469    let mut bytes = Vec::new();
470    file.take(32 * 1024 + 1).read_to_end(&mut bytes)?;
471    if bytes.len() > 32 * 1024 {
472        return Err(io::Error::other("read marker exceeds byte limit"));
473    }
474    let metadata: ReadMarkerMetadata = match serde_json::from_slice(&bytes) {
475        Ok(metadata) => metadata,
476        Err(_) => return Ok(MarkerProtection::Malformed),
477    };
478    if metadata.hostname != current_host {
479        let mtime_ms = file_metadata
480            .modified()
481            .ok()
482            .map(system_time_ms)
483            .unwrap_or(now);
484        return Ok(
485            if now.saturating_sub(mtime_ms) <= READ_MARKER_CROSS_HOST_STALE_MS {
486                MarkerProtection::Protected
487            } else {
488                MarkerProtection::Stale
489            },
490        );
491    }
492    Ok(
493        if fs_lock::process_alive(metadata.pid) && marker_start_matches(&metadata, started) {
494            MarkerProtection::Protected
495        } else {
496            MarkerProtection::Stale
497        },
498    )
499}
500
501fn marker_start_matches(
502    metadata: &ReadMarkerMetadata,
503    started: &mut HashMap<u32, Option<u64>>,
504) -> bool {
505    // Same-host PID liveness is authoritative for the process instance. When the
506    // OS can tell us the live PID started after this marker was created, the PID
507    // has been reused and the marker belongs to a dead prior process; otherwise
508    // a live PID protects the marker without consulting marker mtime.
509    let started_at_ms = match started.get(&metadata.pid) {
510        Some(cached) => *cached,
511        None => {
512            #[cfg(any(test, feature = "test-support"))]
513            PROCESS_START_RESOLUTIONS.with(|count| count.set(count.get() + 1));
514            let resolved = process_start_time_ms(metadata.pid);
515            started.insert(metadata.pid, resolved);
516            resolved
517        }
518    };
519    // A cached start time only ever over-retains: PIDs are reused with ever
520    // newer start times, so a cached (older) start protects a superset of the
521    // markers the current start would protect. A negative answer is never
522    // cached: liveness itself is re-probed per marker above.
523    started_at_ms
524        .map(|started_at_ms| {
525            started_at_ms
526                <= metadata
527                    .created_at_ms
528                    .saturating_add(PROCESS_START_TIME_GRACE_MS)
529        })
530        .unwrap_or(true)
531}
532
533#[cfg(any(test, feature = "test-support"))]
534pub fn write_marker_file(path: &Path, metadata: &ReadMarkerMetadata) -> io::Result<()> {
535    let parent = crate::pinned_dir::PinnedDir::repair_open_path(
536        path.parent()
537            .ok_or_else(|| io::Error::other("marker has no parent"))?,
538    )?;
539    write_marker_file_pinned(&parent, path.file_name().unwrap(), metadata)
540}
541
542fn write_marker_file_pinned(
543    generation: &crate::pinned_dir::PinnedDir,
544    name: &std::ffi::OsStr,
545    metadata: &ReadMarkerMetadata,
546) -> io::Result<()> {
547    let mut bytes = serde_json::to_vec(metadata).map_err(io::Error::other)?;
548    bytes.push(b'\n');
549    generation.repair_replace_file(name, &bytes)
550}
551
552fn sanitize_marker_component(value: &str) -> String {
553    value
554        .chars()
555        .map(|ch| {
556            if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_') {
557                ch
558            } else {
559                '_'
560            }
561        })
562        .collect()
563}
564
565fn now_ms() -> u64 {
566    system_time_ms(SystemTime::now())
567}
568
569fn system_time_ms(time: SystemTime) -> u64 {
570    time.duration_since(UNIX_EPOCH)
571        .unwrap_or(Duration::ZERO)
572        .as_millis() as u64
573}
574
575#[cfg(unix)]
576fn current_hostname() -> String {
577    #[cfg(any(test, feature = "test-support"))]
578    HOSTNAME_RESOLUTIONS.with(|count| count.set(count.get() + 1));
579    let mut buffer = [0u8; 256];
580    let result = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) };
581    if result == 0 {
582        let len = buffer
583            .iter()
584            .position(|byte| *byte == 0)
585            .unwrap_or(buffer.len());
586        if len > 0 {
587            return String::from_utf8_lossy(&buffer[..len]).into_owned();
588        }
589    }
590    "unknown-host".to_string()
591}
592
593#[cfg(windows)]
594fn current_hostname() -> String {
595    #[cfg(any(test, feature = "test-support"))]
596    HOSTNAME_RESOLUTIONS.with(|count| count.set(count.get() + 1));
597    crate::environment::non_empty_var("COMPUTERNAME").unwrap_or_else(|| "unknown-host".to_string())
598}
599
600#[cfg(all(not(unix), not(windows)))]
601fn current_hostname() -> String {
602    "unknown-host".to_string()
603}
604
605#[cfg(test)]
606mod tests {
607    use super::*;
608    use crate::process_identity::clear_process_start_time_for_test;
609    use crate::process_identity::set_process_start_time_for_test;
610    #[test]
611    fn durability_read_marker_count() {
612        let dir = tempfile::tempdir().unwrap();
613        crate::durability::take();
614        let marker = ReadMarker::create(dir.path(), "current").unwrap();
615        marker.touch().unwrap();
616        assert!(protected_read_marker_exists(dir.path(), "current"));
617        drop(marker);
618        let events = crate::durability::take();
619        assert_eq!(crate::durability::sync_count(&events), 0, "{events:?}");
620    }
621
622    #[test]
623    fn read_marker_file_is_private_and_touchable() {
624        let dir = tempfile::tempdir().unwrap();
625        let marker = ReadMarker::create(dir.path(), "current").unwrap();
626        assert!(marker.path().is_file());
627        marker.touch().unwrap();
628        let bytes = fs::read(marker.path()).unwrap();
629        let parsed: ReadMarkerMetadata = serde_json::from_slice(&bytes).unwrap();
630        assert_eq!(parsed.pid, std::process::id());
631        #[cfg(unix)]
632        {
633            use std::os::unix::fs::PermissionsExt;
634            assert_eq!(
635                fs::metadata(marker.path()).unwrap().permissions().mode() & 0o777,
636                0o600
637            );
638        }
639    }
640
641    #[test]
642    fn same_host_live_marker_ignores_stale_mtime() {
643        let dir = tempfile::tempdir().unwrap();
644        let marker = ReadMarker::create(dir.path(), "current").unwrap();
645        filetime::set_file_mtime(marker.path(), filetime::FileTime::from_unix_time(0, 0)).unwrap();
646
647        assert!(protected_read_marker_exists(dir.path(), "current"));
648    }
649
650    #[test]
651    fn sweep_removes_dead_same_host_marker() {
652        let dir = tempfile::tempdir().unwrap();
653        let marker_path = read_marker_dir(dir.path(), "old").join("dead.json");
654        let metadata = ReadMarkerMetadata {
655            pid: 0,
656            hostname: current_hostname(),
657            created_at_ms: now_ms(),
658            nonce: None,
659        };
660        fs::create_dir_all(marker_path.parent().unwrap()).unwrap();
661        write_marker_file(&marker_path, &metadata).unwrap();
662
663        let sweep = sweep_read_markers(dir.path(), "old");
664
665        assert!(!sweep.protected);
666        assert_eq!(sweep.removed_stale, 1);
667        assert!(!marker_path.exists());
668    }
669
670    #[test]
671    fn sweep_removes_reused_pid_marker_when_created_at_predates_process_start() {
672        let dir = tempfile::tempdir().unwrap();
673        let marker_path = read_marker_dir(dir.path(), "old").join("reused.json");
674        let pid = std::process::id();
675        let metadata = ReadMarkerMetadata {
676            pid,
677            hostname: current_hostname(),
678            created_at_ms: 1_000,
679            nonce: None,
680        };
681        fs::create_dir_all(marker_path.parent().unwrap()).unwrap();
682        write_marker_file(&marker_path, &metadata).unwrap();
683        set_process_start_time_for_test(pid, Some(10_000));
684
685        let sweep = sweep_read_markers(dir.path(), "old");
686        clear_process_start_time_for_test(pid);
687
688        assert!(!sweep.protected);
689        assert_eq!(sweep.removed_stale, 1);
690        assert!(!marker_path.exists());
691    }
692
693    #[test]
694    fn sweep_removes_expired_cross_host_marker() {
695        let dir = tempfile::tempdir().unwrap();
696        let marker_path = read_marker_dir(dir.path(), "old").join("cross-host.json");
697        let metadata = ReadMarkerMetadata {
698            pid: 123,
699            hostname: format!("other-{}", current_hostname()),
700            created_at_ms: now_ms(),
701            nonce: None,
702        };
703        fs::create_dir_all(marker_path.parent().unwrap()).unwrap();
704        write_marker_file(&marker_path, &metadata).unwrap();
705        let stale_time = SystemTime::now()
706            .checked_sub(Duration::from_millis(
707                READ_MARKER_CROSS_HOST_STALE_MS.saturating_add(1_000),
708            ))
709            .unwrap_or(UNIX_EPOCH);
710        filetime::set_file_mtime(
711            &marker_path,
712            filetime::FileTime::from_system_time(stale_time),
713        )
714        .unwrap();
715
716        let sweep = sweep_read_markers(dir.path(), "old");
717
718        assert!(!sweep.protected);
719        assert_eq!(sweep.removed_stale, 1);
720        assert!(!marker_path.exists());
721    }
722}
723
724#[cfg(test)]
725mod residency_tests {
726    use super::*;
727
728    #[test]
729    fn live_scope_marker_is_held_until_its_last_actor_leaves() {
730        let storage = tempfile::tempdir().unwrap();
731        let project = tempfile::tempdir().unwrap();
732        let key = crate::path_identity::project_scope_key(project.path());
733        register_live_scope(storage.path(), project.path());
734        register_live_scope(storage.path(), project.path());
735        let directory = read_marker_dir(&storage.path().join("retention"), &key);
736        let names = std::fs::read_dir(&directory)
737            .unwrap()
738            .map(|entry| entry.unwrap().path())
739            .collect::<Vec<_>>();
740        assert_eq!(names.len(), 1, "actors sharing a root share its marker");
741        unregister_live_scope(storage.path(), project.path());
742        assert!(names[0].exists(), "the other actor still holds the root");
743        unregister_live_scope(storage.path(), project.path());
744        assert!(!names[0].exists(), "the last actor releases the marker");
745    }
746}