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};
5use mbx_cache_core::{
6    CacheDigest, FileDigestCache, FileDigestScope, FileIdentity, RecordedFileDigest,
7};
8use std::collections::{BTreeMap, BTreeSet};
9use std::ffi::OsString;
10use std::path::{Path, PathBuf};
11use std::time::SystemTime;
12
13/// A side-effect-minimized rustc invocation that emits only dependency data.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct DepInfoCommand {
16    arguments: Vec<OsString>,
17    output: PathBuf,
18}
19
20impl DepInfoCommand {
21    /// Arguments for the real compiler, excluding the compiler executable.
22    pub fn arguments(&self) -> &[OsString] {
23        &self.arguments
24    }
25
26    /// Exact file the compiler must populate with dep-info.
27    pub fn output(&self) -> &Path {
28        &self.output
29    }
30}
31
32/// The source and environment inputs reported by rustc's dep-info output.
33#[derive(Debug, Clone, Default, PartialEq, Eq)]
34pub struct RustcDepInfo {
35    /// Source paths listed in the first dep-info dependency rule.
36    pub files: Vec<PathBuf>,
37    /// Environment inputs recorded by rustc `# env-dep:` lines.
38    pub environment: BTreeMap<String, Option<String>>,
39}
40
41impl RustcDepInfo {
42    /// Read and parse a dep-info file, treating missing or non-UTF-8 output as
43    /// an explicit cache bypass.
44    pub fn read(path: &Path) -> Result<Self, BypassReason> {
45        let contents =
46            std::fs::read_to_string(path).map_err(|error| BypassReason::DepInfoRead {
47                path: path.to_path_buf(),
48                message: error.to_string(),
49            })?;
50        Self::parse(&contents)
51    }
52
53    /// Parse rustc's Makefile-style dep-info format.
54    ///
55    /// This intentionally follows Cargo's parser contract: the first target
56    /// rule contains all source dependencies, spaces are escaped with a
57    /// trailing backslash on each token fragment, and `# env-dep:` records
58    /// contain the environment observed by `env!` and `option_env!`.
59    pub fn parse(contents: &str) -> Result<Self, BypassReason> {
60        let mut files = BTreeSet::new();
61        let mut environment = BTreeMap::new();
62        let mut found_dependencies = false;
63
64        for line in contents.lines() {
65            if let Some(record) = line.strip_prefix("# env-dep:") {
66                let (name, value) = record
67                    .split_once('=')
68                    .map_or((record, None), |(name, value)| (name, Some(value)));
69                let name = unescape_environment(name)?;
70                if name.is_empty() {
71                    return Err(BypassReason::MalformedDepInfo(
72                        "environment input has an empty name".into(),
73                    ));
74                }
75                let value = value.map(unescape_environment).transpose()?;
76                if environment
77                    .insert(name.clone(), value.clone())
78                    .is_some_and(|previous| previous != value)
79                {
80                    return Err(BypassReason::ConflictingEnvironment(name));
81                }
82                continue;
83            }
84
85            let Some(separator) = line.find(": ") else {
86                continue;
87            };
88            if found_dependencies {
89                continue;
90            }
91            found_dependencies = true;
92            let mut fragments = line[separator + 2..].split_whitespace();
93            while let Some(fragment) = fragments.next() {
94                let mut file = fragment.to_string();
95                while file.ends_with('\\') {
96                    file.pop();
97                    let continuation = fragments.next().ok_or_else(|| {
98                        BypassReason::MalformedDepInfo(
99                            "dependency path ends with an unterminated escape".into(),
100                        )
101                    })?;
102                    file.push(' ');
103                    file.push_str(continuation);
104                }
105                if file.is_empty() {
106                    return Err(BypassReason::MalformedDepInfo(
107                        "dependency path is empty".into(),
108                    ));
109                }
110                files.insert(PathBuf::from(file));
111            }
112        }
113
114        if !found_dependencies {
115            return Err(BypassReason::MalformedDepInfo(
116                "dependency rule is missing".into(),
117            ));
118        }
119        if files.is_empty() {
120            return Err(BypassReason::MalformedDepInfo(
121                "dependency rule contains no inputs".into(),
122            ));
123        }
124        Ok(Self {
125            files: files.into_iter().collect(),
126            environment,
127        })
128    }
129}
130
131/// A complete, content-addressed compiler input manifest.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct DiscoveredInputs {
134    working_dir: PathBuf,
135    /// Content-addressed compiler input files.
136    pub inputs: Vec<ActionInput>,
137    /// Environment inputs captured from dep-info.
138    pub environment: BTreeMap<String, Option<String>>,
139}
140
141impl DiscoveredInputs {
142    pub(crate) fn from_paths(
143        working_dir: &Path,
144        paths: BTreeSet<PathBuf>,
145        environment: BTreeMap<String, Option<String>>,
146        digests: &dyn FileDigestCache,
147    ) -> Result<Self, BypassReason> {
148        if !working_dir.is_absolute() {
149            return Err(BypassReason::RelativeWorkingDirectory(
150                working_dir.to_path_buf(),
151            ));
152        }
153        let working_dir = normalize_components(working_dir);
154        // Stat everything first: the identities drive one batched ledger
155        // lookup, so an upstream rlib the session already hashed -- once, when
156        // it was materialized or published -- is not read again by every crate
157        // that links it. A file the filesystem reports no modification time
158        // for gets no identity and is simply hashed.
159        let mut identified = Vec::with_capacity(paths.len());
160        for path in paths {
161            let metadata = std::fs::metadata(&path).map_err(|error| BypassReason::InputRead {
162                path: path.clone(),
163                message: error.to_string(),
164            })?;
165            if !metadata.is_file() {
166                return Err(BypassReason::InputRead {
167                    path,
168                    message: "input is not a regular file".into(),
169                });
170            }
171            let identity = FileIdentity::describe(&path, &metadata);
172            identified.push((path, identity));
173        }
174        let queries = identified
175            .iter()
176            .filter_map(|(_, identity)| identity.clone())
177            .collect::<Vec<_>>();
178        let mut recorded = digests.find(FileDigestScope::Content, &queries).into_iter();
179        let mut inputs = Vec::with_capacity(identified.len());
180        let mut fresh = Vec::new();
181        for (path, identity) in identified {
182            let remembered = identity
183                .as_ref()
184                .and_then(|_| recorded.next().flatten())
185                .filter(|digest| {
186                    identity
187                        .as_ref()
188                        .is_some_and(|identity| identity.len == digest.size)
189                });
190            let digest = match remembered {
191                Some(digest) => digest,
192                None => {
193                    let digest = CacheDigest::blake3_file(&path).map_err(|error| {
194                        BypassReason::InputRead {
195                            path: path.clone(),
196                            message: error.to_string(),
197                        }
198                    })?;
199                    if let Some(identity) = identity
200                        && identity.len == digest.size
201                    {
202                        fresh.push(RecordedFileDigest {
203                            file: identity,
204                            digest: digest.clone(),
205                        });
206                    }
207                    digest
208                }
209            };
210            inputs.push(ActionInput { path, digest });
211        }
212        if !fresh.is_empty() {
213            digests.record(FileDigestScope::Content, fresh);
214        }
215        Ok(Self {
216            working_dir,
217            inputs,
218            environment,
219        })
220    }
221
222    /// Reject inputs whose modification time overlaps the compiler invocation.
223    ///
224    /// Input contents are first hashed after rustc reports their paths. This
225    /// timestamp barrier prevents a post-compile write from being mistaken for
226    /// the contents that produced the artifact. `verify` closes the remaining
227    /// race after hashing.
228    pub fn verify_not_modified_since(&self, started_at: SystemTime) -> Result<(), BypassReason> {
229        for input in &self.inputs {
230            let modified = std::fs::metadata(&input.path)
231                .and_then(|metadata| metadata.modified())
232                .map_err(|error| BypassReason::InputRead {
233                    path: input.path.clone(),
234                    message: error.to_string(),
235                })?;
236            if modified >= started_at {
237                return Err(BypassReason::InputModifiedDuringCompilation(
238                    input.path.clone(),
239                ));
240            }
241        }
242        Ok(())
243    }
244
245    /// Rehash every discovered file after compilation and before publication.
246    /// This closes the discovery/compile race by degrading changed inputs to a
247    /// cache miss rather than storing outputs beneath a stale action key.
248    pub fn verify(&self) -> Result<(), BypassReason> {
249        for input in &self.inputs {
250            let matches = input.digest.matches_file(&input.path).map_err(|error| {
251                BypassReason::InputRead {
252                    path: input.path.clone(),
253                    message: error.to_string(),
254                }
255            })?;
256            if !matches {
257                return Err(BypassReason::InputChanged(input.path.clone()));
258            }
259        }
260        Ok(())
261    }
262
263    /// Merge the manifest into an action context after verifying that both use
264    /// the same compiler working directory.
265    pub fn apply_to(self, context: &mut ActionContext) -> Result<(), BypassReason> {
266        if normalize_components(&context.working_dir) != self.working_dir {
267            return Err(BypassReason::DiscoveryWorkingDirectory);
268        }
269        for (name, value) in &self.environment {
270            if context
271                .environment
272                .get(name)
273                .is_some_and(|previous| previous != value)
274            {
275                return Err(BypassReason::ConflictingEnvironment(name.clone()));
276            }
277        }
278        context.environment.extend(self.environment);
279        context.inputs.extend(self.inputs);
280        Ok(())
281    }
282}
283
284impl RustcInvocation {
285    /// Replace the original output flags with a single explicit dep-info file.
286    pub fn dep_info_command(&self, output: &Path) -> Result<DepInfoCommand, BypassReason> {
287        if !output.is_absolute() {
288            return Err(BypassReason::RelativeDepInfoPath(output.to_path_buf()));
289        }
290        let output_text = output
291            .to_str()
292            .ok_or_else(|| BypassReason::NonUtf8Path(output.to_path_buf()))?;
293        if output_text.contains(',') {
294            return Err(BypassReason::UnsafeDepInfoPath(output.to_path_buf()));
295        }
296
297        let mut arguments = Vec::new();
298        for argument in &self.arguments {
299            match argument {
300                Argument::Emit(_) => {}
301                Argument::Path { flag, .. } if flag == "--out-dir" || flag == "-o" => {}
302                argument => arguments.push(render_argument(argument)?),
303            }
304        }
305        arguments.push(format!("--emit=dep-info={output_text}").into());
306        arguments.push(self.source.clone().into_os_string());
307        Ok(DepInfoCommand {
308            arguments,
309            output: output.to_path_buf(),
310        })
311    }
312
313    /// Hash dep-info sources plus every direct compiler input already modeled
314    /// by the invocation (`--extern` artifacts and custom target specs).
315    pub fn discover_inputs(
316        &self,
317        dep_info: &RustcDepInfo,
318        working_dir: &Path,
319    ) -> Result<DiscoveredInputs, BypassReason> {
320        self.discover_inputs_with_mappings(
321            dep_info,
322            working_dir,
323            &[],
324            &mbx_cache_core::NoFileDigestCache,
325        )
326    }
327
328    /// Hash dep-info sources plus modeled compiler inputs, allowing native
329    /// search directories beneath the working directory or a mapped root.
330    ///
331    /// `digests` may answer for files the session already read in full;
332    /// pass [`mbx_cache_core::NoFileDigestCache`] to hash everything.
333    pub fn discover_inputs_with_mappings(
334        &self,
335        dep_info: &RustcDepInfo,
336        working_dir: &Path,
337        path_mappings: &[PathMapping],
338        digests: &dyn FileDigestCache,
339    ) -> Result<DiscoveredInputs, BypassReason> {
340        if !working_dir.is_absolute() {
341            return Err(BypassReason::RelativeWorkingDirectory(
342                working_dir.to_path_buf(),
343            ));
344        }
345        let working_dir = normalize_components(working_dir);
346        let mut paths = dep_info
347            .files
348            .iter()
349            .chain(&self.required_inputs)
350            .map(|path| {
351                let absolute = if path.is_absolute() {
352                    path.to_path_buf()
353                } else {
354                    working_dir.join(path)
355                };
356                normalize_components(&absolute)
357            })
358            .collect::<BTreeSet<_>>();
359        let admitted_roots = native_input_roots(&working_dir, path_mappings);
360        let mut native_bytes = 0_u64;
361        for argument in &self.arguments {
362            if let Argument::SearchPath { kind, path } = argument
363                && kind == "native"
364            {
365                let directory = if path.is_absolute() {
366                    path.clone()
367                } else {
368                    working_dir.join(path)
369                };
370                // An inert directory outside every mapped root enters the key
371                // by its literal path in the arguments, not by its contents --
372                // predictions skip it under the same rule, so both discovery
373                // paths agree on the action key.
374                if self.native_search_is_inert()
375                    && matches!(
376                        super::normalize_mapped_path(&directory, &working_dir, path_mappings),
377                        Err(BypassReason::UnmappedAbsolutePath(_))
378                    )
379                {
380                    continue;
381                }
382                collect_native_directory(
383                    &directory,
384                    &admitted_roots,
385                    &mut paths,
386                    &mut native_bytes,
387                )?;
388            }
389        }
390        DiscoveredInputs::from_paths(&working_dir, paths, dep_info.environment.clone(), digests)
391    }
392}
393
394/// Return normalized roots whose native search directories can be tracked.
395pub(super) fn native_input_roots(
396    working_dir: &Path,
397    path_mappings: &[PathMapping],
398) -> Vec<PathBuf> {
399    std::iter::once(working_dir)
400        .chain(path_mappings.iter().map(|mapping| mapping.root.as_path()))
401        .map(normalize_components)
402        .collect()
403}
404
405/// Add regular files beneath an admitted native search directory, enforcing
406/// the prediction input count and the caller's cumulative native byte budget.
407pub(super) fn collect_native_directory(
408    directory: &Path,
409    admitted_roots: &[PathBuf],
410    paths: &mut BTreeSet<PathBuf>,
411    native_bytes: &mut u64,
412) -> Result<(), BypassReason> {
413    let directory = normalize_components(directory);
414    if !admitted_roots
415        .iter()
416        .any(|root| directory.starts_with(root))
417    {
418        return Err(BypassReason::UnsupportedSearchPath("native".into()));
419    }
420
421    let mut pending = vec![directory];
422    while let Some(directory) = pending.pop() {
423        let entries = match std::fs::read_dir(&directory) {
424            Ok(entries) => entries,
425            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
426            Err(error) => {
427                return Err(BypassReason::InputRead {
428                    path: directory,
429                    message: error.to_string(),
430                });
431            }
432        };
433        for entry in entries {
434            let entry = entry.map_err(|error| BypassReason::InputRead {
435                path: directory.clone(),
436                message: error.to_string(),
437            })?;
438            let path = entry.path();
439            let file_type = entry.file_type().map_err(|error| BypassReason::InputRead {
440                path: path.clone(),
441                message: error.to_string(),
442            })?;
443            if file_type.is_dir() {
444                pending.push(path);
445            } else if file_type.is_file() {
446                *native_bytes = native_bytes
447                    .checked_add(
448                        entry
449                            .metadata()
450                            .map_err(|error| BypassReason::InputRead {
451                                path: path.clone(),
452                                message: error.to_string(),
453                            })?
454                            .len(),
455                    )
456                    .ok_or_else(|| BypassReason::UnsupportedSearchPath("native".into()))?;
457                paths.insert(path);
458            } else {
459                return Err(BypassReason::UnsupportedSearchPath("native".into()));
460            }
461            if paths.len() > MAX_PREDICTED_INPUTS || *native_bytes > MAX_NATIVE_INPUT_BYTES {
462                return Err(BypassReason::UnsupportedSearchPath("native".into()));
463            }
464        }
465    }
466    Ok(())
467}
468
469fn render_argument(argument: &Argument) -> Result<OsString, BypassReason> {
470    let rendered = match argument {
471        Argument::Plain(value) => value.clone(),
472        Argument::Path { flag, path } => format!(
473            "{flag}={}",
474            path.to_str()
475                .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?
476        ),
477        Argument::SearchPath { kind, path } => format!(
478            "-L{kind}={}",
479            path.to_str()
480                .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?
481        ),
482        Argument::Extern { name, path } => match path {
483            Some(path) => format!(
484                "--extern={name}={}",
485                path.to_str()
486                    .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?
487            ),
488            None => format!("--extern={name}"),
489        },
490        Argument::Emit(_) => unreachable!("emit arguments are removed before rendering"),
491        Argument::RemapPath { from, to } => format!(
492            "--remap-path-prefix={}={to}",
493            from.to_str()
494                .ok_or_else(|| BypassReason::NonUtf8Path(from.clone()))?
495        ),
496        // Nothing links while emitting dep-info, so the prefix is inert here;
497        // it is replayed verbatim to keep the command faithful.
498        Argument::OsoPrefix {
499            path,
500            trailing_slash,
501        } => format!(
502            "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
503            path.to_str()
504                .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?,
505            if *trailing_slash { "/" } else { "" }
506        ),
507    };
508    Ok(rendered.into())
509}
510
511fn unescape_environment(value: &str) -> Result<String, BypassReason> {
512    let mut output = String::with_capacity(value.len());
513    let mut characters = value.chars();
514    while let Some(character) = characters.next() {
515        if character != '\\' {
516            output.push(character);
517            continue;
518        }
519        match characters.next() {
520            Some('\\') => output.push('\\'),
521            Some('n') => output.push('\n'),
522            Some('r') => output.push('\r'),
523            Some(character) => {
524                return Err(BypassReason::MalformedDepInfo(format!(
525                    "unknown environment escape \\{character}"
526                )));
527            }
528            None => {
529                return Err(BypassReason::MalformedDepInfo(
530                    "environment input ends with an unterminated escape".into(),
531                ));
532            }
533        }
534    }
535    Ok(output)
536}
537
538#[cfg(test)]
539mod tests {
540    use super::*;
541    use std::process::Command;
542
543    fn args(values: &[&str]) -> Vec<OsString> {
544        values.iter().map(OsString::from).collect()
545    }
546
547    #[test]
548    fn parses_files_spaces_and_environment_records() {
549        let parsed = RustcDepInfo::parse(
550            "target/lib.rlib: src/lib.rs src/a\\ file.rs generated.rs\n\
551             src/lib.rs:\n\
552             # env-dep:SET=value\\nnext\n\
553             # env-dep:UNSET\n\
554             # env-dep:SLASH=a\\\\b\n",
555        )
556        .unwrap();
557        assert_eq!(
558            parsed.files,
559            vec![
560                PathBuf::from("generated.rs"),
561                PathBuf::from("src/a file.rs"),
562                PathBuf::from("src/lib.rs"),
563            ]
564        );
565        assert_eq!(parsed.environment["SET"], Some("value\nnext".into()));
566        assert_eq!(parsed.environment["UNSET"], None);
567        assert_eq!(parsed.environment["SLASH"], Some(r"a\b".into()));
568    }
569
570    #[test]
571    fn malformed_dep_info_bypasses_caching() {
572        for contents in [
573            "",
574            "target: ",
575            "target: src/trailing\\\n",
576            "target: src/lib.rs\n# env-dep:NAME=bad\\q\n",
577        ] {
578            assert!(RustcDepInfo::parse(contents).is_err(), "{contents:?}");
579        }
580    }
581
582    #[test]
583    fn native_directory_byte_limit_is_cumulative() {
584        let directory = tempfile::tempdir().unwrap();
585        let native = directory.path().join("native");
586        std::fs::create_dir_all(&native).unwrap();
587        std::fs::write(native.join("input.lib"), b"xx").unwrap();
588        let roots = native_input_roots(directory.path(), &[]);
589        let mut paths = BTreeSet::new();
590        let mut native_bytes = MAX_NATIVE_INPUT_BYTES - 1;
591
592        assert_eq!(
593            collect_native_directory(&native, &roots, &mut paths, &mut native_bytes),
594            Err(BypassReason::UnsupportedSearchPath("native".into()))
595        );
596    }
597
598    #[test]
599    fn discovery_command_removes_real_outputs() {
600        let invocation = RustcInvocation::parse(&args(&[
601            "--crate-name=widget",
602            "--crate-type=lib",
603            "--emit=dep-info,metadata,link",
604            "--out-dir=target/debug/deps",
605            "-o",
606            "target/debug/libwidget.rlib",
607            "src/lib.rs",
608        ]))
609        .unwrap();
610        let output = if cfg!(windows) {
611            PathBuf::from(r"C:\tmp\mbx cache\inputs.d")
612        } else {
613            PathBuf::from("/tmp/mbx cache/inputs.d")
614        };
615        let command = invocation.dep_info_command(&output).unwrap();
616        let arguments = command
617            .arguments()
618            .iter()
619            .map(|value| value.to_string_lossy())
620            .collect::<Vec<_>>();
621        assert_eq!(
622            arguments,
623            vec![
624                "--crate-name=widget",
625                "--crate-type=lib",
626                &format!("--emit=dep-info={}", output.display()),
627                "src/lib.rs",
628            ]
629        );
630    }
631
632    #[test]
633    fn discovery_hashes_externs_and_custom_targets() {
634        let directory = tempfile::tempdir().unwrap();
635        let root = directory.path();
636        let source = root.join("src/lib.rs");
637        let external = root.join("target/libdependency.rlib");
638        let target = root.join("targets/custom.json");
639        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
640        std::fs::create_dir_all(external.parent().unwrap()).unwrap();
641        std::fs::create_dir_all(target.parent().unwrap()).unwrap();
642        std::fs::write(&source, "pub fn library() {}\n").unwrap();
643        std::fs::write(&external, "dependency artifact\n").unwrap();
644        std::fs::write(&target, "{}\n").unwrap();
645
646        let invocation = RustcInvocation::parse(&[
647            "--crate-name=widget".into(),
648            "--crate-type=lib".into(),
649            "--emit=metadata".into(),
650            format!("--extern=dependency={}", external.display()).into(),
651            format!("--target={}", target.display()).into(),
652            source.clone().into_os_string(),
653        ])
654        .unwrap();
655        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
656        let discovered = invocation.discover_inputs(&dep_info, root).unwrap();
657        assert_eq!(discovered.inputs.len(), 3);
658
659        std::fs::remove_file(&external).unwrap();
660        assert!(matches!(
661            invocation.discover_inputs(&dep_info, root),
662            Err(BypassReason::InputRead { path, .. }) if path == external
663        ));
664    }
665
666    #[test]
667    fn discovery_rejects_inputs_modified_during_compilation() {
668        let directory = tempfile::tempdir().unwrap();
669        let source = directory.path().join("lib.rs");
670        std::fs::write(&source, "pub fn library() {}\n").unwrap();
671        let invocation = RustcInvocation::parse(&[
672            "--crate-name=widget".into(),
673            "--crate-type=lib".into(),
674            "--emit=dep-info,metadata".into(),
675            source.clone().into_os_string(),
676        ])
677        .unwrap();
678        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
679        let discovered = invocation
680            .discover_inputs(&dep_info, directory.path())
681            .unwrap();
682        let modified = std::fs::metadata(&source).unwrap().modified().unwrap();
683
684        assert_eq!(
685            discovered.verify_not_modified_since(modified),
686            Err(BypassReason::InputModifiedDuringCompilation(source))
687        );
688    }
689
690    /// The MSVC toolset directories `cc`-built dependencies hand to every
691    /// downstream compile on Windows: absolute, version-stamped, and outside
692    /// every mapped root.
693    fn toolchain_native_directory(version: &str) -> PathBuf {
694        if cfg!(windows) {
695            PathBuf::from(format!(r"C:\Program Files\MSVC\{version}\lib\x64"))
696        } else {
697            PathBuf::from(format!("/opt/msvc/{version}/lib/x64"))
698        }
699    }
700
701    fn library_with_native_search(source: &Path, directory: &Path) -> RustcInvocation {
702        RustcInvocation::parse(&[
703            "--crate-name=widget".into(),
704            "--crate-type=lib".into(),
705            "--emit=metadata,link".into(),
706            format!("-Lnative={}", directory.display()).into(),
707            source.to_path_buf().into_os_string(),
708        ])
709        .unwrap()
710    }
711
712    fn library_context(root: &Path, mappings: Vec<PathMapping>) -> ActionContext {
713        ActionContext {
714            compiler: crate::CompilerIdentity {
715                toolchain: "core:rust@test".into(),
716                rustc_version: "test".into(),
717                host: std::env::consts::ARCH.into(),
718            },
719            working_dir: root.to_path_buf(),
720            path_mappings: mappings,
721            environment: BTreeMap::new(),
722            portable_environment: BTreeSet::new(),
723            inputs: Vec::new(),
724        }
725    }
726
727    #[test]
728    fn unmapped_native_directory_is_keyed_by_path_for_library_emits() {
729        let directory = tempfile::tempdir().unwrap();
730        let root = directory.path();
731        let source = root.join("lib.rs");
732        std::fs::write(&source, "pub fn library() {}\n").unwrap();
733        let toolchain = toolchain_native_directory("14.51.36231");
734        let invocation = library_with_native_search(&source, &toolchain);
735        let mappings = vec![PathMapping::new(root, "workspace")];
736        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
737
738        // The directory does not even exist: its contents are not inputs.
739        let discovered = invocation
740            .discover_inputs_with_mappings(
741                &dep_info,
742                root,
743                &mappings,
744                &mbx_cache_core::NoFileDigestCache,
745            )
746            .unwrap();
747        assert_eq!(discovered.inputs.len(), 1);
748        assert_eq!(discovered.inputs[0].path, source);
749
750        // The literal path is key material, so a toolset update misses.
751        let context = library_context(root, mappings.clone());
752        let digest = invocation.invocation_digest(&context).unwrap();
753        let updated = library_with_native_search(&source, &toolchain_native_directory("14.52.0"));
754        assert_ne!(digest, updated.invocation_digest(&context).unwrap());
755
756        // The prediction skips the directory the same way discovery does, so a
757        // build that replays it derives the action key dep-info would have.
758        let mut recorded = context.clone();
759        discovered.clone().apply_to(&mut recorded).unwrap();
760        let action = invocation.action(recorded).unwrap();
761        let prediction = invocation.prediction(&context, &discovered).unwrap();
762        let replayed = prediction
763            .discover(
764                root,
765                &context.path_mappings,
766                &mbx_cache_core::NoFileDigestCache,
767            )
768            .unwrap();
769        let mut replay_context = context.clone();
770        replayed.apply_to(&mut replay_context).unwrap();
771        assert_eq!(
772            invocation.action(replay_context).unwrap().digest,
773            action.digest
774        );
775    }
776
777    #[test]
778    fn unmapped_native_directory_still_refuses_a_native_link() {
779        let directory = tempfile::tempdir().unwrap();
780        let root = directory.path();
781        let source = root.join("main.rs");
782        std::fs::write(&source, "fn main() {}\n").unwrap();
783        let toolchain = toolchain_native_directory("14.51.36231");
784        let invocation = RustcInvocation::parse_with(
785            &[
786                "--crate-name=app".into(),
787                "--crate-type=bin".into(),
788                "--emit=link".into(),
789                format!("-Lnative={}", toolchain.display()).into(),
790                source.clone().into_os_string(),
791            ],
792            crate::ParseOptions::caching_native_links(true),
793        )
794        .unwrap();
795        let mappings = vec![PathMapping::new(root, "workspace")];
796
797        // A linker reads those directories, so their contents stay inputs the
798        // key must account for, and an unmapped one stays a bypass.
799        let context = library_context(root, mappings.clone());
800        assert!(matches!(
801            invocation.invocation_digest(&context),
802            Err(BypassReason::UnmappedAbsolutePath(_))
803        ));
804        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
805        assert_eq!(
806            invocation.discover_inputs_with_mappings(
807                &dep_info,
808                root,
809                &mappings,
810                &mbx_cache_core::NoFileDigestCache
811            ),
812            Err(BypassReason::UnsupportedSearchPath("native".into()))
813        );
814    }
815
816    #[test]
817    fn discovery_resolves_parent_components_against_the_working_directory() {
818        let directory = tempfile::tempdir().unwrap();
819        let root = directory.path().join("project");
820        let shared = directory.path().join("shared.rs");
821        std::fs::create_dir(&root).unwrap();
822        std::fs::write(&shared, "pub fn shared() {}\n").unwrap();
823
824        let invocation = RustcInvocation::parse(&args(&[
825            "--crate-name=widget",
826            "--crate-type=lib",
827            "--emit=metadata",
828            "../shared.rs",
829        ]))
830        .unwrap();
831        let dep_info = RustcDepInfo::parse("output: ../shared.rs\n").unwrap();
832        let discovered = invocation.discover_inputs(&dep_info, &root).unwrap();
833
834        assert_eq!(discovered.inputs.len(), 1);
835        assert_eq!(discovered.inputs[0].path, shared);
836    }
837
838    #[test]
839    fn rustc_dep_info_round_trip_discovers_real_inputs() {
840        let directory = tempfile::tempdir().unwrap();
841        let root = directory.path();
842        std::fs::write(
843            root.join("lib.rs"),
844            "mod child; const _: &str = include_str!(\"data file.txt\"); \
845             const _: &str = env!(\"MBX_DISCOVERY_TEST\"); \
846             const _: Option<&str> = option_env!(\"MBX_DISCOVERY_UNSET\");",
847        )
848        .unwrap();
849        std::fs::write(root.join("child.rs"), "pub fn child() {}\n").unwrap();
850        std::fs::write(root.join("data file.txt"), "included\n").unwrap();
851
852        let invocation = RustcInvocation::parse(&args(&[
853            "--crate-name=mbx_cache_discovery_test",
854            "--crate-type=lib",
855            "--emit=metadata,link",
856            "lib.rs",
857        ]))
858        .unwrap();
859        let dep_info_path = root.join("discovery inputs.d");
860        let discovery_command = invocation.dep_info_command(&dep_info_path).unwrap();
861        let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
862        let output = match Command::new(rustc)
863            .args(discovery_command.arguments())
864            .current_dir(root)
865            .env("MBX_DISCOVERY_TEST", "observed")
866            .env_remove("MBX_DISCOVERY_UNSET")
867            .output()
868        {
869            Ok(output) => output,
870            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
871            Err(error) => panic!("failed to execute rustc: {error}"),
872        };
873        assert!(
874            output.status.success(),
875            "{}",
876            String::from_utf8_lossy(&output.stderr)
877        );
878        let parsed = RustcDepInfo::read(&dep_info_path).unwrap();
879        let discovered = invocation.discover_inputs(&parsed, root).unwrap();
880        assert_eq!(
881            discovered.environment["MBX_DISCOVERY_TEST"],
882            Some("observed".into())
883        );
884        assert_eq!(discovered.environment["MBX_DISCOVERY_UNSET"], None);
885        assert_eq!(discovered.inputs.len(), 3);
886        assert!(
887            discovered
888                .inputs
889                .iter()
890                .all(|input| input.digest.algorithm == "blake3")
891        );
892        let mut context = ActionContext {
893            compiler: crate::CompilerIdentity {
894                toolchain: "core:rust@test".into(),
895                rustc_version: "test".into(),
896                host: std::env::consts::ARCH.into(),
897            },
898            working_dir: root.to_path_buf(),
899            path_mappings: vec![crate::PathMapping::new(root, "workspace")],
900            environment: BTreeMap::new(),
901            portable_environment: BTreeSet::new(),
902            inputs: Vec::new(),
903        };
904        discovered.clone().apply_to(&mut context).unwrap();
905        let action = invocation.action(context).unwrap();
906        assert!(
907            String::from_utf8(action.bytes)
908                .unwrap()
909                .contains(r#""MBX_DISCOVERY_TEST":"observed""#)
910        );
911        discovered.verify().unwrap();
912        std::fs::write(root.join("child.rs"), "pub fn changed() {}\n").unwrap();
913        assert_eq!(
914            discovered.verify(),
915            Err(BypassReason::InputChanged(root.join("child.rs")))
916        );
917    }
918
919    /// A ledger that answers with a sentinel and remembers what was recorded.
920    struct SentinelLedger {
921        known: FileIdentity,
922        digest: CacheDigest,
923        recorded: std::sync::Mutex<Vec<RecordedFileDigest>>,
924    }
925
926    impl FileDigestCache for SentinelLedger {
927        fn find(&self, scope: FileDigestScope, files: &[FileIdentity]) -> Vec<Option<CacheDigest>> {
928            assert_eq!(scope, FileDigestScope::Content);
929            files
930                .iter()
931                .map(|file| (*file == self.known).then(|| self.digest.clone()))
932                .collect()
933        }
934
935        fn record(&self, scope: FileDigestScope, entries: Vec<RecordedFileDigest>) {
936            assert_eq!(scope, FileDigestScope::Content);
937            self.recorded.lock().unwrap().extend(entries);
938        }
939    }
940
941    #[test]
942    fn discovery_reuses_recorded_digests_and_records_fresh_ones() {
943        let directory = tempfile::tempdir().unwrap();
944        let root = directory.path();
945        let known_path = root.join("libdep.rlib");
946        let fresh_path = root.join("lib.rs");
947        std::fs::write(&known_path, b"rlib bytes").unwrap();
948        std::fs::write(&fresh_path, b"fn lib() {}").unwrap();
949        let metadata = std::fs::metadata(&known_path).unwrap();
950        // A sentinel digest that hashing could never produce proves the read
951        // was skipped: the discovered input carries it verbatim.
952        let sentinel = CacheDigest {
953            algorithm: "blake3".into(),
954            hash: "c".repeat(64),
955            size: metadata.len(),
956        };
957        let ledger = SentinelLedger {
958            known: FileIdentity::describe(&known_path, &metadata).unwrap(),
959            digest: sentinel.clone(),
960            recorded: std::sync::Mutex::new(Vec::new()),
961        };
962
963        let discovered = DiscoveredInputs::from_paths(
964            root,
965            BTreeSet::from([known_path.clone(), fresh_path.clone()]),
966            BTreeMap::new(),
967            &ledger,
968        )
969        .unwrap();
970
971        let by_path = |path: &Path| {
972            discovered
973                .inputs
974                .iter()
975                .find(|input| input.path == path)
976                .unwrap()
977                .digest
978                .clone()
979        };
980        assert_eq!(
981            by_path(&known_path),
982            sentinel,
983            "the recorded digest answers"
984        );
985        assert_eq!(
986            by_path(&fresh_path),
987            CacheDigest::blake3_file(&fresh_path).unwrap(),
988            "an unrecorded file is hashed"
989        );
990        let recorded = ledger.recorded.lock().unwrap();
991        assert_eq!(recorded.len(), 1, "only the fresh hash is recorded");
992        assert_eq!(recorded[0].file.path, fresh_path);
993        assert_eq!(recorded[0].digest, by_path(&fresh_path));
994    }
995
996    /// A rewrite that restores length and modification time must still be
997    /// hashed: the platform change token moves with every write, so the
998    /// identity the ledger recorded no longer describes the file.
999    #[cfg(unix)]
1000    #[test]
1001    fn a_disguised_rewrite_is_not_answered_from_the_ledger() {
1002        let directory = tempfile::tempdir().unwrap();
1003        let root = directory.path();
1004        let path = root.join("lib.rs");
1005        std::fs::write(&path, b"fn lib() -> u8 { 1 }").unwrap();
1006        let before = std::fs::metadata(&path).unwrap();
1007        let identity = FileIdentity::describe(&path, &before).unwrap();
1008
1009        // Same length, modification time put back: only the change token can
1010        // tell this file has new contents.
1011        std::fs::write(&path, b"fn lib() -> u8 { 2 }").unwrap();
1012        let file = std::fs::File::options().write(true).open(&path).unwrap();
1013        file.set_times(std::fs::FileTimes::new().set_modified(before.modified().unwrap()))
1014            .unwrap();
1015        drop(file);
1016        let after = std::fs::metadata(&path).unwrap();
1017        let disguised = FileIdentity::describe(&path, &after).unwrap();
1018        assert_eq!(disguised.len, identity.len);
1019        assert_eq!(disguised.modified, identity.modified);
1020        assert_ne!(
1021            disguised, identity,
1022            "the change token must expose the rewrite"
1023        );
1024
1025        let ledger = SentinelLedger {
1026            known: identity,
1027            digest: CacheDigest {
1028                algorithm: "blake3".into(),
1029                hash: "e".repeat(64),
1030                size: after.len(),
1031            },
1032            recorded: std::sync::Mutex::new(Vec::new()),
1033        };
1034        let discovered = DiscoveredInputs::from_paths(
1035            root,
1036            BTreeSet::from([path.clone()]),
1037            BTreeMap::new(),
1038            &ledger,
1039        )
1040        .unwrap();
1041        assert_eq!(
1042            discovered.inputs[0].digest,
1043            CacheDigest::blake3_file(&path).unwrap(),
1044            "the disguised rewrite is hashed, not answered from the ledger"
1045        );
1046    }
1047}