Skip to main content

mbx_cache_rustc/
dep_info.rs

1use super::{
2    ActionContext, ActionInput, Argument, BypassReason, MAX_NATIVE_INPUT_BYTES,
3    MAX_PREDICTED_INPUTS, PathMapping, RustcInvocation, normalize_components,
4};
5#[cfg(test)]
6use mbx_cache_core::CacheDigest;
7use mbx_cache_core::{
8    FileDigestCache, FileDigestResolution, FileDigestScope, FileIdentity, FileSnapshot,
9    RecordedFileDigest, digest_file, digest_file_validated,
10};
11use std::collections::{BTreeMap, BTreeSet};
12use std::ffi::OsString;
13use std::path::{Path, PathBuf};
14use std::time::SystemTime;
15
16/// A side-effect-minimized rustc invocation that emits only dependency data.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct DepInfoCommand {
19    arguments: Vec<OsString>,
20    output: PathBuf,
21}
22
23impl DepInfoCommand {
24    /// Arguments for the real compiler, excluding the compiler executable.
25    pub fn arguments(&self) -> &[OsString] {
26        &self.arguments
27    }
28
29    /// Exact file the compiler must populate with dep-info.
30    pub fn output(&self) -> &Path {
31        &self.output
32    }
33}
34
35/// The source and environment inputs reported by rustc's dep-info output.
36#[derive(Debug, Clone, Default, PartialEq, Eq)]
37pub struct RustcDepInfo {
38    /// Source paths listed in the first dep-info dependency rule.
39    pub files: Vec<PathBuf>,
40    /// Environment inputs recorded by rustc `# env-dep:` lines.
41    pub environment: BTreeMap<String, Option<String>>,
42}
43
44impl RustcDepInfo {
45    /// Read and parse a dep-info file, treating missing or non-UTF-8 output as
46    /// an explicit cache bypass.
47    pub fn read(path: &Path) -> Result<Self, BypassReason> {
48        let contents =
49            std::fs::read_to_string(path).map_err(|error| BypassReason::DepInfoRead {
50                path: path.to_path_buf(),
51                message: error.to_string(),
52            })?;
53        Self::parse(&contents)
54    }
55
56    /// Parse rustc's Makefile-style dep-info format.
57    ///
58    /// This intentionally follows Cargo's parser contract: the first target
59    /// rule contains all source dependencies, spaces are escaped with a
60    /// trailing backslash on each token fragment, and `# env-dep:` records
61    /// contain the environment observed by `env!` and `option_env!`.
62    pub fn parse(contents: &str) -> Result<Self, BypassReason> {
63        let mut files = BTreeSet::new();
64        let mut environment = BTreeMap::new();
65        let mut found_dependencies = false;
66
67        for line in contents.lines() {
68            if let Some(record) = line.strip_prefix("# env-dep:") {
69                let (name, value) = record
70                    .split_once('=')
71                    .map_or((record, None), |(name, value)| (name, Some(value)));
72                let name = unescape_environment(name)?;
73                if name.is_empty() {
74                    return Err(BypassReason::MalformedDepInfo(
75                        "environment input has an empty name".into(),
76                    ));
77                }
78                let value = value.map(unescape_environment).transpose()?;
79                if environment
80                    .insert(name.clone(), value.clone())
81                    .is_some_and(|previous| previous != value)
82                {
83                    return Err(BypassReason::ConflictingEnvironment(name));
84                }
85                continue;
86            }
87
88            let Some(separator) = line.find(": ") else {
89                continue;
90            };
91            if found_dependencies {
92                continue;
93            }
94            found_dependencies = true;
95            let mut fragments = line[separator + 2..].split_whitespace();
96            while let Some(fragment) = fragments.next() {
97                let mut file = fragment.to_string();
98                while file.ends_with('\\') {
99                    file.pop();
100                    let continuation = fragments.next().ok_or_else(|| {
101                        BypassReason::MalformedDepInfo(
102                            "dependency path ends with an unterminated escape".into(),
103                        )
104                    })?;
105                    file.push(' ');
106                    file.push_str(continuation);
107                }
108                if file.is_empty() {
109                    return Err(BypassReason::MalformedDepInfo(
110                        "dependency path is empty".into(),
111                    ));
112                }
113                files.insert(PathBuf::from(file));
114            }
115        }
116
117        if !found_dependencies {
118            return Err(BypassReason::MalformedDepInfo(
119                "dependency rule is missing".into(),
120            ));
121        }
122        if files.is_empty() {
123            return Err(BypassReason::MalformedDepInfo(
124                "dependency rule contains no inputs".into(),
125            ));
126        }
127        Ok(Self {
128            files: files.into_iter().collect(),
129            environment,
130        })
131    }
132}
133
134/// A complete, content-addressed compiler input manifest.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct DiscoveredInputs {
137    working_dir: PathBuf,
138    /// Content-addressed compiler input files.
139    pub inputs: Vec<ActionInput>,
140    /// Environment inputs captured from dep-info.
141    pub environment: BTreeMap<String, Option<String>>,
142    /// What each input looked like on disk when its digest was established,
143    /// index-aligned with `inputs`; `None` where the filesystem gave nothing to
144    /// compare against later. Lets `verify` confirm an input by stat instead of
145    /// by reading it again.
146    identities: Vec<Option<FileIdentity>>,
147    /// Inputs that entered only because they sit in a native search directory,
148    /// not because dep-info or the invocation named them. They belong in a
149    /// shared action key, but they are not the crate's own sources.
150    native_only: BTreeSet<PathBuf>,
151    /// What collecting native inputs traversed. Its timestamps guard changes
152    /// made during compilation that leave only old files behind.
153    native_walk: NativeWalk,
154}
155
156/// The directories and directory aliases a native search walk went through.
157#[derive(Debug, Clone, Default, PartialEq, Eq)]
158pub(super) struct NativeWalk {
159    aliases: BTreeSet<PathBuf>,
160    /// Every directory listed, under the name it was searched by. An entry
161    /// renamed into or removed from one changes its modification time, which
162    /// nothing about the entries found afterwards need show.
163    directories: BTreeSet<PathBuf>,
164}
165
166impl NativeWalk {
167    pub(super) fn extend(&mut self, other: Self) {
168        self.aliases.extend(other.aliases);
169        self.directories.extend(other.directories);
170    }
171
172    fn verify_not_modified_since(&self, started_at: SystemTime) -> Result<(), BypassReason> {
173        // Aliases first, so a retarget is reported by the name that moved
174        // rather than by the directory holding it.
175        let aliases = self
176            .aliases
177            .iter()
178            .map(|path| (path, std::fs::symlink_metadata(path)));
179        let directories = self
180            .directories
181            .iter()
182            .map(|path| (path, std::fs::metadata(path)));
183        for (path, metadata) in aliases.chain(directories) {
184            let modified = metadata
185                .and_then(|metadata| metadata.modified())
186                .map_err(|error| BypassReason::InputRead {
187                    path: path.clone(),
188                    message: error.to_string(),
189                })?;
190            if modified >= started_at {
191                return Err(BypassReason::InputModifiedDuringCompilation(path.clone()));
192            }
193        }
194        Ok(())
195    }
196}
197
198impl DiscoveredInputs {
199    pub(crate) fn from_paths(
200        working_dir: &Path,
201        paths: BTreeSet<PathBuf>,
202        environment: BTreeMap<String, Option<String>>,
203        digests: &dyn FileDigestCache,
204    ) -> Result<Self, BypassReason> {
205        if !working_dir.is_absolute() {
206            return Err(BypassReason::RelativeWorkingDirectory(
207                working_dir.to_path_buf(),
208            ));
209        }
210        let working_dir = normalize_components(working_dir);
211        // Stat everything first: the identities drive one batched ledger
212        // lookup, so an upstream rlib the session already hashed -- once, when
213        // it was materialized or published -- is not read again by every crate
214        // that links it. A file the filesystem reports no modification time
215        // for gets no identity and is simply hashed.
216        let mut identified = Vec::with_capacity(paths.len());
217        for path in paths {
218            let metadata = std::fs::metadata(&path).map_err(|error| BypassReason::InputRead {
219                path: path.clone(),
220                message: error.to_string(),
221            })?;
222            if !metadata.is_file() {
223                return Err(BypassReason::InputRead {
224                    path,
225                    message: "input is not a regular file".into(),
226                });
227            }
228            let identity = FileIdentity::for_digest_cache(&path, &metadata).map_err(|error| {
229                BypassReason::InputRead {
230                    path: path.clone(),
231                    message: error.to_string(),
232                }
233            })?;
234            identified.push((path, identity));
235        }
236        let queries = identified
237            .iter()
238            .filter_map(|(_, identity)| identity.clone())
239            .collect::<Vec<_>>();
240        let mut recorded = digests
241            .resolve(FileDigestScope::Content, &queries)
242            .into_iter();
243        let mut inputs = Vec::with_capacity(identified.len());
244        let mut identities = Vec::with_capacity(identified.len());
245        let mut fresh = Vec::new();
246        for (path, identity) in identified {
247            let resolution = identity
248                .as_ref()
249                .and_then(|_| recorded.next())
250                .unwrap_or(FileDigestResolution::Unresolved);
251            let cached = match resolution {
252                FileDigestResolution::Digest(digest)
253                    if identity.as_ref().is_some_and(|identity| {
254                        identity.len == digest.size && identity.still_describes().unwrap_or(false)
255                    }) =>
256                {
257                    Some(digest)
258                }
259                FileDigestResolution::Digest(_)
260                | FileDigestResolution::EmbeddedTimestampMacro
261                | FileDigestResolution::Unresolved => None,
262            };
263            let digest = if let Some(digest) = cached {
264                identities.push(identity);
265                digest
266            } else {
267                let observed =
268                    digest_file_validated(FileDigestScope::Content, &path).map_err(|error| {
269                        BypassReason::InputRead {
270                            path: path.clone(),
271                            message: error.to_string(),
272                        }
273                    })?;
274                let (digest, observed_identity) = if let Some(observed) = observed {
275                    let digest = observed.resolution.into_digest().ok_or_else(|| {
276                        BypassReason::InputRead {
277                            path: path.clone(),
278                            message: "content digest resolution returned no digest".into(),
279                        }
280                    })?;
281                    if let Some(file) = observed.cache_identity.clone()
282                        && file.len == digest.size
283                    {
284                        fresh.push(RecordedFileDigest {
285                            file,
286                            digest: digest.clone(),
287                        });
288                    }
289                    (digest, observed.cache_identity)
290                } else {
291                    let digest = digest_file(FileDigestScope::Content, &path)
292                        .and_then(|resolution| {
293                            resolution.into_digest().ok_or_else(|| {
294                                std::io::Error::other(
295                                    "content digest resolution returned no digest",
296                                )
297                            })
298                        })
299                        .map_err(|error| BypassReason::InputRead {
300                            path: path.clone(),
301                            message: error.to_string(),
302                        })?;
303                    (digest, None)
304                };
305                identities.push(observed_identity);
306                digest
307            };
308            inputs.push(ActionInput { path, digest });
309        }
310        if !fresh.is_empty() {
311            digests.record(FileDigestScope::Content, fresh);
312        }
313        Ok(Self {
314            working_dir,
315            inputs,
316            environment,
317            identities,
318            native_only: BTreeSet::new(),
319            native_walk: NativeWalk::default(),
320        })
321    }
322
323    /// Mark inputs that were found only by scanning native search directories.
324    pub(crate) fn with_native_only(mut self, native_only: BTreeSet<PathBuf>) -> Self {
325        self.native_only = native_only;
326        self
327    }
328
329    pub(super) fn with_native_walk(mut self, walk: NativeWalk) -> Self {
330        self.native_walk = walk;
331        self
332    }
333
334    /// Whether `path` is an input only because a native search directory holds it.
335    pub fn is_native_only(&self, path: &Path) -> bool {
336        self.native_only.contains(path)
337    }
338
339    /// Reject inputs whose modification time overlaps the compiler invocation.
340    ///
341    /// Input contents are first hashed after rustc reports their paths. This
342    /// timestamp barrier prevents a post-compile write from being mistaken for
343    /// the contents that produced the artifact. `verify` closes the remaining
344    /// race after hashing.
345    pub fn verify_not_modified_since(&self, started_at: SystemTime) -> Result<(), BypassReason> {
346        self.verify_not_modified_since_with_snapshots(started_at, &BTreeMap::new())
347    }
348
349    /// Reject inputs that changed from snapshots captured before rustc ran,
350    /// falling back to the wall-clock barrier for inputs only dep-info named.
351    ///
352    /// A snapshot may use metadata or content depending on what its filesystem
353    /// can compare reliably. Metadata snapshots need a change token: without
354    /// one a same-length rewrite can restore its mtime.
355    pub fn verify_not_modified_since_with_snapshots(
356        &self,
357        started_at: SystemTime,
358        before: &BTreeMap<PathBuf, FileSnapshot>,
359    ) -> Result<(), BypassReason> {
360        self.verify_snapshots(Some(started_at), before)
361    }
362
363    /// Like [`Self::verify_not_modified_since_with_snapshots`], but judging
364    /// only the inputs that have a snapshot. Use it when the compiler may
365    /// legitimately write other inputs, such as generated files, while it runs.
366    pub fn verify_snapshots_unchanged(
367        &self,
368        before: &BTreeMap<PathBuf, FileSnapshot>,
369    ) -> Result<(), BypassReason> {
370        self.verify_snapshots(None, before)
371    }
372
373    fn verify_snapshots(
374        &self,
375        started_at: Option<SystemTime>,
376        before: &BTreeMap<PathBuf, FileSnapshot>,
377    ) -> Result<(), BypassReason> {
378        // A metadata-only change keeps the result, so it must not hide a
379        // content change to a later input.
380        let mut metadata_changed = None;
381        for input in &self.inputs {
382            if let Some(previous) = before.get(&input.path)
383                && previous.proves_content_change()
384            {
385                let metadata =
386                    std::fs::metadata(&input.path).map_err(|error| BypassReason::InputRead {
387                        path: input.path.clone(),
388                        message: error.to_string(),
389                    })?;
390                let identity = FileIdentity::for_digest_cache(&input.path, &metadata)
391                    .map_err(|error| BypassReason::InputRead {
392                        path: input.path.clone(),
393                        message: error.to_string(),
394                    })?
395                    .or_else(|| FileIdentity::describe(&input.path, &metadata));
396                if previous.matches(identity.as_ref(), &input.digest) {
397                    continue;
398                }
399                if previous.differs_only_in_change_token(identity.as_ref()) {
400                    metadata_changed.get_or_insert_with(|| input.path.clone());
401                    continue;
402                }
403                return Err(BypassReason::InputModifiedDuringCompilation(
404                    input.path.clone(),
405                ));
406            }
407            let Some(started_at) = started_at else {
408                continue;
409            };
410            let metadata =
411                std::fs::metadata(&input.path).map_err(|error| BypassReason::InputRead {
412                    path: input.path.clone(),
413                    message: error.to_string(),
414                })?;
415            let modified = metadata
416                .modified()
417                .map_err(|error| BypassReason::InputRead {
418                    path: input.path.clone(),
419                    message: error.to_string(),
420                })?;
421            if modified >= started_at {
422                return Err(BypassReason::InputModifiedDuringCompilation(
423                    input.path.clone(),
424                ));
425            }
426        }
427        // After the inputs: a directory has no snapshot, so reporting it first
428        // would hide a change to a file that does, and the compiler's result
429        // would be kept when it should be discarded.
430        if let Some(started_at) = started_at {
431            self.native_walk.verify_not_modified_since(started_at)?;
432        }
433        metadata_changed.map_or(Ok(()), |path| {
434            Err(BypassReason::InputMetadataChangedDuringCompilation(path))
435        })
436    }
437
438    /// Compatibility form for callers that captured metadata identities.
439    pub fn verify_not_modified_since_with_identities(
440        &self,
441        started_at: SystemTime,
442        before: &BTreeMap<PathBuf, FileIdentity>,
443    ) -> Result<(), BypassReason> {
444        let snapshots = before
445            .iter()
446            .map(|(path, identity)| (path.clone(), identity.clone().into()))
447            .collect();
448        self.verify_not_modified_since_with_snapshots(started_at, &snapshots)
449    }
450
451    /// Rehash every discovered file after compilation and before publication.
452    /// This closes the discovery/compile race by degrading changed inputs to a
453    /// cache miss rather than storing outputs beneath a stale action key.
454    pub fn verify(&self) -> Result<(), BypassReason> {
455        for (index, input) in self.inputs.iter().enumerate() {
456            let read_error = |error: std::io::Error| BypassReason::InputRead {
457                path: input.path.clone(),
458                message: error.to_string(),
459            };
460            // An input still wearing the identity discovery recorded -- length,
461            // modification time, and change time -- is confirmed by that stat
462            // alone. The change time is what makes this as good as reading: it
463            // cannot be set from user space, so a rewrite that puts the old
464            // modification time back still shows, where a platform that reports
465            // none would let a same-length rewrite inside one timestamp tick
466            // through. Such an identity is not trusted here, and neither is an
467            // input that had none. Reading everything again cost as much as
468            // keying the compilation did: a large binary's dependency rlibs, a
469            // gigabyte of them, read twice for every edit.
470            if let Some(Some(identity)) = self.identities.get(index)
471                && identity.can_skip_content_verification()
472                && identity.still_describes().map_err(read_error)?
473            {
474                continue;
475            }
476            let matches = input.digest.matches_file(&input.path).map_err(|error| {
477                BypassReason::InputRead {
478                    path: input.path.clone(),
479                    message: error.to_string(),
480                }
481            })?;
482            if !matches {
483                return Err(BypassReason::InputChanged(input.path.clone()));
484            }
485        }
486        Ok(())
487    }
488
489    /// Merge the manifest into an action context after verifying that both use
490    /// the same compiler working directory.
491    pub fn apply_to(self, context: &mut ActionContext) -> Result<(), BypassReason> {
492        if normalize_components(&context.working_dir) != self.working_dir {
493            return Err(BypassReason::DiscoveryWorkingDirectory);
494        }
495        for (name, value) in &self.environment {
496            if context
497                .environment
498                .get(name)
499                .is_some_and(|previous| previous != value)
500            {
501                return Err(BypassReason::ConflictingEnvironment(name.clone()));
502            }
503        }
504        context.environment.extend(self.environment);
505        context.inputs.extend(self.inputs);
506        Ok(())
507    }
508}
509
510impl RustcInvocation {
511    /// Replace the original output flags with a single explicit dep-info file.
512    pub fn dep_info_command(&self, output: &Path) -> Result<DepInfoCommand, BypassReason> {
513        if !output.is_absolute() {
514            return Err(BypassReason::RelativeDepInfoPath(output.to_path_buf()));
515        }
516        let output_text = output
517            .to_str()
518            .ok_or_else(|| BypassReason::NonUtf8Path(output.to_path_buf()))?;
519        if output_text.contains(',') {
520            return Err(BypassReason::UnsafeDepInfoPath(output.to_path_buf()));
521        }
522
523        let mut arguments = Vec::new();
524        for argument in &self.arguments {
525            match argument {
526                Argument::Emit(_) => {}
527                Argument::Path { flag, .. } if flag == "--out-dir" || flag == "-o" => {}
528                argument => arguments.push(render_argument(argument)?),
529            }
530        }
531        arguments.push(format!("--emit=dep-info={output_text}").into());
532        arguments.push(self.source.clone().into_os_string());
533        Ok(DepInfoCommand {
534            arguments,
535            output: output.to_path_buf(),
536        })
537    }
538
539    /// Hash dep-info sources plus every direct compiler input already modeled
540    /// by the invocation (`--extern` artifacts and custom target specs).
541    pub fn discover_inputs(
542        &self,
543        dep_info: &RustcDepInfo,
544        working_dir: &Path,
545    ) -> Result<DiscoveredInputs, BypassReason> {
546        self.discover_inputs_with_mappings(
547            dep_info,
548            working_dir,
549            &[],
550            &mbx_cache_core::NoFileDigestCache,
551        )
552    }
553
554    /// Hash dep-info sources plus modeled compiler inputs, allowing native
555    /// search directories beneath the working directory or a mapped root.
556    ///
557    /// `digests` may answer for files the session already read in full;
558    /// pass [`mbx_cache_core::NoFileDigestCache`] to hash everything.
559    pub fn discover_inputs_with_mappings(
560        &self,
561        dep_info: &RustcDepInfo,
562        working_dir: &Path,
563        path_mappings: &[PathMapping],
564        digests: &dyn FileDigestCache,
565    ) -> Result<DiscoveredInputs, BypassReason> {
566        self.discover(dep_info, working_dir, Some(path_mappings), digests)
567    }
568
569    /// Hash dep-info sources and modeled compiler inputs, leaving native search
570    /// directories out.
571    ///
572    /// The result cannot key a shared action: the linker may read libraries it
573    /// does not list. It is enough to tell whether a crate's own sources changed,
574    /// which is all that private incremental state needs, so it works for a
575    /// compilation whose search paths [`Self::discover_inputs_with_mappings`]
576    /// refuses.
577    pub fn discover_source_inputs(
578        &self,
579        dep_info: &RustcDepInfo,
580        working_dir: &Path,
581        digests: &dyn FileDigestCache,
582    ) -> Result<DiscoveredInputs, BypassReason> {
583        self.discover(dep_info, working_dir, None, digests)
584    }
585
586    /// Native search directories are collected only when `path_mappings` is given.
587    fn discover(
588        &self,
589        dep_info: &RustcDepInfo,
590        working_dir: &Path,
591        path_mappings: Option<&[PathMapping]>,
592        digests: &dyn FileDigestCache,
593    ) -> Result<DiscoveredInputs, BypassReason> {
594        if !working_dir.is_absolute() {
595            return Err(BypassReason::RelativeWorkingDirectory(
596                working_dir.to_path_buf(),
597            ));
598        }
599        let working_dir = normalize_components(working_dir);
600        let absolute = |path: &PathBuf| {
601            let absolute = if path.is_absolute() {
602                path.to_path_buf()
603            } else {
604                working_dir.join(path)
605            };
606            normalize_components(&absolute)
607        };
608        // What dep-info names is the crate's own. A required input also covers
609        // the crate root, `--extern` artifacts and target specifications, so it
610        // is a source unless a native search directory holds it: there it is a
611        // library resolved from that directory, which belongs in a shared key
612        // but is no more a source than the directory around it.
613        let sources = dep_info.files.iter().map(absolute).collect::<BTreeSet<_>>();
614        let mut paths = sources.clone();
615        paths.extend(self.required_inputs.iter().map(absolute));
616        let admitted_roots = native_input_roots(&working_dir, path_mappings.unwrap_or_default());
617        let mut native_bytes = 0_u64;
618        let mut counted = BTreeSet::new();
619        let mut native_walk = NativeWalk::default();
620        for argument in &self.arguments {
621            if path_mappings.is_some()
622                && let Argument::SearchPath { kind, path } = argument
623                && super::searches_native(kind)
624            {
625                let directory = if path.is_absolute() {
626                    path.clone()
627                } else {
628                    working_dir.join(path)
629                };
630                native_walk.extend(collect_native_directory(
631                    &directory,
632                    &admitted_roots,
633                    &mut paths,
634                    &mut native_bytes,
635                    &mut counted,
636                )?);
637            }
638        }
639        let native_directories = self
640            .arguments
641            .iter()
642            .filter_map(|argument| match argument {
643                Argument::SearchPath { kind, path } if super::searches_native(kind) => {
644                    Some(absolute(path))
645                }
646                _ => None,
647            })
648            .collect::<Vec<_>>();
649        let native_only = paths
650            .difference(&sources)
651            .filter(|path| native_directories.iter().any(|root| path.starts_with(root)))
652            .cloned()
653            .collect();
654        Ok(DiscoveredInputs::from_paths(
655            &working_dir,
656            paths,
657            dep_info.environment.clone(),
658            digests,
659        )?
660        .with_native_only(native_only)
661        .with_native_walk(native_walk))
662    }
663}
664
665/// Return normalized roots whose native search directories can be tracked.
666pub(super) fn native_input_roots(
667    working_dir: &Path,
668    path_mappings: &[PathMapping],
669) -> Vec<PathBuf> {
670    std::iter::once(working_dir)
671        .chain(path_mappings.iter().map(|mapping| mapping.root.as_path()))
672        .map(normalize_components)
673        .collect()
674}
675
676/// Add regular files beneath an admitted native search directory, enforcing
677/// the prediction input count and the caller's cumulative native byte budget.
678/// `counted` holds the files already charged to that budget, so overlapping
679/// walks charge each file once even when `paths` already names it.
680pub(super) fn collect_native_directory(
681    directory: &Path,
682    admitted_roots: &[PathBuf],
683    paths: &mut BTreeSet<PathBuf>,
684    native_bytes: &mut u64,
685    counted: &mut BTreeSet<PathBuf>,
686) -> Result<NativeWalk, BypassReason> {
687    let directory = normalize_components(directory);
688    if !admitted_roots
689        .iter()
690        .any(|root| directory.starts_with(root))
691    {
692        return Err(BypassReason::UnsupportedSearchPath("native".into()));
693    }
694
695    let canonical_root = match directory.canonicalize() {
696        Ok(root) => root,
697        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
698            return Ok(NativeWalk::default());
699        }
700        Err(error) => {
701            return Err(BypassReason::InputRead {
702                path: directory,
703                message: error.to_string(),
704            });
705        }
706    };
707    let mut pending = vec![(directory, vec![canonical_root.clone()])];
708    let mut directories = 0;
709    let mut walk = NativeWalk::default();
710    while let Some((directory, aliases)) = pending.pop() {
711        directories += 1;
712        if directories > MAX_PREDICTED_INPUTS {
713            return Err(BypassReason::UnsupportedSearchPath("native".into()));
714        }
715        let entries = match std::fs::read_dir(&directory) {
716            Ok(entries) => entries,
717            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
718            Err(error) => {
719                return Err(BypassReason::InputRead {
720                    path: directory,
721                    message: error.to_string(),
722                });
723            }
724        };
725        walk.directories.insert(directory.clone());
726        for entry in entries {
727            let entry = entry.map_err(|error| BypassReason::InputRead {
728                path: directory.clone(),
729                message: error.to_string(),
730            })?;
731            let path = entry.path();
732            let file_type = entry.file_type().map_err(|error| BypassReason::InputRead {
733                path: path.clone(),
734                message: error.to_string(),
735            })?;
736            if file_type.is_dir() {
737                if !is_linker_irrelevant_directory(&path) {
738                    pending.push((path, aliases.clone()));
739                }
740            } else if is_linker_irrelevant_file(&path) {
741                continue;
742            } else if file_type.is_file() || file_type.is_symlink() {
743                // Homebrew's versionless dylibs are symlinks. Hash their
744                // referents under the searched name. Directory aliases need
745                // the same treatment: canonicalizing their children would
746                // hide a retarget between two directories already in the tree.
747                if file_type.is_symlink() {
748                    let resolved =
749                        path.canonicalize()
750                            .map_err(|error| BypassReason::InputRead {
751                                path: path.clone(),
752                                message: error.to_string(),
753                            })?;
754                    if !resolved.starts_with(&canonical_root) {
755                        return Err(BypassReason::UnsupportedSearchPath("native".into()));
756                    }
757                    if resolved.is_dir() {
758                        // Keep the cycle check local to this walk's ancestry:
759                        // separate aliases may legitimately name the same tree.
760                        if aliases.contains(&resolved) || aliases.len() >= 64 {
761                            return Err(BypassReason::UnsupportedSearchPath("native".into()));
762                        }
763                        if !is_linker_irrelevant_directory(&path) {
764                            let mut aliases = aliases.clone();
765                            aliases.push(resolved);
766                            walk.aliases.insert(path.clone());
767                            pending.push((path, aliases));
768                        }
769                        continue;
770                    }
771                    if !resolved.is_file() {
772                        return Err(BypassReason::UnsupportedSearchPath("native".into()));
773                    }
774                }
775                let len = std::fs::metadata(&path)
776                    .map_err(|error| BypassReason::InputRead {
777                        path: path.clone(),
778                        message: error.to_string(),
779                    })?
780                    .len();
781                // A directory named by several `-L native=` arguments, or nested
782                // under another one, is walked more than once; count each file
783                // against the budget only the first time it is seen.
784                paths.insert(path.clone());
785                if counted.insert(path) {
786                    *native_bytes = native_bytes
787                        .checked_add(len)
788                        .ok_or_else(|| BypassReason::UnsupportedSearchPath("native".into()))?;
789                }
790            } else {
791                return Err(BypassReason::UnsupportedSearchPath("native".into()));
792            }
793            if paths.len() > MAX_PREDICTED_INPUTS || *native_bytes > MAX_NATIVE_INPUT_BYTES {
794                return Err(BypassReason::UnsupportedSearchPath("native".into()));
795            }
796        }
797    }
798    Ok(walk)
799}
800
801/// Directories that build scripts leave beside libraries but that a linker
802/// never reads. They often record the absolute output path (`prefix=` in
803/// pkg-config files, `binary-path:` in dSYM relocation YAML), so hashing them
804/// would make the key depend on the target directory.
805fn is_linker_irrelevant_directory(path: &Path) -> bool {
806    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
807        return false;
808    };
809    name == "pkgconfig" || name == "cmake" || name.ends_with(".dSYM")
810}
811
812/// pkg-config and CMake metadata. Headers stay hashed: linker scripts can
813/// `INCLUDE` files from a search path, and `+verbatim` names any file.
814fn is_linker_irrelevant_file(path: &Path) -> bool {
815    path.extension()
816        .and_then(|extension| extension.to_str())
817        .is_some_and(|extension| {
818            ["pc", "cmake"]
819                .iter()
820                .any(|ignored| extension.eq_ignore_ascii_case(ignored))
821        })
822}
823
824fn render_argument(argument: &Argument) -> Result<OsString, BypassReason> {
825    let rendered = match argument {
826        Argument::Plain(value) => value.clone(),
827        Argument::Path { flag, path } => format!(
828            "{flag}={}",
829            path.to_str()
830                .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?
831        ),
832        Argument::SearchPath { kind, path } => format!(
833            "-L{kind}={}",
834            path.to_str()
835                .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?
836        ),
837        Argument::Extern { name, path } => match path {
838            Some(path) => format!(
839                "--extern={name}={}",
840                path.to_str()
841                    .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?
842            ),
843            None => format!("--extern={name}"),
844        },
845        Argument::Emit(_) => unreachable!("emit arguments are removed before rendering"),
846        Argument::RemapPath { from, to } => format!(
847            "--remap-path-prefix={}={to}",
848            from.to_str()
849                .ok_or_else(|| BypassReason::NonUtf8Path(from.clone()))?
850        ),
851        // Nothing links while emitting dep-info, so the prefix is inert here;
852        // it is replayed verbatim to keep the command faithful.
853        Argument::OsoPrefix {
854            path,
855            trailing_slash,
856        } => format!(
857            "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
858            path.to_str()
859                .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?,
860            if *trailing_slash { "/" } else { "" }
861        ),
862        // Nothing links while emitting dep-info either; replayed verbatim for
863        // the same reason as the prefix above.
864        Argument::InstallName(name) => {
865            format!("--codegen=link-arg=-Wl,-install_name,@rpath/{name}")
866        }
867        Argument::Rpath(directory) => format!("--codegen=link-arg=-Wl,-rpath,{directory}"),
868        Argument::FuseLd(selection) => format!("--codegen=link-arg=-fuse-ld={selection}"),
869    };
870    Ok(rendered.into())
871}
872
873fn unescape_environment(value: &str) -> Result<String, BypassReason> {
874    let mut output = String::with_capacity(value.len());
875    let mut characters = value.chars();
876    while let Some(character) = characters.next() {
877        if character != '\\' {
878            output.push(character);
879            continue;
880        }
881        match characters.next() {
882            Some('\\') => output.push('\\'),
883            Some('n') => output.push('\n'),
884            Some('r') => output.push('\r'),
885            Some(character) => {
886                return Err(BypassReason::MalformedDepInfo(format!(
887                    "unknown environment escape \\{character}"
888                )));
889            }
890            None => {
891                return Err(BypassReason::MalformedDepInfo(
892                    "environment input ends with an unterminated escape".into(),
893                ));
894            }
895        }
896    }
897    Ok(output)
898}
899
900#[cfg(test)]
901mod tests {
902    use super::*;
903    use std::process::Command;
904
905    fn args(values: &[&str]) -> Vec<OsString> {
906        values.iter().map(OsString::from).collect()
907    }
908
909    #[test]
910    fn parses_files_spaces_and_environment_records() {
911        let parsed = RustcDepInfo::parse(
912            "target/lib.rlib: src/lib.rs src/a\\ file.rs generated.rs\n\
913             src/lib.rs:\n\
914             # env-dep:SET=value\\nnext\n\
915             # env-dep:UNSET\n\
916             # env-dep:SLASH=a\\\\b\n",
917        )
918        .unwrap();
919        assert_eq!(
920            parsed.files,
921            vec![
922                PathBuf::from("generated.rs"),
923                PathBuf::from("src/a file.rs"),
924                PathBuf::from("src/lib.rs"),
925            ]
926        );
927        assert_eq!(parsed.environment["SET"], Some("value\nnext".into()));
928        assert_eq!(parsed.environment["UNSET"], None);
929        assert_eq!(parsed.environment["SLASH"], Some(r"a\b".into()));
930    }
931
932    #[test]
933    fn malformed_dep_info_bypasses_caching() {
934        for contents in [
935            "",
936            "target: ",
937            "target: src/trailing\\\n",
938            "target: src/lib.rs\n# env-dep:NAME=bad\\q\n",
939        ] {
940            assert!(RustcDepInfo::parse(contents).is_err(), "{contents:?}");
941        }
942    }
943
944    #[test]
945    fn native_directory_byte_limit_is_cumulative() {
946        let directory = tempfile::tempdir().unwrap();
947        let native = directory.path().join("native");
948        std::fs::create_dir_all(&native).unwrap();
949        std::fs::write(native.join("input.lib"), b"xx").unwrap();
950        let roots = native_input_roots(directory.path(), &[]);
951        let mut paths = BTreeSet::new();
952        let mut native_bytes = MAX_NATIVE_INPUT_BYTES - 1;
953        let mut counted = BTreeSet::new();
954
955        assert_eq!(
956            collect_native_directory(&native, &roots, &mut paths, &mut native_bytes, &mut counted),
957            Err(BypassReason::UnsupportedSearchPath("native".into()))
958        );
959    }
960
961    #[test]
962    fn native_directory_walked_twice_counts_bytes_once() {
963        let directory = tempfile::tempdir().unwrap();
964        let native = directory.path().join("native");
965        std::fs::create_dir_all(native.join("lib")).unwrap();
966        std::fs::write(native.join("input.lib"), b"xx").unwrap();
967        std::fs::write(native.join("lib").join("nested.lib"), b"yyy").unwrap();
968        let roots = native_input_roots(directory.path(), &[]);
969        let mut paths = BTreeSet::new();
970        let mut native_bytes = 0;
971        let mut counted = BTreeSet::new();
972
973        for dir in [&native, &native, &native.join("lib")] {
974            collect_native_directory(dir, &roots, &mut paths, &mut native_bytes, &mut counted)
975                .unwrap();
976        }
977
978        assert_eq!(paths.len(), 2);
979        assert_eq!(native_bytes, 5);
980    }
981
982    #[test]
983    fn native_directory_charges_files_already_named_as_inputs() {
984        let directory = tempfile::tempdir().unwrap();
985        let native = directory.path().join("native");
986        std::fs::create_dir_all(&native).unwrap();
987        let archive = native.join("libfoo.a");
988        std::fs::write(&archive, b"xx").unwrap();
989        let roots = native_input_roots(directory.path(), &[]);
990        let mut paths = BTreeSet::from([archive]);
991        let mut native_bytes = 0;
992        let mut counted = BTreeSet::new();
993
994        collect_native_directory(&native, &roots, &mut paths, &mut native_bytes, &mut counted)
995            .unwrap();
996
997        assert_eq!(native_bytes, 2);
998    }
999
1000    #[test]
1001    fn native_directory_skips_files_the_linker_never_reads() {
1002        let directory = tempfile::tempdir().unwrap();
1003        let native = directory.path().join("native");
1004        for ignored in [
1005            "lib/pkgconfig/zlib.pc",
1006            "check.dSYM/Contents/Resources/Relocations/aarch64/check.yml",
1007            "cmake/Config.cmake",
1008            "top.pc",
1009        ] {
1010            let path = native.join(ignored);
1011            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1012            std::fs::write(path, b"prefix=/abs/target\n").unwrap();
1013        }
1014        std::fs::write(native.join("libz.a"), b"!<arch>\n").unwrap();
1015        std::fs::create_dir_all(native.join("lib")).unwrap();
1016        std::fs::write(native.join("lib/libz.so.1"), b"elf").unwrap();
1017        let roots = native_input_roots(directory.path(), &[]);
1018        let mut paths = BTreeSet::new();
1019        let mut native_bytes = 0;
1020        let mut counted = BTreeSet::new();
1021
1022        collect_native_directory(&native, &roots, &mut paths, &mut native_bytes, &mut counted)
1023            .unwrap();
1024
1025        assert_eq!(
1026            paths.into_iter().collect::<Vec<_>>(),
1027            vec![native.join("lib/libz.so.1"), native.join("libz.a")]
1028        );
1029    }
1030
1031    #[test]
1032    fn discovery_command_removes_real_outputs() {
1033        let invocation = RustcInvocation::parse(&args(&[
1034            "--crate-name=widget",
1035            "--crate-type=lib",
1036            "--emit=dep-info,metadata,link",
1037            "--out-dir=target/debug/deps",
1038            "-o",
1039            "target/debug/libwidget.rlib",
1040            "src/lib.rs",
1041        ]))
1042        .unwrap();
1043        let output = if cfg!(windows) {
1044            PathBuf::from(r"C:\tmp\mbx cache\inputs.d")
1045        } else {
1046            PathBuf::from("/tmp/mbx cache/inputs.d")
1047        };
1048        let command = invocation.dep_info_command(&output).unwrap();
1049        let arguments = command
1050            .arguments()
1051            .iter()
1052            .map(|value| value.to_string_lossy())
1053            .collect::<Vec<_>>();
1054        assert_eq!(
1055            arguments,
1056            vec![
1057                "--crate-name=widget",
1058                "--crate-type=lib",
1059                &format!("--emit=dep-info={}", output.display()),
1060                "src/lib.rs",
1061            ]
1062        );
1063    }
1064
1065    #[test]
1066    fn discovery_hashes_externs_and_custom_targets() {
1067        let directory = tempfile::tempdir().unwrap();
1068        let root = directory.path();
1069        let source = root.join("src/lib.rs");
1070        let external = root.join("target/libdependency.rlib");
1071        let target = root.join("targets/custom.json");
1072        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
1073        std::fs::create_dir_all(external.parent().unwrap()).unwrap();
1074        std::fs::create_dir_all(target.parent().unwrap()).unwrap();
1075        std::fs::write(&source, "pub fn library() {}\n").unwrap();
1076        std::fs::write(&external, "dependency artifact\n").unwrap();
1077        std::fs::write(&target, "{}\n").unwrap();
1078
1079        let invocation = RustcInvocation::parse(&[
1080            "--crate-name=widget".into(),
1081            "--crate-type=lib".into(),
1082            "--emit=metadata".into(),
1083            format!("--extern=dependency={}", external.display()).into(),
1084            format!("--target={}", target.display()).into(),
1085            source.clone().into_os_string(),
1086        ])
1087        .unwrap();
1088        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1089        let discovered = invocation.discover_inputs(&dep_info, root).unwrap();
1090        assert_eq!(discovered.inputs.len(), 3);
1091
1092        std::fs::remove_file(&external).unwrap();
1093        assert!(matches!(
1094            invocation.discover_inputs(&dep_info, root),
1095            Err(BypassReason::InputRead { path, .. }) if path == external
1096        ));
1097    }
1098
1099    /// macOS writes extended attributes to a file a second or two after an
1100    /// app saves it, moving its change time alone. That must not discard a
1101    /// compilation as if the source had changed: it leaves it uncached. It
1102    /// must not hide a content change to another input either.
1103    #[cfg(unix)]
1104    #[test]
1105    fn a_metadata_write_during_compilation_bypasses_without_discarding() {
1106        use std::os::unix::fs::PermissionsExt as _;
1107
1108        let directory = tempfile::tempdir().unwrap();
1109        let library = directory.path().join("lib.rs");
1110        let module = directory.path().join("module.rs");
1111        std::fs::write(&library, "mod module;\n").unwrap();
1112        std::fs::write(&module, "pub fn module() {}\n").unwrap();
1113        let invocation = RustcInvocation::parse(&[
1114            "--crate-name=widget".into(),
1115            "--crate-type=lib".into(),
1116            "--emit=dep-info,metadata".into(),
1117            library.clone().into_os_string(),
1118        ])
1119        .unwrap();
1120        let dep_info = RustcDepInfo::parse(&format!(
1121            "output: {} {}\n",
1122            library.display(),
1123            module.display()
1124        ))
1125        .unwrap();
1126        let identity = |path: &Path| {
1127            FileIdentity::for_digest_cache(path, &std::fs::metadata(path).unwrap()).unwrap()
1128        };
1129        // Settled metadata snapshots, whatever the host's timestamp tick.
1130        let Some(settled) = identity(&library).filter(|identity| identity.changed.is_some()) else {
1131            return; // No change token on this filesystem.
1132        };
1133        let before = BTreeMap::from([
1134            (library.clone(), FileSnapshot::from(settled.clone())),
1135            (
1136                module.clone(),
1137                FileSnapshot::from(identity(&module).unwrap()),
1138            ),
1139        ]);
1140
1141        let mode = std::fs::metadata(&library).unwrap().permissions().mode();
1142        std::fs::set_permissions(&library, std::fs::Permissions::from_mode(mode)).unwrap();
1143        if identity(&library) == Some(settled) {
1144            return; // The change time did not move within this tick.
1145        }
1146        let discovered = invocation
1147            .discover_inputs(&dep_info, directory.path())
1148            .unwrap();
1149        assert_eq!(
1150            discovered.verify_not_modified_since_with_snapshots(SystemTime::UNIX_EPOCH, &before),
1151            Err(BypassReason::InputMetadataChangedDuringCompilation(
1152                library.clone()
1153            ))
1154        );
1155
1156        // A rewrite of a different length is still a content change, even
1157        // behind the earlier metadata-only one.
1158        std::fs::write(&module, "pub fn module() { let _ = 1; }\n").unwrap();
1159        let discovered = invocation
1160            .discover_inputs(&dep_info, directory.path())
1161            .unwrap();
1162        assert_eq!(
1163            discovered.verify_not_modified_since_with_snapshots(SystemTime::UNIX_EPOCH, &before),
1164            Err(BypassReason::InputModifiedDuringCompilation(module))
1165        );
1166    }
1167
1168    #[test]
1169    fn discovery_rejects_inputs_modified_during_compilation() {
1170        let directory = tempfile::tempdir().unwrap();
1171        let source = directory.path().join("lib.rs");
1172        std::fs::write(&source, "pub fn library() {}\n").unwrap();
1173        let invocation = RustcInvocation::parse(&[
1174            "--crate-name=widget".into(),
1175            "--crate-type=lib".into(),
1176            "--emit=dep-info,metadata".into(),
1177            source.clone().into_os_string(),
1178        ])
1179        .unwrap();
1180        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1181        let discovered = invocation
1182            .discover_inputs(&dep_info, directory.path())
1183            .unwrap();
1184        let modified = std::fs::metadata(&source).unwrap().modified().unwrap();
1185
1186        assert_eq!(
1187            discovered.verify_not_modified_since(modified),
1188            Err(BypassReason::InputModifiedDuringCompilation(source))
1189        );
1190    }
1191
1192    #[test]
1193    fn profile_use_is_discovered_verified_and_rehashed_by_prediction() {
1194        let directory = tempfile::tempdir().unwrap();
1195        let root = directory.path();
1196        let source = root.join("lib.rs");
1197        let profile = root.join("profile.profdata");
1198        std::fs::write(&source, "pub fn library() {}\n").unwrap();
1199        std::fs::write(&profile, "first profile").unwrap();
1200        let invocation = RustcInvocation::parse(&[
1201            "--crate-name=widget".into(),
1202            "--crate-type=lib".into(),
1203            "--emit=dep-info,metadata".into(),
1204            format!("-Cprofile-use={}", profile.display()).into(),
1205            "lib.rs".into(),
1206        ])
1207        .unwrap();
1208        let mappings = vec![PathMapping::new(root, "workspace")];
1209        let dep_info = RustcDepInfo::parse("widget.d: lib.rs\n").unwrap();
1210        let discover = || {
1211            invocation
1212                .discover_inputs_with_mappings(
1213                    &dep_info,
1214                    root,
1215                    &mappings,
1216                    &mbx_cache_core::NoFileDigestCache,
1217                )
1218                .unwrap()
1219        };
1220        let initial_inputs = discover();
1221        assert!(
1222            initial_inputs
1223                .inputs
1224                .iter()
1225                .any(|input| input.path == profile)
1226        );
1227        let mut context = library_context(root, mappings.clone());
1228        initial_inputs.clone().apply_to(&mut context).unwrap();
1229        let initial_action = invocation.action(context.clone()).unwrap();
1230        let prediction = invocation.prediction(&context, &initial_inputs).unwrap();
1231
1232        std::fs::write(&profile, "updated profile").unwrap();
1233        assert_eq!(
1234            initial_inputs.verify(),
1235            Err(BypassReason::InputChanged(profile.clone()))
1236        );
1237        context.inputs.clear();
1238        let predicted = prediction
1239            .discover(root, &mappings, &mbx_cache_core::NoFileDigestCache)
1240            .unwrap();
1241        predicted.clone().apply_to(&mut context).unwrap();
1242        let predicted_action = invocation.action(context.clone()).unwrap();
1243        assert_ne!(predicted_action.digest, initial_action.digest);
1244        context.inputs.clear();
1245        discover().apply_to(&mut context).unwrap();
1246        assert_eq!(predicted_action, invocation.action(context).unwrap());
1247
1248        let missing_profile = root.join("missing.profdata");
1249        let missing_invocation = RustcInvocation::parse(&[
1250            "--crate-name=widget".into(),
1251            "--crate-type=lib".into(),
1252            "--emit=dep-info,metadata".into(),
1253            format!("-Cprofile-use={}", missing_profile.display()).into(),
1254            "lib.rs".into(),
1255        ])
1256        .unwrap();
1257        assert!(matches!(
1258            missing_invocation.discover_inputs_with_mappings(
1259                &dep_info,
1260                root,
1261                &mappings,
1262                &mbx_cache_core::NoFileDigestCache,
1263            ),
1264            Err(BypassReason::InputRead { path, .. }) if path == missing_profile
1265        ));
1266    }
1267
1268    #[cfg(unix)]
1269    #[test]
1270    fn precompile_snapshot_does_not_depend_on_the_host_clock() {
1271        let directory = tempfile::tempdir().unwrap();
1272        let source = directory.path().join("lib.rs");
1273        std::fs::write(&source, "pub fn library() {0}\n").unwrap();
1274        let invocation = RustcInvocation::parse(&[
1275            "--crate-name=widget".into(),
1276            "--crate-type=lib".into(),
1277            "--emit=dep-info,metadata".into(),
1278            source.clone().into_os_string(),
1279        ])
1280        .unwrap();
1281        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1282        let discovered = invocation
1283            .discover_inputs(&dep_info, directory.path())
1284            .unwrap();
1285        let snapshot = FileSnapshot::capture(&source).unwrap().unwrap();
1286        let before = BTreeMap::from([(source.clone(), snapshot)]);
1287
1288        // Every ordinary mtime is after the epoch. The unchanged identity is
1289        // nevertheless enough proof when the filesystem clock is far ahead.
1290        discovered
1291            .verify_not_modified_since_with_snapshots(SystemTime::UNIX_EPOCH, &before)
1292            .unwrap();
1293
1294        // Conversely, a filesystem clock far behind must not conceal a write.
1295        // Let the coarse ZFS timestamp tick advance before this same-length rewrite.
1296        std::thread::sleep(std::time::Duration::from_millis(20));
1297        std::fs::write(&source, "pub fn library() {1}\n").unwrap();
1298        let discovered = invocation
1299            .discover_inputs(&dep_info, directory.path())
1300            .unwrap();
1301        assert_eq!(
1302            discovered.verify_not_modified_since_with_snapshots(
1303                SystemTime::now() + std::time::Duration::from_secs(60),
1304                &before,
1305            ),
1306            Err(BypassReason::InputModifiedDuringCompilation(source))
1307        );
1308    }
1309
1310    #[cfg(unix)]
1311    #[test]
1312    fn snapshot_only_check_compares_sources_after_a_generated_file() {
1313        let directory = tempfile::tempdir().unwrap();
1314        let source = directory.path().join("lib.rs");
1315        let generated = directory.path().join("a_generated.rs");
1316        std::fs::write(&source, "pub fn library() {0}\n").unwrap();
1317        let invocation = RustcInvocation::parse(&[
1318            "--crate-name=widget".into(),
1319            "--crate-type=lib".into(),
1320            "--emit=dep-info,metadata".into(),
1321            source.clone().into_os_string(),
1322        ])
1323        .unwrap();
1324        let before = BTreeMap::from([(
1325            source.clone(),
1326            FileSnapshot::capture(&source).unwrap().unwrap(),
1327        )]);
1328        // The compiler writes a generated input that sorts first, then the
1329        // source changes while it runs.
1330        std::thread::sleep(std::time::Duration::from_millis(20));
1331        std::fs::write(&generated, "// generated\n").unwrap();
1332        // Far beyond any fixed offset from the start time.
1333        std::fs::File::options()
1334            .write(true)
1335            .open(&generated)
1336            .unwrap()
1337            .set_modified(SystemTime::now() + std::time::Duration::from_secs(30 * 86_400))
1338            .unwrap();
1339        std::fs::write(&source, "pub fn library() {1}\n").unwrap();
1340        let dep_info = RustcDepInfo::parse(&format!(
1341            "output: {} {}\n",
1342            generated.display(),
1343            source.display()
1344        ))
1345        .unwrap();
1346        let discovered = invocation
1347            .discover_inputs(&dep_info, directory.path())
1348            .unwrap();
1349        assert_eq!(
1350            discovered.verify_snapshots_unchanged(&before),
1351            Err(BypassReason::InputModifiedDuringCompilation(source))
1352        );
1353    }
1354
1355    /// An external MSVC toolset directory, outside every mapped root.
1356    fn toolchain_native_directory(version: &str) -> PathBuf {
1357        if cfg!(windows) {
1358            PathBuf::from(format!(
1359                r"C:\Program Files\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\{version}\lib\x64"
1360            ))
1361        } else {
1362            PathBuf::from(format!("/opt/msvc/{version}/lib/x64"))
1363        }
1364    }
1365
1366    fn library_with_native_search(source: &Path, directory: &Path) -> RustcInvocation {
1367        RustcInvocation::parse(&[
1368            "--crate-name=widget".into(),
1369            "--crate-type=lib".into(),
1370            "--emit=metadata,link".into(),
1371            format!("-Lnative={}", directory.display()).into(),
1372            source.to_path_buf().into_os_string(),
1373        ])
1374        .unwrap()
1375    }
1376
1377    fn library_context(root: &Path, mappings: Vec<PathMapping>) -> ActionContext {
1378        ActionContext {
1379            compiler: crate::CompilerIdentity {
1380                toolchain: "core:rust@test".into(),
1381                rustc_version: "test".into(),
1382                host: std::env::consts::ARCH.into(),
1383                driver: None,
1384            },
1385            working_dir: root.to_path_buf(),
1386            path_mappings: mappings,
1387            environment: BTreeMap::new(),
1388            portable_environment: BTreeSet::new(),
1389            inputs: Vec::new(),
1390        }
1391    }
1392
1393    #[cfg(windows)]
1394    #[test]
1395    fn unmapped_toolchain_directory_cannot_hide_a_static_archive() {
1396        let directory = tempfile::tempdir().unwrap();
1397        let root = directory.path();
1398        let source = root.join("lib.rs");
1399        std::fs::write(&source, "pub fn library() {}\n").unwrap();
1400        let toolchain = toolchain_native_directory("14.51.36231");
1401        let invocation = library_with_native_search(&source, &toolchain);
1402        let mappings = vec![PathMapping::new(root, "workspace")];
1403        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1404
1405        let context = library_context(root, mappings.clone());
1406        assert!(matches!(
1407            invocation.invocation_digest(&context),
1408            Err(BypassReason::UnmappedAbsolutePath(path)) if path == toolchain
1409        ));
1410        assert_eq!(
1411            invocation.discover_inputs_with_mappings(
1412                &dep_info,
1413                root,
1414                &mappings,
1415                &mbx_cache_core::NoFileDigestCache,
1416            ),
1417            Err(BypassReason::UnsupportedSearchPath("native".into()))
1418        );
1419    }
1420
1421    #[test]
1422    fn source_level_static_link_cannot_hide_an_unmapped_archive() {
1423        let directory = tempfile::tempdir().unwrap();
1424        let workspace = directory.path().join("workspace");
1425        let external = directory.path().join("external");
1426        std::fs::create_dir(&workspace).unwrap();
1427        std::fs::create_dir(&external).unwrap();
1428        let source = workspace.join("lib.rs");
1429        std::fs::write(
1430            &source,
1431            "#[link(name = \"foo\", kind = \"static\")] unsafe extern \"C\" {}\n",
1432        )
1433        .unwrap();
1434        std::fs::write(external.join("libfoo.a"), b"first archive").unwrap();
1435        let invocation = library_with_native_search(&source, &external);
1436        let mappings = vec![PathMapping::new(&workspace, "workspace")];
1437        let context = library_context(&workspace, mappings.clone());
1438        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1439
1440        // rustc's dep-info names the source but not an archive from #[link].
1441        // A path-only key would restore a stale rlib after libfoo.a changed.
1442        assert!(matches!(
1443            invocation.invocation_digest(&context),
1444            Err(BypassReason::UnmappedAbsolutePath(path)) if path == external
1445        ));
1446        assert_eq!(
1447            invocation.discover_inputs_with_mappings(
1448                &dep_info,
1449                &workspace,
1450                &mappings,
1451                &mbx_cache_core::NoFileDigestCache,
1452            ),
1453            Err(BypassReason::UnsupportedSearchPath("native".into()))
1454        );
1455    }
1456
1457    #[cfg(windows)]
1458    #[test]
1459    fn project_directory_with_toolchain_suffix_is_not_trusted() {
1460        let directory = tempfile::tempdir().unwrap();
1461        let root = directory.path().join("workspace");
1462        std::fs::create_dir(&root).unwrap();
1463        let source = root.join("lib.rs");
1464        std::fs::write(&source, "pub fn library() {}\n").unwrap();
1465        let fake_toolchain = directory.path().join("MSVC/14.51.36231/lib/x64");
1466        let invocation = library_with_native_search(&source, &fake_toolchain);
1467        let context = library_context(&root, vec![PathMapping::new(&root, "workspace")]);
1468
1469        // The apparent toolset version cannot make a mutable project archive inert.
1470        assert!(matches!(
1471            invocation.invocation_digest(&context),
1472            Err(BypassReason::UnmappedAbsolutePath(path)) if path == fake_toolchain
1473        ));
1474    }
1475
1476    #[test]
1477    fn unmapped_native_directory_still_refuses_a_native_link() {
1478        let directory = tempfile::tempdir().unwrap();
1479        let root = directory.path();
1480        let source = root.join("main.rs");
1481        std::fs::write(&source, "fn main() {}\n").unwrap();
1482        let toolchain = toolchain_native_directory("14.51.36231");
1483        let invocation = RustcInvocation::parse_with(
1484            &[
1485                "--crate-name=app".into(),
1486                "--crate-type=bin".into(),
1487                "--emit=link".into(),
1488                format!("-Lnative={}", toolchain.display()).into(),
1489                source.clone().into_os_string(),
1490            ],
1491            crate::ParseOptions::caching_native_links(true),
1492        )
1493        .unwrap();
1494        let mappings = vec![PathMapping::new(root, "workspace")];
1495
1496        // A linker reads those directories, so their contents stay inputs the
1497        // key must account for, and an unmapped one stays a bypass.
1498        let context = library_context(root, mappings.clone());
1499        assert!(matches!(
1500            invocation.invocation_digest(&context),
1501            Err(BypassReason::UnmappedAbsolutePath(_))
1502        ));
1503        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1504        assert_eq!(
1505            invocation.discover_inputs_with_mappings(
1506                &dep_info,
1507                root,
1508                &mappings,
1509                &mbx_cache_core::NoFileDigestCache
1510            ),
1511            Err(BypassReason::UnsupportedSearchPath("native".into()))
1512        );
1513    }
1514
1515    #[test]
1516    fn discovery_resolves_parent_components_against_the_working_directory() {
1517        let directory = tempfile::tempdir().unwrap();
1518        let root = directory.path().join("project");
1519        let shared = directory.path().join("shared.rs");
1520        std::fs::create_dir(&root).unwrap();
1521        std::fs::write(&shared, "pub fn shared() {}\n").unwrap();
1522
1523        let invocation = RustcInvocation::parse(&args(&[
1524            "--crate-name=widget",
1525            "--crate-type=lib",
1526            "--emit=metadata",
1527            "../shared.rs",
1528        ]))
1529        .unwrap();
1530        let dep_info = RustcDepInfo::parse("output: ../shared.rs\n").unwrap();
1531        let discovered = invocation.discover_inputs(&dep_info, &root).unwrap();
1532
1533        assert_eq!(discovered.inputs.len(), 1);
1534        assert_eq!(discovered.inputs[0].path, shared);
1535    }
1536
1537    #[test]
1538    fn rustc_dep_info_round_trip_discovers_real_inputs() {
1539        let directory = tempfile::tempdir().unwrap();
1540        let root = directory.path();
1541        std::fs::write(
1542            root.join("lib.rs"),
1543            "mod child; const _: &str = include_str!(\"data file.txt\"); \
1544             const _: &str = env!(\"MBX_DISCOVERY_TEST\"); \
1545             const _: Option<&str> = option_env!(\"MBX_DISCOVERY_UNSET\");",
1546        )
1547        .unwrap();
1548        std::fs::write(root.join("child.rs"), "pub fn child() {}\n").unwrap();
1549        std::fs::write(root.join("data file.txt"), "included\n").unwrap();
1550
1551        let invocation = RustcInvocation::parse(&args(&[
1552            "--crate-name=mbx_cache_discovery_test",
1553            "--crate-type=lib",
1554            "--emit=metadata,link",
1555            "lib.rs",
1556        ]))
1557        .unwrap();
1558        let dep_info_path = root.join("discovery inputs.d");
1559        let discovery_command = invocation.dep_info_command(&dep_info_path).unwrap();
1560        let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
1561        let output = match Command::new(rustc)
1562            .args(discovery_command.arguments())
1563            .current_dir(root)
1564            .env("MBX_DISCOVERY_TEST", "observed")
1565            .env_remove("MBX_DISCOVERY_UNSET")
1566            .output()
1567        {
1568            Ok(output) => output,
1569            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
1570            Err(error) => panic!("failed to execute rustc: {error}"),
1571        };
1572        assert!(
1573            output.status.success(),
1574            "{}",
1575            String::from_utf8_lossy(&output.stderr)
1576        );
1577        let parsed = RustcDepInfo::read(&dep_info_path).unwrap();
1578        let discovered = invocation.discover_inputs(&parsed, root).unwrap();
1579        assert_eq!(
1580            discovered.environment["MBX_DISCOVERY_TEST"],
1581            Some("observed".into())
1582        );
1583        assert_eq!(discovered.environment["MBX_DISCOVERY_UNSET"], None);
1584        assert_eq!(discovered.inputs.len(), 3);
1585        assert!(
1586            discovered
1587                .inputs
1588                .iter()
1589                .all(|input| input.digest.algorithm == "blake3")
1590        );
1591        let mut context = ActionContext {
1592            compiler: crate::CompilerIdentity {
1593                toolchain: "core:rust@test".into(),
1594                rustc_version: "test".into(),
1595                host: std::env::consts::ARCH.into(),
1596                driver: None,
1597            },
1598            working_dir: root.to_path_buf(),
1599            path_mappings: vec![crate::PathMapping::new(root, "workspace")],
1600            environment: BTreeMap::new(),
1601            portable_environment: BTreeSet::new(),
1602            inputs: Vec::new(),
1603        };
1604        discovered.clone().apply_to(&mut context).unwrap();
1605        let action = invocation.action(context).unwrap();
1606        assert!(
1607            String::from_utf8(action.bytes)
1608                .unwrap()
1609                .contains(r#""MBX_DISCOVERY_TEST":"observed""#)
1610        );
1611        discovered.verify().unwrap();
1612        std::fs::write(root.join("child.rs"), "pub fn changed() {}\n").unwrap();
1613        assert_eq!(
1614            discovered.verify(),
1615            Err(BypassReason::InputChanged(root.join("child.rs")))
1616        );
1617    }
1618
1619    /// A ledger that answers with a sentinel and remembers what was recorded.
1620    struct SentinelLedger {
1621        known: FileIdentity,
1622        digest: CacheDigest,
1623        recorded: std::sync::Mutex<Vec<RecordedFileDigest>>,
1624    }
1625
1626    impl FileDigestCache for SentinelLedger {
1627        fn find(&self, scope: FileDigestScope, files: &[FileIdentity]) -> Vec<Option<CacheDigest>> {
1628            assert_eq!(scope, FileDigestScope::Content);
1629            files
1630                .iter()
1631                .map(|file| (*file == self.known).then(|| self.digest.clone()))
1632                .collect()
1633        }
1634
1635        fn record(&self, scope: FileDigestScope, entries: Vec<RecordedFileDigest>) {
1636            assert_eq!(scope, FileDigestScope::Content);
1637            self.recorded.lock().unwrap().extend(entries);
1638        }
1639    }
1640
1641    #[cfg(unix)]
1642    struct ReplacingLedger {
1643        path: PathBuf,
1644        replacement: PathBuf,
1645        recorded: std::sync::Mutex<Vec<RecordedFileDigest>>,
1646    }
1647
1648    #[cfg(unix)]
1649    impl FileDigestCache for ReplacingLedger {
1650        fn find(&self, scope: FileDigestScope, files: &[FileIdentity]) -> Vec<Option<CacheDigest>> {
1651            assert_eq!(scope, FileDigestScope::Content);
1652            assert_eq!(files.len(), 1);
1653            std::fs::remove_file(&self.path).unwrap();
1654            std::fs::rename(&self.replacement, &self.path).unwrap();
1655            // Digests of files changed this moment are withheld from reuse.
1656            std::thread::sleep(std::time::Duration::from_millis(50));
1657            vec![None]
1658        }
1659
1660        fn record(&self, scope: FileDigestScope, entries: Vec<RecordedFileDigest>) {
1661            assert_eq!(scope, FileDigestScope::Content);
1662            self.recorded.lock().unwrap().extend(entries);
1663        }
1664    }
1665
1666    #[cfg(unix)]
1667    #[test]
1668    fn discovery_binds_a_replacement_digest_to_the_replacement_identity() {
1669        let directory = tempfile::tempdir().unwrap();
1670        let root = directory.path();
1671        let path = root.join("libdep.rlib");
1672        let replacement = root.join("replacement.rlib");
1673        std::fs::write(&path, b"original....").unwrap();
1674        std::fs::File::options()
1675            .write(true)
1676            .open(&path)
1677            .unwrap()
1678            .set_times(std::fs::FileTimes::new().set_modified(SystemTime::UNIX_EPOCH))
1679            .unwrap();
1680        std::fs::write(&replacement, b"replacement!").unwrap();
1681        std::fs::File::options()
1682            .write(true)
1683            .open(&replacement)
1684            .unwrap()
1685            .set_times(std::fs::FileTimes::new().set_modified(SystemTime::UNIX_EPOCH))
1686            .unwrap();
1687        let ledger = ReplacingLedger {
1688            path: path.clone(),
1689            replacement,
1690            recorded: std::sync::Mutex::new(Vec::new()),
1691        };
1692
1693        let discovered = DiscoveredInputs::from_paths(
1694            root,
1695            BTreeSet::from([path.clone()]),
1696            BTreeMap::new(),
1697            &ledger,
1698        )
1699        .unwrap();
1700        let current = FileIdentity::for_digest_cache(&path, &std::fs::metadata(&path).unwrap())
1701            .unwrap()
1702            .unwrap();
1703        let digest = CacheDigest::blake3_file(&path).unwrap();
1704
1705        assert_eq!(discovered.inputs[0].digest, digest);
1706        assert_eq!(discovered.identities[0].as_ref(), Some(&current));
1707        assert_eq!(
1708            ledger.recorded.lock().unwrap().as_slice(),
1709            &[RecordedFileDigest {
1710                file: current,
1711                digest,
1712            }]
1713        );
1714        discovered.verify().unwrap();
1715    }
1716
1717    #[test]
1718    fn discovery_reuses_recorded_digests_and_records_fresh_ones() {
1719        let directory = tempfile::tempdir().unwrap();
1720        let root = directory.path();
1721        let known_path = root.join("libdep.rlib");
1722        let fresh_path = root.join("lib.rs");
1723        std::fs::write(&known_path, b"rlib bytes").unwrap();
1724        std::fs::write(&fresh_path, b"fn lib() {}").unwrap();
1725        // Digests of files written this moment are withheld from reuse.
1726        std::thread::sleep(std::time::Duration::from_millis(50));
1727        let metadata = std::fs::metadata(&known_path).unwrap();
1728        // A sentinel digest that hashing could never produce proves the read
1729        // was skipped: the discovered input carries it verbatim.
1730        let sentinel = CacheDigest {
1731            algorithm: "blake3".into(),
1732            hash: "c".repeat(64),
1733            size: metadata.len(),
1734        };
1735        let ledger = SentinelLedger {
1736            known: FileIdentity::describe(&known_path, &metadata).unwrap(),
1737            digest: sentinel.clone(),
1738            recorded: std::sync::Mutex::new(Vec::new()),
1739        };
1740
1741        let discovered = DiscoveredInputs::from_paths(
1742            root,
1743            BTreeSet::from([known_path.clone(), fresh_path.clone()]),
1744            BTreeMap::new(),
1745            &ledger,
1746        )
1747        .unwrap();
1748
1749        let by_path = |path: &Path| {
1750            discovered
1751                .inputs
1752                .iter()
1753                .find(|input| input.path == path)
1754                .unwrap()
1755                .digest
1756                .clone()
1757        };
1758        assert_eq!(
1759            by_path(&known_path),
1760            sentinel,
1761            "the recorded digest answers"
1762        );
1763        assert_eq!(
1764            by_path(&fresh_path),
1765            CacheDigest::blake3_file(&fresh_path).unwrap(),
1766            "an unrecorded file is hashed"
1767        );
1768        let recorded = ledger.recorded.lock().unwrap();
1769        assert_eq!(recorded.len(), 1, "only the fresh hash is recorded");
1770        assert_eq!(recorded[0].file.path, fresh_path);
1771        assert_eq!(recorded[0].digest, by_path(&fresh_path));
1772    }
1773
1774    /// Verification after the compiler runs confirms an input by its recorded
1775    /// identity rather than by reading it again; a file that has moved on is
1776    /// still read and still fails. Only where the identity carries a change
1777    /// time, which is what makes the stat as good as the read.
1778    #[cfg(unix)]
1779    #[test]
1780    fn verification_trusts_an_unchanged_identity_and_rereads_a_changed_one() {
1781        let directory = tempfile::tempdir().unwrap();
1782        let root = directory.path();
1783        let known_path = root.join("libdep.rlib");
1784        std::fs::write(&known_path, b"rlib bytes").unwrap();
1785        let metadata = std::fs::metadata(&known_path).unwrap();
1786        // The sentinel could never come from hashing the file, so a verify
1787        // that passes can only have trusted the identity.
1788        let sentinel = CacheDigest {
1789            algorithm: "blake3".into(),
1790            hash: "c".repeat(64),
1791            size: metadata.len(),
1792        };
1793        let ledger = SentinelLedger {
1794            known: FileIdentity::describe(&known_path, &metadata).unwrap(),
1795            digest: sentinel,
1796            recorded: std::sync::Mutex::new(Vec::new()),
1797        };
1798        let discovered = DiscoveredInputs::from_paths(
1799            root,
1800            BTreeSet::from([known_path.clone()]),
1801            BTreeMap::new(),
1802            &ledger,
1803        )
1804        .unwrap();
1805
1806        discovered.verify().unwrap();
1807
1808        // Rewritten with the same length: the identity moves with the write,
1809        // so the file is read again and the sentinel no longer matches it.
1810        std::thread::sleep(std::time::Duration::from_millis(20));
1811        std::fs::write(&known_path, b"RLIB BYTES").unwrap();
1812        assert_eq!(
1813            discovered.verify(),
1814            Err(BypassReason::InputChanged(known_path.clone()))
1815        );
1816
1817        std::fs::remove_file(&known_path).unwrap();
1818        assert!(matches!(
1819            discovered.verify(),
1820            Err(BypassReason::InputRead { path, .. }) if path == known_path
1821        ));
1822    }
1823
1824    /// A rewrite that restores length and modification time must still be
1825    /// hashed: the platform change token moves with every write, so the
1826    /// identity the ledger recorded no longer describes the file.
1827    #[cfg(unix)]
1828    #[test]
1829    fn a_disguised_rewrite_is_not_answered_from_the_ledger() {
1830        let directory = tempfile::tempdir().unwrap();
1831        let root = directory.path();
1832        let path = root.join("lib.rs");
1833        std::fs::write(&path, b"fn lib() -> u8 { 1 }").unwrap();
1834        let before = std::fs::metadata(&path).unwrap();
1835        let identity = FileIdentity::describe(&path, &before).unwrap();
1836
1837        // Same length, modification time put back: only the change token can
1838        // tell this file has new contents. Filesystems such as ZFS stamp
1839        // files from a 1 ms tick, so wait for the change token to move.
1840        std::thread::sleep(std::time::Duration::from_millis(20));
1841        std::fs::write(&path, b"fn lib() -> u8 { 2 }").unwrap();
1842        let file = std::fs::File::options().write(true).open(&path).unwrap();
1843        file.set_times(std::fs::FileTimes::new().set_modified(before.modified().unwrap()))
1844            .unwrap();
1845        drop(file);
1846        let after = std::fs::metadata(&path).unwrap();
1847        let disguised = FileIdentity::describe(&path, &after).unwrap();
1848        assert_eq!(disguised.len, identity.len);
1849        assert_eq!(disguised.modified, identity.modified);
1850        assert_ne!(
1851            disguised, identity,
1852            "the change token must expose the rewrite"
1853        );
1854
1855        let ledger = SentinelLedger {
1856            known: identity,
1857            digest: CacheDigest {
1858                algorithm: "blake3".into(),
1859                hash: "e".repeat(64),
1860                size: after.len(),
1861            },
1862            recorded: std::sync::Mutex::new(Vec::new()),
1863        };
1864        let discovered = DiscoveredInputs::from_paths(
1865            root,
1866            BTreeSet::from([path.clone()]),
1867            BTreeMap::new(),
1868            &ledger,
1869        )
1870        .unwrap();
1871        assert_eq!(
1872            discovered.inputs[0].digest,
1873            CacheDigest::blake3_file(&path).unwrap(),
1874            "the disguised rewrite is hashed, not answered from the ledger"
1875        );
1876    }
1877    #[cfg(unix)]
1878    #[test]
1879    fn native_directory_aliases_preserve_searched_names_on_prediction() {
1880        use std::os::unix::fs::symlink;
1881        let directory = tempfile::tempdir().unwrap();
1882        let root = directory.path();
1883        let source = root.join("lib.rs");
1884        let native = root.join("native");
1885        for version in ["first", "second"] {
1886            std::fs::create_dir_all(native.join(version)).unwrap();
1887            std::fs::write(native.join(version).join("libwidget.a"), version).unwrap();
1888            std::fs::write(native.join(version).join("widget.h"), version).unwrap();
1889        }
1890        std::fs::write(&source, "pub fn value() {}\n").unwrap();
1891        let alias = native.join("current");
1892        symlink("first", &alias).unwrap();
1893        let invocation = library_with_native_search(&source, &native);
1894        let mappings = vec![PathMapping::new(root, "workspace")];
1895        let dep_info = RustcDepInfo {
1896            files: vec![source],
1897            environment: BTreeMap::new(),
1898        };
1899        let discover = || {
1900            invocation
1901                .discover_inputs_with_mappings(
1902                    &dep_info,
1903                    root,
1904                    &mappings,
1905                    &mbx_cache_core::NoFileDigestCache,
1906                )
1907                .unwrap()
1908        };
1909        let original = discover();
1910        assert!(
1911            original
1912                .inputs
1913                .iter()
1914                .any(|input| input.path == alias.join("libwidget.a"))
1915        );
1916        let mut context = library_context(root, mappings.clone());
1917        original.clone().apply_to(&mut context).unwrap();
1918        let initial = invocation.action(context.clone()).unwrap();
1919        let prediction = invocation.prediction(&context, &original).unwrap();
1920        context.inputs.clear();
1921
1922        let mut previous = initial.digest;
1923        let mut retargeted = None;
1924        for change in ["library", "header", "retarget", "remove", "return"] {
1925            match change {
1926                "library" => std::fs::write(native.join("first/libwidget.a"), "other").unwrap(),
1927                "header" => std::fs::write(native.join("first/widget.h"), "other").unwrap(),
1928                "retarget" => {
1929                    // Both destinations already exist. Only the searched alias
1930                    // changes; canonicalizing its inputs would miss this.
1931                    std::fs::remove_file(&alias).unwrap();
1932                    symlink("second", &alias).unwrap();
1933                }
1934                "remove" => std::fs::remove_file(&alias).unwrap(),
1935                _ => symlink("second", &alias).unwrap(),
1936            }
1937            let predicted = prediction
1938                .discover(root, &mappings, &mbx_cache_core::NoFileDigestCache)
1939                .unwrap();
1940            let mut predicted_context = context.clone();
1941            predicted.apply_to(&mut predicted_context).unwrap();
1942            let after = invocation.action(predicted_context).unwrap();
1943            assert_ne!(after.digest, previous, "{change}");
1944            let mut discovered_context = context.clone();
1945            discover().apply_to(&mut discovered_context).unwrap();
1946            assert_eq!(after, invocation.action(discovered_context).unwrap());
1947            if change == "retarget" {
1948                retargeted = Some(after.digest.clone());
1949            } else if change == "return" {
1950                assert_eq!(Some(after.digest.clone()), retargeted);
1951            }
1952            previous = after.digest;
1953        }
1954
1955        // Directory aliases cannot bring untracked files into the search tree.
1956        let outside = root.join("outside");
1957        std::fs::create_dir(&outside).unwrap();
1958        std::fs::write(outside.join("libwidget.a"), "outside").unwrap();
1959        std::fs::remove_file(&alias).unwrap();
1960        symlink(&outside, &alias).unwrap();
1961        assert!(
1962            prediction
1963                .discover(root, &mappings, &mbx_cache_core::NoFileDigestCache)
1964                .is_err()
1965        );
1966    }
1967
1968    #[cfg(unix)]
1969    #[test]
1970    fn native_directory_alias_retarget_during_compilation_is_not_published() {
1971        use std::os::unix::fs::symlink;
1972        let directory = tempfile::tempdir().unwrap();
1973        let root = directory.path();
1974        let source = root.join("lib.rs");
1975        let native = root.join("native");
1976        std::fs::write(&source, "pub fn value() {}\n").unwrap();
1977        for version in ["first", "second"] {
1978            std::fs::create_dir_all(native.join(version)).unwrap();
1979            std::fs::write(native.join(version).join("libwidget.a"), version).unwrap();
1980        }
1981        for path in [
1982            &source,
1983            &native.join("first/libwidget.a"),
1984            &native.join("second/libwidget.a"),
1985        ] {
1986            std::fs::File::options()
1987                .write(true)
1988                .open(path)
1989                .unwrap()
1990                .set_times(std::fs::FileTimes::new().set_modified(SystemTime::UNIX_EPOCH))
1991                .unwrap();
1992        }
1993        let alias = native.join("current");
1994        symlink("first", &alias).unwrap();
1995        let started_at = std::fs::symlink_metadata(&alias)
1996            .unwrap()
1997            .modified()
1998            .unwrap();
1999        std::fs::remove_file(&alias).unwrap();
2000        symlink("second", &alias).unwrap();
2001        let invocation = library_with_native_search(&source, &native);
2002        let discovered = invocation
2003            .discover_inputs_with_mappings(
2004                &RustcDepInfo {
2005                    files: vec![source],
2006                    environment: BTreeMap::new(),
2007                },
2008                root,
2009                &[PathMapping::new(root, "workspace")],
2010                &mbx_cache_core::NoFileDigestCache,
2011            )
2012            .unwrap();
2013        assert_eq!(
2014            discovered.verify_not_modified_since(started_at),
2015            Err(BypassReason::InputModifiedDuringCompilation(alias))
2016        );
2017        discovered
2018            .verify_not_modified_since(SystemTime::now() + std::time::Duration::from_secs(1))
2019            .unwrap();
2020    }
2021
2022    #[cfg(unix)]
2023    #[test]
2024    fn native_directory_alias_replaced_or_removed_during_compilation_is_not_published() {
2025        use std::os::unix::fs::symlink;
2026        for change in ["replace", "remove"] {
2027            let directory = tempfile::tempdir().unwrap();
2028            let root = directory.path();
2029            let source = root.join("lib.rs");
2030            let native = root.join("native");
2031            std::fs::write(&source, "pub fn value() {}\n").unwrap();
2032            for version in ["first", "second"] {
2033                std::fs::create_dir_all(native.join(version)).unwrap();
2034                std::fs::write(native.join(version).join("libwidget.a"), version).unwrap();
2035            }
2036            let alias = native.join("current");
2037            symlink("first", &alias).unwrap();
2038            // Made before the compilation starts, so renaming it over the
2039            // alias leaves no timestamp on the link that postdates the start.
2040            let older = root.join("older");
2041            symlink("second", &older).unwrap();
2042            std::thread::sleep(std::time::Duration::from_millis(50));
2043            let started_at = SystemTime::now();
2044            std::thread::sleep(std::time::Duration::from_millis(50));
2045            match change {
2046                "replace" => std::fs::rename(&older, &alias).unwrap(),
2047                _ => std::fs::remove_file(&alias).unwrap(),
2048            }
2049            let discovered = library_with_native_search(&source, &native)
2050                .discover_inputs_with_mappings(
2051                    &RustcDepInfo {
2052                        files: vec![source],
2053                        environment: BTreeMap::new(),
2054                    },
2055                    root,
2056                    &[PathMapping::new(root, "workspace")],
2057                    &mbx_cache_core::NoFileDigestCache,
2058                )
2059                .unwrap();
2060            assert_eq!(
2061                discovered.verify_not_modified_since(started_at),
2062                Err(BypassReason::InputModifiedDuringCompilation(native)),
2063                "{change}"
2064            );
2065        }
2066    }
2067
2068    #[cfg(unix)]
2069    #[test]
2070    fn a_proven_input_change_outranks_a_changed_native_directory() {
2071        let directory = tempfile::tempdir().unwrap();
2072        let root = directory.path();
2073        let source = root.join("lib.rs");
2074        let native = root.join("native");
2075        std::fs::create_dir(&native).unwrap();
2076        std::fs::write(&source, "pub fn value() {}\n").unwrap();
2077        let before = BTreeMap::from([(
2078            source.clone(),
2079            FileSnapshot::capture(&source).unwrap().unwrap(),
2080        )]);
2081        std::thread::sleep(std::time::Duration::from_millis(50));
2082        let started_at = SystemTime::now();
2083        std::thread::sleep(std::time::Duration::from_millis(50));
2084        std::fs::write(&source, "pub fn other() {}\n").unwrap();
2085        std::fs::write(native.join("libwidget.a"), "new").unwrap();
2086        let discovered = library_with_native_search(&source, &native)
2087            .discover_inputs_with_mappings(
2088                &RustcDepInfo {
2089                    files: vec![source.clone()],
2090                    environment: BTreeMap::new(),
2091                },
2092                root,
2093                &[PathMapping::new(root, "workspace")],
2094                &mbx_cache_core::NoFileDigestCache,
2095            )
2096            .unwrap();
2097        // The archive is new, so it only has a timestamp; sorted before it,
2098        // the snapshotted source is the proof that discards the result.
2099        assert_eq!(
2100            discovered.verify_not_modified_since_with_snapshots(started_at, &before),
2101            Err(BypassReason::InputModifiedDuringCompilation(source))
2102        );
2103    }
2104
2105    #[cfg(unix)]
2106    #[test]
2107    fn native_directory_alias_cycles_are_refused() {
2108        use std::os::unix::fs::symlink;
2109        let directory = tempfile::tempdir().unwrap();
2110        let native = directory.path().join("native");
2111        for name in ["first", "second"] {
2112            std::fs::create_dir_all(native.join(name)).unwrap();
2113        }
2114        symlink("../second", native.join("first/next")).unwrap();
2115        symlink("../first", native.join("second/next")).unwrap();
2116        assert_eq!(
2117            collect_native_directory(
2118                &native,
2119                &native_input_roots(directory.path(), &[]),
2120                &mut BTreeSet::new(),
2121                &mut 0,
2122                &mut BTreeSet::new(),
2123            ),
2124            Err(BypassReason::UnsupportedSearchPath("native".into())),
2125        );
2126    }
2127
2128    #[cfg(unix)]
2129    #[test]
2130    fn native_file_symlinks_are_rehashed_on_prediction() {
2131        use std::os::unix::fs::symlink;
2132        let directory = tempfile::tempdir().unwrap();
2133        let workspace = directory.path().join("workspace");
2134        let native = directory.path().join("cellar/lib");
2135        std::fs::create_dir_all(&workspace).unwrap();
2136        std::fs::create_dir_all(&native).unwrap();
2137        let source = workspace.join("lib.rs");
2138        std::fs::write(&source, "pub fn value() {}\n").unwrap();
2139        std::fs::write(native.join("libssl.3.dylib"), "first").unwrap();
2140        symlink("libssl.3.dylib", native.join("libssl.dylib")).unwrap();
2141        let opt = directory.path().join("opt");
2142        symlink(&native, &opt).unwrap();
2143        let invocation = library_with_native_search(&source, &opt);
2144        let mappings = vec![
2145            PathMapping::new(&workspace, "workspace"),
2146            PathMapping::new(&opt, "native"),
2147        ];
2148        let dep_info = RustcDepInfo {
2149            files: vec![source],
2150            environment: BTreeMap::new(),
2151        };
2152        let discover = || {
2153            invocation
2154                .discover_inputs_with_mappings(
2155                    &dep_info,
2156                    &workspace,
2157                    &mappings,
2158                    &mbx_cache_core::NoFileDigestCache,
2159                )
2160                .unwrap()
2161        };
2162        let original = discover();
2163        let mut context = library_context(&workspace, mappings.clone());
2164        original.clone().apply_to(&mut context).unwrap();
2165        let initial = invocation.action(context.clone()).unwrap();
2166        let prediction = invocation.prediction(&context, &original).unwrap();
2167        context.inputs.clear();
2168        let mut previous = initial.digest;
2169        for change in ["contents", "add", "retarget", "remove"] {
2170            match change {
2171                "contents" => std::fs::write(native.join("libssl.3.dylib"), "updated").unwrap(),
2172                "add" => std::fs::write(native.join("libssl.4.dylib"), "replacement").unwrap(),
2173                "retarget" => {
2174                    std::fs::remove_file(native.join("libssl.dylib")).unwrap();
2175                    symlink("libssl.4.dylib", native.join("libssl.dylib")).unwrap();
2176                }
2177                _ => std::fs::remove_file(native.join("libssl.3.dylib")).unwrap(),
2178            }
2179            let predicted = prediction
2180                .discover(&workspace, &mappings, &mbx_cache_core::NoFileDigestCache)
2181                .unwrap();
2182            let mut predicted_context = context.clone();
2183            predicted.apply_to(&mut predicted_context).unwrap();
2184            let predicted_action = invocation.action(predicted_context).unwrap();
2185            let mut discovered_context = context.clone();
2186            discover().apply_to(&mut discovered_context).unwrap();
2187            assert_eq!(
2188                predicted_action,
2189                invocation.action(discovered_context).unwrap()
2190            );
2191            assert_ne!(predicted_action.digest, previous, "{change}");
2192            previous = predicted_action.digest;
2193        }
2194        std::fs::remove_file(native.join("libssl.dylib")).unwrap();
2195        let outside = directory.path().join("outside");
2196        std::fs::write(&outside, "untracked").unwrap();
2197        symlink(&outside, native.join("libssl.dylib")).unwrap();
2198        assert!(
2199            prediction
2200                .discover(&workspace, &mappings, &mbx_cache_core::NoFileDigestCache)
2201                .is_err()
2202        );
2203        std::fs::remove_file(native.join("libssl.dylib")).unwrap();
2204        symlink(".", native.join("loop")).unwrap();
2205        assert!(
2206            prediction
2207                .discover(&workspace, &mappings, &mbx_cache_core::NoFileDigestCache)
2208                .is_err()
2209        );
2210    }
2211}