Skip to main content

aft_base/
cache_location.rs

1//! Explicit durable/artifact locations and conservative cache-volume repair.
2
3use std::collections::{HashMap, HashSet};
4use std::fs::{self, File};
5use std::io;
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::{Arc, Mutex, OnceLock, Weak};
9use std::time::Duration;
10
11pub mod markers;
12use crate::pinned_dir::{PinnedDir, RepairBudget};
13
14pub struct ReaderFloorHooks {
15    pub prepare: fn(&Path),
16    pub prepare_artifact_root: fn(&Path, &Path),
17}
18
19static READER_FLOOR_HOOKS: OnceLock<ReaderFloorHooks> = OnceLock::new();
20
21pub fn register_reader_floor_hooks(hooks: ReaderFloorHooks) {
22    let _ = READER_FLOOR_HOOKS.set(hooks);
23}
24
25fn reader_floor_hooks(slot: &OnceLock<ReaderFloorHooks>) -> io::Result<&ReaderFloorHooks> {
26    slot.get().ok_or_else(|| {
27        const MESSAGE: &str = "Storage preparation requires reader_floor::register_cache_hooks; no reader-floor check was run";
28        static MISSING_REGISTRATION: std::sync::Once = std::sync::Once::new();
29        MISSING_REGISTRATION.call_once(|| log::error!("{MESSAGE}"));
30        io::Error::other(MESSAGE)
31    })
32}
33
34#[cfg(any(test, feature = "test-support"))]
35pub fn reader_floor_hooks_registered() -> bool {
36    READER_FLOOR_HOOKS.get().is_some()
37}
38
39use serde::{Deserialize, Serialize};
40
41pub const CACHE_DIR_UNAVAILABLE: &str = "cache_dir_unavailable";
42pub const CACHE_DIR_BUSY: &str = "cache_dir_busy";
43/// What agents read when a project's cache folder was contended at setup.
44/// The project keeps working and AFT retries with backoff while it stays bound.
45pub const CACHE_DIR_BUSY_MESSAGE: &str =
46    "cache folder busy: another project was creating it at the same moment; AFT retries automatically";
47pub fn cache_status_code(reason: &str) -> &'static str {
48    if reason.starts_with(CACHE_DIR_BUSY) {
49        CACHE_DIR_BUSY
50    } else {
51        CACHE_DIR_UNAVAILABLE
52    }
53}
54pub const CACHE_DIR_ON_STORAGE_DEVICE: &str = "cache_dir_on_storage_device";
55/// `storage.cache_dir` contains the durable storage root or sits inside it.
56pub const CACHE_DIR_OVERLAPS_STORAGE: &str = "cache_dir_overlaps_storage";
57pub fn unavailable_code(reason: &str) -> &'static str {
58    if reason.starts_with(CACHE_DIR_BUSY) {
59        CACHE_DIR_BUSY
60    } else if reason.starts_with(CACHE_DIR_ON_STORAGE_DEVICE) {
61        CACHE_DIR_ON_STORAGE_DEVICE
62    } else if reason.starts_with(CACHE_DIR_OVERLAPS_STORAGE) {
63        CACHE_DIR_OVERLAPS_STORAGE
64    } else {
65        CACHE_DIR_UNAVAILABLE
66    }
67}
68
69#[derive(Debug)]
70struct ForeignCacheOwner;
71impl std::fmt::Display for ForeignCacheOwner {
72    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        formatter.write_str("artifact root belongs to another storage root")
74    }
75}
76impl std::error::Error for ForeignCacheOwner {}
77fn foreign_owner_error() -> io::Error {
78    io::Error::other(ForeignCacheOwner)
79}
80/// `storage.cache_dir` and the durable storage root overlap: the cache
81/// folder contains durable storage or sits inside it. A configuration error,
82/// never recorded as an unavailable cache root: with cache `/data` and storage
83/// `/data/aft` the cache root would be the storage root itself, and recording
84/// it would refuse every durable write.
85#[derive(Debug)]
86struct StorageOverlap(String);
87impl std::fmt::Display for StorageOverlap {
88    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        formatter.write_str(&self.0)
90    }
91}
92impl std::error::Error for StorageOverlap {}
93fn storage_overlap_error(cache_dir: &Path, storage: &Path) -> io::Error {
94    io::Error::other(StorageOverlap(format!(
95        "{CACHE_DIR_OVERLAPS_STORAGE}: storage.cache_dir {} overlaps the storage root {}; the cache folder must neither contain durable storage nor sit inside it",
96        cache_dir.display(),
97        storage.display()
98    )))
99}
100/// Whether `a` and `b` are the same folder or one contains the other, under
101/// any of their spellings (see [`path_spellings`]).
102fn paths_overlap(a: &Path, b: &Path) -> bool {
103    let b_spellings = path_spellings(b);
104    path_spellings(a).iter().any(|a| {
105        b_spellings
106            .iter()
107            .any(|b| a.starts_with(b) || b.starts_with(a))
108    })
109}
110#[rustfmt::skip]
111test_support_visibility! {
112const OWNER: &str = ".aft-owner.json";
113}
114#[rustfmt::skip]
115test_support_visibility! {
116const IN_USE: &str = ".aft-in-use.lock";
117}
118const DAEMON_USE: &str = "daemon-use.lock";
119static EPOCH: AtomicU64 = AtomicU64::new(1);
120#[derive(Default)]
121struct AccessRegistry {
122    admitted: HashMap<Identity, (PathBuf, Option<String>, u64)>,
123    owners: HashMap<Identity, PathBuf>,
124    // Pathnames can only deny access (missing/replaced/unprepared volumes).
125    // Successful admission always requires an open directory's identity.
126    locations: HashMap<PathBuf, (Option<String>, u64, Option<Identity>)>,
127    // Durable roots configured with a separate `storage.cache_dir`, recorded
128    // whether or not that cache root is currently available. New rebuildable
129    // cache folders must never appear under these roots.
130    split_durable: HashSet<PathBuf>,
131    // Cache roots refused because they overlap durable storage. They are
132    // never given a location entry, not even the "not prepared" placeholder.
133    storage_overlaps: HashSet<PathBuf>,
134}
135static STATUS: OnceLock<Mutex<AccessRegistry>> = OnceLock::new();
136#[cfg(any(test, feature = "test-support"))]
137thread_local! { pub static BEFORE_REPAIR_REMOVE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; }
138#[cfg(any(test, feature = "test-support"))]
139thread_local! { pub static BEFORE_ENROLLMENT_DEVICE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; }
140#[cfg(any(test, feature = "test-support"))]
141thread_local! { pub static BEFORE_OTHER_ROOT_OVERLAP: std::cell::RefCell<Option<(PathBuf, Box<dyn FnOnce()>)>> = const { std::cell::RefCell::new(None) }; }
142#[cfg(any(test, feature = "test-support"))]
143thread_local! { pub static AFTER_CACHE_ROOT_CREATE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; }
144#[cfg(any(test, feature = "test-support"))]
145thread_local! { pub static BEFORE_ROOT_HISTORY_WRITE: std::cell::RefCell<Option<Box<dyn FnOnce() -> io::Result<()>>>> = const { std::cell::RefCell::new(None) }; }
146#[cfg(any(test, feature = "test-support"))]
147thread_local! { pub static AFTER_CACHE_ROOT_RENAME: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; }
148
149/// Both roots travel together whenever an operation mixes artifacts and metadata.
150#[derive(Clone, Debug, PartialEq, Eq, Hash)]
151pub struct StoragePaths {
152    pub durable: PathBuf,
153    pub artifacts: PathBuf,
154}
155impl StoragePaths {
156    pub fn new(durable: PathBuf, artifacts: PathBuf) -> Self {
157        Self { durable, artifacts }
158    }
159    pub fn same(root: &Path) -> Self {
160        Self::new(root.to_path_buf(), root.to_path_buf())
161    }
162    pub fn for_config(config: &crate::config::Config) -> Self {
163        Self::new(
164            crate::storage_path::storage_dir(config.storage_dir.as_deref()),
165            cache_root(config),
166        )
167    }
168}
169
170/// The shared filesystem lock is released only after the last context/config
171/// snapshot using this root is dropped, including snapshots held by workers.
172#[derive(Debug)]
173pub struct CacheLease {
174    #[cfg(any(test, feature = "test-support"))]
175    pub _file: File,
176    #[cfg(not(any(test, feature = "test-support")))]
177    _file: File,
178    root: PinnedDir,
179    root_identity: Identity,
180}
181
182/// Ownership of durable storage retained before cache openers run. Keeping the
183/// root open prevents its identity from being recycled for an unrelated directory.
184#[derive(Debug)]
185pub struct ProcessStorageLease {
186    _file: File,
187    _root: PinnedDir,
188    identity: Identity,
189}
190static PROCESS_STORAGE_LEASES: OnceLock<Mutex<HashMap<Identity, Weak<ProcessStorageLease>>>> =
191    OnceLock::new();
192
193#[derive(Debug)]
194pub struct SpeechServingLease {
195    _file: File,
196    _root: PinnedDir,
197    _storage_use: Arc<ProcessStorageLease>,
198    identity: Identity,
199}
200
201// Ordinary guard drop is not proof that detached speech work has stopped.
202// Managed runtimes explicitly remove their matching anchor after quiescence;
203// every other owner remains pinned until process exit.
204static SPEECH_SERVING_LEASES: OnceLock<Mutex<HashMap<Identity, Arc<SpeechServingLease>>>> =
205    OnceLock::new();
206impl CacheLease {
207    pub fn same_root(&self, other: &Self) -> bool {
208        self.root_identity == other.root_identity
209    }
210    pub fn root_key(&self) -> (u64, u64) {
211        (self.root_identity.device, self.root_identity.inode)
212    }
213}
214impl PartialEq for CacheLease {
215    fn eq(&self, other: &Self) -> bool {
216        self.same_root(other)
217    }
218}
219impl Eq for CacheLease {}
220
221#[rustfmt::skip]
222test_support_visibility! {
223#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
224#[serde(deny_unknown_fields)]
225struct Identity {
226    #[cfg(any(test, feature = "test-support"))]
227    pub device: u64,
228    #[cfg(not(any(test, feature = "test-support")))]
229    device: u64,
230    #[cfg(any(test, feature = "test-support"))]
231    pub inode: u64,
232    #[cfg(not(any(test, feature = "test-support")))]
233    inode: u64,
234}
235}
236#[rustfmt::skip]
237test_support_visibility! {
238fn identity(path: &Path) -> io::Result<Identity> {
239    #[cfg(any(test, feature = "test-support"))]
240    if let Some((device, inode)) =
241        crate::pinned_dir::REPAIR_IDENTITIES.with(|ids| ids.borrow().get(path).copied())
242    {
243        return Ok(Identity { device, inode });
244    }
245    crate::dir_identity::dir_identity(path)
246        .map(|(device, inode)| Identity { device, inode })
247        .ok_or_else(|| io::Error::other(format!("cannot identify directory {}", path.display())))
248}
249}
250fn real_directory(path: &Path) -> io::Result<Identity> {
251    let metadata = fs::symlink_metadata(path)?;
252    if metadata.file_type().is_symlink() {
253        return Err(io::Error::other("root is a symlink"));
254    }
255    if !metadata.is_dir() {
256        return Err(io::Error::other("root is not a directory"));
257    }
258    identity(path)
259}
260
261#[rustfmt::skip]
262test_support_visibility! {
263#[derive(Serialize, Deserialize)]
264struct ParentIdentity {
265    #[cfg(any(test, feature = "test-support"))]
266    pub path: PathBuf,
267    #[cfg(not(any(test, feature = "test-support")))]
268    path: PathBuf,
269    #[cfg(any(test, feature = "test-support"))]
270    pub identity: Identity,
271    #[cfg(not(any(test, feature = "test-support")))]
272    identity: Identity,
273    #[cfg(any(test, feature = "test-support"))]
274    /// The spelling the user configured, when it differs from `path` because
275    /// it runs through a symlink. It must keep naming the same directory.
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub configured: Option<PathBuf>,
278    #[cfg(not(any(test, feature = "test-support")))]
279    /// The spelling the user configured, when it differs from `path` because
280    /// it runs through a symlink. It must keep naming the same directory.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    configured: Option<PathBuf>,
283    #[cfg(any(test, feature = "test-support"))]
284    #[serde(default)]
285    pub volume_uuid: Option<String>,
286    #[cfg(not(any(test, feature = "test-support")))]
287    #[serde(default)]
288    volume_uuid: Option<String>,
289}
290}
291#[rustfmt::skip]
292test_support_visibility! {
293#[derive(Serialize, Deserialize)]
294struct ParentState {
295    #[cfg(any(test, feature = "test-support"))]
296    pub version: u32,
297    #[cfg(not(any(test, feature = "test-support")))]
298    version: u32,
299    #[cfg(any(test, feature = "test-support"))]
300    pub parents: Vec<ParentIdentity>,
301    #[cfg(not(any(test, feature = "test-support")))]
302    parents: Vec<ParentIdentity>,
303}
304}
305#[rustfmt::skip]
306test_support_visibility! {
307fn parent_state_path(storage: &Path) -> PathBuf {
308    storage.join("retention/cache-parents.json")
309}
310}
311#[rustfmt::skip]
312test_support_visibility! {
313fn read_parent_state(storage: &Path) -> io::Result<ParentState> {
314    match fs::read(parent_state_path(storage)) {
315        Ok(bytes) => {
316            let state: ParentState = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
317            if state.version != 1 {
318                return Err(io::Error::other("unsupported cache parent identity state"));
319            }
320            Ok(state)
321        }
322        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(ParentState {
323            version: 1,
324            parents: Vec::new(),
325        }),
326        Err(error) => Err(error),
327    }
328}
329}
330fn validate_saved_parent(
331    storage: &Path,
332    configured: &Path,
333    parent: &Path,
334    actual: Identity,
335) -> io::Result<()> {
336    if read_parent_state(storage)?.parents.iter().any(|saved| {
337        ((saved.path == parent
338            || saved.path == configured
339            || saved.configured.as_deref() == Some(configured))
340            && saved.identity != actual)
341            || saved.identity == actual
342                && saved.volume_uuid != crate::volume::cache_volume_uuid(parent)
343    }) {
344        return Err(io::Error::other("cache_dir is not the volume it was"));
345    }
346    Ok(())
347}
348fn remember_parent(
349    storage: &Path,
350    configured: &Path,
351    parent: &Path,
352    actual: Identity,
353) -> io::Result<()> {
354    let _lock = crate::fs_lock::try_acquire(
355        &storage.join("retention/cache-parents.lock"),
356        Duration::from_secs(5),
357    )
358    .map_err(io::Error::other)?;
359    validate_saved_parent(storage, configured, parent, actual)?;
360    let mut state = read_parent_state(storage)?;
361    let configured = (configured != parent).then(|| configured.to_path_buf());
362    let known = state.parents.iter().any(|saved| {
363        saved.identity == actual && (configured.is_none() || saved.configured == configured)
364    });
365    if !known {
366        state.parents.push(ParentIdentity {
367            path: parent.to_path_buf(),
368            identity: actual,
369            configured,
370            volume_uuid: crate::volume::cache_volume_uuid(parent),
371        });
372        crate::durability::atomic_write(
373            &parent_state_path(storage),
374            &serde_json::to_vec(&state).map_err(io::Error::other)?,
375            crate::durability::AtomicWriteDurability::FileAndDirectory,
376        )?;
377    }
378    Ok(())
379}
380
381#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
382fn verify_mounted_parent_under(
383    parent: &Path,
384    actual: Identity,
385    volumes: &Path,
386    system_devices: &[u64],
387) -> io::Result<()> {
388    let volumes_id = real_directory(volumes)?;
389    if actual == volumes_id {
390        return Err(io::Error::other("cache_dir cannot be /Volumes"));
391    }
392    let mut directory = parent;
393    while let Some(ancestor) = directory.parent() {
394        if identity(ancestor)? == volumes_id {
395            if system_devices.contains(&actual.device) {
396                return Err(io::Error::other(format!(
397                    "volume {} is not mounted",
398                    directory.file_name().unwrap_or_default().to_string_lossy()
399                )));
400            }
401            break;
402        }
403        directory = ancestor;
404    }
405    Ok(())
406}
407#[cfg(any(test, feature = "test-support"))]
408thread_local! { pub static MOUNT_TEST_SEAM: std::cell::RefCell<Option<(PathBuf, Vec<u64>)>> = const { std::cell::RefCell::new(None) }; }
409fn check_parent_mount(parent: &Path, actual: Identity) -> io::Result<()> {
410    #[cfg(any(test, feature = "test-support"))]
411    if let Some((volumes, devices)) = MOUNT_TEST_SEAM.with(|seam| seam.borrow().clone()) {
412        return verify_mounted_parent_under(parent, actual, &volumes, &devices);
413    }
414    #[cfg(target_os = "macos")]
415    {
416        let mut devices = vec![identity(Path::new("/"))?.device];
417        let data = Path::new("/System/Volumes/Data");
418        if data.try_exists()? {
419            devices.push(identity(data)?.device);
420        }
421        verify_mounted_parent_under(parent, actual, Path::new("/Volumes"), &devices)
422    }
423    #[cfg(not(target_os = "macos"))]
424    {
425        let _ = (parent, actual);
426        Ok(())
427    }
428}
429
430pub fn cache_root(config: &crate::config::Config) -> PathBuf {
431    let root = config
432        .cache_dir
433        .as_ref()
434        .map(|root| root.join("aft"))
435        .unwrap_or_else(|| crate::storage_path::storage_dir(config.storage_dir.as_deref()));
436    if config.cache_dir.is_some() {
437        crate::project_content::register_storage_root(&root);
438        // A root that is, contains or sits inside durable storage never gets a
439        // location entry: an entry denies every path under it, durable
440        // writes included.
441        let storage = crate::storage_path::storage_dir(config.storage_dir.as_deref());
442        let mut registry = STATUS
443            .get_or_init(Default::default)
444            .lock()
445            .unwrap_or_else(|error| error.into_inner());
446        if registry.storage_overlaps.contains(&root)
447            || root.starts_with(&storage)
448            || storage.starts_with(&root)
449        {
450            return root;
451        }
452        registry.locations.entry(root.clone()).or_insert_with(|| {
453            (
454                Some("configured cache root has not been prepared".into()),
455                0,
456                None,
457            )
458        });
459    }
460    root
461}
462pub fn cache_unavailable(config: &crate::config::Config) -> Option<String> {
463    cache_unavailable_for_root(config, &cache_root(config))
464}
465/// [`cache_unavailable`] against an already-resolved cache root. The health
466/// rollup resolves each distinct root once per tick and reuses it here so a
467/// many-context tick does not re-resolve the same root once per context.
468pub fn cache_unavailable_for_root(config: &crate::config::Config, root: &Path) -> Option<String> {
469    if let Some(reason) = &config.cache_config_unknown {
470        return Some(format!("cache_dir_config_unknown: {reason}"));
471    }
472    if let Some(reason) = &config.cache_unavailable {
473        return Some(reason.clone());
474    }
475    config.cache_dir.as_ref()?;
476    if config.cache_epoch == 0 || config.cache_lease.is_none() {
477        return Some("configured cache root has not been prepared".into());
478    }
479    config.cache_unavailable.clone().or_else(|| {
480        let (reason, epoch, _) = status(root);
481        reason.or_else(|| {
482            (epoch != config.cache_epoch).then(|| "cache root transition pending configure".into())
483        })
484    })
485}
486/// The storage root whose identity records key the artifacts kept under
487/// `storage`.
488///
489/// A cache root prepared for `storage.cache_dir` holds rebuildable artifacts
490/// only. A project's saved identity record and artifact-key memo stay on the
491/// durable storage root that owns the cache root, and configure memoizes the
492/// project's key under that durable root. Readers often name the cache root,
493/// because that is where they open the artifacts; resolving the identity
494/// there would find no record and could pick a different key, which names
495/// folders configure never wrote. So a prepared cache root resolves to its
496/// durable owner. Every other path is returned as given, which includes every
497/// root while no `cache_dir` is configured: those keys do not change.
498pub fn identity_storage_root(storage: &Path) -> std::borrow::Cow<'_, Path> {
499    let registry = STATUS
500        .get_or_init(Default::default)
501        .lock()
502        .unwrap_or_else(|error| error.into_inner());
503    let owner = registry
504        .locations
505        .get(storage)
506        .and_then(|(_, _, identity)| identity.as_ref())
507        .and_then(|identity| registry.owners.get(identity));
508    match owner {
509        Some(durable) if durable != storage => std::borrow::Cow::Owned(durable.clone()),
510        _ => std::borrow::Cow::Borrowed(storage),
511    }
512}
513
514/// The same location as `path`, spelled under the durable storage root that
515/// owns the prepared `storage.cache_dir` cache root containing it, or `None`
516/// when `path` is not inside such a cache root (always the case while no
517/// `cache_dir` is configured).
518///
519/// Version-floor refusals belong to the storage root an artifact is reached
520/// through. A cache root on another volume is never reached through its
521/// storage root, so this gives its artifacts the route they would have if
522/// the cache were linked under that storage root: `<cache>/aft/index/k` reads
523/// as `<storage>/index/k`. That route is only a name for ownership; nothing
524/// opens it.
525pub fn durable_route(path: &Path) -> Option<PathBuf> {
526    let registry = STATUS
527        .get_or_init(Default::default)
528        .lock()
529        .unwrap_or_else(|error| error.into_inner());
530    registry
531        .locations
532        .iter()
533        .filter_map(|(root, (_, _, identity))| {
534            let durable = registry.owners.get(identity.as_ref()?)?;
535            let relative = path.strip_prefix(root).ok()?;
536            (durable != root).then(|| (root.components().count(), durable.join(relative)))
537        })
538        .max_by_key(|(depth, _)| *depth)
539        .map(|(_, route)| route)
540}
541fn status(root: &Path) -> (Option<String>, u64, Option<Identity>) {
542    STATUS
543        .get_or_init(Default::default)
544        .lock()
545        .unwrap_or_else(|error| error.into_inner())
546        .locations
547        .get(root)
548        .cloned()
549        .unwrap_or_default()
550}
551/// Give the configured spelling of an artifact root the same status as the
552/// resolved root, so paths built from either spelling are admitted or refused
553/// alike. Only the resolved root is recorded as the admitted identity.
554fn mirror_status(configured: Option<&Path>, root: &Path) {
555    let Some(configured) = configured.filter(|configured| *configured != root) else {
556        return;
557    };
558    let mut roots = STATUS
559        .get_or_init(Default::default)
560        .lock()
561        .unwrap_or_else(|error| error.into_inner());
562    if let Some(entry) = roots.locations.get(root).cloned() {
563        roots.locations.insert(configured.to_path_buf(), entry);
564    }
565}
566#[rustfmt::skip]
567test_support_visibility! {
568fn set_status(root: &Path, reason: Option<String>, identity: Option<Identity>) -> u64 {
569    let mut roots = STATUS
570        .get_or_init(Default::default)
571        .lock()
572        .unwrap_or_else(|error| error.into_inner());
573    if roots
574        .locations
575        .get(root)
576        .is_none_or(|(old, _, old_identity)| {
577            *old != reason || identity.is_some_and(|id| Some(id) != *old_identity)
578        })
579    {
580        let identity = identity.or_else(|| roots.locations.get(root).and_then(|(_, _, id)| *id));
581        let epoch = EPOCH.fetch_add(1, Ordering::Relaxed);
582        roots
583            .locations
584            .insert(root.to_path_buf(), (reason.clone(), epoch, identity));
585        if let Some(id) = identity {
586            roots
587                .admitted
588                .insert(id, (root.to_path_buf(), reason, epoch));
589        }
590    }
591    roots.locations[root].1
592}
593}
594
595/// Creation below a configured artifact root must use non-recursive mkdirs:
596/// an admitted worker must not recreate an unmounted/missing root later.
597fn registered_cache_path(path: &Path) -> io::Result<Option<(PathBuf, Identity)>> {
598    let (admitted, locations) = {
599        let roots = STATUS
600            .get_or_init(Default::default)
601            .lock()
602            .unwrap_or_else(|error| error.into_inner());
603        (roots.admitted.clone(), roots.locations.clone())
604    };
605    let mut unprepared = false;
606    // Inspect enclosing identities before descendants, including case/bind
607    // aliases, so a nested namespace cannot bypass its enclosing boundary.
608    for ancestor in path.ancestors().collect::<Vec<_>>().into_iter().rev() {
609        match fs::metadata(ancestor) {
610            Ok(metadata) if metadata.is_dir() => {
611                let actual = identity(ancestor)?;
612                if let Some((root, reason, _)) = admitted.get(&actual) {
613                    // An inode can be reused after a retired temporary volume
614                    // disappears. It grants nothing without its namespace or
615                    // its still-current registered pathname.
616                    if identity(root).ok() != Some(actual)
617                        && !ancestor.join(OWNER).try_exists()?
618                        && !path.starts_with(root)
619                    {
620                        continue;
621                    }
622                    let checked = (|| {
623                        if let Some(reason) = reason {
624                            return Err(io::Error::other(reason.clone()));
625                        }
626                        if real_directory(root)? != actual {
627                            return Err(io::Error::other("artifact root identity changed"));
628                        }
629                        for ancestor in root.ancestors() {
630                            if fs::symlink_metadata(ancestor)?.file_type().is_symlink() {
631                                return Err(io::Error::other(
632                                    "artifact root has a symlink ancestor",
633                                ));
634                            }
635                        }
636                        Ok(())
637                    })();
638                    if let Err(error) = checked {
639                        set_status(root, Some(error.to_string()), Some(actual));
640                        return Err(io::Error::other(format!(
641                            "{CACHE_DIR_UNAVAILABLE}: {} ({error})",
642                            root.display()
643                        )));
644                    }
645                    return Ok(Some((ancestor.to_path_buf(), actual)));
646                }
647                unprepared |= ancestor.join(OWNER).try_exists()?;
648                unprepared |= locations.keys().any(|root| {
649                    root.parent().and_then(|parent| identity(parent).ok()) == Some(actual)
650                        && path
651                            .strip_prefix(ancestor)
652                            .ok()
653                            .and_then(|rest| rest.components().next())
654                            .is_some_and(|component| {
655                                component
656                                    .as_os_str()
657                                    .to_string_lossy()
658                                    .eq_ignore_ascii_case("aft")
659                            })
660                });
661            }
662            Ok(_) => {}
663            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
664            Err(error) => return Err(error),
665        }
666    }
667    if let Some((_, (reason, _, _))) = locations.iter().find(|(root, _)| path.starts_with(root)) {
668        return Err(io::Error::other(format!(
669            "{CACHE_DIR_UNAVAILABLE}: {}",
670            reason
671                .as_deref()
672                .unwrap_or("artifact root identity changed")
673        )));
674    }
675    if unprepared {
676        return Err(io::Error::other(format!(
677            "{CACHE_DIR_UNAVAILABLE}: unprepared artifact namespace"
678        )));
679    }
680    Ok(None)
681}
682
683/// A cache pathname is only a label. Keep the admitted directory open while
684/// resolving descendants so replacement ancestors cannot redirect an operation.
685pub struct CachePath {
686    pub(crate) root: PinnedDir,
687    pub(crate) relative: PathBuf,
688}
689impl CachePath {
690    pub fn directory(&self, create: bool) -> io::Result<PinnedDir> {
691        self.root.repair_descendant(&self.relative, create)
692    }
693    #[rustfmt::skip]
694    test_support_visibility! {
695    pub(crate) fn parent(&self) -> io::Result<(PinnedDir, std::ffi::OsString)> {
696        let name = self
697            .relative
698            .file_name()
699            .ok_or_else(|| io::Error::other("cache file requires a child name"))?
700            .to_os_string();
701        let parent = self
702            .root
703            .repair_descendant(self.relative.parent().unwrap_or(Path::new("")), false)?;
704        Ok((parent, name))
705    }
706
707    }
708}
709
710pub fn pin_cache_path(path: &Path) -> io::Result<Option<CachePath>> {
711    // A nested alias must not replace the enclosing registered namespace as
712    // the admission boundary. The pathname selects a candidate; its open
713    // handle still has to match that registration before it grants access.
714    let lexical = STATUS
715        .get_or_init(Default::default)
716        .lock()
717        .unwrap_or_else(|error| error.into_inner())
718        .locations
719        .iter()
720        .filter(|(root, _)| path.starts_with(root))
721        .max_by_key(|(root, _)| root.components().count())
722        .map(|(root, (reason, _, expected))| (root.clone(), reason.clone(), *expected));
723    let selected = if let Some((root, reason, expected)) = lexical {
724        if let Some(reason) = reason {
725            return Err(io::Error::other(format!(
726                "{CACHE_DIR_UNAVAILABLE}: {reason}"
727            )));
728        }
729        Some((
730            root,
731            expected.ok_or_else(|| io::Error::other("unprepared artifact namespace"))?,
732        ))
733    } else {
734        registered_cache_path(path)?
735    };
736    let Some((root_path, expected)) = selected else {
737        return Ok(None);
738    };
739    let root = PinnedDir::repair_open_path(&root_path)?;
740    if pinned_identity(&root)? != expected {
741        return Err(io::Error::other(
742            "cache_dir_unavailable: admitted artifact root identity changed while pinning",
743        ));
744    }
745    let relative = path
746        .strip_prefix(&root_path)
747        .map_err(io::Error::other)?
748        .to_path_buf();
749    Ok(Some(CachePath { root, relative }))
750}
751
752pub fn check_cache_access(path: &Path) -> io::Result<Option<PathBuf>> {
753    let Some(access) = pin_cache_path(path)? else {
754        return Ok(None);
755    };
756    access.root.repair_validate_descendants(&access.relative)?;
757    Ok(Some(access.root.path().to_path_buf()))
758}
759
760/// Prepare a folder that a third-party library will write into by pathname,
761/// such as the hf-hub model downloader. Those libraries create any missing
762/// folders themselves with a recursive mkdir, so if the cache volume vanished
763/// after configure and left a writable mount point behind, handing them the
764/// saved pathname would rebuild the cache path on the main disk. Call this
765/// immediately before the hand-off.
766///
767/// Under a configured cache root this applies the same admission AFT's own
768/// cache writes use: the root must still be the enrolled directory (same
769/// device and inode) and the missing folders below it are created through the
770/// pinned root, never recreating the root itself. Outside a cache root, a write
771/// on durable storage whose caches were moved to `storage.cache_dir` is
772/// refused. A refused root reports the `cache_dir_unavailable` reason.
773pub fn prepare_third_party_cache_dir(path: &Path) -> Result<(), String> {
774    let checked = (|| -> io::Result<()> {
775        if let Some(access) = pin_cache_path(path)? {
776            access.directory(true)?;
777            return Ok(());
778        }
779        refuse_durable_cache_write(path)
780    })();
781    checked.map_err(|error| {
782        let message = error.to_string();
783        if message.starts_with(CACHE_DIR_UNAVAILABLE)
784            || message.starts_with(CACHE_WRITE_ON_DURABLE_STORAGE)
785        {
786            message
787        } else {
788            format!("{CACHE_DIR_UNAVAILABLE}: {} ({message})", path.display())
789        }
790    })
791}
792
793pub const CACHE_WRITE_ON_DURABLE_STORAGE: &str = "cache_write_on_durable_storage";
794
795/// Spellings under which a durable root is recognised: as configured, and
796/// with its existing prefix resolved (for example macOS `/var` -> `/private/var`).
797fn path_spellings(path: &Path) -> Vec<PathBuf> {
798    let mut spellings = vec![path.to_path_buf()];
799    let mut existing = path;
800    let mut rest = Vec::new();
801    while !existing.exists() {
802        let (Some(parent), Some(name)) = (existing.parent(), existing.file_name()) else {
803            return spellings;
804        };
805        rest.push(name.to_os_string());
806        existing = parent;
807    }
808    if let Ok(mut resolved) = fs::canonicalize(existing) {
809        resolved.extend(rest.iter().rev());
810        if resolved != path {
811            spellings.push(resolved);
812        }
813    }
814    spellings
815}
816
817fn record_split_durable(storage: &Path, split: bool) {
818    let mut status = STATUS
819        .get_or_init(Default::default)
820        .lock()
821        .unwrap_or_else(|error| error.into_inner());
822    for spelling in path_spellings(storage) {
823        if split {
824            status.split_durable.insert(spelling);
825        } else {
826            status.split_durable.remove(&spelling);
827        }
828    }
829}
830
831/// Refuse to create a new rebuildable cache folder or database on a durable
832/// root whose caches were moved to `storage.cache_dir`. Such a write would
833/// silently put cache data back on the volume the setting is meant to relieve,
834/// even while the configured cache volume is unavailable. Entries that already
835/// exist there (caches from before the setting) stay readable and removable.
836pub(crate) fn refuse_new_durable_cache_entry(path: &Path) -> io::Result<()> {
837    if fs::symlink_metadata(path).is_ok() {
838        return Ok(());
839    }
840    refuse_durable_cache_write(path)
841}
842
843/// Existing legacy cache databases may be inspected or removed, but a writable
844/// open could grow them and create WAL/SHM on the primary volume again.
845pub fn refuse_durable_cache_write(path: &Path) -> io::Result<()> {
846    let split = STATUS
847        .get_or_init(Default::default)
848        .lock()
849        .unwrap_or_else(|error| error.into_inner())
850        .split_durable
851        .clone();
852    if split.is_empty() {
853        return Ok(());
854    }
855    for spelling in path_spellings(path) {
856        for durable in &split {
857            let Ok(relative) = spelling.strip_prefix(durable) else {
858                continue;
859            };
860            let domain = relative
861                .components()
862                .next()
863                .and_then(|component| match component {
864                    std::path::Component::Normal(name) => name.to_str(),
865                    _ => None,
866                });
867            if domain.is_some_and(|domain| CACHE_DOMAINS.contains(&domain)) {
868                return Err(io::Error::new(
869                    io::ErrorKind::PermissionDenied,
870                    format!(
871                        "{CACHE_WRITE_ON_DURABLE_STORAGE}: refusing to write {} on durable storage while its caches are split or their location is unknown",
872                        path.display()
873                    ),
874                ));
875            }
876        }
877    }
878    Ok(())
879}
880pub fn unavailable_warning(path: &Path, reason: &str) -> crate::config_resolve::ConfigWarning {
881    let code = unavailable_code(reason);
882    crate::config_resolve::ConfigWarning {
883        code,
884        key: "storage.cache_dir",
885        tier: "user".into(),
886        value: path.display().to_string(),
887        message: if code == CACHE_DIR_BUSY {
888            CACHE_DIR_BUSY_MESSAGE.to_string()
889        } else {
890            format!("storage.cache_dir {} is unavailable ({reason}); AFT is running without its caches until it is back.", path.display())
891        },
892    }
893}
894
895#[rustfmt::skip]
896test_support_visibility! {
897
898fn open_use_lock(root: &PinnedDir) -> io::Result<File> {
899    root.repair_coordination_file(std::ffi::OsStr::new(IN_USE))
900}
901}
902#[rustfmt::skip]
903test_support_visibility! {
904fn pinned_identity(root: &PinnedDir) -> io::Result<Identity> {
905    let (device, inode) = root.directory_identity()?;
906    Ok(Identity { device, inode })
907}
908}
909#[rustfmt::skip]
910test_support_visibility! {
911/// A configured durable root may be a symlink. Resolve it at the operation's
912/// boundary and retain the directory handle for every ownership comparison.
913/// Artifact descendants still use no-follow walks, not this resolver.
914fn pin_storage_root(storage: &Path) -> io::Result<PinnedDir> {
915    let resolved = crate::pinned_dir::resolve_configured_root(storage)?;
916    PinnedDir::repair_open_path(&resolved)
917}
918}
919/// How long preparation waits for a conflicting exclusive hold on a root's
920/// use lock (cache cleanup takes one briefly) before reporting the root busy.
921#[cfg(not(any(test, feature = "test-support")))]
922const USE_LOCK_WAIT: Duration = Duration::from_secs(2);
923#[cfg(any(test, feature = "test-support"))]
924const USE_LOCK_WAIT: Duration = Duration::from_millis(400);
925
926fn take_shared_pinned(root: PinnedDir) -> io::Result<Arc<CacheLease>> {
927    let file = open_use_lock(&root).map_err(|error| {
928        // A bounded create/reopen failure already carries its operation, path
929        // and retryable type; do not flatten it into a cache-folder failure.
930        #[cfg(unix)]
931        if error
932            .get_ref()
933            .is_some_and(|error| error.is::<crate::pinned_dir::CoordinationCreateContended>())
934        {
935            return error;
936        }
937        io::Error::new(
938            error.kind(),
939            format!(
940                "open shared use lock {}: {error}",
941                root.path().join(IN_USE).display()
942            ),
943        )
944    })?;
945    let deadline = std::time::Instant::now() + USE_LOCK_WAIT;
946    loop {
947        match file.try_lock_shared() {
948            Ok(()) => break,
949            Err(std::fs::TryLockError::WouldBlock) if std::time::Instant::now() < deadline => {
950                std::thread::sleep(Duration::from_millis(20));
951            }
952            Err(error) => return Err(storage_lock_error(error)),
953        }
954    }
955    let root_identity = pinned_identity(&root)?;
956    Ok(Arc::new(CacheLease {
957        _file: file,
958        root_identity,
959        root,
960    }))
961}
962
963fn has_ancestor(path: &Path, ancestor: Identity) -> io::Result<bool> {
964    let mut current = fs::canonicalize(path)?;
965    loop {
966        if identity(&current)? == ancestor {
967            return Ok(true);
968        }
969        if !current.pop() {
970            return Ok(false);
971        }
972    }
973}
974fn overlap(left: &Path, right: &Path) -> io::Result<bool> {
975    Ok(has_ancestor(left, identity(right)?)? || has_ancestor(right, identity(left)?)?)
976}
977
978pub fn prepare_cache_root(
979    config: &mut crate::config::Config,
980) -> Option<crate::config_resolve::ConfigWarning> {
981    prepare_cache_root_with_floor_hooks(config, &READER_FLOOR_HOOKS)
982}
983
984fn prepare_cache_root_with_floor_hooks(
985    config: &mut crate::config::Config,
986    floor_hooks: &OnceLock<ReaderFloorHooks>,
987) -> Option<crate::config_resolve::ConfigWarning> {
988    let storage = crate::storage_path::storage_dir(config.storage_dir.as_deref());
989    if let Some(reason) = &config.cache_config_unknown {
990        // The cache configuration is unknown. Treat durable storage as split
991        // so database and directory creation there stays blocked until a valid
992        // configuration explicitly selects the cache location.
993        record_split_durable(&storage, true);
994        config.cache_unavailable = Some(format!("cache_dir_config_unknown: {reason}"));
995        config.cache_lease = None;
996        return Some(crate::config_resolve::ConfigWarning {
997            code: "cache_dir_config_unknown", key: "storage.cache_dir", tier: "user".into(), value: "unknown".into(),
998            message: format!("User configuration is unreadable or invalid ({reason}); AFT is running without its caches until the configuration is valid."),
999        });
1000    }
1001    // A prepared config holds the resolved directory in `cache_dir`. Recheck
1002    // the spelling the user configured instead, so a symlink in it that now
1003    // names another directory is refused rather than silently ignored. A
1004    // `cache_dir` changed since preparation is a new setting and is used as is.
1005    let requested = match (&config.cache_dir, &config.cache_dir_configured) {
1006        (Some(current), Some(configured)) if *current == configured.resolved => {
1007            Some(configured.spelling.clone())
1008        }
1009        (current, _) => current.clone(),
1010    };
1011    if requested.is_none() && !config.cache_dir_opt_out {
1012        // A storage root that once kept its caches on another volume must not
1013        // quietly start writing them to its own volume again because the
1014        // setting went missing (a typo, a deleted user file). Only an
1015        // explicit `main_disk` choice moves caches back.
1016        let message = match previous_cache_parent(&storage) {
1017            Ok(None) => None,
1018            Ok(Some(parent)) => Some(format!(
1019                "storage.cache_dir is not set, but this storage root's caches live on {}; set it again, or set \"cache_dir\": {{\"kind\": \"main_disk\"}} to move caches back to the primary disk.",
1020                parent.display()
1021            )),
1022            Err(error) => Some(format!(
1023                "storage.cache_dir is not set, and this storage root's cache records cannot be read ({error}); set it again, or set \"cache_dir\": {{\"kind\": \"main_disk\"}} to move caches back to the primary disk."
1024            )),
1025        };
1026        if let Some(message) = message {
1027            record_split_durable(&storage, true);
1028            config.cache_lease = None;
1029            config.cache_unavailable = Some(format!("{CACHE_DIR_UNAVAILABLE}: {message}"));
1030            return Some(crate::config_resolve::ConfigWarning {
1031                code: CACHE_DIR_UNAVAILABLE,
1032                key: "storage.cache_dir",
1033                tier: "user".into(),
1034                value: "unset".into(),
1035                message,
1036            });
1037        }
1038    }
1039    record_split_durable(&storage, requested.is_some());
1040    // The artifact root under the spelling the user configured. It differs
1041    // from the resolved root when that spelling runs through a symlink.
1042    let configured_root = requested.as_ref().map(|parent| parent.join("aft"));
1043    let mut root = cache_root(config);
1044    let result = (|| -> io::Result<Arc<CacheLease>> {
1045        let floor_hooks = reader_floor_hooks(floor_hooks)?;
1046        if let Some(parent) = requested.as_ref() {
1047            if !parent.is_absolute() {
1048                return Err(io::Error::other("path must be absolute after ~ expansion"));
1049            }
1050            // Refuse an overlap with durable storage before anything about
1051            // this cache folder is registered or created.
1052            if paths_overlap(parent, &storage) {
1053                return Err(storage_overlap_error(parent, &storage));
1054            }
1055            // A configured path may run through symlinks the user chose (macOS
1056            // /var, a symlinked home, an alias of a /Volumes mount). Resolve it
1057            // once here; the resolved directory is then pinned by device and
1058            // inode, remembered with the configured spelling, and a later
1059            // change of what that spelling names is refused below.
1060            let configured = parent;
1061            let parent = crate::pinned_dir::resolve_configured_root(configured)?;
1062            let expected_parent = real_directory(&parent)?;
1063            for ancestor in parent.ancestors() {
1064                if fs::symlink_metadata(ancestor.join(OWNER)).is_ok() {
1065                    return Err(io::Error::other(
1066                        "cache root overlaps another configured artifact root",
1067                    ));
1068                }
1069            }
1070            // Check before creating even the durable directory: an unavailable
1071            // volume must not cause an artifact write at any alternate location.
1072            root = parent.join("aft");
1073            config.cache_dir_configured = Some(crate::config::ConfiguredCacheDir {
1074                spelling: configured.clone(),
1075                resolved: parent.clone(),
1076            });
1077            config.cache_dir = Some(parent.clone());
1078            let storage_exists = storage.exists();
1079            let mut existing = storage.as_path();
1080            while !existing.exists() {
1081                existing = existing
1082                    .parent()
1083                    .ok_or_else(|| io::Error::other("storage ancestor unavailable"))?;
1084            }
1085            let durable_pin = if storage_exists {
1086                pin_storage_root(existing)?
1087            } else {
1088                PinnedDir::pin_unregistered_root(existing)?
1089            };
1090            // The same check by directory identity, which also catches an
1091            // overlap through a bind mount or another alias.
1092            if storage_exists {
1093                if overlap(&parent, durable_pin.path())? {
1094                    return Err(storage_overlap_error(configured, &storage));
1095                }
1096            } else {
1097                if has_ancestor(durable_pin.path(), expected_parent)? {
1098                    return Err(storage_overlap_error(configured, &storage));
1099                }
1100            }
1101            let roots = STATUS
1102                .get_or_init(Default::default)
1103                .lock()
1104                .unwrap_or_else(|error| error.into_inner())
1105                .locations
1106                .keys()
1107                .cloned()
1108                .collect::<Vec<_>>();
1109            for other in roots {
1110                if other == root
1111                    || Some(&other) == configured_root.as_ref()
1112                    || !other.exists()
1113                    // Another spelling of this same root is not an overlap.
1114                    || crate::pinned_dir::canonical_root_path(&other)
1115                        .ok()
1116                        .as_ref()
1117                        == Some(&root)
1118                {
1119                    continue;
1120                }
1121                #[cfg(any(test, feature = "test-support"))]
1122                BEFORE_OTHER_ROOT_OVERLAP.with(|hook| {
1123                    let mut hook = hook.borrow_mut();
1124                    if hook.as_ref().is_some_and(|(path, _)| path == &other) {
1125                        if let Some((_, hook)) = hook.take() {
1126                            hook();
1127                        }
1128                    }
1129                });
1130                let overlaps = match overlap(&parent, &other) {
1131                    Ok(overlaps) => overlaps,
1132                    // Registered labels outlive their roots. Another operation
1133                    // may retire this root after the existence check above;
1134                    // that must not disable an unrelated cache's enrollment.
1135                    Err(_) if !other.try_exists()? => continue,
1136                    Err(error) => return Err(error),
1137                };
1138                if overlaps {
1139                    return Err(io::Error::other(
1140                        "cache root overlaps another configured artifact root",
1141                    ));
1142                }
1143            }
1144            let parent_pin = PinnedDir::open(&parent)?;
1145            if pinned_identity(&parent_pin)? != expected_parent {
1146                return Err(io::Error::other(
1147                    "cache parent identity changed during prepare",
1148                ));
1149            }
1150            validate_saved_parent(&storage, configured, &parent, expected_parent)?;
1151            check_parent_mount(&parent, expected_parent)?;
1152            let first_enrollment = !read_parent_state(&storage)?
1153                .parents
1154                .iter()
1155                .any(|saved| saved.path == parent);
1156            let primary_device = if first_enrollment {
1157                #[cfg(any(test, feature = "test-support"))]
1158                BEFORE_ENROLLMENT_DEVICE.with(|hook| {
1159                    if let Some(hook) = hook.borrow_mut().take() {
1160                        hook();
1161                    }
1162                });
1163                let primary_device = durable_pin.cache_device()?;
1164                if parent_pin.cache_device()? == primary_device {
1165                    return Err(io::Error::other("cache_dir_on_storage_device: cache directory must be on a different volume from durable storage"));
1166                }
1167                Some(primary_device)
1168            } else {
1169                None
1170            };
1171            let probe = format!(
1172                ".aft-probe-{}-{}",
1173                std::process::id(),
1174                EPOCH.fetch_add(1, Ordering::Relaxed)
1175            );
1176            parent_pin.repair_new_file(std::ffi::OsStr::new(&probe))?;
1177            parent_pin.repair_remove_file(std::ffi::OsStr::new(&probe))?;
1178            crate::private_storage::open_root(&storage)?;
1179            let storage_pin = if storage_exists {
1180                durable_pin
1181            } else {
1182                pin_storage_root(&storage)?
1183            };
1184            (floor_hooks.prepare)(&storage);
1185            reconcile_root_history(&storage_pin)?;
1186            let (root_pin, enrollment) = match parent_pin.repair_child(std::ffi::OsStr::new("aft"))
1187            {
1188                Ok(root) => (root, None),
1189                Err(error) if error.kind() == io::ErrorKind::NotFound => {
1190                    let mut random = [0u8; 32];
1191                    getrandom::fill(&mut random).map_err(io::Error::other)?;
1192                    let registration = random
1193                        .iter()
1194                        .map(|byte| format!("{byte:02x}"))
1195                        .collect::<String>();
1196                    // Save an unfinished enrollment before publishing `aft`.
1197                    // Retries create a fresh staging folder rather than adopting
1198                    // an orphan; pending records protect any surviving folders.
1199                    let name = std::ffi::OsString::from(format!(".aft-enrolling-{registration}"));
1200                    let root = parent_pin.repair_create_dir(&name)?;
1201                    (root, Some((name, registration)))
1202                }
1203                Err(error) => return Err(error),
1204            };
1205            let created = enrollment.is_some();
1206            #[cfg(any(test, feature = "test-support"))]
1207            if created {
1208                AFTER_CACHE_ROOT_CREATE.with(|hook| {
1209                    if let Some(hook) = hook.borrow_mut().take() {
1210                        hook();
1211                    }
1212                });
1213            }
1214            let expected_root = pinned_identity(&root_pin)?;
1215            if let Some(primary_device) = primary_device {
1216                if root_pin.cache_device()? == primary_device {
1217                    return Err(io::Error::other("cache_dir_on_storage_device: artifact namespace is on the durable storage volume"));
1218                }
1219                if root_pin.cache_device()? != parent_pin.cache_device()? {
1220                    return Err(io::Error::other(
1221                        "artifact namespace is on a different volume than its enrolled parent",
1222                    ));
1223                }
1224            }
1225            let owner = pinned_identity(&storage_pin)?;
1226            let registration = if let Some((_, registration)) = &enrollment {
1227                registration.clone()
1228            } else {
1229                marker_matches_pinned(&root_pin, &storage_pin)?
1230            };
1231            let mut lease = take_shared_pinned(root_pin)?;
1232            if real_directory(lease.root.path())? != expected_root
1233                || lease.root_identity != expected_root
1234            {
1235                return Err(io::Error::other(
1236                    "artifact root identity changed during prepare",
1237                ));
1238            }
1239            match lease.root.repair_read_file(std::ffi::OsStr::new(OWNER)) {
1240                Ok(file) => {
1241                    let marker = read_marker_identity(file)?;
1242                    if marker.owner != owner {
1243                        return Err(foreign_owner_error());
1244                    }
1245                    if marker.registration != registration {
1246                        return Err(io::Error::other(
1247                            "artifact registration changed during prepare",
1248                        ));
1249                    }
1250                }
1251                Err(error) if error.kind() == io::ErrorKind::NotFound => {
1252                    if !created {
1253                        return Err(io::Error::other(
1254                            "artifact root has no AFT ownership marker",
1255                        ));
1256                    }
1257                    let mut marker = lease.root.repair_new_file(std::ffi::OsStr::new(OWNER))?;
1258                    use std::io::Write;
1259                    marker.write_all(
1260                        &serde_json::to_vec(&OwnerMarker {
1261                            owner,
1262                            registration: registration.clone(),
1263                        })
1264                        .map_err(io::Error::other)?,
1265                    )?;
1266                    aft_store::sync::sync_all(&marker, &lease.root.path().join(OWNER))?;
1267                }
1268                Err(error) => return Err(error),
1269            }
1270            lease.root.repair_private_dir()?;
1271            lease.root.repair_sync()?;
1272            remember_roots(
1273                &storage_pin,
1274                &root,
1275                expected_root,
1276                &registration,
1277                enrollment.as_ref().map(|_| lease.root.path()),
1278            )?;
1279            remember_parent(&storage, configured, &parent, expected_parent)?;
1280            // Publication and cleanup share the history lock, so a pending
1281            // folder cannot move out from under cleanup's protection snapshot.
1282            let _publication_lock = lock_root_history(&storage)?;
1283            if let Some((name, _)) = enrollment {
1284                let source = parent_pin.repair_entry_for_rename(&name)?;
1285                if pinned_identity(&source.directory()?)? != expected_root {
1286                    return Err(io::Error::other("enrollment source identity changed"));
1287                }
1288                // Windows refuses to rename a directory while a file inside it
1289                // is open (ERROR_ACCESS_DENIED), and the staging lease holds
1290                // `.aft-in-use.lock` open in the folder being published. Close
1291                // that lease first. Cleanup cannot step in meanwhile: it needs
1292                // the history lock held above, and the pending record still
1293                // protects the staging folder. The lease is taken again on
1294                // `aft` right after the rename.
1295                #[cfg(windows)]
1296                drop(lease);
1297                // No-replace publication must refuse even an empty foreign folder
1298                // or symlink installed at the destination during registration.
1299                parent_pin.repair_rename_entry_to(
1300                    &name,
1301                    &source,
1302                    &parent_pin,
1303                    std::ffi::OsStr::new("aft"),
1304                )?;
1305                #[cfg(any(test, feature = "test-support"))]
1306                AFTER_CACHE_ROOT_RENAME.with(|hook| {
1307                    if let Some(hook) = hook.borrow_mut().take() {
1308                        hook();
1309                    }
1310                });
1311                parent_pin.repair_sync()?;
1312                // Reopen `aft` after the rename so the lease uses its final path
1313                // while retaining the identity of the same directory.
1314                lease = take_shared_pinned(parent_pin.repair_child(std::ffi::OsStr::new("aft"))?)?;
1315            }
1316            if real_directory(&root)? != expected_root || lease.root_identity != expected_root {
1317                return Err(io::Error::other(
1318                    "artifact root identity changed during publication",
1319                ));
1320            }
1321            reconcile_root_history_locked(&storage_pin)?;
1322            Ok(lease)
1323        } else {
1324            crate::private_storage::open_root(&storage)?;
1325            let storage_pin = pin_storage_root(&storage)?;
1326            (floor_hooks.prepare)(&storage);
1327            reconcile_root_history(&storage_pin)?;
1328            take_shared_pinned(storage_pin)
1329        }
1330    })();
1331    match result {
1332        Ok(lease) => {
1333            STATUS
1334                .get_or_init(Default::default)
1335                .lock()
1336                .unwrap_or_else(|error| error.into_inner())
1337                .owners
1338                .insert(lease.root_identity, storage.clone());
1339            config.cache_lease = Some(Arc::clone(&lease));
1340            config.cache_unavailable = None;
1341            config.cache_epoch = if requested.is_some() {
1342                set_status(&root, None, Some(lease.root_identity))
1343            } else {
1344                0
1345            };
1346            mirror_status(configured_root.as_deref(), &root);
1347            config.semantic.local_cache_dir =
1348                requested.as_ref().map(|_| root.join("semantic/models"));
1349            crate::project_content::register_storage_root(&root);
1350            (floor_hooks
1351                .get()
1352                .expect("storage preparation checked reader-floor registration")
1353                .prepare_artifact_root)(&storage, &root);
1354            None
1355        }
1356        Err(error) => {
1357            config.cache_lease = None;
1358            config.cache_unavailable = Some(error.to_string());
1359            // Reject the second store without quarantining the legitimate
1360            // owner's healthy artifact root in this process.
1361            let foreign_owner = error
1362                .get_ref()
1363                .is_some_and(|error| error.is::<ForeignCacheOwner>());
1364            // A busy use lock (a cleanup holding it past the bounded wait) is
1365            // transient: this config reports it, and the next prepare retries.
1366            // It is never recorded in the process-wide registry, which would
1367            // refuse every later path under the root until a restart.
1368            let busy = error.kind() == io::ErrorKind::WouldBlock;
1369            let storage_overlap = error
1370                .get_ref()
1371                .is_some_and(|error| error.is::<StorageOverlap>())
1372                || paths_overlap(&root, &storage);
1373            if storage_overlap && requested.is_some() {
1374                // Drop the "not prepared" placeholders `cache_root` may have
1375                // added, and keep it from adding them again.
1376                let mut registry = STATUS
1377                    .get_or_init(Default::default)
1378                    .lock()
1379                    .unwrap_or_else(|error| error.into_inner());
1380                for refused in std::iter::once(&root).chain(configured_root.as_ref()) {
1381                    registry.locations.remove(refused);
1382                    registry.storage_overlaps.insert(refused.clone());
1383                }
1384            }
1385            config.cache_epoch = if requested.is_none() || storage_overlap {
1386                // Without `storage.cache_dir` the "cache root" is the durable
1387                // storage root itself, and an overlapping cache root contains
1388                // durable storage or sits inside it. The registry only
1389                // describes separate cache roots; recording either there
1390                // would block backups, bash task records and every other
1391                // durable write.
1392                0
1393            } else if foreign_owner || busy {
1394                status(&root).1
1395            } else {
1396                set_status(&root, Some(error.to_string()), None)
1397            };
1398            mirror_status(configured_root.as_deref(), &root);
1399            config.semantic.local_cache_dir = None;
1400            Some(unavailable_warning(
1401                requested.as_deref().unwrap_or(&root),
1402                &error.to_string(),
1403            ))
1404        }
1405    }
1406}
1407
1408#[rustfmt::skip]
1409test_support_visibility! {
1410#[derive(Clone, Debug, Serialize, Deserialize)]
1411struct RecordedRoot {
1412    #[cfg(any(test, feature = "test-support"))]
1413    pub path: PathBuf,
1414    #[cfg(not(any(test, feature = "test-support")))]
1415    path: PathBuf,
1416    #[cfg(any(test, feature = "test-support"))]
1417    pub identity: Option<Identity>,
1418    #[cfg(not(any(test, feature = "test-support")))]
1419    identity: Option<Identity>,
1420    #[serde(default)]
1421    registration: Option<String>,
1422}
1423}
1424#[rustfmt::skip]
1425test_support_visibility! {
1426#[derive(Serialize, Deserialize)]
1427struct OwnerMarker {
1428    #[cfg(any(test, feature = "test-support"))]
1429    pub owner: Identity,
1430    #[cfg(not(any(test, feature = "test-support")))]
1431    owner: Identity,
1432    registration: String,
1433}
1434}
1435#[rustfmt::skip]
1436test_support_visibility! {
1437#[derive(Debug, Serialize, Deserialize)]
1438struct History {
1439    version: u32,
1440    #[cfg(any(test, feature = "test-support"))]
1441    pub roots: Vec<RecordedRoot>,
1442    #[cfg(not(any(test, feature = "test-support")))]
1443    roots: Vec<RecordedRoot>,
1444    #[cfg(any(test, feature = "test-support"))]
1445    #[serde(default)]
1446    pub pending: Vec<PendingRoot>,
1447    #[cfg(not(any(test, feature = "test-support")))]
1448    #[serde(default)]
1449    pending: Vec<PendingRoot>,
1450}
1451}
1452#[rustfmt::skip]
1453test_support_visibility! {
1454#[derive(Debug, Serialize, Deserialize)]
1455struct PendingRoot {
1456    #[cfg(any(test, feature = "test-support"))]
1457    pub root: RecordedRoot,
1458    #[cfg(not(any(test, feature = "test-support")))]
1459    root: RecordedRoot,
1460    #[cfg(any(test, feature = "test-support"))]
1461    pub staging: PathBuf,
1462    #[cfg(not(any(test, feature = "test-support")))]
1463    staging: PathBuf,
1464}
1465}
1466#[rustfmt::skip]
1467test_support_visibility! {
1468fn history_path(storage: &Path) -> PathBuf {
1469    storage.join("retention/cache-roots.json")
1470}
1471}
1472/// The cache parent this storage root last used, from its durable records
1473/// (enrolled cache parents, then recorded artifact roots); None when it has
1474/// always kept its caches on itself.
1475fn previous_cache_parent(storage: &Path) -> io::Result<Option<PathBuf>> {
1476    if let Some(saved) = read_parent_state(storage)?.parents.last() {
1477        return Ok(Some(
1478            saved
1479                .configured
1480                .clone()
1481                .unwrap_or_else(|| saved.path.clone()),
1482        ));
1483    }
1484    let bytes = match fs::read(history_path(storage)) {
1485        Ok(bytes) => bytes,
1486        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1487        Err(error) => return Err(error),
1488    };
1489    let roots = match serde_json::from_slice::<History>(&bytes) {
1490        Ok(history) => history
1491            .roots
1492            .into_iter()
1493            .chain(history.pending.into_iter().map(|pending| pending.root))
1494            .map(|root| root.path)
1495            .collect(),
1496        Err(_) => serde_json::from_slice::<Vec<PathBuf>>(&bytes).map_err(io::Error::other)?,
1497    };
1498    Ok(roots
1499        .into_iter()
1500        .rev()
1501        .find(|root| root != storage)
1502        .map(|root| root.parent().map(Path::to_path_buf).unwrap_or(root)))
1503}
1504fn remember_roots(
1505    storage: &PinnedDir,
1506    artifacts: &Path,
1507    artifact_identity: Identity,
1508    registration: &str,
1509    staging: Option<&Path>,
1510) -> io::Result<()> {
1511    let _lock = lock_root_history(storage.path())?;
1512    let mut history = read_root_history(storage.path())?;
1513    reconcile_pending_roots(storage, &mut history)?;
1514    let record = RecordedRoot {
1515        path: artifacts.to_path_buf(),
1516        identity: Some(artifact_identity),
1517        registration: Some(registration.to_owned()),
1518    };
1519    if let Some(staging) = staging {
1520        history.pending.push(PendingRoot {
1521            root: record,
1522            staging: staging.to_path_buf(),
1523        });
1524    } else {
1525        add_published_root(&mut history, record);
1526    }
1527    #[cfg(any(test, feature = "test-support"))]
1528    BEFORE_ROOT_HISTORY_WRITE.with(|hook| {
1529        if let Some(hook) = hook.borrow_mut().take() {
1530            hook()?;
1531        }
1532        Ok::<_, io::Error>(())
1533    })?;
1534    write_root_history(storage.path(), &history)
1535}
1536
1537fn lock_root_history(storage: &Path) -> io::Result<crate::fs_lock::LockGuard> {
1538    crate::private_storage::open_dir(storage, &storage.join("retention"))?;
1539    crate::fs_lock::try_acquire(
1540        &storage.join("retention/cache-roots.lock"),
1541        Duration::from_secs(5),
1542    )
1543    .map_err(io::Error::other)
1544}
1545
1546#[rustfmt::skip]
1547test_support_visibility! {
1548
1549fn read_root_history(storage: &Path) -> io::Result<History> {
1550    Ok(match fs::read(history_path(storage)) {
1551        Ok(bytes) => match serde_json::from_slice::<History>(&bytes) {
1552            Ok(history) if history.version == 2 => history,
1553            _ => History {
1554                version: 2,
1555                roots: serde_json::from_slice::<Vec<PathBuf>>(&bytes)
1556                    .map_err(io::Error::other)?
1557                    .into_iter()
1558                    .map(|path| RecordedRoot {
1559                        path,
1560                        identity: None,
1561                        registration: None,
1562                    })
1563                    .collect(),
1564                pending: Vec::new(),
1565            },
1566        },
1567        Err(error) if error.kind() == io::ErrorKind::NotFound => History {
1568            version: 2,
1569            roots: Vec::new(),
1570            pending: Vec::new(),
1571        },
1572        Err(error) => return Err(error),
1573    })
1574}
1575}
1576
1577fn add_published_root(history: &mut History, record: RecordedRoot) {
1578    if !history.roots.iter().any(|old| {
1579        old.path == record.path
1580            && old.identity == record.identity
1581            && old.registration == record.registration
1582    }) {
1583        history.roots.push(record);
1584    }
1585}
1586
1587fn reconcile_pending_roots(storage: &PinnedDir, history: &mut History) -> io::Result<bool> {
1588    let owner = pinned_identity(storage)?;
1589    let mut changed = false;
1590    for pending in std::mem::take(&mut history.pending) {
1591        if recorded_root_matches(&pending.root).is_ok() {
1592            let root = PinnedDir::repair_open_path(&pending.root.path)?;
1593            // Enrollment writes and syncs the ownership marker in the staging
1594            // folder before it records the pending root, so a published root
1595            // always carries one. A folder at the published path with a
1596            // matching identity but no marker is a foreign folder that reused
1597            // the deleted staging folder's inode (ext4 and tmpfs do this
1598            // readily). It is not adopted; the staging check below decides
1599            // the record, as for any other unpublished root.
1600            let marker = match root.repair_read_file(std::ffi::OsStr::new(OWNER)) {
1601                Ok(file) => Some(read_marker_identity(file)?),
1602                Err(error) if error.kind() == io::ErrorKind::NotFound => None,
1603                Err(error) => return Err(error),
1604            };
1605            if let Some(marker) = marker {
1606                if Some(pinned_identity(&root)?) != pending.root.identity
1607                    || marker.owner != owner
1608                    || Some(marker.registration.as_str()) != pending.root.registration.as_deref()
1609                {
1610                    return Err(io::Error::other("pending artifact registration changed"));
1611                }
1612                add_published_root(history, pending.root);
1613                changed = true;
1614                continue;
1615            }
1616        }
1617        match fs::symlink_metadata(&pending.staging) {
1618            Ok(metadata)
1619                if metadata.is_dir()
1620                    && !metadata.file_type().is_symlink()
1621                    && Some(real_directory(&pending.staging)?) == pending.root.identity =>
1622            {
1623                // A surviving staging folder is not published history, but
1624                // cleanup must still protect it, including through aliases.
1625                history.pending.push(pending);
1626            }
1627            Ok(_) => changed = true,
1628            Err(error) if error.kind() == io::ErrorKind::NotFound => changed = true,
1629            Err(error) => return Err(error),
1630        }
1631    }
1632    Ok(changed)
1633}
1634
1635fn reconcile_root_history(storage: &PinnedDir) -> io::Result<()> {
1636    if !history_path(storage.path()).try_exists()? {
1637        return Ok(());
1638    }
1639    let _lock = lock_root_history(storage.path())?;
1640    reconcile_root_history_locked(storage)
1641}
1642
1643fn reconcile_root_history_locked(storage: &PinnedDir) -> io::Result<()> {
1644    let mut history = read_root_history(storage.path())?;
1645    if reconcile_pending_roots(storage, &mut history)? {
1646        write_root_history(storage.path(), &history)?;
1647    }
1648    Ok(())
1649}
1650
1651fn write_root_history(storage: &Path, history: &History) -> io::Result<()> {
1652    crate::durability::atomic_write(
1653        &history_path(storage),
1654        &serde_json::to_vec(history).map_err(io::Error::other)?,
1655        crate::durability::AtomicWriteDurability::FileAndDirectory,
1656    )
1657}
1658
1659#[derive(Debug, Default, Serialize)]
1660pub struct CleanupReport {
1661    pub removed: Vec<PathBuf>,
1662    pub skipped: Vec<String>,
1663    pub partial: Vec<PartialRemoval>,
1664    #[serde(skip_serializing_if = "Vec::is_empty")]
1665    pub warnings: Vec<String>,
1666    pub error: Option<String>,
1667    #[serde(skip_serializing_if = "Option::is_none")]
1668    pub reason: Option<&'static str>,
1669}
1670#[derive(Debug, Serialize)]
1671pub struct CleanupCandidate {
1672    pub path: PathBuf,
1673    pub bytes: u64,
1674}
1675#[derive(Debug, Serialize)]
1676pub struct PartialRemoval {
1677    pub path: PathBuf,
1678    pub removed_entries: usize,
1679}
1680fn recorded_root_matches(record: &RecordedRoot) -> io::Result<()> {
1681    if Some(real_directory(&record.path)?) != record.identity {
1682        return Err(io::Error::other(
1683            "recorded root identity changed or unverified",
1684        ));
1685    }
1686    Ok(())
1687}
1688fn read_marker_identity(file: File) -> io::Result<OwnerMarker> {
1689    if file.metadata()?.len() > 512 {
1690        return Err(io::Error::other("ownership marker is too large"));
1691    }
1692    serde_json::from_reader(file).map_err(io::Error::other)
1693}
1694#[rustfmt::skip]
1695test_support_visibility! {
1696fn marker_matches_pinned(root: &PinnedDir, storage: &PinnedDir) -> io::Result<String> {
1697    let recorded = read_marker_identity(root.repair_read_file(std::ffi::OsStr::new(OWNER))?)?;
1698    if recorded.owner != pinned_identity(storage)? {
1699        return Err(foreign_owner_error());
1700    }
1701    let history: History = serde_json::from_slice(&fs::read(history_path(storage.path()))?)
1702        .map_err(io::Error::other)?;
1703    let actual = pinned_identity(root)?;
1704    if !history.roots.iter().any(|entry| {
1705        entry.identity == Some(actual)
1706            && entry.registration.as_deref() == Some(recorded.registration.as_str())
1707    }) {
1708        return Err(io::Error::other(
1709            "cannot enroll an unregistered artifact namespace",
1710        ));
1711    }
1712    Ok(recorded.registration)
1713}
1714}
1715fn known_harness(name: &str) -> bool {
1716    crate::engram_catalog::harness_label(name).is_some()
1717}
1718#[rustfmt::skip]
1719test_support_visibility! {
1720fn candidates_and_durable(storage: &Path) -> io::Result<(Vec<PathBuf>, Vec<PathBuf>)> {
1721    candidates_and_durable_with_budget(storage, &mut RepairBudget::new())
1722}
1723}
1724
1725fn candidates_and_durable_with_budget(
1726    storage: &Path,
1727    budget: &mut RepairBudget,
1728) -> io::Result<(Vec<PathBuf>, Vec<PathBuf>)> {
1729    let mut candidates = CACHE_DOMAINS
1730        .iter()
1731        .map(|name| storage.join(name))
1732        .collect::<Vec<_>>();
1733    let mut durable = Vec::new();
1734    let mut entries = fs::read_dir(storage)?;
1735    loop {
1736        budget.entry()?;
1737        let Some(entry) = entries.next() else { break };
1738        let entry = entry?;
1739        let name = entry.file_name();
1740        if name
1741            .to_str()
1742            .is_some_and(|name| CACHE_DOMAINS.contains(&name))
1743        {
1744            continue;
1745        }
1746        if name.to_str().is_some_and(known_harness) && entry.file_type()?.is_dir() {
1747            let legacy = [entry.path().join("callgraph"), entry.path().join("inspect")];
1748            candidates.extend(legacy);
1749            let mut children = fs::read_dir(entry.path())?;
1750            loop {
1751                budget.entry()?;
1752                let Some(child) = children.next() else { break };
1753                let child = child?;
1754                if !matches!(child.file_name().to_str(), Some("callgraph" | "inspect")) {
1755                    durable.push(child.path());
1756                }
1757            }
1758        } else {
1759            durable.push(entry.path());
1760        }
1761    }
1762    Ok((candidates, durable))
1763}
1764
1765pub(crate) fn deletion_protections(paths: &[PathBuf]) -> io::Result<Vec<(u64, u64)>> {
1766    deletion_protections_with_budget(paths, &mut RepairBudget::new(), &mut Default::default())
1767}
1768
1769fn deletion_protections_with_budget(
1770    paths: &[PathBuf],
1771    budget: &mut RepairBudget,
1772    examined: &mut crate::pinned_dir::IdentityCensus,
1773) -> io::Result<Vec<(u64, u64)>> {
1774    let mut protected = Vec::new();
1775    for path in paths {
1776        budget.entry()?;
1777        if !path.try_exists()? {
1778            continue;
1779        }
1780        // A path removed after the check above has nothing left to protect,
1781        // the same as one that never existed.
1782        let canonical = match fs::canonicalize(path) {
1783            Ok(canonical) => canonical,
1784            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
1785            Err(error) => return Err(error),
1786        };
1787        if canonical.is_dir() {
1788            match PinnedDir::open(&canonical) {
1789                Ok(pinned) => pinned.directory_identities(&mut protected, budget, examined)?,
1790                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
1791                Err(error) => return Err(error),
1792            }
1793        }
1794        for ancestor in canonical.ancestors() {
1795            budget.entry()?;
1796            let id = identity(ancestor)?;
1797            protected.push((id.device, id.inode));
1798        }
1799    }
1800    Ok(protected)
1801}
1802fn candidate_protected(
1803    candidate: &Path,
1804    storage: &Path,
1805    active: &[PathBuf],
1806    durable: &[PathBuf],
1807) -> io::Result<bool> {
1808    let candidate_id = real_directory(candidate)?;
1809    if has_ancestor(storage, candidate_id)? {
1810        return Ok(true);
1811    }
1812    for protected in active.iter().chain(durable) {
1813        match fs::symlink_metadata(protected) {
1814            Ok(_) => {
1815                if overlap(candidate, protected)? {
1816                    return Ok(true);
1817                }
1818            }
1819            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
1820            Err(error) => return Err(error),
1821        }
1822    }
1823    Ok(false)
1824}
1825fn ensure_cache_idle(
1826    root: &Path,
1827    protected: &[(u64, u64)],
1828) -> io::Result<Vec<crate::fs_lock::LockGuard>> {
1829    fn visit(
1830        dir: &PinnedDir,
1831        root: &PinnedDir,
1832        protected: &[(u64, u64)],
1833        budget: &mut RepairBudget,
1834        depth: usize,
1835    ) -> io::Result<()> {
1836        budget.enter(depth)?;
1837        dir.repair_check_boundary(root, protected)?;
1838        if markers::sweep_all_read_markers_pinned(dir, budget, false)?.protected {
1839            return Err(io::Error::other("cache has live readers"));
1840        }
1841        for name in dir.repair_names(budget)? {
1842            match dir.repair_child(&name) {
1843                Ok(child) => {
1844                    if name == "pins" && !child.repair_names(budget)?.is_empty() {
1845                        return Err(io::Error::other(
1846                            "cache has pins; stop readers before cleanup",
1847                        ));
1848                    }
1849                    visit(&child, root, protected, budget, depth + 1)?;
1850                }
1851                Err(error) if error.kind() == io::ErrorKind::NotADirectory => {
1852                    dir.repair_read_file(&name).map_err(|error| {
1853                        io::Error::other(format!(
1854                            "cache preflight refuses symlink or non-regular file: {error}"
1855                        ))
1856                    })?;
1857                    if matches!(
1858                        name.to_str(),
1859                        Some("writer.lease" | "cache.lock" | "symbols.lock" | "semantic.lock")
1860                    ) {
1861                        // Cleanup holds the namespace's exclusive use lock. A
1862                        // leftover coordination file is not ours to reclaim or
1863                        // heartbeat, even if its contents look stale.
1864                        return Err(io::Error::other("cache coordination lock exists; stop its owner and repair the lock before cleanup"));
1865                    }
1866                }
1867                Err(error) => {
1868                    return Err(io::Error::other(format!(
1869                        "cache preflight refuses symlink or non-directory: {error}"
1870                    )))
1871                }
1872            }
1873        }
1874        Ok(())
1875    }
1876    let root = PinnedDir::open(root)?;
1877    visit(&root, &root, protected, &mut RepairBudget::new(), 0)?;
1878    Ok(Vec::new())
1879}
1880
1881fn cleanup_roots(
1882    storage: &Path,
1883    active: &[PathBuf],
1884    report: &mut CleanupReport,
1885    legacy_root: Option<&PinnedDir>,
1886    mut confirm: Option<&mut dyn FnMut(&[CleanupCandidate]) -> bool>,
1887) -> io::Result<()> {
1888    let legacy = legacy_root.is_some();
1889    let storage_pin = match legacy_root {
1890        Some(root) => root.repair_clone()?,
1891        None => pin_storage_root(storage)?,
1892    };
1893    let _history_lock = lock_root_history(storage)?;
1894    let bytes = match fs::read(history_path(storage)) {
1895        Ok(bytes) => bytes,
1896        Err(error) if error.kind() == io::ErrorKind::NotFound => {
1897            b"{\"version\":2,\"roots\":[]}".to_vec()
1898        }
1899        Err(error) => return Err(error),
1900    };
1901    let mut history = match serde_json::from_slice::<History>(&bytes) {
1902        Ok(history) if history.version == 2 => history,
1903        _ => {
1904            if let Ok(legacy) = serde_json::from_slice::<Vec<PathBuf>>(&bytes) {
1905                for path in legacy {
1906                    report.skipped.push(format!(
1907                        "{}: unverified legacy root has no recorded identity/ownership",
1908                        path.display()
1909                    ));
1910                }
1911            } else {
1912                report
1913                    .skipped
1914                    .push("unrecognized cache root history; no roots removed".into());
1915            }
1916            return Ok(());
1917        }
1918    };
1919    if reconcile_pending_roots(&storage_pin, &mut history)? {
1920        write_root_history(storage, &history)?;
1921    }
1922    let pending_paths = history
1923        .pending
1924        .into_iter()
1925        .map(|pending| pending.staging)
1926        .collect::<Vec<_>>();
1927    let mut records = history.roots;
1928    let owner = pinned_identity(&storage_pin)?;
1929    if legacy {
1930        records = vec![RecordedRoot {
1931            path: storage_pin.path().to_path_buf(),
1932            identity: Some(owner),
1933            registration: None,
1934        }];
1935    }
1936    let (default_candidates, mut durable) = if let Some(root) = legacy_root {
1937        let mut durable = Vec::new();
1938        for name in root.repair_names(&mut RepairBudget::new())? {
1939            if !name
1940                .to_str()
1941                .is_some_and(|name| CACHE_DOMAINS.contains(&name))
1942            {
1943                durable.push(storage.join(name));
1944            }
1945        }
1946        (
1947            CACHE_DOMAINS
1948                .iter()
1949                .map(|domain| storage.join(domain))
1950                .collect(),
1951            durable,
1952        )
1953    } else {
1954        candidates_and_durable(storage)?
1955    };
1956    durable.extend(pending_paths.iter().cloned());
1957    let mut protected_paths = if legacy {
1958        durable.clone()
1959    } else {
1960        vec![storage.to_path_buf()]
1961    };
1962    protected_paths.extend_from_slice(active);
1963    protected_paths.extend(pending_paths);
1964    let protected = deletion_protections(&protected_paths)?;
1965    let mut plans = Vec::new();
1966    let mut refusal = false;
1967    for record in records {
1968        let is_storage = record.identity == Some(owner);
1969        if is_storage && !legacy {
1970            continue;
1971        }
1972        if let Err(error) = recorded_root_matches(&record) {
1973            report.skipped.push(format!(
1974                "{}: root identity/symlink refusal: {error}",
1975                record.path.display()
1976            ));
1977            refusal = true;
1978            continue;
1979        }
1980        let pinned = match PinnedDir::repair_open_path(&record.path).and_then(|pinned| {
1981            if Some(pinned_identity(&pinned)?) != record.identity {
1982                return Err(io::Error::other("recorded root changed while opening"));
1983            }
1984            Ok(pinned)
1985        }) {
1986            Ok(pinned) => pinned,
1987            Err(error) => {
1988                report.skipped.push(format!(
1989                    "{}: root identity/symlink refusal: {error}",
1990                    record.path.display()
1991                ));
1992                refusal = true;
1993                continue;
1994            }
1995        };
1996        if active
1997            .iter()
1998            .any(|path| identity(path).ok() == record.identity)
1999        {
2000            continue;
2001        }
2002        if !is_storage {
2003            if let Err(error) = marker_matches_pinned(&pinned, &storage_pin) {
2004                report
2005                    .skipped
2006                    .push(format!("{}: unowned root: {error}", record.path.display()));
2007                refusal = true;
2008                continue;
2009            }
2010        }
2011        let exclusive = open_use_lock(&pinned)?;
2012        exclusive.try_lock().map_err(|error| {
2013            io::Error::other(format!(
2014                "artifact root {} is in use: {error}",
2015                record.path.display()
2016            ))
2017        })?;
2018        recorded_root_matches(&record)?;
2019        let candidates = if is_storage {
2020            default_candidates.clone()
2021        } else {
2022            CACHE_DOMAINS
2023                .iter()
2024                .map(|domain| record.path.join(domain))
2025                .collect()
2026        };
2027        let mut admitted = Vec::new();
2028        for candidate in candidates {
2029            recorded_root_matches(&record)?;
2030            match fs::symlink_metadata(&candidate) {
2031                Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {}
2032                Ok(_) => {
2033                    if legacy {
2034                        return Err(io::Error::other(
2035                            "old cache candidate is not a real directory",
2036                        ));
2037                    }
2038                    report.skipped.push(format!(
2039                        "{}: candidate is not a real directory",
2040                        candidate.display()
2041                    ));
2042                    continue;
2043                }
2044                Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
2045                Err(error) => return Err(error),
2046            }
2047            if candidate_protected(&candidate, storage_pin.path(), active, &durable)? {
2048                if legacy {
2049                    return Err(io::Error::other(
2050                        "old cache candidate aliases active or durable storage",
2051                    ));
2052                }
2053                report.skipped.push(format!(
2054                    "{}: active artifact or durable subtree",
2055                    candidate.display()
2056                ));
2057                continue;
2058            }
2059            let candidate_identity = real_directory(&candidate)?;
2060            if candidate_identity.device != pinned_identity(&pinned)?.device {
2061                return Err(io::Error::other(
2062                    "cache candidate is a mount on another device",
2063                ));
2064            }
2065            crate::production_storage::refuse_write(&candidate)?;
2066            let base = if is_storage {
2067                storage
2068            } else {
2069                record.path.as_path()
2070            };
2071            let relative = candidate.strip_prefix(base).map_err(io::Error::other)?;
2072            let mut components = relative.components().collect::<Vec<_>>();
2073            let leaf = components
2074                .pop()
2075                .ok_or_else(|| io::Error::other("missing cache child name"))?;
2076            let mut parent = pinned.repair_clone()?;
2077            for component in components {
2078                parent = parent.repair_child_same_mount(component.as_os_str())?;
2079            }
2080            let leaf = leaf.as_os_str().to_os_string();
2081            // Verify every mount and protected-directory boundary before the
2082            // read-only liveness census examines any candidate entries.
2083            parent.repair_child_tree_bytes(&leaf, &protected)?;
2084            let locks = ensure_cache_idle(&candidate, &protected)?;
2085            recorded_root_matches(&record)?;
2086            if real_directory(&candidate)? != candidate_identity {
2087                return Err(io::Error::other(
2088                    "cache candidate identity changed during repair",
2089                ));
2090            }
2091            admitted.push((candidate, parent, leaf, candidate_identity, locks));
2092        }
2093        plans.push((record, exclusive, admitted));
2094    }
2095    if refusal {
2096        return Err(io::Error::other(
2097            "cache cleanup preflight refused; no roots removed",
2098        ));
2099    }
2100    let mut inventory = Vec::new();
2101    for (_, _, admitted) in &plans {
2102        for (candidate, parent, leaf, expected, _) in admitted {
2103            let child = parent.repair_child(leaf)?;
2104            if pinned_identity(&child)? != *expected {
2105                return Err(io::Error::other(
2106                    "cache candidate identity changed during preflight",
2107                ));
2108            }
2109            inventory.push(CleanupCandidate {
2110                path: candidate.clone(),
2111                bytes: parent.repair_child_tree_bytes(leaf, &protected)?,
2112            });
2113        }
2114    }
2115    if let Some(confirm) = confirm.as_mut() {
2116        if !confirm(&inventory) {
2117            report.reason = Some("old_cache_confirmation_required");
2118            return Err(io::Error::other(
2119                "old cache cleanup requires exact confirmation",
2120            ));
2121        }
2122    }
2123    for (record, _exclusive, admitted) in plans {
2124        for (candidate, parent, leaf, candidate_identity, _locks) in admitted {
2125            recorded_root_matches(&record)?;
2126            let mut removed = 0;
2127            #[cfg(any(test, feature = "test-support"))]
2128            BEFORE_REPAIR_REMOVE.with(|hook| {
2129                if let Some(hook) = hook.borrow_mut().take() {
2130                    hook();
2131                }
2132            });
2133            if let Err(error) = parent.repair_remove_child_with_warnings(
2134                &leaf,
2135                (candidate_identity.device, candidate_identity.inode),
2136                &protected,
2137                &mut removed,
2138                &mut report.warnings,
2139            ) {
2140                if removed > 0 {
2141                    report.partial.push(PartialRemoval {
2142                        path: candidate.clone(),
2143                        removed_entries: removed,
2144                    });
2145                }
2146                return Err(error);
2147            }
2148            report.removed.push(candidate);
2149            recorded_root_matches(&record)?;
2150        }
2151    }
2152    Ok(())
2153}
2154
2155#[rustfmt::skip]
2156test_support_visibility! {
2157
2158pub(crate) fn remove_inactive_cache_roots(storage: &Path, active: &[PathBuf]) -> CleanupReport {
2159    let mut report = CleanupReport::default();
2160    if let Err(error) = cleanup_roots(storage, active, &mut report, None, None) {
2161        report.error = Some(error.to_string());
2162    }
2163    report
2164}
2165}
2166
2167#[cfg(any(test, feature = "test-support"))]
2168pub fn remove_legacy_cache_roots(storage: &Path, active: &[PathBuf]) -> CleanupReport {
2169    let mut report = CleanupReport::default();
2170    let root = match pin_storage_root(storage) {
2171        Ok(root) => root,
2172        Err(error) => {
2173            report.error = Some(error.to_string());
2174            return report;
2175        }
2176    };
2177    if let Err(error) = cleanup_roots(storage, active, &mut report, Some(&root), None) {
2178        report.error = Some(error.to_string());
2179    }
2180    report
2181}
2182
2183/// Legacy cache deletion is a separate operation, never automatic repair.
2184/// The callback sees the fully preflighted inventory while all locks are held.
2185pub fn clean_old(
2186    tiers: &[crate::config_resolve::ConfigTier],
2187    storage: &Path,
2188    confirm: impl FnMut(&[CleanupCandidate]) -> bool,
2189) -> CleanupReport {
2190    clean_old_resolved(
2191        tiers,
2192        storage,
2193        &crate::storage_path::storage_dir(None),
2194        confirm,
2195    )
2196}
2197
2198#[rustfmt::skip]
2199test_support_visibility! {
2200pub(crate) fn clean_old_resolved(
2201    tiers: &[crate::config_resolve::ConfigTier],
2202    storage: &Path,
2203    resolved: &Path,
2204    mut confirm: impl FnMut(&[CleanupCandidate]) -> bool,
2205) -> CleanupReport {
2206    let mut report = CleanupReport::default();
2207    let work = (|| -> io::Result<()> {
2208        let result = crate::config_resolve::resolve_config(tiers);
2209        if !result.errors.is_empty() {
2210            return Err(io::Error::other(format!(
2211                "invalid user config: {:?}",
2212                result.errors
2213            )));
2214        }
2215        let mut config = result.config;
2216        if let Some(reason) = &config.cache_config_unknown {
2217            report.reason = Some("cache_dir_config_unknown");
2218            return Err(io::Error::other(reason.clone()));
2219        }
2220        if config.cache_dir.is_none() {
2221            report.reason = Some("old_cache_external_root_required");
2222            return Err(io::Error::other(
2223                "old caches are active: configure an available external storage.cache_dir first",
2224            ));
2225        }
2226        let storage_pin = pin_storage_root(storage)?;
2227        if pin_storage_root(resolved)
2228            .and_then(|root| pinned_identity(&root))
2229            .ok()
2230            != Some(pinned_identity(&storage_pin)?)
2231        {
2232            report.reason = Some("old_cache_storage_root_mismatch");
2233            return Err(io::Error::other(
2234                "old-cache cleanup requires the resolved durable storage root",
2235            ));
2236        }
2237        if !storage_root_proven(&storage_pin)? {
2238            report.reason = Some("old_cache_storage_root_unproven");
2239            return Err(io::Error::other(
2240                "old-cache cleanup requires aft.db or the storage root's AFT owner marker",
2241            ));
2242        }
2243        let _cleanup_lease = acquire_cache_cleanup_lease(storage)?;
2244        config.storage_dir = Some(storage.to_path_buf());
2245        if let Some(warning) = prepare_cache_root(&mut config) {
2246            report.reason = Some(warning.code);
2247            return Err(io::Error::other(warning.message));
2248        }
2249        let active = config
2250            .cache_lease
2251            .as_ref()
2252            .ok_or_else(|| io::Error::other("cache root is not enrolled"))?;
2253        if active.root.cache_device()? == storage_pin.cache_device()? {
2254            report.reason = Some("old_cache_external_root_required");
2255            return Err(io::Error::other(
2256                "old-cache cleanup requires an active enrolled cache root on its own device",
2257            ));
2258        }
2259        cleanup_roots(
2260            storage,
2261            &[cache_root(&config)],
2262            &mut report,
2263            Some(&storage_pin),
2264            Some(&mut confirm),
2265        )
2266    })();
2267    if let Err(error) = work {
2268        report.error = Some(error.to_string());
2269    }
2270    report
2271}
2272}
2273
2274#[cfg(any(test, feature = "test-support"))]
2275pub fn clean_old_for_test(
2276    tiers: &[crate::config_resolve::ConfigTier],
2277    storage: &Path,
2278    confirm: impl FnMut(&[CleanupCandidate]) -> bool,
2279) -> CleanupReport {
2280    let parent = crate::config_resolve::resolve_config(tiers)
2281        .config
2282        .cache_dir;
2283    let _volume = parent
2284        .as_ref()
2285        .filter(|parent| parent.is_dir())
2286        .map(|parent| crate::walk_boundary::simulated_volumes::simulate(parent, u64::MAX - 17));
2287    with_legacy_daemon_processes_for_test_if_unset(|| {
2288        clean_old_resolved(tiers, storage, storage, confirm)
2289    })
2290}
2291
2292/// Whether `storage` holds AFT's database (`aft.db`) or an owner marker that
2293/// names this very folder. Bulk deletions ask for this proof before treating a
2294/// folder as AFT's storage, so a mistyped `AFT_STORAGE_DIR` cannot point them
2295/// at someone else's data.
2296fn storage_root_proven(storage: &PinnedDir) -> io::Result<bool> {
2297    match storage.repair_read_file(std::ffi::OsStr::new("aft.db")) {
2298        Ok(_) => Ok(true),
2299        Err(error) if error.kind() == io::ErrorKind::NotFound => {
2300            match storage.repair_read_file(std::ffi::OsStr::new(OWNER)) {
2301                Ok(marker) => {
2302                    let marker = read_marker_identity(marker)?;
2303                    Ok(
2304                        marker.owner == pinned_identity(storage)?
2305                            && !marker.registration.is_empty(),
2306                    )
2307                }
2308                Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
2309                Err(error) => Err(error),
2310            }
2311        }
2312        Err(error) => Err(error),
2313    }
2314}
2315
2316pub use prune_legacy::{
2317    prune_legacy_stores, LegacyStore, LegacyStoreSkip, PruneLegacyError, PruneLegacyEvent,
2318    PruneLegacyReport,
2319};
2320
2321/// Cache location is storage-wide: only the user base is resolved here, never
2322/// a harness override or a project redirect. Unavailable roots abort repair.
2323pub fn reclaim_configured_inactive_caches(
2324    tiers: &[crate::config_resolve::ConfigTier],
2325    storage: &Path,
2326) -> CleanupReport {
2327    let result = crate::config_resolve::resolve_config(tiers);
2328    if !result.errors.is_empty() {
2329        return CleanupReport {
2330            error: Some(format!("cache cleanup refused: {:?}", result.errors)),
2331            ..Default::default()
2332        };
2333    }
2334    // A fresh install has no storage root yet, so there is nothing to clean.
2335    // Report that rather than failing in the cleanup lease, and do not create
2336    // the root just to clean it.
2337    match fs::symlink_metadata(storage) {
2338        Err(error) if error.kind() == io::ErrorKind::NotFound => {
2339            return CleanupReport::default();
2340        }
2341        _ => {}
2342    }
2343    let mut config = result.config;
2344    config.storage_dir = Some(storage.to_path_buf());
2345    let _cleanup_lease = match acquire_cache_cleanup_lease(storage) {
2346        Ok(lease) => lease,
2347        Err(error) => {
2348            return CleanupReport {
2349                error: Some(error.to_string()),
2350                ..Default::default()
2351            }
2352        }
2353    };
2354    if let Some(warning) = prepare_cache_root(&mut config) {
2355        return CleanupReport {
2356            error: Some(format!("cleanup refused: {}", warning.message)),
2357            reason: Some(warning.code),
2358            ..Default::default()
2359        };
2360    }
2361    remove_inactive_cache_roots(storage, &[cache_root(&config)])
2362}
2363
2364fn open_daemon_storage_lock(root: &PinnedDir) -> io::Result<File> {
2365    let retention = root.repair_descendant(Path::new("retention"), true)?;
2366    retention.repair_coordination_file(std::ffi::OsStr::new(DAEMON_USE))
2367}
2368
2369/// Cache-using processes share a durable-root lock before opening caches.
2370/// Daemon modules hold it even while waiting for their first bind. The kernel
2371/// releases it on exit; a leftover file does not indicate a running owner.
2372pub fn acquire_daemon_storage_lease(storage: &Path) -> io::Result<Arc<ProcessStorageLease>> {
2373    crate::private_storage::open_root(storage)?;
2374    acquire_pinned_storage_lease(pin_storage_root(storage)?)
2375}
2376
2377/// Exclude another speech forwarder until managed quiescence or process exit.
2378pub fn acquire_speech_serving_lease(storage: &Path) -> io::Result<Arc<SpeechServingLease>> {
2379    let storage_use = acquire_daemon_storage_lease(storage)?;
2380    let root = pin_storage_root(storage)?;
2381    let identity = pinned_identity(&root)?;
2382    let mut leases = SPEECH_SERVING_LEASES
2383        .get_or_init(Default::default)
2384        .lock()
2385        .unwrap_or_else(|error| error.into_inner());
2386    if leases.contains_key(&identity) {
2387        return Err(io::Error::new(
2388            io::ErrorKind::WouldBlock,
2389            "speech forwarding already has an owner",
2390        ));
2391    }
2392    let retention = root.repair_descendant(Path::new("retention"), true)?;
2393    let file = retention.repair_coordination_file(std::ffi::OsStr::new("speech-serving.lock"))?;
2394    file.try_lock().map_err(storage_lock_error)?;
2395    let lease = Arc::new(SpeechServingLease {
2396        _file: file,
2397        _root: root,
2398        _storage_use: storage_use,
2399        identity,
2400    });
2401    leases.insert(identity, Arc::clone(&lease));
2402    Ok(lease)
2403}
2404
2405/// Release only the anchor owned by the runtime that proved quiescence.
2406pub fn release_quiescent_speech_serving_lease(lease: &Arc<SpeechServingLease>) -> bool {
2407    let Some(leases) = SPEECH_SERVING_LEASES.get() else {
2408        return false;
2409    };
2410    let Ok(mut leases) = leases.lock() else {
2411        return false;
2412    };
2413    if !leases
2414        .get(&lease.identity)
2415        .is_some_and(|held| Arc::ptr_eq(held, lease))
2416    {
2417        return false;
2418    }
2419    leases.remove(&lease.identity);
2420    true
2421}
2422
2423fn acquire_pinned_storage_lease(root: PinnedDir) -> io::Result<Arc<ProcessStorageLease>> {
2424    let identity = pinned_identity(&root)?;
2425    let mut leases = PROCESS_STORAGE_LEASES
2426        .get_or_init(Default::default)
2427        .lock()
2428        .unwrap_or_else(|error| error.into_inner());
2429    if let Some(lease) = leases.get(&identity).and_then(Weak::upgrade) {
2430        return Ok(lease);
2431    }
2432    // Config snapshots share one ownership handle per storage root. Weak
2433    // entries do not retain file descriptors after the last snapshot is gone.
2434    leases.retain(|_, lease| lease.strong_count() > 0);
2435    let file = open_daemon_storage_lock(&root)?;
2436    file.try_lock_shared().map_err(storage_lock_error)?;
2437    let lease = Arc::new(ProcessStorageLease {
2438        identity,
2439        _file: file,
2440        _root: root,
2441    });
2442    leases.insert(identity, Arc::downgrade(&lease));
2443    Ok(lease)
2444}
2445
2446pub fn ensure_config_storage_lease(config: &mut crate::config::Config) -> io::Result<()> {
2447    let storage = crate::storage_path::storage_dir(config.storage_dir.as_deref());
2448    crate::private_storage::open_root(&storage)?;
2449    let root = pin_storage_root(&storage)?;
2450    let owner = pinned_identity(&root)?;
2451    if config
2452        .storage_lease
2453        .as_ref()
2454        .is_some_and(|lease| owner == lease.identity)
2455    {
2456        return Ok(());
2457    }
2458    config.storage_lease = Some(acquire_pinned_storage_lease(root)?);
2459    Ok(())
2460}
2461
2462pub fn prepare_process_cache_root(
2463    config: &mut crate::config::Config,
2464) -> Option<crate::config_resolve::ConfigWarning> {
2465    if let Err(error) = ensure_config_storage_lease(config) {
2466        let storage = crate::storage_path::storage_dir(config.storage_dir.as_deref());
2467        record_split_durable(&storage, true);
2468        config.cache_unavailable = Some(error.to_string());
2469        config.cache_lease = None;
2470        return Some(unavailable_warning(&storage, &error.to_string()));
2471    }
2472    prepare_cache_root(config)
2473}
2474
2475#[rustfmt::skip]
2476test_support_visibility! {
2477
2478/// Hold exclusion across inventory, confirmation and deletion. A host-wide
2479/// process or connection-file check cannot identify which storage a daemon uses.
2480pub(crate) fn acquire_cache_cleanup_lease(storage: &Path) -> io::Result<File> {
2481    ensure_no_legacy_daemon()?;
2482    let root = pin_storage_root(storage)?;
2483    let file = open_daemon_storage_lock(&root)?;
2484    file.try_lock().map_err(|error| {
2485        let error = storage_lock_error(error);
2486        io::Error::new(
2487            error.kind(),
2488            format!(
2489                "stop the running daemon using storage root {} before cache cleanup: {error}",
2490                storage.display()
2491            ),
2492        )
2493    })?;
2494    Ok(file)
2495}
2496}
2497
2498fn storage_lock_error(error: std::fs::TryLockError) -> io::Error {
2499    match error {
2500        std::fs::TryLockError::WouldBlock => {
2501            io::Error::new(io::ErrorKind::WouldBlock, "storage lease contention")
2502        }
2503        std::fs::TryLockError::Error(error) => error,
2504    }
2505}
2506
2507#[cfg(any(test, feature = "test-support"))]
2508thread_local! { static LEGACY_DAEMON_PROCESSES: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) }; }
2509
2510/// Supply a synthetic process snapshot for this thread. An empty snapshot
2511/// skips the scan so unit tests do not inspect unrelated operator daemons.
2512#[cfg(any(test, feature = "test-support"))]
2513pub fn with_legacy_daemon_processes_for_test<R>(processes: String, run: impl FnOnce() -> R) -> R {
2514    struct Restore(Option<String>);
2515    impl Drop for Restore {
2516        fn drop(&mut self) {
2517            LEGACY_DAEMON_PROCESSES.with(|slot| slot.replace(self.0.take()));
2518        }
2519    }
2520    let _restore = Restore(LEGACY_DAEMON_PROCESSES.with(|slot| slot.replace(Some(processes))));
2521    run()
2522}
2523
2524#[cfg(any(test, feature = "test-support"))]
2525fn with_legacy_daemon_processes_for_test_if_unset<R>(run: impl FnOnce() -> R) -> R {
2526    if LEGACY_DAEMON_PROCESSES.with(|slot| slot.borrow().is_some()) {
2527        run()
2528    } else {
2529        with_legacy_daemon_processes_for_test(String::new(), run)
2530    }
2531}
2532
2533/// A process snapshot has one process per line:
2534/// `pid<TAB>executable<TAB>arguments`.
2535///
2536/// `executable` is the program's path or file name exactly as the operating
2537/// system records it, never a word split from a command line: a daemon at
2538/// `/Users/Jane Doe/.../subc` or `"C:\Program Files\AFT\subc.exe"` would
2539/// otherwise read as `Jane` or `"C:\Program`. A line without the second tab
2540/// means the process's arguments could not be read.
2541struct ListedProcess<'a> {
2542    pid: u32,
2543    executable: &'a str,
2544    args: Option<&'a str>,
2545}
2546
2547/// `None` for a line that does not name a process.
2548fn listed_process(line: &str) -> Option<ListedProcess<'_>> {
2549    let mut fields = line.trim_end_matches('\r').splitn(3, '\t');
2550    let pid = fields.next()?.trim().parse().ok()?;
2551    let executable = fields.next()?.trim();
2552    Some(ListedProcess {
2553        pid,
2554        executable,
2555        args: fields.next(),
2556    })
2557}
2558
2559/// Join the two `ps` queries into a snapshot: `ps -axo pid=,comm=` names each
2560/// process's executable as the whole rest of its line (so a path with spaces
2561/// stays whole), and `ps -axo pid=,args=` gives its command line. The
2562/// executable query defines the snapshot; a process missing from the
2563/// arguments query (it exited in between) has unknown arguments.
2564// Only the Unix scan runs two queries; tests exercise the join everywhere.
2565#[cfg_attr(
2566    all(windows, not(any(test, feature = "test-support"))),
2567    allow(dead_code)
2568)]
2569#[cfg_attr(not(test), allow(dead_code))]
2570fn compose_ps_snapshot(executables: &str, command_lines: &str) -> String {
2571    let flatten = |text: &str| text.replace('\t', " ");
2572    let args = command_lines
2573        .lines()
2574        .filter_map(|line| {
2575            let line = line.trim_start();
2576            let (pid, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
2577            Some((pid.parse::<u32>().ok()?, rest.trim()))
2578        })
2579        .collect::<HashMap<_, _>>();
2580    let mut snapshot = String::new();
2581    for line in executables.lines() {
2582        let line = line.trim();
2583        if line.is_empty() {
2584            continue;
2585        }
2586        let (pid, executable) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
2587        match pid.parse::<u32>() {
2588            Ok(pid) => {
2589                snapshot.push_str(&format!("{pid}\t{}", flatten(executable.trim())));
2590                if let Some(args) = args.get(&pid) {
2591                    snapshot.push('\t');
2592                    snapshot.push_str(&flatten(args));
2593                }
2594            }
2595            // Kept as is so the classifier reports the snapshot as unreadable.
2596            Err(_) => snapshot.push_str(line),
2597        }
2598        snapshot.push('\n');
2599    }
2600    snapshot
2601}
2602
2603/// Whether the snapshot lists a subc daemon other than this process.
2604///
2605/// Every doubt refuses: a snapshot that does not list this process (the scan
2606/// failed partway, returned nothing, or could not see every process), a line
2607/// that names no process, a process whose executable is unknown, or an aft
2608/// executable whose arguments are unknown cannot show that no older daemon is
2609/// running. Those are errors, and cleanup holds.
2610fn legacy_daemon_present(processes: &str, current_pid: u32) -> io::Result<bool> {
2611    let cannot_tell = |why: String| {
2612        io::Error::other(format!(
2613            "legacy_daemon_upgrade_window: cannot tell whether an older subc daemon is running ({why}); cleanup refused"
2614        ))
2615    };
2616    let mut lists_this_process = false;
2617    let mut present = false;
2618    for line in processes.lines().filter(|line| !line.trim().is_empty()) {
2619        let process = listed_process(line)
2620            .ok_or_else(|| cannot_tell(format!("unreadable process scan line {line:?}")))?;
2621        if process.pid == current_pid {
2622            lists_this_process = true;
2623            continue;
2624        }
2625        if process.executable.is_empty() {
2626            return Err(cannot_tell(format!(
2627                "the executable of process {} is unknown",
2628                process.pid
2629            )));
2630        }
2631        // Windows file names are case-insensitive; elsewhere a differently
2632        // cased name only makes the check stricter.
2633        let name = Path::new(process.executable)
2634            .file_name()
2635            .and_then(|name| name.to_str())
2636            .unwrap_or(process.executable)
2637            .to_ascii_lowercase();
2638        if matches!(name.as_str(), "subc" | "subc.exe") {
2639            present = true;
2640        } else if matches!(name.as_str(), "aft" | "aft.exe" | "ck-aft" | "ck-aft.exe") {
2641            let args = process.args.ok_or_else(|| {
2642                cannot_tell(format!(
2643                    "the arguments of {} process {} are unknown",
2644                    name, process.pid
2645                ))
2646            })?;
2647            present |= args
2648                .split_whitespace()
2649                .any(|word| word == "--subc" || word.starts_with("--subc="));
2650        }
2651    }
2652    if !lists_this_process {
2653        return Err(cannot_tell(
2654            "the process scan did not list this process".to_string(),
2655        ));
2656    }
2657    Ok(present)
2658}
2659
2660/// List every process in the snapshot format `legacy_daemon_present` reads.
2661fn legacy_process_query(label: &str, timeout: Duration) -> io::Result<String> {
2662    #[cfg(windows)]
2663    {
2664        let mut command = std::process::Command::new("powershell.exe");
2665        // `Name` is the executable's file name. Tabs separate the fields and
2666        // line breaks inside a command line are flattened, so each process is
2667        // one line; a command line Windows does not disclose is left out, which
2668        // marks its arguments unknown.
2669        command.args([
2670            "-NoProfile",
2671            "-NonInteractive",
2672            "-Command",
2673            "Get-CimInstance Win32_Process | ForEach-Object { if ($null -eq $_.CommandLine) { \"{0}`t{1}\" -f $_.ProcessId, $_.Name } else { \"{0}`t{1}`t{2}\" -f $_.ProcessId, $_.Name, ($_.CommandLine -replace '[\\r\\n\\t]+', ' ') } }",
2674        ]);
2675        legacy_process_snapshot(&mut command, label, timeout)
2676    }
2677    #[cfg(not(windows))]
2678    {
2679        let mut executables = std::process::Command::new("ps");
2680        executables.args(["-axo", "pid=,comm="]);
2681        let executables =
2682            legacy_process_snapshot(&mut executables, &format!("{label} (executables)"), timeout)?;
2683        let mut command_lines = std::process::Command::new("ps");
2684        command_lines.args(["-axo", "pid=,args="]);
2685        let command_lines =
2686            legacy_process_snapshot(&mut command_lines, &format!("{label} (arguments)"), timeout)?;
2687        Ok(compose_ps_snapshot(&executables, &command_lines))
2688    }
2689}
2690
2691fn legacy_process_snapshot(
2692    command: &mut std::process::Command,
2693    label: &str,
2694    timeout: Duration,
2695) -> io::Result<String> {
2696    use std::io::Read;
2697    use std::process::Stdio;
2698    use std::time::Instant;
2699
2700    command
2701        .stdin(Stdio::null())
2702        .stdout(Stdio::piped())
2703        .stderr(Stdio::null());
2704    #[cfg(unix)]
2705    {
2706        use std::os::unix::process::CommandExt;
2707        command.process_group(0);
2708    }
2709    let deadline = Instant::now() + timeout;
2710    let mut child = command.spawn().map_err(|error| {
2711        io::Error::new(
2712            error.kind(),
2713            format!("{label}: cannot start process scan: {error}; cleanup refused"),
2714        )
2715    })?;
2716    let mut stdout = child.stdout.take().expect("piped process snapshot stdout");
2717    let (sender, reader) = std::sync::mpsc::channel();
2718    std::thread::spawn(move || {
2719        let mut bytes = Vec::new();
2720        let result = stdout.read_to_end(&mut bytes).map(|_| bytes);
2721        let _ = sender.send(result);
2722    });
2723    let timed_out = |waiting_for: &str| {
2724        io::Error::new(
2725            io::ErrorKind::TimedOut,
2726            format!(
2727                "{label}: deadline {timeout:?} exceeded waiting for {waiting_for}; cleanup refused"
2728            ),
2729        )
2730    };
2731    let mut exited = false;
2732    let result = (|| {
2733        // Reading on a worker avoids blocking forever on a scan or inherited
2734        // stdout writer. Stdout EOF and child exit share the same deadline.
2735        let bytes = reader
2736            .recv_timeout(deadline.saturating_duration_since(Instant::now()))
2737            .map_err(|_| timed_out("process snapshot stdout EOF"))??;
2738        loop {
2739            if let Some(status) = child.try_wait()? {
2740                exited = true;
2741                if !status.success() {
2742                    return Err(io::Error::other(format!(
2743                        "{label} exited with {status}; cleanup refused"
2744                    )));
2745                }
2746                return Ok(String::from_utf8_lossy(&bytes).into_owned());
2747            }
2748            if Instant::now() >= deadline {
2749                return Err(timed_out("process snapshot exit"));
2750            }
2751            std::thread::sleep(Duration::from_millis(10));
2752        }
2753    })();
2754    if result.is_err() && !exited {
2755        // Terminate the scan's process group before reaping: a descendant can
2756        // retain stdout even after the direct child has exited.
2757        #[cfg(unix)]
2758        unsafe {
2759            libc::kill(-(child.id() as i32), libc::SIGKILL);
2760        }
2761        let _ = child.kill();
2762        let reap_deadline = Instant::now() + Duration::from_secs(2);
2763        while child.try_wait()?.is_none() {
2764            if Instant::now() >= reap_deadline {
2765                return Err(io::Error::new(io::ErrorKind::TimedOut, format!("{label}: deadline 2s exceeded waiting for terminated process snapshot to be reaped; cleanup refused")));
2766            }
2767            std::thread::sleep(Duration::from_millis(10));
2768        }
2769    }
2770    result
2771}
2772
2773fn ensure_no_legacy_daemon() -> io::Result<()> {
2774    // Upgrade-window protection: older daemons do not hold the durable-root
2775    // lock and cannot be excluded by it. Keep this host-wide refusal for this release.
2776    #[cfg(any(test, feature = "test-support"))]
2777    if let Some(processes) = LEGACY_DAEMON_PROCESSES.with(|slot| slot.borrow().clone()) {
2778        return if processes.is_empty() {
2779            Ok(())
2780        } else {
2781            refuse_legacy_daemon(&processes)
2782        };
2783    }
2784    #[cfg(test)]
2785    return Ok(());
2786    #[cfg(not(test))]
2787    refuse_legacy_daemon(&legacy_process_query(
2788        "legacy-daemon process scan",
2789        Duration::from_secs(10),
2790    )?)
2791}
2792
2793fn refuse_legacy_daemon(processes: &str) -> io::Result<()> {
2794    if legacy_daemon_present(processes, std::process::id())? {
2795        return Err(io::Error::other(
2796            "legacy_daemon_upgrade_window: stop the running subc daemon before cache cleanup",
2797        ));
2798    }
2799    Ok(())
2800}
2801
2802/// `aft cache prune-legacy`: deletes the index stores AFT used before version
2803/// 0.64. From 0.64 every index lives in `data/` and nothing opens the old
2804/// stores, so this runs while AFT daemons keep running. It never deletes on its
2805/// own initiative; the command is the only caller.
2806///
2807/// Safety rules, in the order a run applies them:
2808/// - The storage root must prove it is AFT's (`aft.db` or its owner marker).
2809///   An external `storage.cache_dir` root must carry an owner marker naming
2810///   that storage root and be listed in the storage root's record of the cache
2811///   roots it prepared (`retention/cache-roots.json`).
2812/// - Only the fixed folder names below are candidates, plus each child of
2813///   `semantic/` except the live `semantic/models/`. Each is opened without
2814///   following symlinks and must be a real folder on the root's own device and
2815///   mount; a symlink, a mount point or a folder on another device is skipped.
2816/// - A bounded walk sizes each candidate and refuses one that holds a mount, a
2817///   hard-linked file or a special file within the part it read.
2818/// - With `--yes`, each candidate is first renamed into
2819///   `<root>/.prune-legacy-<time>-<pid>/` on the same filesystem, and only that
2820///   moved copy is deleted. A folder that cannot be renamed (on Windows, a
2821///   file open inside it) is skipped, never deleted in place.
2822/// - Deletion runs in bounded passes that never follow links or cross mounts.
2823///   A run that stops early leaves the moved folder behind, and the next run
2824///   deletes every `.prune-legacy-*` leftover.
2825mod prune_legacy {
2826    use std::ffi::{OsStr, OsString};
2827    use std::fs;
2828    use std::io;
2829    use std::path::{Path, PathBuf};
2830    use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
2831
2832    use super::{
2833        known_harness, marker_matches_pinned, paths_overlap, pin_storage_root, pinned_identity,
2834        storage_root_proven, DAEMON_USE,
2835    };
2836    use crate::pinned_dir::{PinnedDir, RepairBudget, RepairLimitExceeded};
2837
2838    /// The stores AFT kept directly under a storage or cache root before 0.64.
2839    /// `semantic/` is handled apart (see `SEMANTIC_DIR`).
2840    pub(super) const LEGACY_STORE_DIRS: [&str; 8] = [
2841        "views",
2842        "blobs",
2843        "callgraph",
2844        "index",
2845        "symbols",
2846        "artifact-owners",
2847        "migration",
2848        "semantic-batch-leases-v1",
2849    ];
2850    /// Each harness folder (`opencode/`, `pi/`, ...) once held its own call
2851    /// graph store under this name. Nothing else in a harness folder is touched.
2852    pub(super) const LEGACY_HARNESS_STORE_DIR: &str = "callgraph";
2853    /// `semantic/` mixes old per-project indexes with this live folder: the
2854    /// embedding and reranker models AFT downloads (`FASTEMBED_CACHE_DIR`
2855    /// and `semantic.local_cache_dir` point here). It is kept, so every other
2856    /// child of `semantic/` is a candidate on its own instead of the folder.
2857    pub(super) const SEMANTIC_DIR: &str = "semantic";
2858    pub(super) const SEMANTIC_MODELS_DIR: &str = "models";
2859    /// Name prefix of the folder a run moves stores into before deleting them.
2860    pub(super) const ASIDE_PREFIX: &str = ".prune-legacy-";
2861    /// Held exclusively for a whole `--yes` run so two runs never delete the
2862    /// same moved folder at once. Lives in `retention/` with the other
2863    /// storage-root locks.
2864    const RUN_LOCK: &str = "prune-legacy.lock";
2865    /// Most entries one size walk reads before it reports a lower bound.
2866    const SIZE_ENTRY_LIMIT: usize = 500_000;
2867    /// Longest one size walk runs before it reports a lower bound.
2868    const SIZE_TIME_LIMIT: Duration = Duration::from_secs(20);
2869    /// Deepest folder nesting the deletion walk accepts (see `RepairBudget`).
2870    const MAX_DEPTH: usize = 64;
2871    /// Most bounded deletion passes over one folder. Each pass removes up to
2872    /// one `RepairBudget` worth of entries, and a pass that removes nothing
2873    /// ends the deletion, so this only caps a pathological tree.
2874    const MAX_DELETE_PASSES: usize = 10_000;
2875
2876    #[cfg(any(test, feature = "test-support"))]
2877    thread_local! {
2878        /// Folder names whose rename aside fails, as it does on Windows while
2879        /// a file inside the folder is open.
2880        pub(super) static RENAME_REFUSED: std::cell::RefCell<Vec<OsString>> =
2881            const { std::cell::RefCell::new(Vec::new()) };
2882        /// Stop a `--yes` run right after the moves, as a crash would.
2883        pub(super) static STOP_AFTER_MOVE: std::cell::Cell<bool> =
2884            const { std::cell::Cell::new(false) };
2885    }
2886
2887    /// One folder a run found.
2888    #[derive(Clone, Debug, PartialEq, Eq)]
2889    pub struct LegacyStore {
2890        /// Where the folder was found, before any move.
2891        pub path: PathBuf,
2892        /// Bytes counted by the bounded size walk.
2893        pub bytes: u64,
2894        /// False when the size walk stopped at its bound, so `bytes` is only
2895        /// a lower bound.
2896        pub complete: bool,
2897        /// A `.prune-legacy-*` folder that an earlier, interrupted run left.
2898        pub leftover: bool,
2899    }
2900
2901    /// A folder the run left in place, with the reason in plain words.
2902    #[derive(Clone, Debug, PartialEq, Eq)]
2903    pub struct LegacyStoreSkip {
2904        pub path: PathBuf,
2905        pub reason: String,
2906    }
2907
2908    #[derive(Debug, Default)]
2909    pub struct PruneLegacyReport {
2910        /// Every root the run examined, the storage root first. Empty when
2911        /// the storage root does not exist.
2912        pub roots: Vec<PathBuf>,
2913        /// Folders a dry run would delete, or a `--yes` run tried to delete.
2914        pub stores: Vec<LegacyStore>,
2915        /// Folders a `--yes` run deleted.
2916        pub removed: Vec<LegacyStore>,
2917        /// Folders (or a whole cache root) the run left in place.
2918        pub skipped: Vec<LegacyStoreSkip>,
2919        /// Things the run could not check, such as an unreadable config.
2920        pub notes: Vec<String>,
2921    }
2922
2923    /// Reported while a `--yes` run works, so a long deletion shows progress.
2924    #[derive(Debug)]
2925    pub enum PruneLegacyEvent<'a> {
2926        Deleting(&'a LegacyStore),
2927        Removed(&'a LegacyStore),
2928        Skipped(&'a LegacyStoreSkip),
2929    }
2930
2931    #[derive(Debug)]
2932    pub enum PruneLegacyError {
2933        /// The run stopped before changing anything; the text says why.
2934        Refused(String),
2935        /// An unexpected I/O failure.
2936        Failed(io::Error),
2937    }
2938
2939    impl From<io::Error> for PruneLegacyError {
2940        fn from(error: io::Error) -> Self {
2941            Self::Failed(error)
2942        }
2943    }
2944
2945    /// One root to clean: the storage root or the external cache root.
2946    struct Root {
2947        dir: PinnedDir,
2948        /// Identities of the directories kept at the top of this root. A
2949        /// deletion walk that meets one of them (through a bind mount or an
2950        /// aliased directory) stops instead of deleting it.
2951        protected: Vec<(u64, u64)>,
2952        candidates: Vec<Candidate>,
2953    }
2954
2955    /// A folder that passed every check and may be moved and deleted.
2956    struct Candidate {
2957        store: LegacyStore,
2958        /// The folder that holds it: the root, or a harness folder.
2959        parent: PinnedDir,
2960        name: OsString,
2961        identity: (u64, u64),
2962    }
2963
2964    /// Lists (and with `yes`, deletes) the legacy stores under `storage` and
2965    /// under the external cache root `storage.cache_dir` from `tiers`.
2966    pub fn prune_legacy_stores(
2967        tiers: &[crate::config_resolve::ConfigTier],
2968        storage: &Path,
2969        yes: bool,
2970        on_event: &mut dyn FnMut(PruneLegacyEvent<'_>),
2971    ) -> Result<PruneLegacyReport, PruneLegacyError> {
2972        let mut report = PruneLegacyReport::default();
2973        match fs::symlink_metadata(storage) {
2974            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(report),
2975            Err(error) => return Err(error.into()),
2976            Ok(_) => {}
2977        }
2978        let storage_dir = pin_storage_root(storage).map_err(|error| {
2979            PruneLegacyError::Refused(format!(
2980                "Cannot open the AFT storage folder {}: {error}",
2981                storage.display()
2982            ))
2983        })?;
2984        if !storage_root_proven(&storage_dir)? {
2985            return Err(PruneLegacyError::Refused(format!(
2986                "{} does not look like an AFT storage folder: it has no aft.db and no AFT owner marker.",
2987                storage.display()
2988            )));
2989        }
2990        // A dry run only reads, so it takes no lock and writes nothing.
2991        let _locks = if yes {
2992            Some(lock_run(&storage_dir, storage)?)
2993        } else {
2994            None
2995        };
2996        let mut roots = vec![storage_dir.repair_clone()?];
2997        if let Some(cache) = external_cache_root(tiers, storage, &storage_dir, &mut report)? {
2998            roots.push(cache);
2999        }
3000        let mut planned = Vec::new();
3001        for dir in roots {
3002            report.roots.push(dir.path().to_path_buf());
3003            planned.push(plan_root(dir, &mut report)?);
3004        }
3005        if !yes {
3006            return Ok(report);
3007        }
3008        for root in planned {
3009            delete_root(root, &mut report, on_event)?;
3010        }
3011        Ok(report)
3012    }
3013
3014    /// Takes the run lock and a shared hold on the storage root's daemon lock.
3015    /// Daemons share that lock too, so AFT keeps running; an old-cache cleanup
3016    /// takes it exclusively and so never deletes the same folders at once.
3017    fn lock_run(
3018        storage_dir: &PinnedDir,
3019        storage: &Path,
3020    ) -> Result<Vec<fs::File>, PruneLegacyError> {
3021        let retention = storage_dir.repair_descendant(Path::new("retention"), true)?;
3022        let busy = || {
3023            PruneLegacyError::Refused(format!(
3024                "Another cleanup is running on {}. Try again when it has finished.",
3025                storage.display()
3026            ))
3027        };
3028        let run = retention.repair_coordination_file(OsStr::new(RUN_LOCK))?;
3029        match run.try_lock() {
3030            Ok(()) => {}
3031            Err(std::fs::TryLockError::WouldBlock) => return Err(busy()),
3032            Err(std::fs::TryLockError::Error(error)) => return Err(error.into()),
3033        }
3034        let daemon = retention.repair_coordination_file(OsStr::new(DAEMON_USE))?;
3035        match daemon.try_lock_shared() {
3036            Ok(()) => {}
3037            Err(std::fs::TryLockError::WouldBlock) => return Err(busy()),
3038            Err(std::fs::TryLockError::Error(error)) => return Err(error.into()),
3039        }
3040        Ok(vec![run, daemon])
3041    }
3042
3043    /// The `aft/` folder under a configured `storage.cache_dir`, once it is
3044    /// proven to belong to `storage`. Anything that prevents checking it is
3045    /// reported, never treated as "nothing there".
3046    fn external_cache_root(
3047        tiers: &[crate::config_resolve::ConfigTier],
3048        storage: &Path,
3049        storage_dir: &PinnedDir,
3050        report: &mut PruneLegacyReport,
3051    ) -> io::Result<Option<PinnedDir>> {
3052        let resolved = crate::config_resolve::resolve_config(tiers);
3053        if !resolved.errors.is_empty() {
3054            report.notes.push(
3055                "Your AFT config has errors, so a cache folder set by storage.cache_dir was not checked."
3056                    .to_string(),
3057            );
3058            return Ok(None);
3059        }
3060        if let Some(reason) = &resolved.config.cache_config_unknown {
3061            report.notes.push(format!(
3062                "AFT could not tell whether storage.cache_dir is set, so no cache folder was checked: {reason}"
3063            ));
3064            return Ok(None);
3065        }
3066        let Some(cache_dir) = resolved.config.cache_dir else {
3067            return Ok(None);
3068        };
3069        let root = cache_dir.join("aft");
3070        match fs::symlink_metadata(&root) {
3071            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
3072            Err(error) => return Err(error),
3073            Ok(_) => {}
3074        }
3075        let skip = |report: &mut PruneLegacyReport, reason: String| {
3076            report.skipped.push(LegacyStoreSkip {
3077                path: root.clone(),
3078                reason,
3079            });
3080            Ok(None)
3081        };
3082        if !root.is_absolute() {
3083            return skip(
3084                report,
3085                "storage.cache_dir is not an absolute path, so this folder was not checked."
3086                    .to_string(),
3087            );
3088        }
3089        let dir = match pin_storage_root(&root) {
3090            Ok(dir) => dir,
3091            Err(error) => return skip(report, format!("It could not be opened: {error}")),
3092        };
3093        if pinned_identity(&dir)? == pinned_identity(storage_dir)? {
3094            // The same folder as the storage root, which is already checked.
3095            return Ok(None);
3096        }
3097        if paths_overlap(&root, storage) {
3098            return skip(
3099                report,
3100                "It is inside the storage folder or contains it, so it was not checked separately."
3101                    .to_string(),
3102            );
3103        }
3104        if let Err(error) = marker_matches_pinned(&dir, storage_dir) {
3105            return skip(
3106                report,
3107                format!("It is not proven to belong to this AFT storage folder: {error}"),
3108            );
3109        }
3110        Ok(Some(dir))
3111    }
3112
3113    /// Finds and checks every candidate under one root. Adds each admitted
3114    /// folder to `report.stores` and each refused one to `report.skipped`.
3115    fn plan_root(dir: PinnedDir, report: &mut PruneLegacyReport) -> io::Result<Root> {
3116        let mut protected = vec![dir.directory_identity()?];
3117        // (parent, name, leftover) for every folder that may be a candidate.
3118        let mut found: Vec<(PinnedDir, OsString, bool)> = Vec::new();
3119        let mut names = dir.repair_names(&mut RepairBudget::new())?;
3120        names.sort();
3121        for name in names {
3122            let text = name.to_str();
3123            if text == Some(SEMANTIC_DIR) {
3124                match dir.repair_child(&name) {
3125                    Ok(semantic) => {
3126                        protected.push(semantic.directory_identity()?);
3127                        let mut inner_names = semantic.repair_names(&mut RepairBudget::new())?;
3128                        inner_names.sort();
3129                        for inner in inner_names {
3130                            if inner == OsStr::new(SEMANTIC_MODELS_DIR) {
3131                                if let Ok(models) = semantic.repair_child(&inner) {
3132                                    protected.push(models.directory_identity()?);
3133                                }
3134                                continue;
3135                            }
3136                            // Old indexes are per-project folders. A plain
3137                            // file here is no store, so it stays unmentioned;
3138                            // a link is still listed and refused.
3139                            let plain_file = fs::symlink_metadata(semantic.path().join(&inner))
3140                                .is_ok_and(|metadata| metadata.is_file());
3141                            if !plain_file {
3142                                found.push((semantic.repair_clone()?, inner, false));
3143                            }
3144                        }
3145                    }
3146                    // Not a real folder: the check below names the reason.
3147                    Err(_) => found.push((dir.repair_clone()?, name, false)),
3148                }
3149                continue;
3150            }
3151            if text.is_some_and(|text| LEGACY_STORE_DIRS.contains(&text)) {
3152                found.push((dir.repair_clone()?, name, false));
3153                continue;
3154            }
3155            if text.is_some_and(|text| text.starts_with(ASIDE_PREFIX)) {
3156                found.push((dir.repair_clone()?, name, true));
3157                continue;
3158            }
3159            // Everything else at the top of the root is kept. Remember the
3160            // identity of each kept folder so no deletion walk can reach it.
3161            let Ok(child) = dir.repair_child(&name) else {
3162                continue;
3163            };
3164            protected.push(child.directory_identity()?);
3165            if !text.is_some_and(known_harness) {
3166                continue;
3167            }
3168            for inner in child.repair_names(&mut RepairBudget::new())? {
3169                if inner == OsStr::new(LEGACY_HARNESS_STORE_DIR) {
3170                    found.push((child.repair_clone()?, inner, false));
3171                } else if let Ok(kept) = child.repair_child(&inner) {
3172                    protected.push(kept.directory_identity()?);
3173                }
3174            }
3175        }
3176        let mut candidates = Vec::new();
3177        for (parent, name, leftover) in found {
3178            let path = parent.path().join(&name);
3179            match check_candidate(&dir, &parent, &name, &protected) {
3180                Ok(None) => {}
3181                Ok(Some((identity, bytes, complete))) => {
3182                    let store = LegacyStore {
3183                        path,
3184                        bytes,
3185                        complete,
3186                        leftover,
3187                    };
3188                    report.stores.push(store.clone());
3189                    candidates.push(Candidate {
3190                        store,
3191                        parent,
3192                        name,
3193                        identity,
3194                    });
3195                }
3196                Err(reason) => report.skipped.push(LegacyStoreSkip { path, reason }),
3197            }
3198        }
3199        Ok(Root {
3200            dir,
3201            protected,
3202            candidates,
3203        })
3204    }
3205
3206    /// Opens `name` in `parent` without following a link and sizes it. `None`
3207    /// when it is gone; `Err` holds the reason it must be left in place.
3208    fn check_candidate(
3209        root: &PinnedDir,
3210        parent: &PinnedDir,
3211        name: &OsStr,
3212        protected: &[(u64, u64)],
3213    ) -> Result<Option<((u64, u64), u64, bool)>, String> {
3214        let folder = match parent.repair_child(name) {
3215            Ok(folder) => folder,
3216            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
3217            Err(error) if leaf_error(&error) => {
3218                // Looking up the path's own metadata (without following a
3219                // link) only names the entry's kind for the message; the
3220                // entry itself is never opened through the link.
3221                let link = fs::symlink_metadata(parent.path().join(name))
3222                    .is_ok_and(|metadata| metadata.file_type().is_symlink());
3223                return Err(if link {
3224                    "It is a symbolic link. This command never follows links.".to_string()
3225                } else {
3226                    "It is not a folder.".to_string()
3227                });
3228            }
3229            Err(error) => return Err(format!("It could not be opened: {error}")),
3230        };
3231        if folder.repair_check_boundary(root, protected).is_err() {
3232            return Err(
3233                "It is on another disk or is a mount point, so it was left alone.".to_string(),
3234            );
3235        }
3236        let identity = folder
3237            .directory_identity()
3238            .map_err(|error| format!("It could not be checked: {error}"))?;
3239        let mut walk = SizeWalk {
3240            bytes: 0,
3241            entries: 0,
3242            deadline: Instant::now() + SIZE_TIME_LIMIT,
3243            budget: RepairBudget::new(),
3244        };
3245        match walk.measure(&folder, root, protected, 0) {
3246            Ok(()) => Ok(Some((identity, walk.bytes, true))),
3247            Err(SizeStop::Bound) => Ok(Some((identity, walk.bytes, false))),
3248            Err(SizeStop::Refuse(reason)) => Err(reason),
3249        }
3250    }
3251
3252    /// Whether opening an entry as a folder failed because it is not one: a
3253    /// file, or a symlink that a no-follow open refuses.
3254    fn leaf_error(error: &io::Error) -> bool {
3255        #[cfg(unix)]
3256        if error.raw_os_error() == Some(libc::ELOOP) {
3257            return true;
3258        }
3259        error.kind() == io::ErrorKind::NotADirectory
3260    }
3261
3262    fn budget_stop(error: &io::Error) -> bool {
3263        error
3264            .get_ref()
3265            .is_some_and(|inner| inner.is::<RepairLimitExceeded>())
3266    }
3267
3268    enum SizeStop {
3269        /// The walk reached its entry or time bound; the count is a lower bound.
3270        Bound,
3271        /// The folder holds something this command must not delete.
3272        Refuse(String),
3273    }
3274
3275    /// A bounded size walk that also refuses what deletion must not touch.
3276    /// It checks its bound before every entry, not after a whole folder.
3277    struct SizeWalk {
3278        bytes: u64,
3279        entries: usize,
3280        deadline: Instant,
3281        budget: RepairBudget,
3282    }
3283
3284    impl SizeWalk {
3285        fn measure(
3286            &mut self,
3287            folder: &PinnedDir,
3288            root: &PinnedDir,
3289            protected: &[(u64, u64)],
3290            depth: usize,
3291        ) -> Result<(), SizeStop> {
3292            if depth > MAX_DEPTH {
3293                return Err(SizeStop::Refuse(format!(
3294                    "It is nested more than {MAX_DEPTH} folders deep."
3295                )));
3296            }
3297            if folder.repair_check_boundary(root, protected).is_err() {
3298                return Err(SizeStop::Refuse(format!(
3299                    "It contains {}, which is a mount point or on another disk.",
3300                    folder.path().display()
3301                )));
3302            }
3303            let names = match folder.repair_names(&mut self.budget) {
3304                Ok(names) => names,
3305                Err(error) if budget_stop(&error) => return Err(SizeStop::Bound),
3306                Err(error) => {
3307                    return Err(SizeStop::Refuse(format!(
3308                        "{} could not be listed: {error}",
3309                        folder.path().display()
3310                    )))
3311                }
3312            };
3313            for name in names {
3314                self.entries += 1;
3315                if self.entries > SIZE_ENTRY_LIMIT || Instant::now() >= self.deadline {
3316                    return Err(SizeStop::Bound);
3317                }
3318                match folder.repair_child(&name) {
3319                    Ok(child) => self.measure(&child, root, protected, depth + 1)?,
3320                    Err(error) if error.kind() == io::ErrorKind::NotFound => {}
3321                    Err(error) if leaf_error(&error) => match folder.repair_read_file(&name) {
3322                        Ok(file) => {
3323                            let length = file.metadata().map(|metadata| metadata.len());
3324                            self.bytes = self.bytes.saturating_add(length.unwrap_or(0));
3325                        }
3326                        // A symlink is deleted as a link; its target is never
3327                        // opened or counted.
3328                        Err(error) if leaf_error(&error) => {}
3329                        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
3330                        Err(error) => {
3331                            return Err(SizeStop::Refuse(format!(
3332                                "It contains {}, which has more than one hard link or is not a regular file ({error}).",
3333                                folder.path().join(&name).display()
3334                            )))
3335                        }
3336                    },
3337                    Err(error) => {
3338                        return Err(SizeStop::Refuse(format!(
3339                            "{} could not be opened: {error}",
3340                            folder.path().join(&name).display()
3341                        )))
3342                    }
3343                }
3344            }
3345            Ok(())
3346        }
3347    }
3348
3349    /// Moves every admitted folder of one root aside, then deletes what moved
3350    /// and every leftover from earlier runs.
3351    fn delete_root(
3352        root: Root,
3353        report: &mut PruneLegacyReport,
3354        on_event: &mut dyn FnMut(PruneLegacyEvent<'_>),
3355    ) -> io::Result<()> {
3356        let Root {
3357            dir,
3358            protected,
3359            candidates,
3360        } = root;
3361        let (leftovers, stores): (Vec<_>, Vec<_>) = candidates
3362            .into_iter()
3363            .partition(|candidate| candidate.store.leftover);
3364        // Each moved folder is deleted from inside the aside folder:
3365        // (store, its name there, its identity).
3366        let mut moved: Vec<(LegacyStore, OsString, (u64, u64))> = Vec::new();
3367        let mut aside: Option<(PinnedDir, OsString)> = None;
3368        for (index, candidate) in stores.into_iter().enumerate() {
3369            if aside.is_none() {
3370                aside = Some(create_aside(&dir)?);
3371            }
3372            let (aside_dir, _) = aside.as_ref().expect("aside folder was just created");
3373            // A harness store keeps its harness in its moved name so two
3374            // `callgraph` folders never collide.
3375            let target = OsString::from(format!(
3376                "{index}-{}",
3377                candidate
3378                    .store
3379                    .path
3380                    .strip_prefix(dir.path())
3381                    .unwrap_or(&candidate.store.path)
3382                    .to_string_lossy()
3383                    .replace(['/', '\\'], "-")
3384            ));
3385            match move_aside(&candidate, aside_dir, &target) {
3386                Ok(()) => moved.push((candidate.store, target, candidate.identity)),
3387                Err(error) => {
3388                    let skip = LegacyStoreSkip {
3389                        path: candidate.store.path,
3390                        reason: format!(
3391                            "It could not be moved aside, so nothing in it was deleted: {error}"
3392                        ),
3393                    };
3394                    on_event(PruneLegacyEvent::Skipped(&skip));
3395                    report.skipped.push(skip);
3396                }
3397            }
3398        }
3399        #[cfg(any(test, feature = "test-support"))]
3400        if STOP_AFTER_MOVE.with(|stop| stop.get()) {
3401            return Ok(());
3402        }
3403        if let Some((aside_dir, aside_name)) = &aside {
3404            for (store, name, identity) in moved {
3405                on_event(PruneLegacyEvent::Deleting(&store));
3406                match delete_in_passes(aside_dir, &name, identity, &protected) {
3407                    Ok(()) => {
3408                        on_event(PruneLegacyEvent::Removed(&store));
3409                        report.removed.push(store);
3410                    }
3411                    Err(error) => {
3412                        let skip = LegacyStoreSkip {
3413                            reason: format!(
3414                                "It was moved to {} but not fully deleted: {error}. The next run tries again.",
3415                                aside_dir.path().join(&name).display()
3416                            ),
3417                            path: store.path,
3418                        };
3419                        on_event(PruneLegacyEvent::Skipped(&skip));
3420                        report.skipped.push(skip);
3421                    }
3422                }
3423            }
3424            // The aside folder is empty unless something above was kept.
3425            let aside_identity = aside_dir.directory_identity()?;
3426            if aside_dir.repair_names(&mut RepairBudget::new())?.is_empty() {
3427                delete_in_passes(&dir, aside_name, aside_identity, &protected)?;
3428            }
3429        }
3430        for leftover in leftovers {
3431            on_event(PruneLegacyEvent::Deleting(&leftover.store));
3432            match delete_in_passes(
3433                &leftover.parent,
3434                &leftover.name,
3435                leftover.identity,
3436                &protected,
3437            ) {
3438                Ok(()) => {
3439                    on_event(PruneLegacyEvent::Removed(&leftover.store));
3440                    report.removed.push(leftover.store);
3441                }
3442                Err(error) => {
3443                    let skip = LegacyStoreSkip {
3444                        path: leftover.store.path,
3445                        reason: format!(
3446                            "It was not fully deleted: {error}. The next run tries again."
3447                        ),
3448                    };
3449                    on_event(PruneLegacyEvent::Skipped(&skip));
3450                    report.skipped.push(skip);
3451                }
3452            }
3453        }
3454        Ok(())
3455    }
3456
3457    /// Creates `<root>/.prune-legacy-<unix-millis>-<pid>[-n]/`.
3458    fn create_aside(root: &PinnedDir) -> io::Result<(PinnedDir, OsString)> {
3459        let millis = SystemTime::now()
3460            .duration_since(UNIX_EPOCH)
3461            .map(|elapsed| elapsed.as_millis())
3462            .unwrap_or(0);
3463        let base = format!("{ASIDE_PREFIX}{millis}-{}", std::process::id());
3464        for attempt in 0..16 {
3465            let name = OsString::from(if attempt == 0 {
3466                base.clone()
3467            } else {
3468                format!("{base}-{attempt}")
3469            });
3470            match root.repair_create_dir(&name) {
3471                Ok(created) => return Ok((created, name)),
3472                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
3473                Err(error) => return Err(error),
3474            }
3475        }
3476        Err(io::Error::new(
3477            io::ErrorKind::AlreadyExists,
3478            format!("every {base}-* name is taken"),
3479        ))
3480    }
3481
3482    /// Renames one folder into the aside folder with a single rename that
3483    /// never replaces anything, after checking it is still the folder sized
3484    /// earlier.
3485    fn move_aside(candidate: &Candidate, aside: &PinnedDir, target: &OsStr) -> io::Result<()> {
3486        #[cfg(any(test, feature = "test-support"))]
3487        if RENAME_REFUSED.with(|names| names.borrow().iter().any(|name| *name == candidate.name)) {
3488            return Err(io::Error::new(
3489                io::ErrorKind::PermissionDenied,
3490                "a file inside it is open (simulated)",
3491            ));
3492        }
3493        let entry = candidate.parent.repair_entry_for_rename(&candidate.name)?;
3494        if entry.identity()? != candidate.identity {
3495            return Err(io::Error::other("it changed while it was being checked"));
3496        }
3497        candidate
3498            .parent
3499            .repair_rename_entry_to(&candidate.name, &entry, aside, target)
3500    }
3501
3502    /// Deletes folder `name` inside `parent` in bounded passes. Each pass reads
3503    /// at most one `RepairBudget` of entries, never follows a link and stops
3504    /// at a mount or a protected folder. Passes repeat while they make
3505    /// progress, so a large store is deleted in one run.
3506    fn delete_in_passes(
3507        parent: &PinnedDir,
3508        name: &OsStr,
3509        identity: (u64, u64),
3510        protected: &[(u64, u64)],
3511    ) -> io::Result<()> {
3512        let mut warnings = Vec::new();
3513        for _ in 0..MAX_DELETE_PASSES {
3514            let mut removed = 0;
3515            match parent.repair_remove_child_with_budget(
3516                name,
3517                identity,
3518                protected,
3519                &mut removed,
3520                &mut warnings,
3521                &mut RepairBudget::new(),
3522            ) {
3523                Ok(()) => return Ok(()),
3524                Err(error) if removed > 0 && budget_stop(&error) => continue,
3525                Err(error) => return Err(error),
3526            }
3527        }
3528        Err(io::Error::other(RepairLimitExceeded))
3529    }
3530}
3531
3532pub const CACHE_DOMAINS: [&str; 8] = [
3533    "grammars",
3534    "views",
3535    "blobs",
3536    "callgraph",
3537    "semantic",
3538    "index",
3539    "symbols",
3540    "inspect",
3541];
3542
3543pub fn canonical_root(project_root: &Path) -> PathBuf {
3544    // Nearest-existing-ancestor canonicalization, not a raw-spelling fallback:
3545    // registration can precede the directory's creation (and lookups can follow
3546    // it), and on macOS the raw tempdir spelling (/var/...) differs from the
3547    // canonical one (/private/var/...). Keying the access registry by whichever
3548    // spelling happened to win the existence race made a registered root miss
3549    // its own entry and fail closed.
3550    canonical_process_lease_dir(project_root)
3551}
3552
3553pub fn canonical_process_lease_dir(path: &Path) -> PathBuf {
3554    if let Ok(canonical) = std::fs::canonicalize(path) {
3555        return canonical;
3556    }
3557
3558    let normalized = lexical_normalize(path);
3559    let mut missing_components = Vec::new();
3560    let mut current = normalized.as_path();
3561    while !current.exists() {
3562        let Some(name) = current.file_name() else {
3563            return normalized;
3564        };
3565        missing_components.push(name.to_os_string());
3566        let Some(parent) = current.parent() else {
3567            return normalized;
3568        };
3569        current = parent;
3570    }
3571
3572    let mut canonical = std::fs::canonicalize(current).unwrap_or_else(|_| current.to_path_buf());
3573    for component in missing_components.iter().rev() {
3574        canonical.push(component);
3575    }
3576    canonical
3577}
3578
3579fn lexical_normalize(path: &Path) -> PathBuf {
3580    let mut normalized = PathBuf::new();
3581    for component in path.components() {
3582        match component {
3583            std::path::Component::CurDir => {}
3584            std::path::Component::ParentDir => {
3585                normalized.pop();
3586            }
3587            other => normalized.push(other.as_os_str()),
3588        }
3589    }
3590    normalized
3591}
3592
3593pub fn existing_ancestor(path: &Path) -> PathBuf {
3594    let mut current = path;
3595    loop {
3596        if current.exists() {
3597            return current.to_path_buf();
3598        }
3599        let Some(parent) = current.parent() else {
3600            return PathBuf::from(".");
3601        };
3602        current = parent;
3603    }
3604}
3605
3606#[cfg(any(test, feature = "test-support"))]
3607#[path = "cache_location_tests.rs"]
3608#[cfg_attr(not(test), allow(dead_code, unused_imports))]
3609pub mod tests;
3610
3611#[cfg(any(test, feature = "test-support"))]
3612#[path = "gh_shim_speech/serving_tests.rs"]
3613#[cfg_attr(not(test), allow(dead_code, unused_imports))]
3614pub mod speech_serving_tests;
3615
3616#[cfg(any(test, feature = "test-support"))]
3617#[cfg_attr(not(test), allow(dead_code, unused_imports))]
3618pub mod prune_legacy_tests {
3619    use super::prune_legacy::ASIDE_PREFIX;
3620    #[cfg(test)]
3621    use super::prune_legacy::RENAME_REFUSED;
3622    #[cfg(test)]
3623    use super::prune_legacy::STOP_AFTER_MOVE;
3624    use super::*;
3625    use std::collections::BTreeMap;
3626
3627    #[cfg(test)]
3628    use std::ffi::OsString;
3629
3630    /// Every legacy entry the fixture plants, relative to the storage root.
3631    const LEGACY: [&str; 12] = [
3632        "views/view-1/derived.sqlite",
3633        "blobs/ab/cdef",
3634        "callgraph/key-1/build-breaker.sqlite",
3635        "index/key-1/cache.bin",
3636        "semantic/key-1/semantic.bin",
3637        "semantic/key-2/semantic.bin",
3638        "symbols/key-1/symbols.sqlite",
3639        "artifact-owners/owner.json",
3640        "migration/state.json",
3641        "semantic-batch-leases-v1/lease.json",
3642        "opencode/callgraph/key-1/graph.sqlite",
3643        "pi/callgraph/key-2/graph.sqlite",
3644    ];
3645    /// The folders a run must find for `LEGACY`, written out by hand so the
3646    /// expectation does not reuse the code's own list.
3647    const LEGACY_FOLDERS: [&str; 12] = [
3648        "artifact-owners",
3649        "blobs",
3650        "callgraph",
3651        "index",
3652        "migration",
3653        "opencode/callgraph",
3654        "pi/callgraph",
3655        "semantic-batch-leases-v1",
3656        "semantic/key-1",
3657        "semantic/key-2",
3658        "symbols",
3659        "views",
3660    ];
3661    /// What a run must leave byte-identical.
3662    const PROTECTED: [&str; 15] = [
3663        "aft.db",
3664        "aft.db-wal",
3665        "cache-keys.json",
3666        "data/store/main.sqlite",
3667        "inspect/key-1/inspect.sqlite",
3668        "retention/daemon-use.lock",
3669        "root-identities/key-1.json",
3670        "backups/session/stack",
3671        "opencode/inspect/key-1/inspect.sqlite",
3672        "opencode/sessions/one.json",
3673        "pi/settings.json",
3674        "semantic/models/models--Qdrant--all-MiniLM-L6-v2-onnx/model.onnx",
3675        "semantic/notes.txt",
3676        "unknown-folder/views/keep",
3677        "views.txt",
3678    ];
3679
3680    struct Fixture {
3681        _temp: tempfile::TempDir,
3682        base: PathBuf,
3683        storage: PathBuf,
3684    }
3685
3686    fn fixture() -> Fixture {
3687        let temp = tempfile::tempdir().unwrap();
3688        // Canonical, so test hooks keyed by path match the pinned spelling
3689        // (macOS reaches temp folders through /var -> /private/var).
3690        let base = fs::canonicalize(temp.path()).unwrap();
3691        // On Windows canonical paths carry the verbatim `\\?\` prefix, and
3692        // the command reports and keys paths in their plain spelling.
3693        #[cfg(windows)]
3694        let base = crate::windows_path::normalize_windows_path(&base);
3695        let storage = base.join("storage");
3696        for relative in LEGACY.iter().chain(&PROTECTED) {
3697            let path = storage.join(relative);
3698            fs::create_dir_all(path.parent().unwrap()).unwrap();
3699            fs::write(&path, format!("contents of {relative}")).unwrap();
3700        }
3701        Fixture {
3702            _temp: temp,
3703            base,
3704            storage,
3705        }
3706    }
3707
3708    /// Every file and folder under `root` with its bytes (folders map to
3709    /// nothing), read without following links.
3710    fn tree(root: &Path) -> BTreeMap<PathBuf, Option<Vec<u8>>> {
3711        let mut found = BTreeMap::new();
3712        let mut pending = vec![root.to_path_buf()];
3713        while let Some(dir) = pending.pop() {
3714            for entry in fs::read_dir(&dir).unwrap() {
3715                let path = entry.unwrap().path();
3716                let kind = fs::symlink_metadata(&path).unwrap().file_type();
3717                let relative = path.strip_prefix(root).unwrap().to_path_buf();
3718                if kind.is_dir() {
3719                    pending.push(path);
3720                    found.insert(relative, None);
3721                } else if kind.is_symlink() {
3722                    found.insert(relative, Some(b"<link>".to_vec()));
3723                } else {
3724                    found.insert(relative, Some(fs::read(&path).unwrap()));
3725                }
3726            }
3727        }
3728        found
3729    }
3730
3731    fn protected_bytes(storage: &Path) -> Vec<(String, Vec<u8>)> {
3732        PROTECTED
3733            .iter()
3734            .map(|relative| {
3735                (
3736                    relative.to_string(),
3737                    fs::read(storage.join(relative)).unwrap(),
3738                )
3739            })
3740            .collect()
3741    }
3742
3743    fn legacy_folders(storage: &Path) -> Vec<PathBuf> {
3744        let mut paths = LEGACY_FOLDERS
3745            .iter()
3746            .map(|relative| storage.join(relative))
3747            .collect::<Vec<_>>();
3748        paths.sort();
3749        paths
3750    }
3751
3752    fn run(storage: &Path, yes: bool) -> PruneLegacyReport {
3753        run_with_tiers(&[], storage, yes)
3754    }
3755
3756    pub fn run_with_tiers(
3757        tiers: &[crate::config_resolve::ConfigTier],
3758        storage: &Path,
3759        yes: bool,
3760    ) -> PruneLegacyReport {
3761        match prune_legacy_stores(tiers, storage, yes, &mut |_| {}) {
3762            Ok(report) => report,
3763            Err(PruneLegacyError::Refused(reason)) => panic!("refused: {reason}"),
3764            Err(PruneLegacyError::Failed(error)) => panic!("failed: {error}"),
3765        }
3766    }
3767
3768    pub fn found_paths(stores: &[LegacyStore]) -> Vec<PathBuf> {
3769        let mut paths = stores
3770            .iter()
3771            .map(|store| store.path.clone())
3772            .collect::<Vec<_>>();
3773        paths.sort();
3774        paths
3775    }
3776
3777    pub fn asides(root: &Path) -> Vec<PathBuf> {
3778        fs::read_dir(root)
3779            .unwrap()
3780            .map(|entry| entry.unwrap().path())
3781            .filter(|path| {
3782                path.file_name()
3783                    .and_then(|name| name.to_str())
3784                    .is_some_and(|name| name.starts_with(ASIDE_PREFIX))
3785            })
3786            .collect()
3787    }
3788
3789    #[test]
3790    fn prune_legacy_dry_run_lists_exactly_the_legacy_stores_and_changes_nothing() {
3791        let fixture = fixture();
3792        let before = tree(&fixture.base);
3793        let report = run(&fixture.storage, false);
3794        assert_eq!(tree(&fixture.base), before, "a dry run changed the disk");
3795        assert_eq!(
3796            found_paths(&report.stores),
3797            legacy_folders(&fixture.storage)
3798        );
3799        assert!(report
3800            .stores
3801            .iter()
3802            .all(|store| store.complete && !store.leftover));
3803        let views = report
3804            .stores
3805            .iter()
3806            .find(|store| store.path.ends_with("views"))
3807            .unwrap();
3808        assert_eq!(
3809            views.bytes,
3810            "contents of views/view-1/derived.sqlite".len() as u64
3811        );
3812        assert!(report.removed.is_empty());
3813        assert!(report.skipped.is_empty(), "{:?}", report.skipped);
3814        assert!(report.notes.is_empty(), "{:?}", report.notes);
3815        assert_eq!(report.roots, vec![fixture.storage.clone()]);
3816    }
3817
3818    #[test]
3819    fn prune_legacy_yes_removes_the_stores_and_keeps_everything_else_byte_identical() {
3820        let fixture = fixture();
3821        let kept = protected_bytes(&fixture.storage);
3822        let mut events = Vec::new();
3823        let report = prune_legacy_stores(&[], &fixture.storage, true, &mut |event| {
3824            events.push(format!("{event:?}"));
3825        })
3826        .unwrap_or_else(|error| panic!("{error:?}"));
3827        assert!(report.skipped.is_empty(), "{:?}", report.skipped);
3828        assert_eq!(
3829            found_paths(&report.removed),
3830            legacy_folders(&fixture.storage)
3831        );
3832        for path in legacy_folders(&fixture.storage) {
3833            assert!(
3834                fs::symlink_metadata(&path).is_err(),
3835                "{} survived",
3836                path.display()
3837            );
3838        }
3839        assert_eq!(protected_bytes(&fixture.storage), kept);
3840        assert!(
3841            asides(&fixture.storage).is_empty(),
3842            "the aside folder stayed"
3843        );
3844        // The run lock is the only new file.
3845        assert!(fixture
3846            .storage
3847            .join("retention/prune-legacy.lock")
3848            .is_file());
3849        assert_eq!(
3850            events
3851                .iter()
3852                .filter(|event| event.starts_with("Removed"))
3853                .count(),
3854            legacy_folders(&fixture.storage).len()
3855        );
3856        // Harness folders keep everything except their call graph store.
3857        assert!(fixture.storage.join("opencode/inspect").is_dir());
3858        assert!(fixture.storage.join("unknown-folder/views/keep").is_file());
3859    }
3860
3861    #[cfg(unix)]
3862    #[test]
3863    fn prune_legacy_refuses_a_symlinked_store_and_never_follows_it() {
3864        let fixture = fixture();
3865        let outside = fixture.base.join("outside");
3866        fs::create_dir(&outside).unwrap();
3867        fs::write(outside.join("precious"), "keep me").unwrap();
3868        fs::remove_dir_all(fixture.storage.join("views")).unwrap();
3869        std::os::unix::fs::symlink(&outside, fixture.storage.join("views")).unwrap();
3870        fs::remove_dir_all(fixture.storage.join("opencode/callgraph")).unwrap();
3871        std::os::unix::fs::symlink(&outside, fixture.storage.join("opencode/callgraph")).unwrap();
3872        for yes in [false, true] {
3873            let report = run(&fixture.storage, yes);
3874            let skipped = report
3875                .skipped
3876                .iter()
3877                .map(|skip| (skip.path.clone(), skip.reason.clone()))
3878                .collect::<Vec<_>>();
3879            assert_eq!(skipped.len(), 2, "{skipped:?}");
3880            for (path, reason) in &skipped {
3881                assert!(
3882                    path.ends_with("views") || path.ends_with("opencode/callgraph"),
3883                    "{skipped:?}"
3884                );
3885                assert!(reason.contains("symbolic link"), "{reason}");
3886            }
3887            assert!(!found_paths(&report.stores).contains(&fixture.storage.join("views")));
3888        }
3889        assert_eq!(
3890            fs::read_to_string(outside.join("precious")).unwrap(),
3891            "keep me"
3892        );
3893        assert!(fs::symlink_metadata(fixture.storage.join("views"))
3894            .unwrap()
3895            .file_type()
3896            .is_symlink());
3897    }
3898
3899    #[test]
3900    fn prune_legacy_refuses_a_store_on_another_device() {
3901        use crate::pinned_dir::REPAIR_IDENTITIES;
3902        let fixture = fixture();
3903        let blobs = fixture.storage.join("blobs");
3904        let (device, inode) = PinnedDir::open(&blobs)
3905            .unwrap()
3906            .directory_identity()
3907            .unwrap();
3908        REPAIR_IDENTITIES.with(|ids| {
3909            ids.borrow_mut()
3910                .insert(blobs.clone(), (device.wrapping_add(1), inode));
3911        });
3912        let dry = run(&fixture.storage, false);
3913        let report = run(&fixture.storage, true);
3914        REPAIR_IDENTITIES.with(|ids| ids.borrow_mut().clear());
3915        for report in [&dry, &report] {
3916            assert_eq!(report.skipped.len(), 1, "{:?}", report.skipped);
3917            assert_eq!(report.skipped[0].path, blobs);
3918            assert!(
3919                report.skipped[0].reason.contains("another disk"),
3920                "{:?}",
3921                report.skipped
3922            );
3923        }
3924        assert_eq!(
3925            fs::read_to_string(blobs.join("ab/cdef")).unwrap(),
3926            "contents of blobs/ab/cdef"
3927        );
3928        assert!(!fixture.storage.join("views").exists());
3929    }
3930
3931    #[test]
3932    fn prune_legacy_skips_and_reports_a_store_that_cannot_be_moved_aside() {
3933        let fixture = fixture();
3934        let kept = fs::read(fixture.storage.join("index/key-1/cache.bin")).unwrap();
3935        RENAME_REFUSED.with(|names| names.borrow_mut().push(OsString::from("index")));
3936        let mut skipped_events = 0;
3937        let report = prune_legacy_stores(&[], &fixture.storage, true, &mut |event| {
3938            if matches!(event, PruneLegacyEvent::Skipped(_)) {
3939                skipped_events += 1;
3940            }
3941        });
3942        RENAME_REFUSED.with(|names| names.borrow_mut().clear());
3943        let report = report.unwrap_or_else(|error| panic!("{error:?}"));
3944        assert_eq!(skipped_events, 1);
3945        assert_eq!(report.skipped.len(), 1, "{:?}", report.skipped);
3946        assert_eq!(report.skipped[0].path, fixture.storage.join("index"));
3947        assert!(
3948            report.skipped[0]
3949                .reason
3950                .contains("could not be moved aside"),
3951            "{}",
3952            report.skipped[0].reason
3953        );
3954        assert_eq!(
3955            fs::read(fixture.storage.join("index/key-1/cache.bin")).unwrap(),
3956            kept
3957        );
3958        assert_eq!(
3959            report.removed.len(),
3960            legacy_folders(&fixture.storage).len() - 1
3961        );
3962        assert!(!fixture.storage.join("views").exists());
3963        assert!(asides(&fixture.storage).is_empty());
3964    }
3965
3966    #[test]
3967    fn prune_legacy_rerun_removes_what_an_interrupted_run_moved_aside() {
3968        let fixture = fixture();
3969        let kept = protected_bytes(&fixture.storage);
3970        STOP_AFTER_MOVE.with(|stop| stop.set(true));
3971        let interrupted = prune_legacy_stores(&[], &fixture.storage, true, &mut |_| {});
3972        STOP_AFTER_MOVE.with(|stop| stop.set(false));
3973        interrupted.unwrap_or_else(|error| panic!("{error:?}"));
3974        let left = asides(&fixture.storage);
3975        assert_eq!(left.len(), 1, "{left:?}");
3976        assert!(left[0].join("0-artifact-owners/owner.json").is_file());
3977        for path in legacy_folders(&fixture.storage) {
3978            assert!(fs::symlink_metadata(&path).is_err(), "{}", path.display());
3979        }
3980
3981        let dry = run(&fixture.storage, false);
3982        assert_eq!(found_paths(&dry.stores), left);
3983        assert!(dry.stores[0].leftover);
3984        assert!(dry.stores[0].bytes > 0);
3985
3986        let report = run(&fixture.storage, true);
3987        assert!(report.skipped.is_empty(), "{:?}", report.skipped);
3988        assert_eq!(found_paths(&report.removed), left);
3989        assert!(asides(&fixture.storage).is_empty());
3990        assert_eq!(protected_bytes(&fixture.storage), kept);
3991    }
3992
3993    #[test]
3994    fn prune_legacy_refuses_a_folder_that_is_not_aft_storage() {
3995        let fixture = fixture();
3996        fs::remove_file(fixture.storage.join("aft.db")).unwrap();
3997        let before = tree(&fixture.base);
3998        for yes in [false, true] {
3999            match prune_legacy_stores(&[], &fixture.storage, yes, &mut |_| {}) {
4000                Err(PruneLegacyError::Refused(reason)) => {
4001                    assert!(reason.contains("does not look like"), "{reason}")
4002                }
4003                other => panic!("expected a refusal, got {other:?}"),
4004            }
4005        }
4006        assert_eq!(tree(&fixture.base), before);
4007    }
4008
4009    #[test]
4010    fn prune_legacy_reports_a_missing_storage_folder_as_nothing_to_do() {
4011        let temp = tempfile::tempdir().unwrap();
4012        let report = run(&temp.path().join("absent"), true);
4013        assert!(report.roots.is_empty());
4014        assert!(!temp.path().join("absent").exists());
4015    }
4016
4017    #[test]
4018    fn prune_legacy_refuses_while_another_run_holds_the_lock() {
4019        let fixture = fixture();
4020        let retention = fixture.storage.join("retention");
4021        let lock = fs::OpenOptions::new()
4022            .create(true)
4023            .truncate(false)
4024            .write(true)
4025            .open(retention.join("prune-legacy.lock"))
4026            .unwrap();
4027        lock.try_lock().unwrap();
4028        match prune_legacy_stores(&[], &fixture.storage, true, &mut |_| {}) {
4029            Err(PruneLegacyError::Refused(reason)) => {
4030                assert!(reason.contains("Another cleanup"), "{reason}")
4031            }
4032            other => panic!("expected a refusal, got {other:?}"),
4033        }
4034        assert!(fixture
4035            .storage
4036            .join("views/view-1/derived.sqlite")
4037            .is_file());
4038    }
4039
4040    #[test]
4041    fn prune_legacy_skips_an_external_cache_root_it_cannot_prove() {
4042        let fixture = fixture();
4043        let parent = fixture.base.join("cache-volume");
4044        fs::create_dir_all(parent.join("aft/views")).unwrap();
4045        fs::write(parent.join("aft/views/a"), "someone else's").unwrap();
4046        let tiers = [crate::config_resolve::ConfigTier {
4047            tier: "user".into(),
4048            source: "test".into(),
4049            doc: serde_json::json!({"storage": {"cache_dir": parent}}).to_string(),
4050        }];
4051        let report = run_with_tiers(&tiers, &fixture.storage, true);
4052        assert_eq!(report.roots, vec![fixture.storage.clone()]);
4053        assert_eq!(report.skipped.len(), 1, "{:?}", report.skipped);
4054        assert_eq!(report.skipped[0].path, parent.join("aft"));
4055        assert!(
4056            report.skipped[0].reason.contains("not proven"),
4057            "{}",
4058            report.skipped[0].reason
4059        );
4060        assert!(parent.join("aft/views/a").is_file());
4061    }
4062}