Skip to main content

proa_cli/rsjs/
cache.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Explicit, coordinate-addressed reuse for descriptor-phase Cargo builds.
5//!
6//! Cargo still owns freshness. This cache never discovers outputs by walking a
7//! target directory: every reuse decision starts from the exact
8//! `compiler-artifact` messages emitted by the current Cargo invocation. Each
9//! cached unit's rustc-observed source/environment inputs and exact
10//! `--extern` bytes are validated before a descriptor object is admitted into
11//! the linked invocation. Package-local files that are not inputs to that unit
12//! remain under Cargo and build-script freshness tracking, so editing docs,
13//! styles, or other unrelated assets does not invalidate the entire descriptor
14//! target. Cached descriptor objects remain in their immutable,
15//! content-addressed cache slots under the retained cache lease instead of
16//! being copied into fresh staging. Cargo's `fresh` bit is authoritative for
17//! other target outputs; the cache deliberately does not reread every emitted
18//! file.
19
20use std::collections::{BTreeMap, BTreeSet};
21use std::ffi::OsStr;
22use std::fmt;
23use std::fs::{self, File, OpenOptions};
24use std::io::{self, Read, Write};
25use std::path::{Path, PathBuf};
26use std::sync::atomic::{AtomicU64, Ordering};
27
28use rayon::prelude::*;
29use serde::{Deserialize, Serialize};
30use serde_json::Value;
31use sha2::{Digest, Sha256};
32use thiserror::Error;
33
34use crate::rsjs::build::wrapper_control_environment;
35use crate::rsjs::build::{
36    acquire_descriptor_target_lease, classify_dependency_artifact, descriptor_input_content_hash,
37    descriptor_package_source_closure_hash, descriptor_staging_marker_is_valid,
38    descriptor_target_dirty_journal_path, descriptor_target_marker_is_valid,
39    join_cargo_enumerated_descriptor_units, join_descriptor_units_to_cargo_artifacts,
40    managed_paths_overlap, normalize_managed_path_identity, prepare_descriptor_target_directory,
41    run_descriptor_cargo_allow_empty, run_descriptor_cargo_allow_empty_resuming,
42    uplifted_root_lib_hashed_rlib, validate_descriptor_managed_paths,
43    validate_descriptor_observed_inputs, CargoCompilerArtifact, DescriptorCargoOutput,
44    DescriptorCargoRequest, DescriptorCargoRun, DescriptorCargoRunError, DescriptorCargoUnitId,
45    DescriptorSidecarError, DescriptorTargetLease, DescriptorUnitSidecar, UnitArtifactJoinError,
46    ValidatedDescriptorUnit, DESCRIPTOR_OBJECT_HASH_DOMAIN,
47};
48#[cfg(test)]
49use crate::rsjs::build::{
50    descriptor_environment_dependency_value_hash, descriptor_object_content_hash,
51    descriptor_out_dir_dependency_content_hash, descriptor_source_dependency_content_hash,
52    DescriptorEnvironmentDependency, DescriptorOutDirDependency, DescriptorSourceDependency,
53};
54
55pub(crate) const DESCRIPTOR_CACHE_SCHEMA_VERSION: u16 = 5;
56const ARTIFACT_COORDINATE_DOMAIN: &[u8] = b"proa.rsjs.descriptor-cache-coordinate.v2";
57const ARTIFACT_SET_COORDINATE_DOMAIN: &[u8] = b"proa.rsjs.descriptor-cache-coordinate-set.v2";
58const CACHED_SIDECAR_HASH_DOMAIN: &[u8] = b"proa.rsjs.descriptor-cache-sidecar.v1";
59static CACHE_WRITE_NONCE: AtomicU64 = AtomicU64::new(0);
60
61/// Run Cargo's descriptor compilation and reuse exact units from an explicit
62/// persistent cache when Cargo reports artifacts as fresh.
63///
64/// `request.staging_directory` remains fresh and invocation-local during
65/// ordinary builds. Crash recovery instead resumes only the exact
66/// marker-owned staging root named by the target journal and gives each retry
67/// a fresh child writer directory. The current Cargo JSON stream authorizes
68/// every cache hit, whose object is then validated in place and retained under
69/// the returned cache lease.
70pub fn run_descriptor_cargo_cached(
71    request: &DescriptorCargoRequest,
72    cache_directory: &Path,
73) -> Result<CachedDescriptorCargoLease, DescriptorCacheError> {
74    run_descriptor_cargo_cached_leased(request, cache_directory)
75}
76
77/// Cache/descriptor-target lease retained by the linked pipeline until every
78/// shared target byte has been consumed into an immutable plan.
79#[must_use = "descriptor cache leases retain filesystem locks until consumed or dropped"]
80pub struct CachedDescriptorCargoLease {
81    output: DescriptorCargoOutput,
82    // Fields drop in declaration order. Release the cache lock before the
83    // outer target lock, reversing acquisition order.
84    _cache_lock: CacheGenerationLock,
85    _target_lock: DescriptorTargetLease,
86}
87
88impl fmt::Debug for CachedDescriptorCargoLease {
89    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
90        formatter
91            .debug_struct("CachedDescriptorCargoLease")
92            .field("artifacts", &self.output.cargo_artifacts.len())
93            .field("units", &self.output.units.len())
94            .finish_non_exhaustive()
95    }
96}
97
98impl crate::rsjs::build::descriptor_run_sealed::Sealed for CachedDescriptorCargoLease {
99    fn output(&self) -> &DescriptorCargoOutput {
100        &self.output
101    }
102
103    fn into_output(self) -> DescriptorCargoOutput {
104        self.output
105    }
106}
107
108impl DescriptorCargoRun for CachedDescriptorCargoLease {}
109
110pub(crate) fn run_descriptor_cargo_cached_leased(
111    request: &DescriptorCargoRequest,
112    cache_directory: &Path,
113) -> Result<CachedDescriptorCargoLease, DescriptorCacheError> {
114    validate_descriptor_managed_paths(request).map_err(DescriptorCacheError::DescriptorCargo)?;
115    let cache_directory = validate_cache_directories(
116        cache_directory,
117        &request.staging_directory,
118        &request.target_directory,
119        &request.source_exclusion_directory,
120        &request.working_directory,
121    )?;
122    let target_lock = acquire_descriptor_target_lease(&request.target_directory)
123        .map_err(DescriptorCacheError::DescriptorCargo)?;
124    ensure_plain_directory(&cache_directory)?;
125    let cache_lock = CacheGenerationLock::acquire_path(&cache_directory.join("generation.lock"))?;
126    create_cache_layout(&cache_directory)?;
127    prepare_descriptor_target_directory(&request.target_directory)
128        .map_err(DescriptorCacheError::DescriptorCargo)?;
129    let interrupted_staging = interrupted_cache_generation_staging(&cache_directory, request)?;
130    let mut active_request = request.clone();
131    if let Some(staging) = &interrupted_staging {
132        active_request.staging_directory = staging.clone();
133        eprintln!(
134            "recovering interrupted RSJS descriptor cache transaction from `{}` while preserving Cargo target `{}`",
135            staging.display(),
136            request.target_directory.display(),
137        );
138    } else {
139        mark_cache_generation_dirty(request)?;
140    }
141
142    let result = match run_descriptor_cargo_cached_once(
143        &active_request,
144        &cache_directory,
145        false,
146        interrupted_staging.is_some(),
147    ) {
148        Ok(output) => Ok(output),
149        Err(error)
150            if recoverable_cache_authority_error(&error)
151                || (interrupted_staging.is_some()
152                    && recoverable_interrupted_generation_error(&error)) =>
153        {
154            eprintln!(
155                "RSJS descriptor cache recovery could not prove exact reuse ({error}); rebuilding its marker-owned Cargo target once"
156            );
157            reset_descriptor_request_owned_state(
158                &active_request,
159                &active_request.staging_directory,
160            )?;
161            mark_cache_generation_dirty(request)?;
162            run_descriptor_cargo_cached_once(request, &cache_directory, true, false)
163        }
164        Err(error) => Err(error),
165    };
166    match result {
167        Ok(output) => {
168            clear_cache_generation_dirty(request)?;
169            Ok(CachedDescriptorCargoLease {
170                output,
171                _cache_lock: cache_lock,
172                _target_lock: target_lock,
173            })
174        }
175        Err(error) => Err(error),
176    }
177}
178
179#[derive(Debug, Serialize, Deserialize)]
180#[serde(deny_unknown_fields)]
181struct DirtyCacheGeneration {
182    schema_version: u16,
183    target_directory: PathBuf,
184    staging_directory: PathBuf,
185}
186
187fn interrupted_cache_generation_staging(
188    cache_directory: &Path,
189    request: &DescriptorCargoRequest,
190) -> Result<Option<PathBuf>, DescriptorCacheError> {
191    let path = descriptor_target_dirty_journal_path(&request.target_directory)
192        .map_err(DescriptorCacheError::DescriptorCargo)?;
193    let metadata = match fs::symlink_metadata(&path) {
194        Ok(metadata) => metadata,
195        Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(None),
196        Err(source) => return Err(DescriptorCacheError::ReadCacheFile { path, source }),
197    };
198    if !metadata.file_type().is_file() {
199        return Err(DescriptorCacheError::InvalidDirtyMarker(path));
200    }
201    let bytes = fs::read(&path).map_err(|source| DescriptorCacheError::ReadCacheFile {
202        path: path.clone(),
203        source,
204    })?;
205    let marker: DirtyCacheGeneration =
206        serde_json::from_slice(&bytes).map_err(|source| DescriptorCacheError::ParseCacheFile {
207            path: path.clone(),
208            source,
209        })?;
210    if marker.schema_version != DESCRIPTOR_CACHE_SCHEMA_VERSION {
211        return Err(DescriptorCacheError::UnsupportedCacheSchema {
212            path,
213            actual: marker.schema_version,
214            expected: DESCRIPTOR_CACHE_SCHEMA_VERSION,
215        });
216    }
217    let expected = normalize_managed_path(&request.target_directory)?;
218    let actual = normalize_managed_path(&marker.target_directory)?;
219    if actual != expected {
220        return Err(DescriptorCacheError::DirtyTargetMismatch { expected, actual });
221    }
222    validate_cache_directories(
223        cache_directory,
224        &marker.staging_directory,
225        &request.target_directory,
226        &request.source_exclusion_directory,
227        &request.working_directory,
228    )?;
229    let normalized_staging = normalize_managed_path(&marker.staging_directory)?;
230    let normalized_exclusion = normalize_managed_path(&request.source_exclusion_directory)?;
231    let relative = normalized_staging
232        .strip_prefix(&normalized_exclusion)
233        .map_err(
234            |_| DescriptorCacheError::GeneratedStateOutsideSourceExclusion {
235                kind: "staging",
236                path: normalized_staging.clone(),
237                exclusion: normalized_exclusion,
238            },
239        )?;
240    let request_spelling = request.source_exclusion_directory.join(relative);
241    let rebound = normalize_managed_path(&request_spelling)?;
242    if rebound != normalized_staging {
243        return Err(DescriptorCacheError::DirtyStagingMismatch {
244            expected: normalized_staging,
245            actual: rebound,
246        });
247    }
248    Ok(Some(request_spelling))
249}
250
251fn mark_cache_generation_dirty(
252    request: &DescriptorCargoRequest,
253) -> Result<(), DescriptorCacheError> {
254    let marker = DirtyCacheGeneration {
255        schema_version: DESCRIPTOR_CACHE_SCHEMA_VERSION,
256        target_directory: normalize_managed_path(&request.target_directory)?,
257        staging_directory: normalize_managed_path(&request.staging_directory)?,
258    };
259    let bytes =
260        serde_json::to_vec_pretty(&marker).map_err(DescriptorCacheError::SerializeCacheRecord)?;
261    let path = descriptor_target_dirty_journal_path(&request.target_directory)
262        .map_err(DescriptorCacheError::DescriptorCargo)?;
263    atomic_write_replaceable(&path, &bytes)
264}
265
266fn clear_cache_generation_dirty(
267    request: &DescriptorCargoRequest,
268) -> Result<(), DescriptorCacheError> {
269    let path = descriptor_target_dirty_journal_path(&request.target_directory)
270        .map_err(DescriptorCacheError::DescriptorCargo)?;
271    fs::remove_file(&path).map_err(|source| DescriptorCacheError::WriteCacheFile {
272        path: path.clone(),
273        source,
274    })?;
275    let parent = path
276        .parent()
277        .expect("descriptor target journals always have a parent");
278    sync_directory(parent).map_err(|source| DescriptorCacheError::WriteCacheFile {
279        path: parent.to_path_buf(),
280        source,
281    })
282}
283
284fn run_descriptor_cargo_cached_once(
285    request: &DescriptorCargoRequest,
286    cache_directory: &Path,
287    require_complete_rebuild: bool,
288    resume_interrupted_staging: bool,
289) -> Result<DescriptorCargoOutput, DescriptorCacheError> {
290    let mut fresh = if resume_interrupted_staging {
291        run_descriptor_cargo_allow_empty_resuming(request)
292    } else {
293        run_descriptor_cargo_allow_empty(request)
294    }
295    .map_err(DescriptorCacheError::DescriptorCargo)?;
296    if require_complete_rebuild && fresh.cargo_artifacts.iter().any(|artifact| artifact.fresh) {
297        return Err(DescriptorCacheError::RecoveryDidNotFullyRebuild);
298    }
299    if resume_interrupted_staging {
300        retain_current_interrupted_units(&mut fresh, request)?;
301    }
302    let evidence = collect_artifact_evidence(&fresh.cargo_artifacts)?;
303    let artifact_set_coordinate = artifact_set_coordinate(&evidence);
304    if fresh.units.is_empty() {
305        reject_rebuilt_artifact_without_wrapper_units(&evidence)?;
306    }
307
308    let fresh_joined = join_cargo_enumerated_descriptor_units(&fresh.units, &fresh.cargo_artifacts)
309        .map_err(DescriptorCacheError::ArtifactJoin)?;
310    let mut fresh_by_artifact = BTreeMap::<String, DescriptorCargoUnitId>::new();
311    for (unit, artifact) in &fresh_joined {
312        let coordinate = coordinate_for_artifact(artifact, &evidence)?;
313        if let Some(previous) = fresh_by_artifact.insert(coordinate.clone(), *unit) {
314            return Err(DescriptorCacheError::MultipleFreshUnitsForArtifact {
315                coordinate,
316                first: previous,
317                second: *unit,
318            });
319        }
320    }
321
322    let fresh_ids = fresh
323        .units
324        .iter()
325        .map(|unit| unit.unit)
326        .collect::<BTreeSet<_>>();
327    let mut cached_generations = BTreeMap::new();
328    let mut expected_artifact_by_cached_unit = BTreeMap::new();
329
330    if fresh.units.is_empty() && !require_complete_rebuild {
331        let snapshot = load_snapshot(cache_directory, &artifact_set_coordinate, &evidence)?;
332        for generation in snapshot.units {
333            insert_cached_generation(&mut cached_generations, generation)?;
334        }
335    } else {
336        for artifact in &evidence {
337            if fresh_by_artifact.contains_key(&artifact.coordinate) {
338                continue;
339            }
340
341            match load_artifact_index(cache_directory, &artifact.coordinate) {
342                Ok(index) => {
343                    if !artifact.artifact.fresh && !index.units.is_empty() {
344                        return Err(DescriptorCacheError::RebuiltArtifactMissingFreshUnit {
345                            coordinate: artifact.coordinate.clone(),
346                        });
347                    }
348                    for generation in index.units {
349                        let unit = generation.unit(Path::new("artifact-index"))?;
350                        if let Some(previous) = expected_artifact_by_cached_unit
351                            .insert(unit, artifact.coordinate.clone())
352                        {
353                            if previous != artifact.coordinate {
354                                return Err(
355                                    DescriptorCacheError::CachedUnitClaimedByMultipleArtifacts {
356                                        unit,
357                                        first: previous,
358                                        second: artifact.coordinate.clone(),
359                                    },
360                                );
361                            }
362                        }
363                        insert_cached_generation(&mut cached_generations, generation)?;
364                    }
365                }
366                Err(DescriptorCacheError::MissingArtifactIndex { .. })
367                    if !artifact.artifact.fresh =>
368                {
369                    // A freshly rebuilt Cargo artifact with no joined wrapper
370                    // unit is a confirmed negative entry (for example a Cargo
371                    // unit with no distinct compiler-artifact/wrapper pair).
372                    // It is persisted below, never guessed on a future fresh
373                    // invocation.
374                }
375                Err(error) => return Err(error),
376            }
377        }
378    }
379
380    cached_generations.retain(|unit, _| !fresh_ids.contains(unit));
381    let cached_ids = cached_generations.keys().copied().collect::<BTreeSet<_>>();
382    let fresh_generations = persist_fresh_units(cache_directory, &fresh.units)?;
383    let mut generations = cached_generations;
384    for (_, generation) in fresh_generations {
385        insert_cached_generation(&mut generations, generation)?;
386    }
387    // Both rebuilt and reused units are now immutable cache generations. This
388    // makes every path in the returned output independent of nonce staging and
389    // lets successful invocations remove staging before releasing the lease.
390    let units = load_cached_units_direct(cache_directory, &generations)?;
391    let units_by_id = units
392        .iter()
393        .map(|unit| (unit.unit, unit))
394        .collect::<BTreeMap<_, _>>();
395    for expected in fresh_ids.iter().chain(cached_ids.iter()) {
396        if !units_by_id.contains_key(expected) {
397            return Err(DescriptorCacheError::MissingMergedUnit(*expected));
398        }
399    }
400
401    let validation_ids = if require_complete_rebuild || resume_interrupted_staging {
402        units_by_id.keys().copied().collect::<BTreeSet<_>>()
403    } else {
404        cached_ids.clone()
405    };
406    validate_cached_unit_inputs(
407        &units_by_id,
408        &validation_ids,
409        &request.target_directory,
410        &fresh.cargo_artifacts,
411    )?;
412    validate_cached_artifact_joins(
413        &units_by_id,
414        &cached_ids,
415        &expected_artifact_by_cached_unit,
416        &fresh.cargo_artifacts,
417        &evidence,
418        fresh.units.is_empty(),
419    )?;
420
421    if let Some(unit) = units_by_id
422        .keys()
423        .find(|unit| !generations.contains_key(unit))
424    {
425        return Err(DescriptorCacheError::MissingCachedGeneration(*unit));
426    }
427    persist_artifact_indexes(
428        cache_directory,
429        &units,
430        &generations,
431        &fresh.cargo_artifacts,
432        &evidence,
433    )?;
434    persist_snapshot(
435        cache_directory,
436        &artifact_set_coordinate,
437        &evidence,
438        units.iter().map(|unit| generations[&unit.unit].clone()),
439    )?;
440    remove_completed_staging(&request.staging_directory)?;
441
442    Ok(DescriptorCargoOutput {
443        cargo_artifacts: fresh.cargo_artifacts,
444        units,
445    })
446}
447
448fn retain_current_interrupted_units(
449    output: &mut DescriptorCargoOutput,
450    request: &DescriptorCargoRequest,
451) -> Result<(), DescriptorCacheError> {
452    let candidates = std::mem::take(&mut output.units);
453    let candidate_count = candidates.len();
454    let mut retained = BTreeMap::<DescriptorCargoUnitId, ValidatedDescriptorUnit>::new();
455    let mut stale = 0usize;
456    for unit in candidates {
457        if interrupted_unit_matches_current_inputs(
458            &unit,
459            &request.target_directory,
460            &request.source_exclusion_directory,
461            &output.cargo_artifacts,
462        )? {
463            if let Some(previous) = retained.get(&unit.unit) {
464                if previous.sidecar != unit.sidecar {
465                    return Err(DescriptorCacheError::ConflictingInterruptedUnitCandidates(
466                        unit.unit,
467                    ));
468                }
469            } else {
470                retained.insert(unit.unit, unit);
471            }
472        } else {
473            stale += 1;
474        }
475    }
476    if stale != 0 {
477        eprintln!(
478            "discarded {stale} stale descriptor recovery candidate{} after current-input validation",
479            if stale == 1 { "" } else { "s" },
480        );
481    }
482    let duplicate_count = candidate_count.saturating_sub(stale + retained.len());
483    if duplicate_count != 0 {
484        eprintln!(
485            "deduplicated {duplicate_count} exact descriptor recovery candidate{}",
486            if duplicate_count == 1 { "" } else { "s" },
487        );
488    }
489    output.units = retained.into_values().collect();
490    Ok(())
491}
492
493fn interrupted_unit_matches_current_inputs(
494    unit: &ValidatedDescriptorUnit,
495    descriptor_target: &Path,
496    source_exclusion: &Path,
497    cargo_artifacts: &[CargoCompilerArtifact],
498) -> Result<bool, DescriptorCacheError> {
499    if !interrupted_unit_matches_local_inputs(unit, descriptor_target, source_exclusion) {
500        return Ok(false);
501    }
502
503    let units_by_id = BTreeMap::from([(unit.unit, unit)]);
504    let unit_ids = BTreeSet::from([unit.unit]);
505    match validate_cached_dependency_artifacts(&units_by_id, &unit_ids, cargo_artifacts) {
506        Ok(()) => {}
507        Err(
508            DescriptorCacheError::CachedDependencyNotEnumerated { .. }
509            | DescriptorCacheError::StaleCachedDependency { .. },
510        ) => return Ok(false),
511        Err(error) => return Err(error),
512    }
513    match join_descriptor_units_to_cargo_artifacts(std::slice::from_ref(unit), cargo_artifacts) {
514        Ok(_) => Ok(true),
515        Err(UnitArtifactJoinError::MissingArtifact(_)) => Err(
516            DescriptorCacheError::InterruptedUnitMissingArtifact(unit.unit),
517        ),
518        Err(error) => Err(DescriptorCacheError::ArtifactJoin(error)),
519    }
520}
521
522fn interrupted_unit_matches_local_inputs(
523    unit: &ValidatedDescriptorUnit,
524    descriptor_target: &Path,
525    source_exclusion: &Path,
526) -> bool {
527    let Some(manifest) = unit.sidecar.cargo_manifest_path.as_deref() else {
528        return false;
529    };
530    let Some(package_root) = manifest.parent() else {
531        return false;
532    };
533    let current_closure =
534        match descriptor_package_source_closure_hash(package_root, source_exclusion) {
535            Ok(hash) => hash,
536            Err(_) => return false,
537        };
538    if current_closure != unit.sidecar.package_source_closure_hash {
539        return false;
540    }
541    validate_descriptor_observed_inputs(descriptor_target, &unit.sidecar).is_ok()
542}
543
544fn reject_rebuilt_artifact_without_wrapper_units(
545    evidence: &[ArtifactEvidence],
546) -> Result<(), DescriptorCacheError> {
547    if let Some(artifact) = evidence.iter().find(|artifact| !artifact.artifact.fresh) {
548        return Err(DescriptorCacheError::RebuiltArtifactMissingFreshUnit {
549            coordinate: artifact.coordinate.clone(),
550        });
551    }
552    Ok(())
553}
554
555fn insert_cached_generation(
556    generations: &mut BTreeMap<DescriptorCargoUnitId, CachedUnitGeneration>,
557    generation: CachedUnitGeneration,
558) -> Result<(), DescriptorCacheError> {
559    let unit = generation.unit(Path::new("cache-generation"))?;
560    if let Some(previous) = generations.insert(unit, generation.clone()) {
561        if previous != generation {
562            return Err(DescriptorCacheError::ConflictingCachedGeneration {
563                unit,
564                first: cached_generation_label(&previous),
565                second: cached_generation_label(&generation),
566            });
567        }
568    }
569    Ok(())
570}
571
572fn validate_cache_directories(
573    cache_directory: &Path,
574    staging_directory: &Path,
575    target_directory: &Path,
576    source_exclusion_directory: &Path,
577    working_directory: &Path,
578) -> Result<PathBuf, DescriptorCacheError> {
579    if !cache_directory.is_absolute() {
580        return Err(DescriptorCacheError::RelativeCacheDirectory(
581            cache_directory.to_path_buf(),
582        ));
583    }
584    for (name, path) in [
585        ("staging", staging_directory),
586        ("target", target_directory),
587        ("source exclusion", source_exclusion_directory),
588        ("working directory", working_directory),
589    ] {
590        if !path.is_absolute() {
591            return Err(DescriptorCacheError::RelativeManagedDirectory {
592                kind: name,
593                path: path.to_path_buf(),
594            });
595        }
596    }
597    let cache = normalize_managed_path(cache_directory)?;
598    let staging = normalize_managed_path(staging_directory)?;
599    let target = normalize_managed_path(target_directory)?;
600    let source_exclusion = normalize_managed_path(source_exclusion_directory)?;
601    let working = normalize_managed_path(working_directory)?;
602
603    for (first_kind, first, second_kind, second) in [
604        ("cache", &cache, "staging", &staging),
605        ("cache", &cache, "target", &target),
606        ("staging", &staging, "target", &target),
607    ] {
608        if managed_paths_overlap(first, second) {
609            return Err(DescriptorCacheError::OverlappingManagedDirectories {
610                first_kind,
611                first: first.clone(),
612                second_kind,
613                second: second.clone(),
614            });
615        }
616    }
617    for (kind, managed) in [("staging", &staging), ("target", &target)] {
618        if working == *managed || working.starts_with(managed) {
619            return Err(DescriptorCacheError::UnsafeManagedDirectory {
620                kind,
621                managed: managed.clone(),
622                working: working.clone(),
623            });
624        }
625    }
626    if target == source_exclusion || !target.starts_with(&source_exclusion) {
627        return Err(DescriptorCacheError::TargetOutsideSourceExclusion {
628            target,
629            exclusion: source_exclusion,
630        });
631    }
632    if source_exclusion == working || working.starts_with(&source_exclusion) {
633        return Err(DescriptorCacheError::UnsafeSourceExclusion {
634            exclusion: source_exclusion,
635            working,
636        });
637    }
638    if source_exclusion.starts_with(&working) {
639        for (kind, managed) in [
640            ("cache", &cache),
641            ("staging", &staging),
642            ("target", &target),
643        ] {
644            if !managed.starts_with(&source_exclusion) {
645                return Err(DescriptorCacheError::GeneratedStateOutsideSourceExclusion {
646                    kind,
647                    path: managed.clone(),
648                    exclusion: source_exclusion.clone(),
649                });
650            }
651        }
652    }
653    Ok(cache)
654}
655
656fn normalize_managed_path(path: &Path) -> Result<PathBuf, DescriptorCacheError> {
657    normalize_managed_path_identity(path).map_err(|source| {
658        DescriptorCacheError::NormalizeManagedDirectory {
659            path: path.to_path_buf(),
660            source,
661        }
662    })
663}
664
665struct CacheGenerationLock {
666    _file: File,
667}
668
669impl CacheGenerationLock {
670    fn acquire_path(path: &Path) -> Result<Self, DescriptorCacheError> {
671        let parent = path
672            .parent()
673            .ok_or_else(|| DescriptorCacheError::CachePathWithoutParent(path.to_path_buf()))?;
674        ensure_plain_directory(parent)?;
675        match fs::symlink_metadata(path) {
676            Ok(metadata) if !metadata.file_type().is_file() => {
677                return Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf()));
678            }
679            Ok(_) => {}
680            Err(source) if source.kind() == io::ErrorKind::NotFound => {}
681            Err(source) => {
682                return Err(DescriptorCacheError::OpenCacheLock {
683                    path: path.to_path_buf(),
684                    source,
685                });
686            }
687        }
688        let file = OpenOptions::new()
689            .create(true)
690            .read(true)
691            .write(true)
692            .truncate(false)
693            .open(path)
694            .map_err(|source| DescriptorCacheError::OpenCacheLock {
695                path: path.to_path_buf(),
696                source,
697            })?;
698        file.lock()
699            .map_err(|source| DescriptorCacheError::AcquireCacheLock {
700                path: path.to_path_buf(),
701                source,
702            })?;
703        Ok(Self { _file: file })
704    }
705}
706
707fn recoverable_cache_authority_error(error: &DescriptorCacheError) -> bool {
708    matches!(
709        error,
710        DescriptorCacheError::MissingArtifactSetSnapshot { .. }
711            | DescriptorCacheError::MissingArtifactIndex { .. }
712            | DescriptorCacheError::MissingCachedUnitFile { .. }
713            | DescriptorCacheError::CachedOutDirDependencyMismatch { .. }
714    )
715}
716
717fn recoverable_interrupted_generation_error(error: &DescriptorCacheError) -> bool {
718    matches!(
719        error,
720        DescriptorCacheError::MultipleFreshUnitsForArtifact { .. }
721            | DescriptorCacheError::RebuiltArtifactMissingFreshUnit { .. }
722            | DescriptorCacheError::ConflictingInterruptedUnitCandidates(_)
723            | DescriptorCacheError::InterruptedUnitMissingArtifact(_)
724            | DescriptorCacheError::ArtifactJoin(_)
725    )
726}
727
728fn reset_descriptor_request_owned_state(
729    request: &DescriptorCargoRequest,
730    staging_directory: &Path,
731) -> Result<(), DescriptorCacheError> {
732    let marker_valid =
733        descriptor_target_marker_is_valid(&request.target_directory).map_err(|source| {
734            DescriptorCacheError::ReadDescriptorTargetMarker {
735                path: request.target_directory.clone(),
736                source,
737            }
738        })?;
739    if !marker_valid {
740        return Err(DescriptorCacheError::UnownedRecoveryTarget(
741            request.target_directory.clone(),
742        ));
743    }
744    let staging_exists = fs::symlink_metadata(staging_directory)
745        .map(|metadata| metadata.file_type().is_dir())
746        .or_else(|source| {
747            if source.kind() == io::ErrorKind::NotFound {
748                Ok(false)
749            } else {
750                Err(source)
751            }
752        })
753        .map_err(|source| DescriptorCacheError::ReadDescriptorStagingMarker {
754            path: staging_directory.to_path_buf(),
755            source,
756        })?;
757    if staging_exists {
758        let staging_owned =
759            descriptor_staging_marker_is_valid(staging_directory).map_err(|source| {
760                DescriptorCacheError::ReadDescriptorStagingMarker {
761                    path: staging_directory.to_path_buf(),
762                    source,
763                }
764            })?;
765        if !staging_owned {
766            return Err(DescriptorCacheError::UnownedRecoveryStaging(
767                staging_directory.to_path_buf(),
768            ));
769        }
770        remove_exact_owned_directory(staging_directory, "staging")?;
771    }
772    remove_exact_owned_directory(&request.target_directory, "target")
773}
774
775fn remove_completed_staging(staging_directory: &Path) -> Result<(), DescriptorCacheError> {
776    let staging_owned =
777        descriptor_staging_marker_is_valid(staging_directory).map_err(|source| {
778            DescriptorCacheError::ReadDescriptorStagingMarker {
779                path: staging_directory.to_path_buf(),
780                source,
781            }
782        })?;
783    if !staging_owned {
784        return Err(DescriptorCacheError::UnownedRecoveryStaging(
785            staging_directory.to_path_buf(),
786        ));
787    }
788    remove_exact_owned_directory(staging_directory, "completed staging")
789}
790
791fn remove_exact_owned_directory(
792    path: &Path,
793    kind: &'static str,
794) -> Result<(), DescriptorCacheError> {
795    let metadata = match fs::symlink_metadata(path) {
796        Ok(metadata) => metadata,
797        Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(()),
798        Err(source) => {
799            return Err(DescriptorCacheError::RemoveRecoveryDirectory {
800                kind,
801                path: path.to_path_buf(),
802                source,
803            });
804        }
805    };
806    if !metadata.file_type().is_dir() {
807        return Err(DescriptorCacheError::UnsafeRecoveryDirectory {
808            kind,
809            path: path.to_path_buf(),
810        });
811    }
812    fs::remove_dir_all(path).map_err(|source| DescriptorCacheError::RemoveRecoveryDirectory {
813        kind,
814        path: path.to_path_buf(),
815        source,
816    })
817}
818
819fn create_cache_layout(cache_directory: &Path) -> Result<(), DescriptorCacheError> {
820    for relative in ["units", "objects", "artifacts", "snapshots"] {
821        let path = cache_directory.join(relative);
822        ensure_plain_directory(&path)?;
823    }
824    Ok(())
825}
826
827fn ensure_plain_directory(path: &Path) -> Result<(), DescriptorCacheError> {
828    match fs::symlink_metadata(path) {
829        Ok(metadata) if metadata.file_type().is_dir() => return Ok(()),
830        Ok(_) => return Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf())),
831        Err(source) if source.kind() == io::ErrorKind::NotFound => {}
832        Err(source) => {
833            return Err(DescriptorCacheError::CreateCacheDirectory {
834                path: path.to_path_buf(),
835                source,
836            });
837        }
838    }
839    fs::create_dir_all(path).map_err(|source| DescriptorCacheError::CreateCacheDirectory {
840        path: path.to_path_buf(),
841        source,
842    })?;
843    let metadata = fs::symlink_metadata(path).map_err(|source| {
844        DescriptorCacheError::CreateCacheDirectory {
845            path: path.to_path_buf(),
846            source,
847        }
848    })?;
849    if metadata.file_type().is_dir() {
850        Ok(())
851    } else {
852        Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf()))
853    }
854}
855
856fn require_plain_directory(path: &Path) -> Result<(), DescriptorCacheError> {
857    match fs::symlink_metadata(path) {
858        Ok(metadata) if metadata.file_type().is_dir() => Ok(()),
859        Ok(_) => Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf())),
860        Err(source) => Err(DescriptorCacheError::ReadCacheFile {
861            path: path.to_path_buf(),
862            source,
863        }),
864    }
865}
866
867#[derive(Clone, Debug)]
868struct ArtifactEvidence {
869    artifact: CargoCompilerArtifact,
870    coordinate: String,
871}
872
873fn collect_artifact_evidence(
874    artifacts: &[CargoCompilerArtifact],
875) -> Result<Vec<ArtifactEvidence>, DescriptorCacheError> {
876    let mut evidence = Vec::with_capacity(artifacts.len());
877    let mut seen = BTreeSet::new();
878    for artifact in artifacts {
879        let mut hash = CacheHasher::new(ARTIFACT_COORDINATE_DOMAIN);
880        hash.field("package_id", artifact.package_id.as_bytes());
881        hash.path("manifest_path", &artifact.manifest_path)?;
882        hash.field("target_name", artifact.target.name.as_bytes());
883        hash.set(
884            "target_kind",
885            artifact.target.kind.iter().map(String::as_bytes),
886        );
887        hash.set(
888            "crate_types",
889            artifact.target.crate_types.iter().map(String::as_bytes),
890        );
891        hash.path("source_path", &artifact.target.src_path)?;
892        hash.field("edition", artifact.target.edition.as_bytes());
893        hash.field("profile", &canonical_json(&artifact.profile));
894        hash.set("features", artifact.features.iter().map(String::as_bytes));
895
896        hash.field(
897            "filename_count",
898            &(artifact.filenames.len() as u64).to_be_bytes(),
899        );
900        for path in &artifact.filenames {
901            hash.path("filename", path)?;
902        }
903        match &artifact.executable {
904            Some(path) => {
905                hash.field("executable_present", b"1");
906                hash.path("executable", path)?;
907            }
908            None => hash.field("executable_present", b"0"),
909        }
910
911        let coordinate = hash.finish();
912        if !seen.insert(coordinate.clone()) {
913            return Err(DescriptorCacheError::DuplicateArtifactCoordinate(
914                coordinate,
915            ));
916        }
917        evidence.push(ArtifactEvidence {
918            artifact: artifact.clone(),
919            coordinate,
920        });
921    }
922    evidence.sort_by(|left, right| left.coordinate.cmp(&right.coordinate));
923    Ok(evidence)
924}
925
926fn artifact_set_coordinate(evidence: &[ArtifactEvidence]) -> String {
927    let mut hash = CacheHasher::new(ARTIFACT_SET_COORDINATE_DOMAIN);
928    hash.field("artifact_count", &(evidence.len() as u64).to_be_bytes());
929    for artifact in evidence {
930        hash.field("artifact", artifact.coordinate.as_bytes());
931    }
932    hash.finish()
933}
934
935fn coordinate_for_artifact(
936    artifact: &CargoCompilerArtifact,
937    evidence: &[ArtifactEvidence],
938) -> Result<String, DescriptorCacheError> {
939    let candidates = evidence
940        .iter()
941        .filter(|candidate| candidate.artifact == *artifact)
942        .collect::<Vec<_>>();
943    match candidates.as_slice() {
944        [candidate] => Ok(candidate.coordinate.clone()),
945        [] => Err(DescriptorCacheError::ArtifactMissingFromCurrentEvidence),
946        _ => Err(DescriptorCacheError::AmbiguousCurrentArtifactEvidence),
947    }
948}
949
950#[derive(Debug, Serialize, Deserialize)]
951#[serde(deny_unknown_fields)]
952struct ArtifactCacheIndex {
953    schema_version: u16,
954    artifact_coordinate: String,
955    units: Vec<CachedUnitGeneration>,
956}
957
958#[derive(Debug, Serialize, Deserialize)]
959#[serde(deny_unknown_fields)]
960struct ArtifactSetSnapshot {
961    schema_version: u16,
962    artifact_set_coordinate: String,
963    artifact_coordinates: Vec<String>,
964    units: Vec<CachedUnitGeneration>,
965}
966
967/// Immutable cache generation selected by an artifact/snapshot pointer.
968#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
969#[serde(deny_unknown_fields)]
970struct CachedUnitGeneration {
971    cargo_unit_id: String,
972    descriptor_object_hash: String,
973    sidecar_hash: String,
974}
975
976impl CachedUnitGeneration {
977    fn unit(&self, path: &Path) -> Result<DescriptorCargoUnitId, DescriptorCacheError> {
978        DescriptorCargoUnitId::from_hex(&self.cargo_unit_id).map_err(|source| {
979            DescriptorCacheError::InvalidCachedUnitId {
980                path: path.to_path_buf(),
981                source,
982            }
983        })
984    }
985
986    fn validate_hashes(&self, path: &Path) -> Result<(), DescriptorCacheError> {
987        validate_cache_hash(&self.descriptor_object_hash).map_err(|reason| {
988            DescriptorCacheError::InvalidCachedGenerationHash {
989                path: path.to_path_buf(),
990                field: "descriptor_object_hash",
991                value: self.descriptor_object_hash.clone(),
992                reason,
993            }
994        })?;
995        validate_cache_hash(&self.sidecar_hash).map_err(|reason| {
996            DescriptorCacheError::InvalidCachedGenerationHash {
997                path: path.to_path_buf(),
998                field: "sidecar_hash",
999                value: self.sidecar_hash.clone(),
1000                reason,
1001            }
1002        })
1003    }
1004}
1005
1006fn load_artifact_index(
1007    cache_directory: &Path,
1008    coordinate: &str,
1009) -> Result<ParsedArtifactIndex, DescriptorCacheError> {
1010    let path = cache_directory
1011        .join("artifacts")
1012        .join(format!("{coordinate}.json"));
1013    match fs::symlink_metadata(&path) {
1014        Ok(metadata) if !metadata.file_type().is_file() => {
1015            return Err(DescriptorCacheError::UnsafeCacheEntry(path));
1016        }
1017        Ok(_) => {}
1018        Err(source) if source.kind() == io::ErrorKind::NotFound => {
1019            return Err(DescriptorCacheError::MissingArtifactIndex {
1020                coordinate: coordinate.to_string(),
1021            });
1022        }
1023        Err(source) => return Err(DescriptorCacheError::ReadCacheFile { path, source }),
1024    }
1025    let bytes = fs::read(&path).map_err(|source| DescriptorCacheError::ReadCacheFile {
1026        path: path.clone(),
1027        source,
1028    })?;
1029    let index: ArtifactCacheIndex =
1030        serde_json::from_slice(&bytes).map_err(|source| DescriptorCacheError::ParseCacheFile {
1031            path: path.clone(),
1032            source,
1033        })?;
1034    if index.schema_version != DESCRIPTOR_CACHE_SCHEMA_VERSION {
1035        return Err(DescriptorCacheError::UnsupportedCacheSchema {
1036            path,
1037            actual: index.schema_version,
1038            expected: DESCRIPTOR_CACHE_SCHEMA_VERSION,
1039        });
1040    }
1041    if index.artifact_coordinate != coordinate {
1042        return Err(DescriptorCacheError::CacheCoordinateMismatch {
1043            path,
1044            expected: coordinate.to_string(),
1045            actual: index.artifact_coordinate,
1046        });
1047    }
1048    Ok(ParsedArtifactIndex {
1049        units: parse_unique_generations(&path, index.units)?,
1050    })
1051}
1052
1053struct ParsedArtifactIndex {
1054    units: Vec<CachedUnitGeneration>,
1055}
1056
1057fn load_snapshot(
1058    cache_directory: &Path,
1059    coordinate: &str,
1060    evidence: &[ArtifactEvidence],
1061) -> Result<ParsedSnapshot, DescriptorCacheError> {
1062    let path = cache_directory
1063        .join("snapshots")
1064        .join(format!("{coordinate}.json"));
1065    match fs::symlink_metadata(&path) {
1066        Ok(metadata) if !metadata.file_type().is_file() => {
1067            return Err(DescriptorCacheError::UnsafeCacheEntry(path));
1068        }
1069        Ok(_) => {}
1070        Err(source) if source.kind() == io::ErrorKind::NotFound => {
1071            return Err(DescriptorCacheError::MissingArtifactSetSnapshot {
1072                coordinate: coordinate.to_string(),
1073            });
1074        }
1075        Err(source) => return Err(DescriptorCacheError::ReadCacheFile { path, source }),
1076    }
1077    let bytes = fs::read(&path).map_err(|source| DescriptorCacheError::ReadCacheFile {
1078        path: path.clone(),
1079        source,
1080    })?;
1081    let snapshot: ArtifactSetSnapshot =
1082        serde_json::from_slice(&bytes).map_err(|source| DescriptorCacheError::ParseCacheFile {
1083            path: path.clone(),
1084            source,
1085        })?;
1086    if snapshot.schema_version != DESCRIPTOR_CACHE_SCHEMA_VERSION {
1087        return Err(DescriptorCacheError::UnsupportedCacheSchema {
1088            path,
1089            actual: snapshot.schema_version,
1090            expected: DESCRIPTOR_CACHE_SCHEMA_VERSION,
1091        });
1092    }
1093    if snapshot.artifact_set_coordinate != coordinate {
1094        return Err(DescriptorCacheError::CacheCoordinateMismatch {
1095            path,
1096            expected: coordinate.to_string(),
1097            actual: snapshot.artifact_set_coordinate,
1098        });
1099    }
1100    let expected_artifacts = evidence
1101        .iter()
1102        .map(|artifact| artifact.coordinate.clone())
1103        .collect::<Vec<_>>();
1104    if snapshot.artifact_coordinates != expected_artifacts {
1105        return Err(DescriptorCacheError::SnapshotArtifactSetMismatch(path));
1106    }
1107    Ok(ParsedSnapshot {
1108        units: parse_unique_generations(&path, snapshot.units)?,
1109    })
1110}
1111
1112struct ParsedSnapshot {
1113    units: Vec<CachedUnitGeneration>,
1114}
1115
1116fn parse_unique_generations(
1117    path: &Path,
1118    encoded: Vec<CachedUnitGeneration>,
1119) -> Result<Vec<CachedUnitGeneration>, DescriptorCacheError> {
1120    let mut units = Vec::with_capacity(encoded.len());
1121    let mut seen = BTreeSet::new();
1122    for generation in encoded {
1123        generation.validate_hashes(path)?;
1124        let unit = generation.unit(path)?;
1125        if !seen.insert(unit) {
1126            return Err(DescriptorCacheError::DuplicateCachedUnit {
1127                path: path.to_path_buf(),
1128                unit,
1129            });
1130        }
1131        units.push(generation);
1132    }
1133    Ok(units)
1134}
1135
1136fn validate_cache_hash(value: &str) -> Result<(), String> {
1137    if value.len() != 64 {
1138        return Err(format!(
1139            "expected 64 lowercase hexadecimal characters, got {}",
1140            value.len()
1141        ));
1142    }
1143    if let Some((offset, byte)) = value
1144        .bytes()
1145        .enumerate()
1146        .find(|(_, byte)| !matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1147    {
1148        return Err(format!(
1149            "invalid byte `{}` at offset {offset}",
1150            char::from(byte)
1151        ));
1152    }
1153    Ok(())
1154}
1155
1156fn load_cached_units_direct(
1157    cache_directory: &Path,
1158    units: &BTreeMap<DescriptorCargoUnitId, CachedUnitGeneration>,
1159) -> Result<Vec<ValidatedDescriptorUnit>, DescriptorCacheError> {
1160    let mut cached = Vec::with_capacity(units.len());
1161    for (unit, generation) in units {
1162        let sidecar_source = cached_sidecar_path(cache_directory, generation);
1163        let object_source = cached_object_path(cache_directory, generation);
1164        require_plain_directory(sidecar_source.parent().ok_or_else(|| {
1165            DescriptorCacheError::CachePathWithoutParent(sidecar_source.clone())
1166        })?)?;
1167        require_plain_directory(
1168            object_source.parent().ok_or_else(|| {
1169                DescriptorCacheError::CachePathWithoutParent(object_source.clone())
1170            })?,
1171        )?;
1172        require_file(&sidecar_source, *unit, CacheUnitFileKind::Sidecar)?;
1173        require_file(&object_source, *unit, CacheUnitFileKind::Object)?;
1174        let sidecar_bytes =
1175            fs::read(&sidecar_source).map_err(|source| DescriptorCacheError::ReadCacheFile {
1176                path: sidecar_source.clone(),
1177                source,
1178            })?;
1179        let actual_sidecar_hash = cached_sidecar_hash(&sidecar_bytes);
1180        if actual_sidecar_hash != generation.sidecar_hash {
1181            return Err(DescriptorCacheError::CachedSidecarHashMismatch {
1182                unit: *unit,
1183                expected: generation.sidecar_hash.clone(),
1184                actual: actual_sidecar_hash,
1185            });
1186        }
1187        let sidecar: DescriptorUnitSidecar =
1188            serde_json::from_slice(&sidecar_bytes).map_err(|source| {
1189                DescriptorCacheError::ParseCacheFile {
1190                    path: sidecar_source.clone(),
1191                    source,
1192                }
1193            })?;
1194        if sidecar.schema_version != crate::rsjs::build::DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION {
1195            return Err(DescriptorCacheError::CachedSidecarSchemaMismatch {
1196                path: sidecar_source,
1197                actual: sidecar.schema_version,
1198                expected: crate::rsjs::build::DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION,
1199            });
1200        }
1201        if sidecar.cargo_unit_id != unit.to_string() {
1202            return Err(DescriptorCacheError::CachedSidecarUnitMismatch {
1203                unit: *unit,
1204                actual: sidecar.cargo_unit_id,
1205            });
1206        }
1207        let expected_object = format!("objects/{unit}.o");
1208        if sidecar.descriptor_object != expected_object {
1209            return Err(DescriptorCacheError::CachedSidecarObjectPathMismatch {
1210                unit: *unit,
1211                actual: sidecar.descriptor_object,
1212                expected: expected_object,
1213            });
1214        }
1215        if sidecar.descriptor_object_hash != generation.descriptor_object_hash {
1216            return Err(DescriptorCacheError::CachedGenerationObjectHashMismatch {
1217                unit: *unit,
1218                pointer: generation.descriptor_object_hash.clone(),
1219                sidecar: sidecar.descriptor_object_hash,
1220            });
1221        }
1222        validate_cached_sidecar_semantics(*unit, &sidecar, &sidecar_source)?;
1223        cached.push(CachedUnitCandidate {
1224            unit: *unit,
1225            sidecar,
1226            sidecar_path: sidecar_source,
1227            descriptor_object: object_source,
1228            expected_object_hash: generation.descriptor_object_hash.clone(),
1229        });
1230    }
1231
1232    // Hash the exact content-addressed cache objects under the retained cache
1233    // lease. Rayon preserves indexed collection order, so I/O failures and
1234    // mismatches are still reported deterministically by Cargo-unit ID below.
1235    let actual_hashes = cached
1236        .par_iter()
1237        .map(|unit| hash_cached_descriptor_object(&unit.descriptor_object))
1238        .collect::<Vec<_>>();
1239    let mut validated = Vec::with_capacity(cached.len());
1240    for (unit, actual_hash) in cached.into_iter().zip(actual_hashes) {
1241        let actual_hash = actual_hash.map_err(|source| DescriptorCacheError::ReadCacheSource {
1242            path: unit.descriptor_object.clone(),
1243            source,
1244        })?;
1245        if actual_hash != unit.expected_object_hash {
1246            return Err(DescriptorCacheError::DescriptorObjectHashMismatch {
1247                unit: unit.unit,
1248                expected: unit.expected_object_hash,
1249                actual: actual_hash,
1250            });
1251        }
1252        // Recheck the entry kind after the byte read. This rejects a
1253        // non-cooperating replacement with a directory or symlink before the
1254        // exact cache path is published to the linker.
1255        require_file(
1256            &unit.descriptor_object,
1257            unit.unit,
1258            CacheUnitFileKind::Object,
1259        )?;
1260        validated.push(ValidatedDescriptorUnit {
1261            unit: unit.unit,
1262            sidecar: unit.sidecar,
1263            sidecar_path: unit.sidecar_path,
1264            descriptor_object: unit.descriptor_object,
1265        });
1266    }
1267    Ok(validated)
1268}
1269
1270struct CachedUnitCandidate {
1271    unit: DescriptorCargoUnitId,
1272    sidecar: DescriptorUnitSidecar,
1273    sidecar_path: PathBuf,
1274    descriptor_object: PathBuf,
1275    expected_object_hash: String,
1276}
1277
1278fn hash_cached_descriptor_object(path: &Path) -> io::Result<String> {
1279    let mut input = File::open(path)?;
1280    let mut hash = Sha256::new();
1281    hash.update(DESCRIPTOR_OBJECT_HASH_DOMAIN);
1282    let mut buffer = [0_u8; 64 * 1024];
1283    loop {
1284        let read = input.read(&mut buffer)?;
1285        if read == 0 {
1286            break;
1287        }
1288        hash.update(&buffer[..read]);
1289    }
1290    Ok(encode_digest(&hash.finalize().into()))
1291}
1292
1293fn validate_cached_sidecar_semantics(
1294    unit: DescriptorCargoUnitId,
1295    sidecar: &DescriptorUnitSidecar,
1296    path: &Path,
1297) -> Result<(), DescriptorCacheError> {
1298    let invalid = |reason| DescriptorCacheError::InvalidCachedSidecar {
1299        unit,
1300        path: path.to_path_buf(),
1301        reason,
1302    };
1303
1304    if sidecar.normalized_rustc_inputs_hash != unit.to_string() {
1305        return Err(invalid(format!(
1306            "normalized rustc input hash `{}` does not equal the selected unit",
1307            sidecar.normalized_rustc_inputs_hash
1308        )));
1309    }
1310    for (name, value) in [
1311        (
1312            "logical environment hash",
1313            sidecar.logical_environment_hash.as_str(),
1314        ),
1315        (
1316            "realized environment hash",
1317            sidecar.realized_environment_hash.as_str(),
1318        ),
1319        (
1320            "package source-closure hash",
1321            sidecar.package_source_closure_hash.as_str(),
1322        ),
1323        (
1324            "descriptor object hash",
1325            sidecar.descriptor_object_hash.as_str(),
1326        ),
1327    ] {
1328        validate_cache_hash(value)
1329            .map_err(|reason| invalid(format!("invalid {name} `{value}`: {reason}")))?;
1330    }
1331    validate_cached_relative_path(&sidecar.dep_info_path)
1332        .map_err(|reason| invalid(format!("invalid target-relative dep-info path: {reason}")))?;
1333    if !sidecar.dep_info_working_directory.is_absolute() {
1334        return Err(invalid(
1335            "dep-info working directory is relative".to_string(),
1336        ));
1337    }
1338    match &sidecar.out_dir {
1339        Some(out_dir) => validate_cached_relative_path(out_dir)
1340            .map_err(|reason| invalid(format!("invalid OUT_DIR path `{out_dir}`: {reason}")))?,
1341        None if !sidecar.out_dir_dependencies.is_empty() => {
1342            return Err(invalid(
1343                "OUT_DIR dependencies are present without an OUT_DIR coordinate".to_string(),
1344            ));
1345        }
1346        None => {}
1347    }
1348
1349    let mut previous_out_dir = None::<&str>;
1350    for dependency in &sidecar.out_dir_dependencies {
1351        validate_cached_relative_path(&dependency.relative_path).map_err(|reason| {
1352            invalid(format!(
1353                "invalid OUT_DIR dependency path `{}`: {reason}",
1354                dependency.relative_path
1355            ))
1356        })?;
1357        validate_cache_hash(&dependency.content_hash).map_err(|reason| {
1358            invalid(format!(
1359                "invalid OUT_DIR dependency hash for `{}`: {reason}",
1360                dependency.relative_path
1361            ))
1362        })?;
1363        if previous_out_dir.is_some_and(|previous| previous >= dependency.relative_path.as_str()) {
1364            return Err(invalid(
1365                "OUT_DIR dependencies are not strictly sorted and unique".to_string(),
1366            ));
1367        }
1368        previous_out_dir = Some(&dependency.relative_path);
1369    }
1370
1371    let mut previous_source = None::<&Path>;
1372    for dependency in &sidecar.source_dependencies {
1373        if !dependency.absolute_path.is_absolute() {
1374            return Err(invalid(format!(
1375                "observed source path `{}` is relative",
1376                dependency.absolute_path.display()
1377            )));
1378        }
1379        validate_cache_hash(&dependency.content_hash).map_err(|reason| {
1380            invalid(format!(
1381                "invalid observed source hash for `{}`: {reason}",
1382                dependency.absolute_path.display()
1383            ))
1384        })?;
1385        if previous_source.is_some_and(|previous| previous >= dependency.absolute_path.as_path()) {
1386            return Err(invalid(
1387                "observed source dependencies are not strictly sorted and unique".to_string(),
1388            ));
1389        }
1390        previous_source = Some(&dependency.absolute_path);
1391    }
1392
1393    let mut previous_environment = None::<&str>;
1394    for dependency in &sidecar.environment_dependencies {
1395        if dependency.name.is_empty()
1396            || dependency.name.bytes().any(|byte| byte == 0)
1397            || wrapper_control_environment(&dependency.name)
1398        {
1399            return Err(invalid(format!(
1400                "invalid observed environment dependency name `{}`",
1401                dependency.name
1402            )));
1403        }
1404        if let Some(value_hash) = &dependency.value_hash {
1405            validate_cache_hash(value_hash).map_err(|reason| {
1406                invalid(format!(
1407                    "invalid observed environment value hash for `{}`: {reason}",
1408                    dependency.name
1409                ))
1410            })?;
1411        }
1412        if previous_environment.is_some_and(|previous| previous >= dependency.name.as_str()) {
1413            return Err(invalid(
1414                "environment dependencies are not strictly sorted and unique".to_string(),
1415            ));
1416        }
1417        previous_environment = Some(&dependency.name);
1418    }
1419    if sidecar.out_dir.is_none()
1420        && sidecar
1421            .environment_dependencies
1422            .iter()
1423            .any(|dependency| dependency.name == "OUT_DIR" && dependency.value_hash.is_some())
1424    {
1425        return Err(invalid(
1426            "present OUT_DIR environment dependency has no OUT_DIR coordinate".to_string(),
1427        ));
1428    }
1429
1430    for (extern_name, artifact) in &sidecar.dependency_artifacts {
1431        if extern_name.is_empty() {
1432            return Err(invalid("dependency name is empty".to_string()));
1433        }
1434        if !artifact.path.is_absolute() {
1435            return Err(invalid(format!(
1436                "dependency `{extern_name}` path `{}` is relative",
1437                artifact.path.display()
1438            )));
1439        }
1440        validate_cache_hash(&artifact.content_hash).map_err(|reason| {
1441            invalid(format!(
1442                "invalid dependency hash for `{extern_name}`: {reason}"
1443            ))
1444        })?;
1445    }
1446    if let Some(extra_filename) = &sidecar.cargo_extra_filename {
1447        validate_cached_extra_filename(extra_filename).map_err(|reason| {
1448            invalid(format!(
1449                "invalid Cargo extra-filename `{extra_filename}`: {reason}"
1450            ))
1451        })?;
1452    }
1453    let codegen = &sidecar.descriptor_codegen;
1454    if codegen.codegen_units != 1
1455        || codegen.incremental
1456        || !codegen.link_dead_code
1457        || codegen.lto != "off"
1458        || codegen.strip != "none"
1459    {
1460        return Err(invalid(
1461            "descriptor retention/codegen policy is incompatible".to_string(),
1462        ));
1463    }
1464    Ok(())
1465}
1466
1467fn validate_cached_relative_path(path: &str) -> Result<(), String> {
1468    if path.is_empty() {
1469        return Err("path is empty".to_string());
1470    }
1471    for component in path.split('/') {
1472        if component.is_empty() || matches!(component, "." | "..") {
1473            return Err(format!("invalid path component `{component}`"));
1474        }
1475        if component.contains('\\')
1476            || component.bytes().any(|byte| byte == 0)
1477            || component
1478                .chars()
1479                .any(|character| character.is_whitespace() && character != ' ')
1480        {
1481            return Err(format!("non-portable path component `{component}`"));
1482        }
1483    }
1484    Ok(())
1485}
1486
1487fn validate_cached_extra_filename(value: &str) -> Result<(), String> {
1488    if value.is_empty() {
1489        return Err("the discriminator is empty".to_string());
1490    }
1491    if value.contains(['/', '\\']) {
1492        return Err("path separators are not allowed".to_string());
1493    }
1494    if let Some((offset, character)) = value
1495        .char_indices()
1496        .find(|(_, character)| character.is_control())
1497    {
1498        return Err(format!(
1499            "control character U+{:04X} at byte offset {offset} is not allowed",
1500            u32::from(character)
1501        ));
1502    }
1503    Ok(())
1504}
1505
1506fn cached_sidecar_path(cache: &Path, generation: &CachedUnitGeneration) -> PathBuf {
1507    cache
1508        .join("units")
1509        .join(&generation.cargo_unit_id)
1510        .join(format!("{}.json", generation.sidecar_hash))
1511}
1512
1513fn cached_object_path(cache: &Path, generation: &CachedUnitGeneration) -> PathBuf {
1514    cache
1515        .join("objects")
1516        .join(&generation.cargo_unit_id)
1517        .join(format!("{}.o", generation.descriptor_object_hash))
1518}
1519
1520fn cached_sidecar_hash(bytes: &[u8]) -> String {
1521    let mut hash = Sha256::new();
1522    hash.update(CACHED_SIDECAR_HASH_DOMAIN);
1523    hash.update(bytes);
1524    encode_digest(&hash.finalize().into())
1525}
1526
1527fn require_file(
1528    path: &Path,
1529    unit: DescriptorCargoUnitId,
1530    kind: CacheUnitFileKind,
1531) -> Result<(), DescriptorCacheError> {
1532    match fs::symlink_metadata(path) {
1533        Ok(metadata) if metadata.file_type().is_file() => Ok(()),
1534        Ok(_) => Err(DescriptorCacheError::UnsafeCacheEntry(path.to_path_buf())),
1535        Err(source) if source.kind() == io::ErrorKind::NotFound => {
1536            Err(DescriptorCacheError::MissingCachedUnitFile {
1537                unit,
1538                kind,
1539                path: path.to_path_buf(),
1540            })
1541        }
1542        Err(source) => Err(DescriptorCacheError::ReadCacheFile {
1543            path: path.to_path_buf(),
1544            source,
1545        }),
1546    }
1547}
1548
1549fn validate_cached_unit_inputs(
1550    units_by_id: &BTreeMap<DescriptorCargoUnitId, &ValidatedDescriptorUnit>,
1551    cached_ids: &BTreeSet<DescriptorCargoUnitId>,
1552    descriptor_target: &Path,
1553    cargo_artifacts: &[CargoCompilerArtifact],
1554) -> Result<(), DescriptorCacheError> {
1555    validate_cached_observed_inputs(units_by_id, cached_ids, descriptor_target)?;
1556    validate_cached_dependency_artifacts(units_by_id, cached_ids, cargo_artifacts)
1557}
1558
1559fn validate_cached_observed_inputs(
1560    units_by_id: &BTreeMap<DescriptorCargoUnitId, &ValidatedDescriptorUnit>,
1561    cached_ids: &BTreeSet<DescriptorCargoUnitId>,
1562    descriptor_target: &Path,
1563) -> Result<(), DescriptorCacheError> {
1564    for unit_id in cached_ids {
1565        let unit = units_by_id
1566            .get(unit_id)
1567            .ok_or(DescriptorCacheError::MissingMergedUnit(*unit_id))?;
1568        validate_descriptor_observed_inputs(descriptor_target, &unit.sidecar).map_err(
1569            |source| DescriptorCacheError::CachedOutDirDependencyMismatch {
1570                unit: *unit_id,
1571                source,
1572            },
1573        )?;
1574    }
1575    Ok(())
1576}
1577
1578fn validate_cached_dependency_artifacts(
1579    units_by_id: &BTreeMap<DescriptorCargoUnitId, &ValidatedDescriptorUnit>,
1580    cached_ids: &BTreeSet<DescriptorCargoUnitId>,
1581    cargo_artifacts: &[CargoCompilerArtifact],
1582) -> Result<(), DescriptorCacheError> {
1583    let mut enumerated = BTreeMap::<PathBuf, BTreeSet<usize>>::new();
1584    for (artifact_index, artifact) in cargo_artifacts.iter().enumerate() {
1585        for path in &artifact.filenames {
1586            if classify_dependency_artifact(artifact, path).is_some() {
1587                enumerated
1588                    .entry(path.clone())
1589                    .or_default()
1590                    .insert(artifact_index);
1591            }
1592        }
1593        // A root package's lib is reported at its uplifted destination while
1594        // same-package dependents link the hashed `deps/` rlib the message
1595        // never lists; the content hash of that exact file is still verified
1596        // below.
1597        if let Some(path) = uplifted_root_lib_hashed_rlib(artifact) {
1598            enumerated.entry(path).or_default().insert(artifact_index);
1599        }
1600    }
1601
1602    let mut expected_by_path = BTreeMap::<PathBuf, (String, DescriptorCargoUnitId, String)>::new();
1603    for unit_id in cached_ids {
1604        let unit = units_by_id
1605            .get(unit_id)
1606            .ok_or(DescriptorCacheError::MissingMergedUnit(*unit_id))?;
1607        for (extern_name, artifact) in &unit.sidecar.dependency_artifacts {
1608            match expected_by_path.entry(artifact.path.clone()) {
1609                std::collections::btree_map::Entry::Vacant(entry) => {
1610                    entry.insert((artifact.content_hash.clone(), *unit_id, extern_name.clone()));
1611                }
1612                std::collections::btree_map::Entry::Occupied(entry)
1613                    if entry.get().0 != artifact.content_hash =>
1614                {
1615                    return Err(DescriptorCacheError::ConflictingSidecarArtifactEvidence {
1616                        path: artifact.path.clone(),
1617                        first: entry.get().0.clone(),
1618                        second: artifact.content_hash.clone(),
1619                        unit: *unit_id,
1620                        extern_name: extern_name.clone(),
1621                    });
1622                }
1623                std::collections::btree_map::Entry::Occupied(_) => {}
1624            }
1625        }
1626    }
1627
1628    let expectations = expected_by_path.into_iter().collect::<Vec<_>>();
1629    for (path, (_, unit, extern_name)) in &expectations {
1630        let matches = enumerated.get(path).map_or(0, BTreeSet::len);
1631        match matches {
1632            0 => {
1633                return Err(DescriptorCacheError::CachedDependencyNotEnumerated {
1634                    unit: *unit,
1635                    extern_name: extern_name.clone(),
1636                    path: path.clone(),
1637                });
1638            }
1639            1 => {}
1640            matches => {
1641                return Err(DescriptorCacheError::AmbiguousCachedDependencyArtifact {
1642                    unit: *unit,
1643                    extern_name: extern_name.clone(),
1644                    path: path.clone(),
1645                    matches,
1646                });
1647            }
1648        }
1649    }
1650    let actuals = expectations
1651        .par_iter()
1652        .map(|(path, _)| descriptor_input_content_hash(path))
1653        .collect::<Vec<_>>();
1654    for ((path, (expected, unit, extern_name)), actual) in expectations.into_iter().zip(actuals) {
1655        let actual = actual.map_err(|source| DescriptorCacheError::HashCurrentInput {
1656            path: path.clone(),
1657            source,
1658        })?;
1659        if actual != expected {
1660            return Err(DescriptorCacheError::StaleCachedDependency {
1661                unit,
1662                extern_name,
1663                path,
1664                expected,
1665                actual,
1666            });
1667        }
1668    }
1669    Ok(())
1670}
1671
1672fn validate_cached_artifact_joins(
1673    units_by_id: &BTreeMap<DescriptorCargoUnitId, &ValidatedDescriptorUnit>,
1674    cached_ids: &BTreeSet<DescriptorCargoUnitId>,
1675    expected_artifact_by_cached_unit: &BTreeMap<DescriptorCargoUnitId, String>,
1676    cargo_artifacts: &[CargoCompilerArtifact],
1677    evidence: &[ArtifactEvidence],
1678    exact_snapshot: bool,
1679) -> Result<(), DescriptorCacheError> {
1680    for unit_id in cached_ids {
1681        let unit = *units_by_id
1682            .get(unit_id)
1683            .ok_or(DescriptorCacheError::MissingMergedUnit(*unit_id))?;
1684        match join_descriptor_units_to_cargo_artifacts(std::slice::from_ref(unit), cargo_artifacts)
1685        {
1686            Ok(joined) => {
1687                let artifact = joined
1688                    .get(unit_id)
1689                    .expect("one-unit join returns the requested unit");
1690                let actual = coordinate_for_artifact(artifact, evidence)?;
1691                if let Some(expected) = expected_artifact_by_cached_unit.get(unit_id) {
1692                    if *expected != actual {
1693                        return Err(DescriptorCacheError::CachedArtifactJoinMismatch {
1694                            unit: *unit_id,
1695                            expected: expected.clone(),
1696                            actual,
1697                        });
1698                    }
1699                }
1700            }
1701            Err(UnitArtifactJoinError::MissingArtifact(_)) if exact_snapshot => {
1702                // Some rustc units have no distinct Cargo compiler-artifact.
1703                // They are reusable only through a snapshot authorized by the
1704                // exact complete artifact set from the current Cargo run.
1705            }
1706            Err(source) => return Err(DescriptorCacheError::ArtifactJoin(source)),
1707        }
1708    }
1709    Ok(())
1710}
1711
1712fn persist_fresh_units(
1713    cache_directory: &Path,
1714    units: &[ValidatedDescriptorUnit],
1715) -> Result<BTreeMap<DescriptorCargoUnitId, CachedUnitGeneration>, DescriptorCacheError> {
1716    let mut generations = BTreeMap::new();
1717    for unit in units {
1718        let sidecar_bytes = fs::read(&unit.sidecar_path).map_err(|source| {
1719            DescriptorCacheError::ReadCacheSource {
1720                path: unit.sidecar_path.clone(),
1721                source,
1722            }
1723        })?;
1724        let generation = CachedUnitGeneration {
1725            cargo_unit_id: unit.unit.to_string(),
1726            descriptor_object_hash: unit.sidecar.descriptor_object_hash.clone(),
1727            sidecar_hash: cached_sidecar_hash(&sidecar_bytes),
1728        };
1729        generation.validate_hashes(&unit.sidecar_path)?;
1730        atomic_copy_descriptor_object_verified(
1731            &unit.descriptor_object,
1732            &cached_object_path(cache_directory, &generation),
1733            unit.unit,
1734            &generation.descriptor_object_hash,
1735        )?;
1736        atomic_write_immutable_bytes(
1737            &cached_sidecar_path(cache_directory, &generation),
1738            &sidecar_bytes,
1739        )?;
1740        if let Some(previous) = generations.insert(unit.unit, generation.clone()) {
1741            return Err(DescriptorCacheError::ConflictingCachedGeneration {
1742                unit: unit.unit,
1743                first: cached_generation_label(&previous),
1744                second: cached_generation_label(&generation),
1745            });
1746        }
1747    }
1748    Ok(generations)
1749}
1750
1751fn cached_generation_label(generation: &CachedUnitGeneration) -> String {
1752    format!(
1753        "object={},sidecar={}",
1754        generation.descriptor_object_hash, generation.sidecar_hash
1755    )
1756}
1757
1758fn atomic_copy_descriptor_object_verified(
1759    source: &Path,
1760    destination: &Path,
1761    unit: DescriptorCargoUnitId,
1762    expected: &str,
1763) -> Result<(), DescriptorCacheError> {
1764    let parent = destination
1765        .parent()
1766        .ok_or_else(|| DescriptorCacheError::CachePathWithoutParent(destination.to_path_buf()))?;
1767    ensure_plain_directory(parent)?;
1768    let nonce = CACHE_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
1769    let file_name = destination
1770        .file_name()
1771        .and_then(OsStr::to_str)
1772        .ok_or_else(|| DescriptorCacheError::InvalidCacheFilename(destination.to_path_buf()))?;
1773    let temporary = parent.join(format!(".{file_name}.{}.{}.tmp", std::process::id(), nonce));
1774    let mut input =
1775        File::open(source).map_err(|source_error| DescriptorCacheError::ReadCacheSource {
1776            path: source.to_path_buf(),
1777            source: source_error,
1778        })?;
1779    let mut output = OpenOptions::new()
1780        .create_new(true)
1781        .write(true)
1782        .open(&temporary)
1783        .map_err(|source| DescriptorCacheError::WriteCacheFile {
1784            path: temporary.clone(),
1785            source,
1786        })?;
1787    let mut hash = Sha256::new();
1788    hash.update(DESCRIPTOR_OBJECT_HASH_DOMAIN);
1789    let mut buffer = [0_u8; 64 * 1024];
1790    loop {
1791        let read = input.read(&mut buffer).map_err(|source_error| {
1792            DescriptorCacheError::ReadCacheSource {
1793                path: source.to_path_buf(),
1794                source: source_error,
1795            }
1796        })?;
1797        if read == 0 {
1798            break;
1799        }
1800        hash.update(&buffer[..read]);
1801        output.write_all(&buffer[..read]).map_err(|source| {
1802            DescriptorCacheError::WriteCacheFile {
1803                path: temporary.clone(),
1804                source,
1805            }
1806        })?;
1807    }
1808    output
1809        .sync_all()
1810        .map_err(|source| DescriptorCacheError::WriteCacheFile {
1811            path: temporary.clone(),
1812            source,
1813        })?;
1814    drop(output);
1815    let actual = encode_digest(&hash.finalize().into());
1816    if actual != expected {
1817        let _ = fs::remove_file(&temporary);
1818        return Err(DescriptorCacheError::DescriptorObjectHashMismatch {
1819            unit,
1820            expected: expected.to_string(),
1821            actual,
1822        });
1823    }
1824    install_immutable(&temporary, destination)
1825}
1826
1827fn persist_artifact_indexes(
1828    cache_directory: &Path,
1829    units: &[ValidatedDescriptorUnit],
1830    generations: &BTreeMap<DescriptorCargoUnitId, CachedUnitGeneration>,
1831    cargo_artifacts: &[CargoCompilerArtifact],
1832    evidence: &[ArtifactEvidence],
1833) -> Result<(), DescriptorCacheError> {
1834    let joined = join_cargo_enumerated_descriptor_units(units, cargo_artifacts)
1835        .map_err(DescriptorCacheError::ArtifactJoin)?;
1836    let mut units_by_artifact = BTreeMap::<String, Vec<CachedUnitGeneration>>::new();
1837    for (unit, artifact) in joined {
1838        let coordinate = coordinate_for_artifact(&artifact, evidence)?;
1839        let generation = generations
1840            .get(&unit)
1841            .ok_or(DescriptorCacheError::MissingCachedGeneration(unit))?
1842            .clone();
1843        units_by_artifact
1844            .entry(coordinate)
1845            .or_default()
1846            .push(generation);
1847    }
1848    for artifact in evidence {
1849        let mut units = units_by_artifact
1850            .remove(&artifact.coordinate)
1851            .unwrap_or_default();
1852        units.sort();
1853        let index = ArtifactCacheIndex {
1854            schema_version: DESCRIPTOR_CACHE_SCHEMA_VERSION,
1855            artifact_coordinate: artifact.coordinate.clone(),
1856            units,
1857        };
1858        let bytes = serde_json::to_vec_pretty(&index)
1859            .map_err(DescriptorCacheError::SerializeCacheRecord)?;
1860        atomic_write_replaceable(
1861            &cache_directory
1862                .join("artifacts")
1863                .join(format!("{}.json", artifact.coordinate)),
1864            &bytes,
1865        )?;
1866    }
1867    Ok(())
1868}
1869
1870fn persist_snapshot(
1871    cache_directory: &Path,
1872    artifact_set_coordinate: &str,
1873    evidence: &[ArtifactEvidence],
1874    units: impl IntoIterator<Item = CachedUnitGeneration>,
1875) -> Result<(), DescriptorCacheError> {
1876    let snapshot = ArtifactSetSnapshot {
1877        schema_version: DESCRIPTOR_CACHE_SCHEMA_VERSION,
1878        artifact_set_coordinate: artifact_set_coordinate.to_string(),
1879        artifact_coordinates: evidence
1880            .iter()
1881            .map(|artifact| artifact.coordinate.clone())
1882            .collect(),
1883        units: units.into_iter().collect(),
1884    };
1885    let bytes =
1886        serde_json::to_vec_pretty(&snapshot).map_err(DescriptorCacheError::SerializeCacheRecord)?;
1887    atomic_write_replaceable(
1888        &cache_directory
1889            .join("snapshots")
1890            .join(format!("{artifact_set_coordinate}.json")),
1891        &bytes,
1892    )
1893}
1894
1895fn atomic_write_immutable_bytes(
1896    destination: &Path,
1897    bytes: &[u8],
1898) -> Result<(), DescriptorCacheError> {
1899    let parent = destination
1900        .parent()
1901        .ok_or_else(|| DescriptorCacheError::CachePathWithoutParent(destination.to_path_buf()))?;
1902    ensure_plain_directory(parent)?;
1903    let nonce = CACHE_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
1904    let file_name = destination
1905        .file_name()
1906        .and_then(OsStr::to_str)
1907        .ok_or_else(|| DescriptorCacheError::InvalidCacheFilename(destination.to_path_buf()))?;
1908    let temporary = parent.join(format!(".{file_name}.{}.{}.tmp", std::process::id(), nonce));
1909    let mut output = OpenOptions::new()
1910        .create_new(true)
1911        .write(true)
1912        .open(&temporary)
1913        .map_err(|source| DescriptorCacheError::WriteCacheFile {
1914            path: temporary.clone(),
1915            source,
1916        })?;
1917    output
1918        .write_all(bytes)
1919        .and_then(|()| output.sync_all())
1920        .map_err(|source| DescriptorCacheError::WriteCacheFile {
1921            path: temporary.clone(),
1922            source,
1923        })?;
1924    drop(output);
1925    install_immutable(&temporary, destination)
1926}
1927
1928fn atomic_write_replaceable(path: &Path, bytes: &[u8]) -> Result<(), DescriptorCacheError> {
1929    let parent = path
1930        .parent()
1931        .ok_or_else(|| DescriptorCacheError::CachePathWithoutParent(path.to_path_buf()))?;
1932    ensure_plain_directory(parent)?;
1933    let nonce = CACHE_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
1934    let file_name = path
1935        .file_name()
1936        .and_then(OsStr::to_str)
1937        .ok_or_else(|| DescriptorCacheError::InvalidCacheFilename(path.to_path_buf()))?;
1938    let temporary = parent.join(format!(".{file_name}.{}.{}.tmp", std::process::id(), nonce));
1939    let mut file = OpenOptions::new()
1940        .create_new(true)
1941        .write(true)
1942        .open(&temporary)
1943        .map_err(|source| DescriptorCacheError::WriteCacheFile {
1944            path: temporary.clone(),
1945            source,
1946        })?;
1947    file.write_all(bytes)
1948        .and_then(|()| file.write_all(b"\n"))
1949        .and_then(|()| file.sync_all())
1950        .map_err(|source| DescriptorCacheError::WriteCacheFile {
1951            path: temporary.clone(),
1952            source,
1953        })?;
1954    drop(file);
1955
1956    // Artifact coordinates deliberately exclude mutable source/output bytes,
1957    // so their unit-set indexes and complete snapshots are atomic pointers to
1958    // the latest Cargo-authorized generation rather than immutable blobs.
1959    if let Err(source) = replace_file_atomic(&temporary, path) {
1960        let _ = fs::remove_file(&temporary);
1961        return Err(DescriptorCacheError::WriteCacheFile {
1962            path: path.to_path_buf(),
1963            source,
1964        });
1965    }
1966    sync_directory(parent).map_err(|source| DescriptorCacheError::WriteCacheFile {
1967        path: parent.to_path_buf(),
1968        source,
1969    })
1970}
1971
1972#[cfg(not(windows))]
1973fn replace_file_atomic(temporary: &Path, destination: &Path) -> io::Result<()> {
1974    fs::rename(temporary, destination)
1975}
1976
1977#[cfg(windows)]
1978fn replace_file_atomic(temporary: &Path, destination: &Path) -> io::Result<()> {
1979    use std::iter;
1980    use std::os::windows::ffi::OsStrExt as _;
1981    use windows_sys::Win32::Storage::FileSystem::{
1982        MoveFileExW, MOVE_FILE_REPLACE_EXISTING, MOVE_FILE_WRITE_THROUGH,
1983    };
1984
1985    let temporary = temporary
1986        .as_os_str()
1987        .encode_wide()
1988        .chain(iter::once(0))
1989        .collect::<Vec<_>>();
1990    let destination = destination
1991        .as_os_str()
1992        .encode_wide()
1993        .chain(iter::once(0))
1994        .collect::<Vec<_>>();
1995    let result = unsafe {
1996        MoveFileExW(
1997            temporary.as_ptr(),
1998            destination.as_ptr(),
1999            MOVE_FILE_REPLACE_EXISTING | MOVE_FILE_WRITE_THROUGH,
2000        )
2001    };
2002    if result == 0 {
2003        Err(io::Error::last_os_error())
2004    } else {
2005        Ok(())
2006    }
2007}
2008
2009#[cfg(unix)]
2010fn sync_directory(path: &Path) -> io::Result<()> {
2011    File::open(path)?.sync_all()
2012}
2013
2014#[cfg(not(unix))]
2015fn sync_directory(_path: &Path) -> io::Result<()> {
2016    // MoveFileExW uses MOVE_FILE_WRITE_THROUGH above. Other non-Unix targets
2017    // have no portable directory-sync primitive in std.
2018    Ok(())
2019}
2020
2021fn install_immutable(temporary: &Path, destination: &Path) -> Result<(), DescriptorCacheError> {
2022    match fs::symlink_metadata(destination) {
2023        Ok(metadata) if !metadata.file_type().is_file() => {
2024            let _ = fs::remove_file(temporary);
2025            return Err(DescriptorCacheError::UnsafeCacheEntry(
2026                destination.to_path_buf(),
2027            ));
2028        }
2029        Ok(_) => {}
2030        Err(source) if source.kind() == io::ErrorKind::NotFound => {}
2031        Err(source) => {
2032            let _ = fs::remove_file(temporary);
2033            return Err(DescriptorCacheError::ReadCacheFile {
2034                path: destination.to_path_buf(),
2035                source,
2036            });
2037        }
2038    }
2039    match fs::hard_link(temporary, destination) {
2040        Ok(()) => {
2041            fs::remove_file(temporary).map_err(|source| DescriptorCacheError::WriteCacheFile {
2042                path: temporary.to_path_buf(),
2043                source,
2044            })?;
2045            Ok(())
2046        }
2047        Err(source) if source.kind() == io::ErrorKind::AlreadyExists => {
2048            let equal = files_equal(temporary, destination)?;
2049            let _ = fs::remove_file(temporary);
2050            if equal {
2051                Ok(())
2052            } else {
2053                Err(DescriptorCacheError::ConflictingCacheEntry(
2054                    destination.to_path_buf(),
2055                ))
2056            }
2057        }
2058        Err(source) => Err(DescriptorCacheError::WriteCacheFile {
2059            path: destination.to_path_buf(),
2060            source,
2061        }),
2062    }
2063}
2064
2065fn files_equal(left: &Path, right: &Path) -> Result<bool, DescriptorCacheError> {
2066    let left_metadata =
2067        fs::metadata(left).map_err(|source| DescriptorCacheError::ReadCacheSource {
2068            path: left.to_path_buf(),
2069            source,
2070        })?;
2071    let right_metadata =
2072        fs::metadata(right).map_err(|source| DescriptorCacheError::ReadCacheSource {
2073            path: right.to_path_buf(),
2074            source,
2075        })?;
2076    if left_metadata.len() != right_metadata.len() {
2077        return Ok(false);
2078    }
2079    let mut left_file =
2080        File::open(left).map_err(|source| DescriptorCacheError::ReadCacheSource {
2081            path: left.to_path_buf(),
2082            source,
2083        })?;
2084    let mut right_file =
2085        File::open(right).map_err(|source| DescriptorCacheError::ReadCacheSource {
2086            path: right.to_path_buf(),
2087            source,
2088        })?;
2089    let mut left_buffer = [0_u8; 64 * 1024];
2090    let mut right_buffer = [0_u8; 64 * 1024];
2091    loop {
2092        let left_read = left_file.read(&mut left_buffer).map_err(|source| {
2093            DescriptorCacheError::ReadCacheSource {
2094                path: left.to_path_buf(),
2095                source,
2096            }
2097        })?;
2098        let right_read = right_file.read(&mut right_buffer).map_err(|source| {
2099            DescriptorCacheError::ReadCacheSource {
2100                path: right.to_path_buf(),
2101                source,
2102            }
2103        })?;
2104        if left_read != right_read || left_buffer[..left_read] != right_buffer[..right_read] {
2105            return Ok(false);
2106        }
2107        if left_read == 0 {
2108            return Ok(true);
2109        }
2110    }
2111}
2112
2113fn canonical_json(value: &Value) -> Vec<u8> {
2114    fn write(value: &Value, output: &mut Vec<u8>) {
2115        match value {
2116            Value::Null => output.extend_from_slice(b"n"),
2117            Value::Bool(value) => {
2118                output.extend_from_slice(if *value { b"t" } else { b"f" });
2119            }
2120            Value::Number(value) => {
2121                output.extend_from_slice(b"d");
2122                output.extend_from_slice(value.to_string().as_bytes());
2123                output.push(0);
2124            }
2125            Value::String(value) => {
2126                output.extend_from_slice(b"s");
2127                output.extend_from_slice(&(value.len() as u64).to_be_bytes());
2128                output.extend_from_slice(value.as_bytes());
2129            }
2130            Value::Array(values) => {
2131                output.extend_from_slice(b"a");
2132                output.extend_from_slice(&(values.len() as u64).to_be_bytes());
2133                for value in values {
2134                    write(value, output);
2135                }
2136            }
2137            Value::Object(values) => {
2138                output.extend_from_slice(b"o");
2139                output.extend_from_slice(&(values.len() as u64).to_be_bytes());
2140                let mut keys = values.keys().collect::<Vec<_>>();
2141                keys.sort();
2142                for key in keys {
2143                    output.extend_from_slice(&(key.len() as u64).to_be_bytes());
2144                    output.extend_from_slice(key.as_bytes());
2145                    write(&values[key], output);
2146                }
2147            }
2148        }
2149    }
2150
2151    let mut output = Vec::new();
2152    write(value, &mut output);
2153    output
2154}
2155
2156struct CacheHasher(Sha256);
2157
2158impl CacheHasher {
2159    fn new(domain: &[u8]) -> Self {
2160        let mut hash = Sha256::new();
2161        hash.update((domain.len() as u64).to_be_bytes());
2162        hash.update(domain);
2163        Self(hash)
2164    }
2165
2166    fn field(&mut self, name: &str, value: &[u8]) {
2167        self.0.update((name.len() as u64).to_be_bytes());
2168        self.0.update(name.as_bytes());
2169        self.0.update((value.len() as u64).to_be_bytes());
2170        self.0.update(value);
2171    }
2172
2173    fn set<'a>(&mut self, name: &str, values: impl IntoIterator<Item = &'a [u8]>) {
2174        let values = values.into_iter().collect::<Vec<_>>();
2175        self.field(&format!("{name}:len"), &(values.len() as u64).to_be_bytes());
2176        for value in values {
2177            self.field(name, value);
2178        }
2179    }
2180
2181    fn path(&mut self, name: &str, path: &Path) -> Result<(), DescriptorCacheError> {
2182        let path = path
2183            .to_str()
2184            .ok_or_else(|| DescriptorCacheError::NonUtf8CargoPath(path.to_path_buf()))?;
2185        self.field(name, path.as_bytes());
2186        Ok(())
2187    }
2188
2189    fn finish(self) -> String {
2190        encode_digest(&self.0.finalize().into())
2191    }
2192}
2193
2194fn encode_digest(digest: &[u8; 32]) -> String {
2195    use std::fmt::Write as _;
2196
2197    let mut output = String::with_capacity(64);
2198    for byte in digest {
2199        let _ = write!(output, "{byte:02x}");
2200    }
2201    output
2202}
2203
2204/// Kind of immutable per-unit cache file.
2205#[derive(Clone, Copy, Debug)]
2206pub enum CacheUnitFileKind {
2207    /// JSON unit sidecar.
2208    Sidecar,
2209    /// Exact descriptor object.
2210    Object,
2211}
2212
2213impl std::fmt::Display for CacheUnitFileKind {
2214    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2215        match self {
2216            Self::Sidecar => formatter.write_str("sidecar"),
2217            Self::Object => formatter.write_str("object"),
2218        }
2219    }
2220}
2221
2222/// Fail-closed descriptor-cache error.
2223#[derive(Debug, Error)]
2224pub enum DescriptorCacheError {
2225    /// Cache identity must not depend on the caller's current directory.
2226    #[error("descriptor cache directory must be absolute: `{0}`")]
2227    RelativeCacheDirectory(PathBuf),
2228    /// Every managed directory must use an absolute deletion-safe identity.
2229    #[error("descriptor {kind} directory must be absolute: `{path}`")]
2230    RelativeManagedDirectory {
2231        /// Directory role.
2232        kind: &'static str,
2233        /// Rejected path.
2234        path: PathBuf,
2235    },
2236    /// Symlinks and lexical aliases are resolved before overlap checks.
2237    #[error("failed to normalize descriptor managed directory `{path}`: {source}")]
2238    NormalizeManagedDirectory {
2239        /// Caller path.
2240        path: PathBuf,
2241        /// Canonicalization failure.
2242        #[source]
2243        source: io::Error,
2244    },
2245    /// Cache, staging, and descriptor target are exact disjoint roots.
2246    #[error("descriptor {first_kind} `{first}` and {second_kind} `{second}` must not overlap")]
2247    OverlappingManagedDirectories {
2248        /// First role.
2249        first_kind: &'static str,
2250        /// First normalized path.
2251        first: PathBuf,
2252        /// Second role.
2253        second_kind: &'static str,
2254        /// Second normalized path.
2255        second: PathBuf,
2256    },
2257    /// Recovery roots may never contain the Cargo working directory.
2258    #[error(
2259        "descriptor {kind} recovery root `{managed}` would contain working directory `{working}`"
2260    )]
2261    UnsafeManagedDirectory {
2262        /// Managed role.
2263        kind: &'static str,
2264        /// Candidate deletion root.
2265        managed: PathBuf,
2266        /// Cargo working directory.
2267        working: PathBuf,
2268    },
2269    /// The exact descriptor target must be within the phase-invariant generated root.
2270    #[error("descriptor target `{target}` is outside source exclusion `{exclusion}`")]
2271    TargetOutsideSourceExclusion {
2272        /// Exact target.
2273        target: PathBuf,
2274        /// Exact generated root.
2275        exclusion: PathBuf,
2276    },
2277    /// Excluding an ancestor of the package would erase actual source inputs.
2278    #[error(
2279        "descriptor source exclusion `{exclusion}` would contain working directory `{working}`"
2280    )]
2281    UnsafeSourceExclusion {
2282        /// Exact generated root.
2283        exclusion: PathBuf,
2284        /// Cargo working directory.
2285        working: PathBuf,
2286    },
2287    /// In-package cache state must live beneath the one exact excluded subtree.
2288    #[error("descriptor {kind} `{path}` must be inside in-package source exclusion `{exclusion}`")]
2289    GeneratedStateOutsideSourceExclusion {
2290        /// Managed role.
2291        kind: &'static str,
2292        /// Managed path.
2293        path: PathBuf,
2294        /// Exact excluded subtree.
2295        exclusion: PathBuf,
2296    },
2297    /// Persistent cache layout could not be created.
2298    #[error("failed to create descriptor cache directory `{path}`: {source}")]
2299    CreateCacheDirectory {
2300        /// Directory.
2301        path: PathBuf,
2302        /// I/O failure.
2303        #[source]
2304        source: io::Error,
2305    },
2306    /// Cache and lock namespaces must not be redirected by symlinks/special files.
2307    #[error("descriptor cache entry is not a plain regular file/directory: `{0}`")]
2308    UnsafeCacheEntry(PathBuf),
2309    /// Per-cache generation lock could not be opened.
2310    #[error("failed to open descriptor cache lock `{path}`: {source}")]
2311    OpenCacheLock {
2312        /// Exact lock path.
2313        path: PathBuf,
2314        /// I/O failure.
2315        #[source]
2316        source: io::Error,
2317    },
2318    /// Another process owns this cache generation until the OS lock releases.
2319    #[error("failed to acquire descriptor cache lock `{path}`: {source}")]
2320    AcquireCacheLock {
2321        /// Exact lock path.
2322        path: PathBuf,
2323        /// I/O failure.
2324        #[source]
2325        source: io::Error,
2326    },
2327    /// The crash marker itself may not be redirected through a symlink.
2328    #[error("descriptor cache dirty marker is not a regular file: `{0}`")]
2329    InvalidDirtyMarker(PathBuf),
2330    /// A dirty cache cannot authorize deletion of another target namespace.
2331    #[error(
2332        "descriptor cache dirty marker belongs to target `{actual}`, not requested target `{expected}`"
2333    )]
2334    DirtyTargetMismatch {
2335        /// Current request target.
2336        expected: PathBuf,
2337        /// Interrupted target.
2338        actual: PathBuf,
2339    },
2340    /// Rebinding a normalized journal path to the request's lexical source
2341    /// exclusion must preserve its exact filesystem identity.
2342    #[error(
2343        "descriptor cache dirty staging path resolves to `{actual}`, not journaled `{expected}`"
2344    )]
2345    DirtyStagingMismatch {
2346        /// Journaled canonical staging identity.
2347        expected: PathBuf,
2348        /// Request-spelled staging identity.
2349        actual: PathBuf,
2350    },
2351    /// Recovery requires a Cargo run in the freshly recreated target.
2352    #[error("descriptor cache recovery did not force every Cargo artifact to rebuild")]
2353    RecoveryDidNotFullyRebuild,
2354    /// Recovery deletion is allowed only for a marker-proven target.
2355    #[error("refusing to reset unowned descriptor target `{0}`")]
2356    UnownedRecoveryTarget(PathBuf),
2357    /// Staging deletion requires its own runner-written marker.
2358    #[error("refusing to reset unowned descriptor staging directory `{0}`")]
2359    UnownedRecoveryStaging(PathBuf),
2360    /// Target marker inspection failed.
2361    #[error("failed to read descriptor target ownership marker in `{path}`: {source}")]
2362    ReadDescriptorTargetMarker {
2363        /// Exact target.
2364        path: PathBuf,
2365        /// I/O failure.
2366        #[source]
2367        source: io::Error,
2368    },
2369    /// Staging ownership marker inspection failed.
2370    #[error("failed to read descriptor staging ownership marker in `{path}`: {source}")]
2371    ReadDescriptorStagingMarker {
2372        /// Exact staging root.
2373        path: PathBuf,
2374        /// I/O failure.
2375        #[source]
2376        source: io::Error,
2377    },
2378    /// A recovery path was replaced with a file or symlink.
2379    #[error("refusing to remove non-directory descriptor {kind} recovery path `{path}`")]
2380    UnsafeRecoveryDirectory {
2381        /// Managed role.
2382        kind: &'static str,
2383        /// Exact path.
2384        path: PathBuf,
2385    },
2386    /// Exact request-owned recovery state could not be removed.
2387    #[error("failed to remove descriptor {kind} recovery directory `{path}`: {source}")]
2388    RemoveRecoveryDirectory {
2389        /// Managed role.
2390        kind: &'static str,
2391        /// Exact path.
2392        path: PathBuf,
2393        /// I/O failure.
2394        #[source]
2395        source: io::Error,
2396    },
2397    /// Descriptor Cargo run failed.
2398    #[error(transparent)]
2399    DescriptorCargo(DescriptorCargoRunError),
2400    /// A current Cargo-enumerated input could not be hashed.
2401    #[error("failed to hash current Cargo input `{path}`: {source}")]
2402    HashCurrentInput {
2403        /// Exact current path.
2404        path: PathBuf,
2405        /// I/O failure.
2406        #[source]
2407        source: io::Error,
2408    },
2409    /// Two descriptor rustc invocations observed different bytes at one exact
2410    /// Cargo artifact path.
2411    #[error(
2412        "descriptor sidecars disagree about Cargo artifact `{path}`: unit {unit} extern `{extern_name}` reports `{second}`, but another unit reports `{first}`"
2413    )]
2414    ConflictingSidecarArtifactEvidence {
2415        /// Exact host-local Cargo path.
2416        path: PathBuf,
2417        /// First wrapper-time descriptor-domain hash.
2418        first: String,
2419        /// Conflicting wrapper-time descriptor-domain hash.
2420        second: String,
2421        /// Unit contributing the conflict.
2422        unit: DescriptorCargoUnitId,
2423        /// Extern contributing the conflict.
2424        extern_name: String,
2425    },
2426    /// Cargo paths originate in JSON and must remain exact UTF-8 strings.
2427    #[error("current Cargo artifact path is not UTF-8: `{0}`")]
2428    NonUtf8CargoPath(PathBuf),
2429    /// Two current artifacts collapsed to one deterministic Cargo coordinate.
2430    #[error("current Cargo artifacts have duplicate coordinate `{0}`")]
2431    DuplicateArtifactCoordinate(String),
2432    /// A joined artifact unexpectedly disappeared from current evidence.
2433    #[error("joined Cargo artifact is absent from current artifact evidence")]
2434    ArtifactMissingFromCurrentEvidence,
2435    /// Current Cargo messages contained indistinguishable artifacts.
2436    #[error("joined Cargo artifact has ambiguous current evidence")]
2437    AmbiguousCurrentArtifactEvidence,
2438    /// Multiple fresh units cannot own one Cargo artifact.
2439    #[error("current artifact `{coordinate}` joined fresh units {first} and {second}")]
2440    MultipleFreshUnitsForArtifact {
2441        /// Current artifact coordinate.
2442        coordinate: String,
2443        /// First fresh unit.
2444        first: DescriptorCargoUnitId,
2445        /// Second fresh unit.
2446        second: DescriptorCargoUnitId,
2447    },
2448    /// No-op recovery requires the exact prior complete artifact-set snapshot.
2449    #[error("descriptor cache has no exact snapshot for current artifact set `{coordinate}`")]
2450    MissingArtifactSetSnapshot {
2451        /// Exact current artifact-set coordinate.
2452        coordinate: String,
2453    },
2454    /// A fresh Cargo artifact has no explicit positive or negative cache index.
2455    #[error("descriptor cache has no index for fresh Cargo artifact `{coordinate}`")]
2456    MissingArtifactIndex {
2457        /// Exact current artifact coordinate.
2458        coordinate: String,
2459    },
2460    /// A rebuilt artifact emitted no fresh wrapper unit.
2461    #[error("rebuilt Cargo artifact `{coordinate}` emitted no fresh descriptor wrapper unit")]
2462    RebuiltArtifactMissingFreshUnit {
2463        /// Exact artifact coordinate.
2464        coordinate: String,
2465    },
2466    /// Interrupted staging is authoritative only when its unit joins an exact
2467    /// artifact from the recovery Cargo invocation.
2468    #[error("interrupted descriptor recovery unit {0} has no exact current Cargo artifact")]
2469    InterruptedUnitMissingArtifact(DescriptorCargoUnitId),
2470    /// Two recovery attempts claimed the same unit with different validated
2471    /// sidecar content, so neither is preferred implicitly.
2472    #[error("interrupted descriptor recovery has conflicting candidates for unit {0}")]
2473    ConflictingInterruptedUnitCandidates(DescriptorCargoUnitId),
2474    /// Corrupt cache JSON.
2475    #[error("failed to parse descriptor cache file `{path}`: {source}")]
2476    ParseCacheFile {
2477        /// Cache record.
2478        path: PathBuf,
2479        /// JSON failure.
2480        #[source]
2481        source: serde_json::Error,
2482    },
2483    /// Cache file read failed.
2484    #[error("failed to read descriptor cache file `{path}`: {source}")]
2485    ReadCacheFile {
2486        /// Cache record.
2487        path: PathBuf,
2488        /// I/O failure.
2489        #[source]
2490        source: io::Error,
2491    },
2492    /// Cache schema mismatch.
2493    #[error("descriptor cache file `{path}` uses schema {actual}; expected {expected}")]
2494    UnsupportedCacheSchema {
2495        /// Cache record.
2496        path: PathBuf,
2497        /// Actual schema.
2498        actual: u16,
2499        /// Required schema.
2500        expected: u16,
2501    },
2502    /// A cached wrapper sidecar uses another wrapper schema.
2503    #[error("cached descriptor sidecar `{path}` uses schema {actual}; expected {expected}")]
2504    CachedSidecarSchemaMismatch {
2505        /// Cached sidecar.
2506        path: PathBuf,
2507        /// Actual schema.
2508        actual: u16,
2509        /// Required schema.
2510        expected: u16,
2511    },
2512    /// Cache filename/unit selection and sidecar identity diverged.
2513    #[error("cached descriptor sidecar for unit {unit} reports unit `{actual}`")]
2514    CachedSidecarUnitMismatch {
2515        /// Cache-selected unit.
2516        unit: DescriptorCargoUnitId,
2517        /// Sidecar unit text.
2518        actual: String,
2519    },
2520    /// A cached sidecar points outside its exact content-addressed object slot.
2521    #[error(
2522        "cached descriptor sidecar for unit {unit} reports object `{actual}`; expected `{expected}`"
2523    )]
2524    CachedSidecarObjectPathMismatch {
2525        /// Cache-selected unit.
2526        unit: DescriptorCargoUnitId,
2527        /// Sidecar path.
2528        actual: String,
2529        /// Required path.
2530        expected: String,
2531    },
2532    /// Coordinate-addressed filename and record diverged.
2533    #[error("descriptor cache file `{path}` reports coordinate `{actual}`; expected `{expected}`")]
2534    CacheCoordinateMismatch {
2535        /// Cache record.
2536        path: PathBuf,
2537        /// Filename-derived identity.
2538        expected: String,
2539        /// Payload identity.
2540        actual: String,
2541    },
2542    /// Exact snapshot lists another artifact set.
2543    #[error("descriptor cache snapshot `{0}` does not list the current artifact set")]
2544    SnapshotArtifactSetMismatch(PathBuf),
2545    /// Unit ID text in cache is malformed.
2546    #[error("descriptor cache file `{path}` has an invalid unit ID: {source}")]
2547    InvalidCachedUnitId {
2548        /// Cache record.
2549        path: PathBuf,
2550        /// ID parser.
2551        #[source]
2552        source: crate::rsjs::build::WrapperError,
2553    },
2554    /// Generation pointers contain only exact lowercase content hashes.
2555    #[error("descriptor cache file `{path}` has invalid {field} `{value}`: {reason}")]
2556    InvalidCachedGenerationHash {
2557        /// Pointer record.
2558        path: PathBuf,
2559        /// Hash field.
2560        field: &'static str,
2561        /// Rejected value.
2562        value: String,
2563        /// Validation detail.
2564        reason: String,
2565    },
2566    /// Cache record repeats a unit.
2567    #[error("descriptor cache file `{path}` repeats unit {unit}")]
2568    DuplicateCachedUnit {
2569        /// Cache record.
2570        path: PathBuf,
2571        /// Duplicate.
2572        unit: DescriptorCargoUnitId,
2573    },
2574    /// One unit cannot be authorized by two current artifacts.
2575    #[error("cached unit {unit} is claimed by current artifacts `{first}` and `{second}`")]
2576    CachedUnitClaimedByMultipleArtifacts {
2577        /// Unit.
2578        unit: DescriptorCargoUnitId,
2579        /// First artifact.
2580        first: String,
2581        /// Second artifact.
2582        second: String,
2583    },
2584    /// Explicitly indexed cache bytes are gone.
2585    #[error("cached unit {unit} {kind} is missing at `{path}`")]
2586    MissingCachedUnitFile {
2587        /// Unit.
2588        unit: DescriptorCargoUnitId,
2589        /// File role.
2590        kind: CacheUnitFileKind,
2591        /// Exact cache path.
2592        path: PathBuf,
2593    },
2594    /// Fresh and cached staging did not contain an authorized unit.
2595    #[error("merged descriptor staging omitted authorized unit {0}")]
2596    MissingMergedUnit(DescriptorCargoUnitId),
2597    /// One materialized unit cannot have two verified object hashes.
2598    #[error(
2599        "descriptor unit {unit} has conflicting prevalidated object hashes `{first}` and `{second}`"
2600    )]
2601    ConflictingPrevalidatedObjectHash {
2602        /// Materialized unit.
2603        unit: DescriptorCargoUnitId,
2604        /// First verified hash.
2605        first: String,
2606        /// Conflicting verified hash.
2607        second: String,
2608    },
2609    /// One logical Cargo unit cannot select two cache generations at once.
2610    #[error("descriptor unit {unit} has conflicting cache generations `{first}` and `{second}`")]
2611    ConflictingCachedGeneration {
2612        /// Logical unit.
2613        unit: DescriptorCargoUnitId,
2614        /// First exact generation.
2615        first: String,
2616        /// Second exact generation.
2617        second: String,
2618    },
2619    /// Every merged sidecar must have a committed immutable generation.
2620    #[error("descriptor unit {0} has no committed cache generation")]
2621    MissingCachedGeneration(DescriptorCargoUnitId),
2622    /// Pointer and sidecar must agree on the immutable object blob.
2623    #[error(
2624        "cached descriptor unit {unit} pointer requires object hash `{pointer}`, but sidecar reports `{sidecar}`"
2625    )]
2626    CachedGenerationObjectHashMismatch {
2627        /// Logical unit.
2628        unit: DescriptorCargoUnitId,
2629        /// Pointer hash.
2630        pointer: String,
2631        /// Sidecar hash.
2632        sidecar: String,
2633    },
2634    /// Immutable sidecar bytes must match their generation address.
2635    #[error(
2636        "cached descriptor sidecar for unit {unit} has hash `{actual}`; expected `{expected}`"
2637    )]
2638    CachedSidecarHashMismatch {
2639        /// Logical unit.
2640        unit: DescriptorCargoUnitId,
2641        /// Generation address.
2642        expected: String,
2643        /// Actual exact bytes.
2644        actual: String,
2645    },
2646    /// A content-addressed sidecar failed the wrapper protocol's semantic
2647    /// validation before its cache object was admitted to the linker.
2648    #[error("cached descriptor sidecar for unit {unit} at `{path}` is invalid: {reason}")]
2649    InvalidCachedSidecar {
2650        /// Logical unit.
2651        unit: DescriptorCargoUnitId,
2652        /// Exact immutable sidecar path.
2653        path: PathBuf,
2654        /// Value-redacted validation detail.
2655        reason: String,
2656    },
2657    /// A cached unit's rustc-declared generated-source inputs changed or are
2658    /// no longer safe beneath the persistent descriptor target.
2659    #[error("cached descriptor unit {unit} OUT_DIR dependency validation failed: {source}")]
2660    CachedOutDirDependencyMismatch {
2661        /// Cached unit.
2662        unit: DescriptorCargoUnitId,
2663        /// Exact generated-input validation failure.
2664        #[source]
2665        source: crate::rsjs::build::WrapperError,
2666    },
2667    /// Cached unit points at a dependency absent from current Cargo artifacts.
2668    #[error(
2669        "cached descriptor unit {unit} extern `{extern_name}` path `{path}` is absent from current Cargo artifacts"
2670    )]
2671    CachedDependencyNotEnumerated {
2672        /// Cached unit.
2673        unit: DescriptorCargoUnitId,
2674        /// Extern.
2675        extern_name: String,
2676        /// Exact wrapper-time path.
2677        path: PathBuf,
2678    },
2679    /// One exact dependency path must belong to one Cargo artifact message.
2680    #[error(
2681        "cached descriptor unit {unit} extern `{extern_name}` path `{path}` matches {matches} current Cargo artifacts"
2682    )]
2683    AmbiguousCachedDependencyArtifact {
2684        /// Cached unit.
2685        unit: DescriptorCargoUnitId,
2686        /// Extern.
2687        extern_name: String,
2688        /// Exact wrapper-time path.
2689        path: PathBuf,
2690        /// Matching Cargo messages.
2691        matches: usize,
2692    },
2693    /// Cached dependency bytes changed after the wrapper observed them.
2694    #[error(
2695        "cached descriptor unit {unit} extern `{extern_name}` path `{path}` has hash `{actual}`; expected `{expected}`"
2696    )]
2697    StaleCachedDependency {
2698        /// Unit.
2699        unit: DescriptorCargoUnitId,
2700        /// Extern.
2701        extern_name: String,
2702        /// Exact wrapper-time path.
2703        path: PathBuf,
2704        /// Wrapper-time exact input hash.
2705        expected: String,
2706        /// Current exact input hash.
2707        actual: String,
2708    },
2709    /// Artifact-specific index did not join back to that exact current artifact.
2710    #[error(
2711        "cached unit {unit} joined current artifact `{actual}` instead of indexed artifact `{expected}`"
2712    )]
2713    CachedArtifactJoinMismatch {
2714        /// Unit.
2715        unit: DescriptorCargoUnitId,
2716        /// Index expectation.
2717        expected: String,
2718        /// Actual current join.
2719        actual: String,
2720    },
2721    /// Merged sidecars/objects failed existing strict validation.
2722    #[error(transparent)]
2723    MergedSidecars(DescriptorSidecarError),
2724    /// Sidecar/Cargo join failed.
2725    #[error(transparent)]
2726    ArtifactJoin(UnitArtifactJoinError),
2727    /// Cache record serialization failed.
2728    #[error("failed to serialize descriptor cache record: {0}")]
2729    SerializeCacheRecord(serde_json::Error),
2730    /// Cached object's exact bytes disagree with its sidecar.
2731    #[error("descriptor object for unit {unit} has hash `{actual}`; expected `{expected}`")]
2732    DescriptorObjectHashMismatch {
2733        /// Unit.
2734        unit: DescriptorCargoUnitId,
2735        /// Sidecar.
2736        expected: String,
2737        /// Current bytes.
2738        actual: String,
2739    },
2740    /// Cache path has no parent.
2741    #[error("descriptor cache path has no parent: `{0}`")]
2742    CachePathWithoutParent(PathBuf),
2743    /// Cache filename cannot support an atomic temporary sibling.
2744    #[error("descriptor cache path has an invalid filename: `{0}`")]
2745    InvalidCacheFilename(PathBuf),
2746    /// Source bytes for an atomic cache copy could not be read.
2747    #[error("failed to read descriptor cache source `{path}`: {source}")]
2748    ReadCacheSource {
2749        /// Source.
2750        path: PathBuf,
2751        /// I/O failure.
2752        #[source]
2753        source: io::Error,
2754    },
2755    /// Atomic cache write failed.
2756    #[error("failed to atomically write descriptor cache file `{path}`: {source}")]
2757    WriteCacheFile {
2758        /// Destination/temporary.
2759        path: PathBuf,
2760        /// I/O failure.
2761        #[source]
2762        source: io::Error,
2763    },
2764    /// Immutable content address already contains different bytes.
2765    #[error("descriptor cache content address already contains different bytes: `{0}`")]
2766    ConflictingCacheEntry(PathBuf),
2767}
2768
2769#[cfg(test)]
2770mod tests;