Skip to main content

ic_build/artifacts/
transaction.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    ffi::{OsStr, OsString},
4    fmt::Write as _,
5    fs::{self, File},
6    io,
7    path::{Path, PathBuf},
8    sync::atomic::{AtomicU64, Ordering},
9    time::{Duration, Instant},
10};
11
12use super::{
13    cache_fs::{
14        ArtifactCacheMaintenance, ArtifactCachePrunePolicy, ArtifactCachePruneReport, CacheFsError,
15        LAST_USED_FILE, RetainedCacheEntry, canonicalize_allow_missing, directory_logical_size,
16        ensure_cache_directory_tag, is_sha256_directory, lock_cache_file,
17        perform_scheduled_cache_maintenance, prune_direct_child_directories,
18        record_cache_entry_use, remove_path_if_present, remove_unretained_entry,
19        try_lock_cache_file,
20    },
21    digest::{
22        FileDigest, InputDigest, InputHasher, copy_file_atomic, digest_bytes, digest_file,
23        digest_labeled_paths, materialize_verified_output, os_bytes, read_file_with_limit,
24    },
25    staging::OwnedDirectory,
26    wasm_cache::{
27        ResolvedCargoBuildInputs, WasmBuildError, WasmBuildSpec, resolve_cargo_build_inputs,
28    },
29};
30
31const ARTIFACT_CACHE_FORMAT: &str = "ic-testkit-artifact-set-v1";
32const MANIFEST_FILE: &str = "manifest.ic-testkit";
33const OUTPUT_FILE_SUFFIX: &str = ".artifact";
34const MAX_PREPARATION_RETRIES: usize = 3;
35static STAGING_SEQUENCE: AtomicU64 = AtomicU64::new(0);
36
37/// Built-in validation applied to one transactional artifact output.
38#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
39pub enum ArtifactOutputValidation {
40    /// Require a regular file; an empty file is valid.
41    RegularFile,
42    /// Require a nonempty regular file.
43    #[default]
44    NonEmptyFile,
45}
46
47/// Complete caller-owned description of one transactional artifact set.
48///
49/// Declared inputs and tools must not be located inside `cache_root`. Output
50/// destinations must remain outside it, resolve to distinct non-nested paths,
51/// and not overlap a declared input or tool. Cargo-derived cache/output paths must
52/// likewise remain outside resolved inputs unless covered by their exact
53/// generated-state exclusions.
54#[derive(Clone, Eq, PartialEq)]
55pub struct ArtifactCacheSpec {
56    cache_root: PathBuf,
57    namespace: String,
58    recipe_id: String,
59    coordination_scope: String,
60    inputs: Vec<LabeledPath>,
61    tools: Vec<LabeledPath>,
62    arguments: Vec<OsString>,
63    environment: BTreeMap<OsString, Option<OsString>>,
64    // Builders keep label/name order canonical; duplicates remain for validation.
65    identities: Vec<LabeledIdentity>,
66    cargo_build_inputs: Vec<CargoBuildInputSet>,
67    outputs: Vec<OutputSpec>,
68    prune_policy: Option<ArtifactCachePrunePolicy>,
69    prune_interval: Option<Duration>,
70}
71
72/// Result of preparing a transactional artifact-set acquisition.
73pub enum ArtifactCachePreparation {
74    /// A complete verified entry was materialized without running the caller's build.
75    Reused(ArtifactCacheRecord),
76    /// The caller must populate and commit a transaction-owned staging directory.
77    Build(ArtifactBuildTransaction),
78}
79
80/// Whether an artifact transaction published or reused its exact output set.
81#[derive(Clone, Debug, Eq, PartialEq)]
82pub enum ArtifactCacheOutcome {
83    /// The caller populated staging and the complete result was published.
84    Built(ArtifactCacheRecord),
85    /// A complete existing entry was verified and materialized.
86    Reused(ArtifactCacheRecord),
87}
88
89/// Details shared by built and reused transactional artifact outcomes.
90#[derive(Clone, Debug, Eq, PartialEq)]
91pub struct ArtifactCacheRecord {
92    key: InputDigest,
93    input_digest: InputDigest,
94    artifacts: Vec<ArtifactCacheArtifact>,
95    _retention: RetainedCacheEntry,
96    timings: ArtifactCacheTimings,
97    maintenance: Option<ArtifactCacheMaintenance>,
98}
99
100/// One read-only exact artifact retained by its owning acquisition record.
101#[derive(Clone, Debug, Eq, PartialEq)]
102pub struct ArtifactCacheArtifact {
103    name: String,
104    path: PathBuf,
105}
106
107/// Phase timings for one transactional artifact-cache acquisition.
108#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
109pub struct ArtifactCacheTimings {
110    coordination_lock_wait: Duration,
111    content_lock_wait: Duration,
112    namespace_lock_wait: Duration,
113    input_capture: Duration,
114    cache_lookup: Duration,
115    caller_build: Option<Duration>,
116    output_validation: Duration,
117    publication: Duration,
118    materialization: Duration,
119    maintenance: Option<Duration>,
120    total: Duration,
121}
122
123/// Owned miss transaction holding the recipe and content-key process locks.
124pub struct ArtifactBuildTransaction {
125    spec: Box<ArtifactCacheSpec>,
126    resolved: ResolvedKey,
127    // Drop the owned staging child before releasing either process lock below.
128    staging_directory: OwnedDirectory,
129    entry_directory: PathBuf,
130    namespace_directory: PathBuf,
131    _coordination_lock: File,
132    _content_lock: File,
133    timings: ArtifactCacheTimings,
134    total_started: Instant,
135    caller_build_started: Instant,
136}
137
138/// Structured failure from transactional artifact caching.
139#[non_exhaustive]
140#[derive(Debug)]
141pub enum ArtifactCacheError {
142    /// The caller supplied an incomplete, ambiguous, or unsafe specification.
143    InvalidSpec {
144        /// Diagnostic describing the rejected input or evidence.
145        message: String,
146    },
147    /// A filesystem operation failed.
148    Io {
149        /// Filesystem or process operation that failed.
150        operation: &'static str,
151        /// Exact path involved in the failed operation.
152        path: PathBuf,
153        /// Original underlying error, including its typed failure evidence.
154        source: io::Error,
155    },
156    /// Inputs repeatedly changed while preparing a stable cache acquisition.
157    InputsChangedDuringPreparation {
158        /// Input identity captured before the operation.
159        before: InputDigest,
160        /// Input identity observed during revalidation.
161        after: InputDigest,
162    },
163    /// Inputs changed while the caller owned a build transaction.
164    InputsChangedDuringAcquisition {
165        /// Input identity captured before the operation.
166        before: InputDigest,
167        /// Input identity observed during revalidation.
168        after: InputDigest,
169    },
170    /// A resolved Cargo source/configuration set changed after it was captured.
171    CargoBuildInputsChanged {
172        /// Caller-selected logical input-set label.
173        label: String,
174        /// Semantic Cargo fingerprint or conservative validation digest captured.
175        before: InputDigest,
176        /// Semantic fingerprint or conservative validation digest revalidated.
177        after: InputDigest,
178    },
179    /// Rehashing a resolved Cargo input set failed.
180    CargoBuildInputRevalidation {
181        /// Caller-selected logical input-set label.
182        label: String,
183        /// Underlying exact Cargo input error.
184        source: WasmBuildError,
185    },
186    /// One or more declared staged outputs were missing or failed validation.
187    InvalidOutputs {
188        /// Logical names and paths of outputs that failed validation.
189        outputs: Vec<(String, PathBuf)>,
190    },
191    /// A logical output name was not declared by the transaction specification.
192    UnknownOutput {
193        /// Undeclared logical output name.
194        name: String,
195    },
196    /// Transaction failure cleanup also failed.
197    FailedTransactionCleanup {
198        /// Original transaction error before cleanup was attempted.
199        transaction_error: Box<Self>,
200        /// Exact path involved in the failed operation.
201        path: PathBuf,
202        /// Original underlying error, including its typed failure evidence.
203        source: io::Error,
204    },
205}
206
207#[derive(Clone, Debug, Eq, PartialEq)]
208struct LabeledPath {
209    label: String,
210    path: PathBuf,
211}
212
213#[derive(Clone, Eq, PartialEq)]
214struct LabeledIdentity {
215    label: String,
216    value: Vec<u8>,
217}
218
219#[derive(Clone, Eq, PartialEq)]
220struct CargoBuildInputSet {
221    label: String,
222    build_spec: WasmBuildSpec,
223    resolved: ResolvedCargoBuildInputs,
224}
225
226#[derive(Clone, Debug, Eq, PartialEq)]
227struct OutputSpec {
228    name: String,
229    destination: PathBuf,
230    validation: ArtifactOutputValidation,
231}
232
233#[derive(Clone, Copy)]
234struct ResolvedKey {
235    key: InputDigest,
236    input_digest: InputDigest,
237}
238
239impl ArtifactCacheSpec {
240    /// Describe one external artifact recipe using non-secret stable identifiers.
241    ///
242    /// The namespace selects an independent content store. `recipe_id` must be
243    /// bumped whenever undeclared pipeline semantics change. The default
244    /// coordination scope is the namespace.
245    #[must_use]
246    pub fn new(cache_root: &Path, namespace: &str, recipe_id: &str) -> Self {
247        Self {
248            cache_root: cache_root.to_owned(),
249            namespace: namespace.to_owned(),
250            recipe_id: recipe_id.to_owned(),
251            coordination_scope: namespace.to_owned(),
252            inputs: Vec::new(),
253            tools: Vec::new(),
254            arguments: Vec::new(),
255            environment: BTreeMap::new(),
256            identities: Vec::new(),
257            cargo_build_inputs: Vec::new(),
258            outputs: Vec::new(),
259            prune_policy: None,
260            prune_interval: None,
261        }
262    }
263
264    /// Serialize recipes that share caller-owned mutable external build state.
265    #[must_use]
266    pub fn with_coordination_scope(mut self, coordination_scope: &str) -> Self {
267        coordination_scope.clone_into(&mut self.coordination_scope);
268        self
269    }
270
271    /// Add one exact input file or directory outside the cache root under a stable label.
272    #[must_use]
273    pub fn with_input(mut self, label: &str, path: &Path) -> Self {
274        self.inputs.push(LabeledPath {
275            label: label.to_owned(),
276            path: path.to_owned(),
277        });
278        self
279    }
280
281    /// Add one exact executable or tool path outside the cache root under a stable label.
282    #[must_use]
283    pub fn with_tool(mut self, label: &str, path: &Path) -> Self {
284        self.tools.push(LabeledPath {
285            label: label.to_owned(),
286            path: path.to_owned(),
287        });
288        self
289    }
290
291    /// Set OS-native ordered command arguments that contribute to the content key.
292    #[must_use]
293    pub fn with_arguments<I, S>(mut self, arguments: I) -> Self
294    where
295        I: IntoIterator<Item = S>,
296        S: AsRef<OsStr>,
297    {
298        self.arguments = arguments
299            .into_iter()
300            .map(|argument| argument.as_ref().to_owned())
301            .collect();
302        self
303    }
304
305    /// Set OS-native environment values that contribute to the content key.
306    ///
307    /// This records identity only. The caller must apply these values to the
308    /// external command executed on a cache miss.
309    #[must_use]
310    pub fn with_environment<I, K, V>(mut self, environment: I) -> Self
311    where
312        I: IntoIterator<Item = (K, V)>,
313        K: Into<OsString>,
314        V: Into<OsString>,
315    {
316        self.environment.extend(
317            environment
318                .into_iter()
319                .map(|(name, value)| (name.into(), Some(value.into()))),
320        );
321        self
322    }
323
324    /// Record OS-native environment names whose unset state contributes to the content key.
325    ///
326    /// The caller must also remove these names from the external command's
327    /// environment on a cache miss.
328    #[must_use]
329    pub fn with_unset_environment<I, S>(mut self, names: I) -> Self
330    where
331        I: IntoIterator<Item = S>,
332        S: Into<OsString>,
333    {
334        self.environment
335            .extend(names.into_iter().map(|name| (name.into(), None)));
336        self
337    }
338
339    /// Add opaque non-secret identity bytes under a stable logical label.
340    ///
341    /// Labels are stored in canonical order; declaration order does not affect identity.
342    #[must_use]
343    pub fn with_identity_bytes(mut self, label: &str, value: &[u8]) -> Self {
344        self.identities.push(LabeledIdentity {
345            label: label.to_owned(),
346            value: value.to_vec(),
347        });
348        self.identities
349            .sort_by(|left, right| left.label.cmp(&right.label));
350        self
351    }
352
353    /// Add one exact Cargo input snapshot as transactional cache identity and guard.
354    ///
355    /// The semantic resolved fingerprint keys toolchain, arguments,
356    /// environment and the selected dependency closure. Its conservative
357    /// Cargo-aware validation paths and exclusions are rehashed automatically
358    /// during preparation, cache-hit materialization and transaction commit.
359    /// Labels are stored in canonical order; declaration order does not affect identity.
360    #[must_use]
361    pub fn with_cargo_build_inputs(
362        mut self,
363        label: &str,
364        build_spec: &WasmBuildSpec,
365        resolved: &ResolvedCargoBuildInputs,
366    ) -> Self {
367        self.cargo_build_inputs.push(CargoBuildInputSet {
368            label: label.to_owned(),
369            build_spec: build_spec.clone(),
370            resolved: resolved.clone(),
371        });
372        self.cargo_build_inputs
373            .sort_by(|left, right| left.label.cmp(&right.label));
374        self
375    }
376
377    /// Declare one nonempty regular-file output and its nonoverlapping public destination.
378    #[must_use]
379    pub fn with_output(self, name: &str, destination: &Path) -> Self {
380        self.with_output_validation(name, destination, ArtifactOutputValidation::NonEmptyFile)
381    }
382
383    /// Declare one output, nonoverlapping public destination, and validation policy.
384    #[must_use]
385    pub fn with_output_validation(
386        mut self,
387        name: &str,
388        destination: &Path,
389        validation: ArtifactOutputValidation,
390    ) -> Self {
391        self.outputs.push(OutputSpec {
392            name: name.to_owned(),
393            destination: destination.to_owned(),
394            validation,
395        });
396        self.outputs
397            .sort_by(|left, right| left.name.cmp(&right.name));
398        self
399    }
400
401    /// Apply best-effort retention while protecting the acquired entry.
402    #[must_use]
403    pub const fn with_prune_policy(mut self, policy: ArtifactCachePrunePolicy) -> Self {
404        self.prune_policy = Some(policy);
405        self.prune_interval = None;
406        self
407    }
408
409    /// Apply retention at most once per `minimum_interval` for this namespace.
410    ///
411    /// The small due-marker check still occurs under the namespace lock.
412    /// Successful acquisitions skip the directory scan until the interval has
413    /// elapsed. The interval applies to attempted maintenance, including a
414    /// nonfatal failed attempt. A zero interval is equivalent to
415    /// [`Self::with_prune_policy`].
416    #[must_use]
417    pub const fn with_prune_policy_at_most_every(
418        mut self,
419        policy: ArtifactCachePrunePolicy,
420        minimum_interval: Duration,
421    ) -> Self {
422        self.prune_policy = Some(policy);
423        self.prune_interval = Some(minimum_interval);
424        self
425    }
426
427    /// Caller-selected root containing cache data and coordination locks.
428    #[must_use]
429    pub fn cache_root(&self) -> &Path {
430        &self.cache_root
431    }
432
433    /// Stable caller-owned content-store namespace.
434    #[must_use]
435    pub fn namespace(&self) -> &str {
436        &self.namespace
437    }
438
439    /// Stable caller-owned external recipe identity.
440    #[must_use]
441    pub fn recipe_id(&self) -> &str {
442        &self.recipe_id
443    }
444}
445
446impl std::fmt::Debug for ArtifactCacheSpec {
447    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448        formatter
449            .debug_struct("ArtifactCacheSpec")
450            .field("cache_root", &self.cache_root)
451            .field("namespace", &self.namespace)
452            .field("recipe_id", &self.recipe_id)
453            .field("coordination_scope", &self.coordination_scope)
454            .field("inputs", &self.inputs)
455            .field("tools", &self.tools)
456            .field("argument_count", &self.arguments.len())
457            .field(
458                "environment_names",
459                &self.environment.keys().collect::<Vec<_>>(),
460            )
461            .field(
462                "identity_labels",
463                &self
464                    .identities
465                    .iter()
466                    .map(|identity| identity.label.as_str())
467                    .collect::<Vec<_>>(),
468            )
469            .field(
470                "cargo_build_input_labels",
471                &self
472                    .cargo_build_inputs
473                    .iter()
474                    .map(|input| input.label.as_str())
475                    .collect::<Vec<_>>(),
476            )
477            .field("outputs", &self.outputs)
478            .field("prune_policy", &self.prune_policy)
479            .field("prune_interval", &self.prune_interval)
480            .finish()
481    }
482}
483
484impl ArtifactCachePreparation {
485    /// Return the already materialized record, or `None` for a cache miss transaction.
486    #[must_use]
487    pub const fn reused_record(&self) -> Option<&ArtifactCacheRecord> {
488        match self {
489            Self::Reused(record) => Some(record),
490            Self::Build(_) => None,
491        }
492    }
493}
494
495impl ArtifactCacheOutcome {
496    /// Read the common acquisition record.
497    #[must_use]
498    pub const fn record(&self) -> &ArtifactCacheRecord {
499        match self {
500            Self::Built(record) | Self::Reused(record) => record,
501        }
502    }
503
504    /// Report whether a complete matching artifact set was reused.
505    #[must_use]
506    pub const fn is_reused(&self) -> bool {
507        matches!(self, Self::Reused(_))
508    }
509}
510
511impl ArtifactCacheRecord {
512    /// Exact content key selecting the immutable cache entry.
513    #[must_use]
514    pub const fn key(&self) -> InputDigest {
515        self.key
516    }
517
518    /// Exact digest of declared input and tool paths.
519    #[must_use]
520    pub const fn input_digest(&self) -> InputDigest {
521        self.input_digest
522    }
523
524    /// Exact, read-only artifacts retained until this record and its clones drop.
525    ///
526    /// Keep a record alive while consuming these paths. Copying a path or an
527    /// artifact descriptor does not retain ownership. Configured materialization
528    /// destinations remain mutable and are not retained.
529    #[must_use]
530    pub fn artifacts(&self) -> &[ArtifactCacheArtifact] {
531        &self.artifacts
532    }
533
534    /// Phase timings for this acquisition.
535    #[must_use]
536    pub const fn timings(&self) -> ArtifactCacheTimings {
537        self.timings
538    }
539
540    /// Best-effort retention attempted during this acquisition, when configured.
541    #[must_use]
542    pub const fn maintenance(&self) -> Option<&ArtifactCacheMaintenance> {
543        self.maintenance.as_ref()
544    }
545}
546
547impl ArtifactCacheArtifact {
548    /// Stable logical output name.
549    #[must_use]
550    pub fn name(&self) -> &str {
551        &self.name
552    }
553
554    /// Exact cache path, valid while the acquisition record or a clone is alive.
555    #[must_use]
556    pub fn path(&self) -> &Path {
557        &self.path
558    }
559}
560
561impl ArtifactCacheTimings {
562    /// Time waiting for the caller-selected coordination scope.
563    #[must_use]
564    pub const fn coordination_lock_wait(self) -> Duration {
565        self.coordination_lock_wait
566    }
567
568    /// Time waiting for exact content-key ownership.
569    #[must_use]
570    pub const fn content_lock_wait(self) -> Duration {
571        self.content_lock_wait
572    }
573
574    /// Time waiting for short namespace mutations.
575    #[must_use]
576    pub const fn namespace_lock_wait(self) -> Duration {
577        self.namespace_lock_wait
578    }
579
580    /// Time spent hashing and verifying declared inputs.
581    #[must_use]
582    pub const fn input_capture(self) -> Duration {
583        self.input_capture
584    }
585
586    /// Time spent validating or rejecting a committed cache entry.
587    #[must_use]
588    pub const fn cache_lookup(self) -> Duration {
589        self.cache_lookup
590    }
591
592    /// Time the caller held a miss transaction before committing it.
593    #[must_use]
594    pub const fn caller_build(self) -> Option<Duration> {
595        self.caller_build
596    }
597
598    /// Time spent validating staged output files.
599    #[must_use]
600    pub const fn output_validation(self) -> Duration {
601        self.output_validation
602    }
603
604    /// Time spent publishing an immutable content entry.
605    #[must_use]
606    pub const fn publication(self) -> Duration {
607        self.publication
608    }
609
610    /// Time spent materializing caller-facing output destinations.
611    #[must_use]
612    pub const fn materialization(self) -> Duration {
613        self.materialization
614    }
615
616    /// Time spent on configured best-effort retention.
617    #[must_use]
618    pub const fn maintenance(self) -> Option<Duration> {
619        self.maintenance
620    }
621
622    /// Complete acquisition duration.
623    #[must_use]
624    pub const fn total(self) -> Duration {
625        self.total
626    }
627
628    pub(super) fn saturating_add(self, other: Self) -> Self {
629        Self {
630            coordination_lock_wait: self
631                .coordination_lock_wait
632                .saturating_add(other.coordination_lock_wait),
633            content_lock_wait: self
634                .content_lock_wait
635                .saturating_add(other.content_lock_wait),
636            namespace_lock_wait: self
637                .namespace_lock_wait
638                .saturating_add(other.namespace_lock_wait),
639            input_capture: self.input_capture.saturating_add(other.input_capture),
640            cache_lookup: self.cache_lookup.saturating_add(other.cache_lookup),
641            caller_build: [self.caller_build, other.caller_build]
642                .into_iter()
643                .flatten()
644                .reduce(Duration::saturating_add),
645            output_validation: self
646                .output_validation
647                .saturating_add(other.output_validation),
648            publication: self.publication.saturating_add(other.publication),
649            materialization: self.materialization.saturating_add(other.materialization),
650            maintenance: [self.maintenance, other.maintenance]
651                .into_iter()
652                .flatten()
653                .reduce(Duration::saturating_add),
654            total: self.total.saturating_add(other.total),
655        }
656    }
657}
658
659impl std::fmt::Display for ArtifactCacheTimings {
660    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
661        write!(
662            formatter,
663            "total={:?} coordination_lock={:?} content_lock={:?} namespace_lock={:?} inputs={:?} lookup={:?} build={:?} validation={:?} publication={:?} materialization={:?} maintenance={:?}",
664            self.total,
665            self.coordination_lock_wait,
666            self.content_lock_wait,
667            self.namespace_lock_wait,
668            self.input_capture,
669            self.cache_lookup,
670            self.caller_build,
671            self.output_validation,
672            self.publication,
673            self.materialization,
674            self.maintenance,
675        )
676    }
677}
678
679impl std::fmt::Display for ArtifactCacheOutcome {
680    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
681        let state = if self.is_reused() { "reused" } else { "built" };
682        write!(
683            formatter,
684            "{state} key={} artifacts={} {}",
685            self.record().key,
686            self.record().artifacts.len(),
687            self.record().timings,
688        )
689    }
690}
691
692impl ArtifactBuildTransaction {
693    /// Transaction-owned directory in which the caller may run its build.
694    ///
695    /// Commit accepts only the cache-created `outputs` child at this root.
696    /// Callers must remove or relocate logs and other temporary root children.
697    #[must_use]
698    pub fn staging_directory(&self) -> &Path {
699        self.staging_directory.path()
700    }
701
702    /// Checked staging destination for one declared logical output.
703    ///
704    /// # Errors
705    /// Returns [`ArtifactCacheError::UnknownOutput`] for an undeclared output name.
706    pub fn output_path(&self, name: &str) -> Result<PathBuf, ArtifactCacheError> {
707        self.output_index(name)
708            .map(|index| staged_output_path(self.staging_directory.path(), index))
709            .ok_or_else(|| ArtifactCacheError::UnknownOutput {
710                name: name.to_owned(),
711            })
712    }
713
714    /// Copy a fixed external output into its transaction-owned staging path.
715    ///
716    /// # Errors
717    /// Returns an unknown-output or atomic source-copy/publication error.
718    pub fn import_output(&self, name: &str, source: &Path) -> Result<(), ArtifactCacheError> {
719        let destination = self.output_path(name)?;
720        copy_file_atomic(source, &destination).map_err(|source_error| ArtifactCacheError::Io {
721            operation: "import artifact output into staging",
722            path: destination,
723            source: source_error,
724        })?;
725        Ok(())
726    }
727
728    /// Validate the exact staging schema and atomically publish the complete output set.
729    ///
730    /// # Errors
731    /// Returns staging-schema, output verification, input-change, lock or publication
732    /// errors. Failed staging cleanup preserves both the transaction and cleanup errors.
733    pub fn commit(mut self) -> Result<ArtifactCacheOutcome, ArtifactCacheError> {
734        let result = self.commit_inner();
735        match result {
736            Ok(outcome) => Ok(outcome),
737            Err(transaction_error) if self.staging_directory.is_armed() => {
738                let path = self.staging_directory.path().to_owned();
739                match self.staging_directory.try_cleanup() {
740                    Ok(()) => Err(transaction_error),
741                    Err(source) => Err(ArtifactCacheError::FailedTransactionCleanup {
742                        transaction_error: Box::new(transaction_error),
743                        path,
744                        source,
745                    }),
746                }
747            }
748            Err(transaction_error) => Err(transaction_error),
749        }
750    }
751
752    /// Abandon the transaction and synchronously remove its staging directory.
753    ///
754    /// # Errors
755    /// Returns the filesystem error if removing the owned staging directory fails.
756    pub fn abort(mut self) -> Result<(), ArtifactCacheError> {
757        self.staging_directory
758            .try_cleanup()
759            .map_err(|source| ArtifactCacheError::Io {
760                operation: "abort artifact cache transaction",
761                path: self.staging_directory.path().to_owned(),
762                source,
763            })?;
764        Ok(())
765    }
766
767    fn output_index(&self, name: &str) -> Option<usize> {
768        self.spec
769            .outputs
770            .iter()
771            .position(|output| output.name == name)
772    }
773
774    fn commit_inner(&mut self) -> Result<ArtifactCacheOutcome, ArtifactCacheError> {
775        self.timings.caller_build = Some(self.caller_build_started.elapsed());
776
777        let validation_started = Instant::now();
778        let output_info = inspect_complete_output_set(&self.spec, self.staging_directory.path())?;
779        self.timings.output_validation = validation_started.elapsed();
780
781        let capture_started = Instant::now();
782        revalidate_cargo_build_input_fingerprints(&self.spec)?;
783        let verified = resolve_key(&self.spec)?;
784        self.timings.input_capture = self
785            .timings
786            .input_capture
787            .saturating_add(capture_started.elapsed());
788        if verified.input_digest != self.resolved.input_digest {
789            return Err(ArtifactCacheError::InputsChangedDuringAcquisition {
790                before: self.resolved.input_digest,
791                after: verified.input_digest,
792            });
793        }
794
795        let publication_started = Instant::now();
796        let manifest =
797            manifest_contents(self.resolved.key, &self.spec, output_info.iter().copied());
798        ic_host_fs::durable::write_bytes(
799            &self.staging_directory.path().join(MANIFEST_FILE),
800            manifest.as_bytes(),
801        )
802        .map_err(|source| ArtifactCacheError::Io {
803            operation: "write artifact cache manifest",
804            path: self.staging_directory.path().join(MANIFEST_FILE),
805            source: io::Error::other(source),
806        })?;
807        let namespace_lock_path = namespace_lock_path(&self.spec);
808        let (_namespace_lock, namespace_wait) =
809            lock_cache_file(&namespace_lock_path).map_err(artifact_cache_fs_error)?;
810        self.timings.namespace_lock_wait = self
811            .timings
812            .namespace_lock_wait
813            .saturating_add(namespace_wait);
814        remove_unretained_entry(&self.entry_directory).map_err(artifact_cache_fs_error)?;
815        fs::rename(self.staging_directory.path(), &self.entry_directory).map_err(|source| {
816            ArtifactCacheError::Io {
817                operation: "publish artifact cache entry",
818                path: self.entry_directory.clone(),
819                source,
820            }
821        })?;
822        self.staging_directory.disarm();
823        self.timings.publication = publication_started.elapsed();
824
825        let materialization_started = Instant::now();
826        materialize_outputs(&self.spec, &self.entry_directory, None)?;
827        self.timings.materialization = materialization_started.elapsed();
828        record_cache_entry_use(&self.entry_directory).map_err(artifact_cache_fs_error)?;
829        let (maintenance, maintenance_timing) = perform_maintenance_locked(
830            &self.spec,
831            &self.namespace_directory,
832            &self.entry_directory,
833        );
834        self.timings.maintenance = maintenance_timing;
835        self.timings.total = self.total_started.elapsed();
836
837        Ok(ArtifactCacheOutcome::Built(cache_record(
838            &self.spec,
839            self.resolved,
840            self.timings,
841            maintenance,
842        )?))
843    }
844}
845
846/// Verify or begin one exact external artifact-set transaction.
847///
848/// A hit validates the complete cached output set and makes every configured
849/// destination available. On Unix, a regular file owned by the effective user,
850/// with owner read/write permissions, one link, no executable or special
851/// permission bits, and matching contents is left in place. Other destinations
852/// are atomically replaced from the verified entry. Cold commits and non-Unix
853/// acquisitions always replace destinations. Callers must coordinate any other
854/// writers to these mutable paths.
855/// Final symlinks with missing or cyclic referents can be replaced. Directories
856/// and directory referents remain invalid destinations.
857///
858/// # Errors
859/// Returns invalid specification/boundary, Cargo input revalidation, input-change,
860/// lock, input-read or cache acquisition/materialization errors.
861///
862/// # Panics
863/// Panics if internal preparation retries exhaust without recording an input change.
864pub fn prepare_artifact_cache(
865    spec: &ArtifactCacheSpec,
866) -> Result<ArtifactCachePreparation, ArtifactCacheError> {
867    let total_started = Instant::now();
868    validate_spec(spec)?;
869    validate_filesystem_boundaries(spec)?;
870    let namespace_directory = initialize_cache(spec)?;
871
872    let coordination_lock_path = coordination_lock_path(spec);
873    let (coordination_lock, coordination_wait) =
874        lock_cache_file(&coordination_lock_path).map_err(artifact_cache_fs_error)?;
875    let mut timings = ArtifactCacheTimings {
876        coordination_lock_wait: coordination_wait,
877        ..ArtifactCacheTimings::default()
878    };
879    let initial_cargo_started = Instant::now();
880    revalidate_cargo_build_input_fingerprints(spec)?;
881    timings.input_capture = initial_cargo_started.elapsed();
882    let mut last_change = None;
883
884    for _ in 0..MAX_PREPARATION_RETRIES {
885        let capture_started = Instant::now();
886        let resolved = resolve_key(spec)?;
887        timings.input_capture = timings
888            .input_capture
889            .saturating_add(capture_started.elapsed());
890
891        let content_lock_path = content_lock_path(spec, resolved.key);
892        let (content_lock, content_wait) =
893            lock_cache_file(&content_lock_path).map_err(artifact_cache_fs_error)?;
894        timings.content_lock_wait = timings.content_lock_wait.saturating_add(content_wait);
895
896        let verification_started = Instant::now();
897        let verified = resolve_key(spec)?;
898        timings.input_capture = timings
899            .input_capture
900            .saturating_add(verification_started.elapsed());
901        if resolved.input_digest != verified.input_digest {
902            last_change = Some((resolved.input_digest, verified.input_digest));
903            drop(content_lock);
904            continue;
905        }
906
907        let entry_directory = entry_directory(&namespace_directory, resolved.key);
908        let namespace_lock_path = namespace_lock_path(spec);
909        let (namespace_lock, namespace_wait) =
910            lock_cache_file(&namespace_lock_path).map_err(artifact_cache_fs_error)?;
911        timings.namespace_lock_wait = timings.namespace_lock_wait.saturating_add(namespace_wait);
912        let lookup_started = Instant::now();
913        let verified_outputs = validated_cache_outputs(spec, resolved.key, &entry_directory)?;
914        timings.cache_lookup = timings
915            .cache_lookup
916            .saturating_add(lookup_started.elapsed());
917
918        if let Some(output_info) = verified_outputs {
919            let materialization_started = Instant::now();
920            materialize_outputs(spec, &entry_directory, Some(&output_info))?;
921            timings.materialization = timings
922                .materialization
923                .saturating_add(materialization_started.elapsed());
924            let after_started = Instant::now();
925            revalidate_cargo_build_input_fingerprints(spec)?;
926            let after = resolve_key(spec)?;
927            timings.input_capture = timings
928                .input_capture
929                .saturating_add(after_started.elapsed());
930            if after.input_digest != resolved.input_digest {
931                last_change = Some((resolved.input_digest, after.input_digest));
932                drop(namespace_lock);
933                drop(content_lock);
934                continue;
935            }
936            record_cache_entry_use(&entry_directory).map_err(artifact_cache_fs_error)?;
937            let (maintenance, maintenance_timing) =
938                perform_maintenance_locked(spec, &namespace_directory, &entry_directory);
939            timings.maintenance = maintenance_timing;
940            timings.total = total_started.elapsed();
941            return Ok(ArtifactCachePreparation::Reused(cache_record(
942                spec,
943                resolved,
944                timings,
945                maintenance,
946            )?));
947        }
948
949        remove_unretained_entry(&entry_directory).map_err(artifact_cache_fs_error)?;
950        let staging_directory = create_staging_directory(&namespace_directory, resolved.key)?;
951        drop(namespace_lock);
952        return Ok(ArtifactCachePreparation::Build(ArtifactBuildTransaction {
953            spec: Box::new(spec.clone()),
954            resolved,
955            staging_directory: OwnedDirectory::new(staging_directory),
956            entry_directory,
957            namespace_directory,
958            _coordination_lock: coordination_lock,
959            _content_lock: content_lock,
960            timings,
961            total_started,
962            caller_build_started: Instant::now(),
963        }));
964    }
965
966    let (before, after) = last_change.expect("preparation retries require a recorded input change");
967    Err(ArtifactCacheError::InputsChangedDuringPreparation { before, after })
968}
969
970fn revalidate_cargo_build_input_fingerprints(
971    spec: &ArtifactCacheSpec,
972) -> Result<(), ArtifactCacheError> {
973    for cargo_input in &spec.cargo_build_inputs {
974        let current = resolve_cargo_build_inputs(&cargo_input.build_spec).map_err(|source| {
975            ArtifactCacheError::CargoBuildInputRevalidation {
976                label: cargo_input.label.clone(),
977                source,
978            }
979        })?;
980        let before_validation = cargo_input.resolved.validation_digest();
981        let after_validation = current.validation_digest();
982        if after_validation != before_validation {
983            return Err(ArtifactCacheError::CargoBuildInputsChanged {
984                label: cargo_input.label.clone(),
985                before: before_validation,
986                after: after_validation,
987            });
988        }
989        let before = cargo_input.resolved.fingerprint();
990        let after = current.fingerprint();
991        if after != before {
992            return Err(ArtifactCacheError::CargoBuildInputsChanged {
993                label: cargo_input.label.clone(),
994                before,
995                after,
996            });
997        }
998    }
999    Ok(())
1000}
1001
1002/// Prune one transactional artifact namespace without acquiring an artifact.
1003///
1004/// This strict maintenance entry point returns cache errors directly. Build
1005/// acquisitions configured with [`ArtifactCacheSpec::with_prune_policy`] use
1006/// the same implementation but attach maintenance as a nonfatal record.
1007/// Abandoned staging is removed only when its content-key lock is currently
1008/// unowned and is reported separately from committed-entry retention.
1009/// Entries owned by live acquisition records are skipped until their last owner drops.
1010///
1011/// # Errors
1012/// Returns invalid namespace/root, lock, cache inspection or removal errors.
1013pub fn prune_artifact_cache(
1014    cache_root: &Path,
1015    namespace: &str,
1016    policy: ArtifactCachePrunePolicy,
1017) -> Result<ArtifactCachePruneReport, ArtifactCacheError> {
1018    validate_identifier("namespace", namespace)?;
1019    if cache_root.as_os_str().is_empty() {
1020        return invalid_spec("cache root must not be empty");
1021    }
1022    ensure_cache_directory_tag(cache_root).map_err(artifact_cache_fs_error)?;
1023    let namespace_directory = namespace_directory_for(cache_root, namespace);
1024    let lock_path = namespace_lock_path_for(cache_root, namespace);
1025    let (_lock, _) = lock_cache_file(&lock_path).map_err(artifact_cache_fs_error)?;
1026    prune_artifact_namespace_locked(cache_root, &namespace_directory, policy, None)
1027}
1028
1029fn initialize_cache(spec: &ArtifactCacheSpec) -> Result<PathBuf, ArtifactCacheError> {
1030    ensure_cache_directory_tag(&spec.cache_root).map_err(artifact_cache_fs_error)?;
1031    let namespace = namespace_directory(spec);
1032    fs::create_dir_all(entries_directory(&namespace)).map_err(|source| ArtifactCacheError::Io {
1033        operation: "create artifact cache namespace",
1034        path: namespace.clone(),
1035        source,
1036    })?;
1037    Ok(namespace)
1038}
1039
1040fn validate_spec(spec: &ArtifactCacheSpec) -> Result<(), ArtifactCacheError> {
1041    validate_identifier("namespace", &spec.namespace)?;
1042    validate_identifier("recipe identity", &spec.recipe_id)?;
1043    validate_identifier("coordination scope", &spec.coordination_scope)?;
1044    if spec.cache_root.as_os_str().is_empty() {
1045        return invalid_spec("cache root must not be empty");
1046    }
1047    if spec.outputs.is_empty() {
1048        return invalid_spec("at least one artifact output is required");
1049    }
1050
1051    let mut labels = BTreeSet::new();
1052    for (kind, paths) in [("input", &spec.inputs), ("tool", &spec.tools)] {
1053        for path in paths {
1054            validate_path_label(kind, &path.label)?;
1055            if !labels.insert((kind, path.label.as_str())) {
1056                return invalid_spec(&format!("duplicate {kind} label `{}`", path.label));
1057            }
1058        }
1059    }
1060    let mut identity_labels = BTreeSet::new();
1061    for identity in &spec.identities {
1062        validate_identifier("identity label", &identity.label)?;
1063        if !identity_labels.insert(&identity.label) {
1064            return invalid_spec(&format!("duplicate identity label `{}`", identity.label));
1065        }
1066    }
1067    let mut cargo_input_labels = BTreeSet::new();
1068    for cargo_inputs in &spec.cargo_build_inputs {
1069        validate_identifier("Cargo build input label", &cargo_inputs.label)?;
1070        if !cargo_input_labels.insert(&cargo_inputs.label) {
1071            return invalid_spec(&format!(
1072                "duplicate Cargo build input label `{}`",
1073                cargo_inputs.label
1074            ));
1075        }
1076    }
1077    if spec
1078        .environment
1079        .keys()
1080        .any(|name| name.as_os_str().is_empty())
1081    {
1082        return invalid_spec("environment names must not be empty");
1083    }
1084    let mut output_names = BTreeSet::new();
1085    let mut destinations = BTreeSet::new();
1086    for output in &spec.outputs {
1087        validate_output_name(&output.name)?;
1088        if !output_names.insert(&output.name) {
1089            return invalid_spec(&format!("duplicate output name `{}`", output.name));
1090        }
1091        if output.destination.as_os_str().is_empty() {
1092            return invalid_spec(&format!(
1093                "output `{}` destination must not be empty",
1094                output.name
1095            ));
1096        }
1097        if !destinations.insert(&output.destination) {
1098            return invalid_spec(&format!(
1099                "output `{}` shares a destination with another output",
1100                output.name
1101            ));
1102        }
1103    }
1104    Ok(())
1105}
1106
1107fn validate_filesystem_boundaries(spec: &ArtifactCacheSpec) -> Result<(), ArtifactCacheError> {
1108    let cache_root =
1109        canonicalize_allow_missing(&spec.cache_root).map_err(|source| ArtifactCacheError::Io {
1110            operation: "resolve artifact cache root",
1111            path: spec.cache_root.clone(),
1112            source,
1113        })?;
1114    let mut declared_paths = Vec::with_capacity(spec.inputs.len() + spec.tools.len());
1115    for (kind, labeled_paths) in [("input", &spec.inputs), ("tool", &spec.tools)] {
1116        for labeled in labeled_paths {
1117            let canonical =
1118                canonicalize_path(&labeled.path, "canonicalize declared artifact cache path")?;
1119            if canonical.starts_with(&cache_root) {
1120                return invalid_spec(&format!(
1121                    "{kind} `{}` must not be located inside the artifact cache root",
1122                    labeled.label
1123                ));
1124            }
1125            let is_directory = fs::metadata(&canonical)
1126                .map_err(|source| ArtifactCacheError::Io {
1127                    operation: "inspect declared artifact cache path",
1128                    path: canonical.clone(),
1129                    source,
1130                })?
1131                .is_dir();
1132            let entry_path =
1133                resolve_file_entry(&labeled.path, "resolve declared artifact cache path entry")?;
1134            if entry_path != canonical {
1135                declared_paths.push((kind, labeled.label.as_str(), entry_path, false));
1136            }
1137            declared_paths.push((kind, labeled.label.as_str(), canonical, is_directory));
1138        }
1139    }
1140    for cargo_inputs in &spec.cargo_build_inputs {
1141        if resolved_cargo_inputs_watch_path(&cargo_inputs.resolved, &cache_root)? {
1142            return invalid_spec(&format!(
1143                "artifact cache root must be outside resolved Cargo build inputs `{}` or inside one of their generated-state exclusions",
1144                cargo_inputs.label
1145            ));
1146        }
1147    }
1148
1149    let mut destinations = BTreeSet::new();
1150    for output in &spec.outputs {
1151        let destination =
1152            resolve_file_entry(&output.destination, "resolve artifact output destination")?;
1153        if destination.starts_with(&cache_root) {
1154            return invalid_spec(&format!(
1155                "output `{}` destination must be outside the artifact cache root",
1156                output.name
1157            ));
1158        }
1159        if destinations.iter().any(|other: &PathBuf| {
1160            destination.starts_with(other) || other.starts_with(&destination)
1161        }) {
1162            return invalid_spec(&format!(
1163                "output `{}` destination overlaps another output",
1164                output.name
1165            ));
1166        }
1167        destinations.insert(destination.clone());
1168        for (kind, label, declared, is_directory) in &declared_paths {
1169            if destination == *declared || (*is_directory && destination.starts_with(declared)) {
1170                return invalid_spec(&format!(
1171                    "output `{}` destination overlaps declared {kind} `{label}`",
1172                    output.name
1173                ));
1174            }
1175        }
1176        for cargo_inputs in &spec.cargo_build_inputs {
1177            if resolved_cargo_inputs_watch_path(&cargo_inputs.resolved, &destination)? {
1178                return invalid_spec(&format!(
1179                    "output `{}` destination must be outside resolved Cargo build inputs `{}` or inside one of their generated-state exclusions",
1180                    output.name, cargo_inputs.label
1181                ));
1182            }
1183        }
1184        // Directory referents remain invalid: replacing their symlink may
1185        // strand another output's parent. Other final symlinks are replaced
1186        // as entries, independently of whether their referents are readable.
1187        match fs::symlink_metadata(&destination) {
1188            Ok(metadata)
1189                if metadata.is_dir()
1190                    || (metadata.file_type().is_symlink()
1191                        && fs::metadata(&destination).is_ok_and(|target| target.is_dir())) =>
1192            {
1193                return invalid_spec(&format!(
1194                    "output `{}` destination must not be an existing directory",
1195                    output.name
1196                ));
1197            }
1198            Ok(_) => {}
1199            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
1200            Err(source) => {
1201                return Err(ArtifactCacheError::Io {
1202                    operation: "inspect artifact output destination",
1203                    path: destination,
1204                    source,
1205                });
1206            }
1207        }
1208    }
1209    Ok(())
1210}
1211
1212// Atomic publication replaces the directory entry, including a final symlink;
1213// resolving that symlink's referent would validate a different write location.
1214fn resolve_file_entry(path: &Path, operation: &'static str) -> Result<PathBuf, ArtifactCacheError> {
1215    let resolved = match (path.parent(), path.file_name()) {
1216        (Some(parent), Some(name)) => {
1217            canonicalize_allow_missing(parent).map(|parent| parent.join(name))
1218        }
1219        _ => canonicalize_allow_missing(path),
1220    };
1221    resolved.map_err(|source| ArtifactCacheError::Io {
1222        operation,
1223        path: path.to_owned(),
1224        source,
1225    })
1226}
1227
1228fn resolved_cargo_inputs_watch_path(
1229    resolved: &ResolvedCargoBuildInputs,
1230    candidate: &Path,
1231) -> Result<bool, ArtifactCacheError> {
1232    for exclusion in resolved.exclusions() {
1233        let exclusion =
1234            canonicalize_allow_missing(exclusion).map_err(|source| ArtifactCacheError::Io {
1235                operation: "resolve Cargo build input exclusion",
1236                path: exclusion.clone(),
1237                source,
1238            })?;
1239        if candidate.starts_with(exclusion) {
1240            return Ok(false);
1241        }
1242    }
1243
1244    for input in resolved.inputs() {
1245        let path = canonicalize_path(input.path(), "canonicalize resolved Cargo build input")?;
1246        let is_directory = fs::metadata(&path)
1247            .map_err(|source| ArtifactCacheError::Io {
1248                operation: "inspect resolved Cargo build input",
1249                path: path.clone(),
1250                source,
1251            })?
1252            .is_dir();
1253        if candidate == path || (is_directory && candidate.starts_with(path)) {
1254            return Ok(true);
1255        }
1256    }
1257    Ok(false)
1258}
1259
1260fn canonicalize_path(path: &Path, operation: &'static str) -> Result<PathBuf, ArtifactCacheError> {
1261    path.canonicalize()
1262        .map_err(|source| ArtifactCacheError::Io {
1263            operation,
1264            path: path.to_owned(),
1265            source,
1266        })
1267}
1268
1269fn validate_identifier(kind: &str, value: &str) -> Result<(), ArtifactCacheError> {
1270    if value.is_empty() {
1271        return invalid_spec(&format!("{kind} must not be empty"));
1272    }
1273    if value.len() > 256 {
1274        return invalid_spec(&format!("{kind} must not exceed 256 bytes"));
1275    }
1276    Ok(())
1277}
1278
1279fn validate_path_label(kind: &str, value: &str) -> Result<(), ArtifactCacheError> {
1280    validate_identifier(&format!("{kind} label"), value)?;
1281    if value
1282        .bytes()
1283        .any(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'/')))
1284        || value
1285            .split('/')
1286            .any(|component| component.is_empty() || matches!(component, "." | ".."))
1287    {
1288        return invalid_spec(&format!(
1289            "{kind} label `{value}` must be a portable relative logical path"
1290        ));
1291    }
1292    Ok(())
1293}
1294
1295fn validate_output_name(name: &str) -> Result<(), ArtifactCacheError> {
1296    if name.is_empty() || name.len() > 128 {
1297        return invalid_spec("output names must contain 1 to 128 bytes");
1298    }
1299    if !name
1300        .bytes()
1301        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
1302    {
1303        return invalid_spec(&format!(
1304            "output name `{name}` must use only ASCII letters, digits, dot, dash, or underscore"
1305        ));
1306    }
1307    if matches!(name, "." | "..") {
1308        return invalid_spec("output names must not be dot path components");
1309    }
1310    Ok(())
1311}
1312
1313fn invalid_spec<T>(message: &str) -> Result<T, ArtifactCacheError> {
1314    Err(ArtifactCacheError::InvalidSpec {
1315        message: message.to_owned(),
1316    })
1317}
1318
1319fn resolve_key(spec: &ArtifactCacheSpec) -> Result<ResolvedKey, ArtifactCacheError> {
1320    let paths = spec
1321        .inputs
1322        .iter()
1323        .map(|input| (PathBuf::from("input").join(&input.label), &input.path))
1324        .chain(
1325            spec.tools
1326                .iter()
1327                .map(|tool| (PathBuf::from("tool").join(&tool.label), &tool.path)),
1328        );
1329    let declared_input_digest = digest_labeled_paths(
1330        "artifact-set-inputs-v1",
1331        paths,
1332        std::slice::from_ref(&spec.cache_root),
1333    )
1334    .map_err(|source| ArtifactCacheError::Io {
1335        operation: "hash artifact cache inputs",
1336        path: spec.cache_root.clone(),
1337        source,
1338    })?;
1339    let input_digest = if spec.cargo_build_inputs.is_empty() {
1340        declared_input_digest
1341    } else {
1342        let mut inputs = InputHasher::new("artifact-set-inputs-with-cargo-v1");
1343        inputs.field("declared-input-digest", declared_input_digest.as_bytes());
1344        for cargo_input in &spec.cargo_build_inputs {
1345            let current = cargo_input
1346                .resolved
1347                .current_validation_digest()
1348                .map_err(|source| ArtifactCacheError::CargoBuildInputRevalidation {
1349                    label: cargo_input.label.clone(),
1350                    source,
1351                })?;
1352            let before = cargo_input.resolved.validation_digest();
1353            if current != before {
1354                return Err(ArtifactCacheError::CargoBuildInputsChanged {
1355                    label: cargo_input.label.clone(),
1356                    before,
1357                    after: current,
1358                });
1359            }
1360            inputs.field("cargo-input-label", cargo_input.label.as_bytes());
1361            inputs.field(
1362                "cargo-build-fingerprint",
1363                cargo_input.resolved.fingerprint().as_bytes(),
1364            );
1365            inputs.field(
1366                "cargo-input-digest",
1367                cargo_input.resolved.input_digest().as_bytes(),
1368            );
1369        }
1370        inputs.finish()
1371    };
1372
1373    let mut hasher = InputHasher::new(ARTIFACT_CACHE_FORMAT);
1374    hasher.field("namespace", spec.namespace.as_bytes());
1375    hasher.field("recipe-id", spec.recipe_id.as_bytes());
1376    hasher.field("input-digest", input_digest.as_bytes());
1377    for argument in &spec.arguments {
1378        hasher.field("argument", &os_bytes(argument));
1379    }
1380    for (name, value) in &spec.environment {
1381        hasher.field("environment-name", &os_bytes(name));
1382        match value {
1383            Some(value) => hasher.field("environment-value", &os_bytes(value)),
1384            None => hasher.field("environment-unset", b""),
1385        }
1386    }
1387    for identity in &spec.identities {
1388        hasher.field("identity-label", identity.label.as_bytes());
1389        hasher.field("identity-value", &identity.value);
1390    }
1391    for output in &spec.outputs {
1392        hasher.field("output-name", output.name.as_bytes());
1393        hasher.field(
1394            "output-validation",
1395            output.validation.cache_token().as_bytes(),
1396        );
1397    }
1398    Ok(ResolvedKey {
1399        key: hasher.finish(),
1400        input_digest,
1401    })
1402}
1403
1404fn validated_cache_outputs(
1405    spec: &ArtifactCacheSpec,
1406    key: InputDigest,
1407    entry: &Path,
1408) -> Result<Option<Vec<FileDigest>>, ArtifactCacheError> {
1409    let entry_metadata = match fs::symlink_metadata(entry) {
1410        Ok(metadata) => metadata,
1411        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1412        Err(source) => {
1413            return Err(ArtifactCacheError::Io {
1414                operation: "inspect artifact cache entry",
1415                path: entry.to_owned(),
1416                source,
1417            });
1418        }
1419    };
1420    if !entry_metadata.file_type().is_dir() || !cache_entry_root_is_valid(entry)? {
1421        return Ok(None);
1422    }
1423    let manifest_path = entry.join(MANIFEST_FILE);
1424    let manifest_metadata = match fs::symlink_metadata(&manifest_path) {
1425        Ok(metadata) => metadata,
1426        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1427        Err(source) => {
1428            return Err(ArtifactCacheError::Io {
1429                operation: "inspect artifact cache manifest",
1430                path: manifest_path,
1431                source,
1432            });
1433        }
1434    };
1435    if !manifest_metadata.file_type().is_file() {
1436        return Ok(None);
1437    }
1438    // The writer owns the layout. Fixed-width digests and the largest byte count
1439    // bound every valid manifest for this declared output set, without inspecting
1440    // cached output bytes or allocating a placeholder output-info vector.
1441    let maximum_len = manifest_contents(
1442        key,
1443        spec,
1444        std::iter::repeat(FileDigest {
1445            bytes: u64::MAX,
1446            digest: key,
1447        }),
1448    )
1449    .len();
1450    let Some(manifest) = read_file_with_limit(&manifest_path, maximum_len).map_err(|source| {
1451        ArtifactCacheError::Io {
1452            operation: "read artifact cache manifest",
1453            path: manifest_path,
1454            source,
1455        }
1456    })?
1457    else {
1458        return Ok(None);
1459    };
1460    if !manifest.starts_with(manifest_header(key).as_bytes()) {
1461        return Ok(None);
1462    }
1463    let Some(output_info) = inspect_cached_output_set(spec, entry)? else {
1464        return Ok(None);
1465    };
1466    Ok(
1467        (manifest == manifest_contents(key, spec, output_info.iter().copied()).as_bytes())
1468            .then_some(output_info),
1469    )
1470}
1471
1472fn inspect_complete_output_set(
1473    spec: &ArtifactCacheSpec,
1474    root: &Path,
1475) -> Result<Vec<FileDigest>, ArtifactCacheError> {
1476    let mut info = Vec::new();
1477    let mut invalid = Vec::new();
1478    let output_directory = root.join("outputs");
1479    if !is_plain_directory(
1480        &output_directory,
1481        "inspect artifact staging output directory",
1482    )? {
1483        invalid.push(("<outputs>".to_owned(), output_directory));
1484        return Err(ArtifactCacheError::InvalidOutputs { outputs: invalid });
1485    }
1486    let outputs = &spec.outputs;
1487    for (index, output) in outputs.iter().enumerate() {
1488        let path = staged_output_path(root, index);
1489        match inspect_artifact(&path, output.validation) {
1490            Ok(Some(artifact)) => info.push(artifact),
1491            Ok(None) => invalid.push((output.name.clone(), path)),
1492            Err(source) => {
1493                return Err(ArtifactCacheError::Io {
1494                    operation: "inspect staged artifact output",
1495                    path,
1496                    source,
1497                });
1498            }
1499        }
1500    }
1501    invalid.extend(
1502        undeclared_output_paths(root, outputs.len())?
1503            .into_iter()
1504            .map(|path| ("<undeclared>".to_owned(), path)),
1505    );
1506    invalid.extend(
1507        undeclared_child_paths(
1508            root,
1509            |name| name == "outputs",
1510            "read artifact staging directory",
1511        )?
1512        .into_iter()
1513        .map(|path| ("<undeclared>".to_owned(), path)),
1514    );
1515    if invalid.is_empty() {
1516        Ok(info)
1517    } else {
1518        Err(ArtifactCacheError::InvalidOutputs { outputs: invalid })
1519    }
1520}
1521
1522fn inspect_cached_output_set(
1523    spec: &ArtifactCacheSpec,
1524    root: &Path,
1525) -> Result<Option<Vec<FileDigest>>, ArtifactCacheError> {
1526    let mut info = Vec::new();
1527    let outputs = &spec.outputs;
1528    for (index, output) in outputs.iter().enumerate() {
1529        let path = staged_output_path(root, index);
1530        match inspect_artifact(&path, output.validation) {
1531            Ok(Some(artifact)) => info.push(artifact),
1532            Ok(None) => return Ok(None),
1533            Err(source) => {
1534                return Err(ArtifactCacheError::Io {
1535                    operation: "inspect cached artifact output",
1536                    path,
1537                    source,
1538                });
1539            }
1540        }
1541    }
1542    if !undeclared_output_paths(root, outputs.len())?.is_empty() {
1543        return Ok(None);
1544    }
1545    Ok(Some(info))
1546}
1547
1548fn undeclared_output_paths(
1549    root: &Path,
1550    output_count: usize,
1551) -> Result<Vec<PathBuf>, ArtifactCacheError> {
1552    let output_directory = root.join("outputs");
1553    undeclared_child_paths(
1554        &output_directory,
1555        |name| {
1556            let Some(name) = name.to_str() else {
1557                return false;
1558            };
1559            name.strip_suffix(OUTPUT_FILE_SUFFIX)
1560                .and_then(|index| index.parse::<usize>().ok())
1561                .is_some_and(|index| index < output_count && name == format_output_index(index))
1562        },
1563        "read artifact output directory",
1564    )
1565}
1566
1567fn undeclared_child_paths(
1568    directory: &Path,
1569    is_expected: impl Fn(&OsStr) -> bool,
1570    operation: &'static str,
1571) -> Result<Vec<PathBuf>, ArtifactCacheError> {
1572    let entries = fs::read_dir(directory).map_err(|source| ArtifactCacheError::Io {
1573        operation,
1574        path: directory.to_owned(),
1575        source,
1576    })?;
1577    let mut undeclared = Vec::new();
1578    for entry in entries {
1579        let entry = entry.map_err(|source| ArtifactCacheError::Io {
1580            operation,
1581            path: directory.to_owned(),
1582            source,
1583        })?;
1584        if !is_expected(&entry.file_name()) {
1585            undeclared.push(entry.path());
1586        }
1587    }
1588    Ok(undeclared)
1589}
1590
1591fn cache_entry_root_is_valid(root: &Path) -> Result<bool, ArtifactCacheError> {
1592    let expected = [
1593        "outputs",
1594        MANIFEST_FILE,
1595        LAST_USED_FILE,
1596        super::cache_fs::RETENTION_LOCK_FILE,
1597    ];
1598    if !undeclared_child_paths(
1599        root,
1600        |name| expected.iter().any(|expected| name == *expected),
1601        "read artifact cache entry",
1602    )?
1603    .is_empty()
1604    {
1605        return Ok(false);
1606    }
1607    if !is_plain_directory(
1608        &root.join("outputs"),
1609        "inspect artifact cache output directory",
1610    )? {
1611        return Ok(false);
1612    }
1613    let last_used = root.join(LAST_USED_FILE);
1614    match fs::symlink_metadata(&last_used) {
1615        Ok(metadata) => Ok(metadata.file_type().is_file()),
1616        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(true),
1617        Err(source) => Err(ArtifactCacheError::Io {
1618            operation: "inspect artifact cache use marker",
1619            path: last_used,
1620            source,
1621        }),
1622    }
1623}
1624
1625fn is_plain_directory(path: &Path, operation: &'static str) -> Result<bool, ArtifactCacheError> {
1626    match fs::symlink_metadata(path) {
1627        Ok(metadata) => Ok(metadata.file_type().is_dir()),
1628        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
1629        Err(source) => Err(ArtifactCacheError::Io {
1630            operation,
1631            path: path.to_owned(),
1632            source,
1633        }),
1634    }
1635}
1636
1637fn inspect_artifact(
1638    path: &Path,
1639    validation: ArtifactOutputValidation,
1640) -> io::Result<Option<FileDigest>> {
1641    let metadata = match fs::symlink_metadata(path) {
1642        Ok(metadata) => metadata,
1643        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1644        Err(error) => return Err(error),
1645    };
1646    if !metadata.file_type().is_file() {
1647        return Ok(None);
1648    }
1649    if validation == ArtifactOutputValidation::NonEmptyFile && metadata.len() == 0 {
1650        return Ok(None);
1651    }
1652    digest_file("artifact-set-output-v1", path).map(Some)
1653}
1654
1655fn manifest_header(key: InputDigest) -> String {
1656    format!("{ARTIFACT_CACHE_FORMAT}\nkey:{key}\n")
1657}
1658
1659fn manifest_contents(
1660    key: InputDigest,
1661    spec: &ArtifactCacheSpec,
1662    output_info: impl IntoIterator<Item = FileDigest>,
1663) -> String {
1664    let mut manifest = manifest_header(key);
1665    for ((index, output), info) in spec.outputs.iter().enumerate().zip(output_info) {
1666        writeln!(
1667            manifest,
1668            "output:{index}:{}:{}:{}:{}",
1669            output.name,
1670            output.validation.cache_token(),
1671            info.bytes,
1672            info.digest,
1673        )
1674        .expect("writing an artifact manifest to a String cannot fail");
1675    }
1676    manifest
1677}
1678
1679fn materialize_outputs(
1680    spec: &ArtifactCacheSpec,
1681    entry: &Path,
1682    verified_outputs: Option<&[FileDigest]>,
1683) -> Result<(), ArtifactCacheError> {
1684    for (index, output) in spec.outputs.iter().enumerate() {
1685        // Only a hit supplies the complete output set checked against its manifest.
1686        // A cold commit always publishes; a hit may leave matching destinations alone.
1687        let cached = staged_output_path(entry, index);
1688        materialize_verified_output(
1689            "artifact-set-output-v1",
1690            &cached,
1691            &output.destination,
1692            verified_outputs.map(|info| &info[index]),
1693        )
1694        .map_err(|source| ArtifactCacheError::Io {
1695            operation: "materialize artifact output",
1696            path: output.destination.clone(),
1697            source,
1698        })?;
1699    }
1700    Ok(())
1701}
1702
1703fn perform_maintenance_locked(
1704    spec: &ArtifactCacheSpec,
1705    namespace: &Path,
1706    protected_entry: &Path,
1707) -> (Option<ArtifactCacheMaintenance>, Option<Duration>) {
1708    spec.prune_policy.map_or((None, None), |policy| {
1709        let identity = policy.maintenance_identity();
1710        perform_scheduled_cache_maintenance(namespace, spec.prune_interval, &identity, || {
1711            prune_artifact_namespace_locked(
1712                &spec.cache_root,
1713                namespace,
1714                policy,
1715                Some(protected_entry),
1716            )
1717            .map_err(|error| error.to_string())
1718        })
1719    })
1720}
1721
1722fn prune_artifact_namespace_locked(
1723    cache_root: &Path,
1724    namespace: &Path,
1725    policy: ArtifactCachePrunePolicy,
1726    protected_entry: Option<&Path>,
1727) -> Result<ArtifactCachePruneReport, ArtifactCacheError> {
1728    let mut report = prune_direct_child_directories(
1729        &entries_directory(namespace),
1730        policy,
1731        protected_entry,
1732        is_sha256_directory,
1733    )
1734    .map_err(artifact_cache_fs_error)?;
1735    remove_abandoned_staging(cache_root, namespace, &mut report)?;
1736    Ok(report)
1737}
1738
1739fn remove_abandoned_staging(
1740    cache_root: &Path,
1741    namespace: &Path,
1742    report: &mut ArtifactCachePruneReport,
1743) -> Result<(), ArtifactCacheError> {
1744    let staging_root = namespace.join("staging");
1745    let entries = match fs::read_dir(&staging_root) {
1746        Ok(entries) => entries,
1747        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
1748        Err(source) => {
1749            return Err(ArtifactCacheError::Io {
1750                operation: "read artifact staging root during pruning",
1751                path: staging_root,
1752                source,
1753            });
1754        }
1755    };
1756    for entry in entries {
1757        let entry = entry.map_err(|source| ArtifactCacheError::Io {
1758            operation: "read artifact staging entry during pruning",
1759            path: staging_root.clone(),
1760            source,
1761        })?;
1762        let file_type = entry.file_type().map_err(|source| ArtifactCacheError::Io {
1763            operation: "inspect artifact staging entry during pruning",
1764            path: entry.path(),
1765            source,
1766        })?;
1767        if !file_type.is_dir() {
1768            continue;
1769        }
1770        let file_name = entry.file_name();
1771        let Some(key) = staging_content_key(&file_name) else {
1772            continue;
1773        };
1774        let lock_path = content_lock_path_for_key(cache_root, key);
1775        let Some(_content_lock) =
1776            try_lock_cache_file(&lock_path).map_err(artifact_cache_fs_error)?
1777        else {
1778            continue;
1779        };
1780        let path = entry.path();
1781        let bytes = directory_logical_size(&path).map_err(|source| ArtifactCacheError::Io {
1782            operation: "measure abandoned artifact staging directory",
1783            path: path.clone(),
1784            source,
1785        })?;
1786        remove_path_if_present(&path).map_err(|source| ArtifactCacheError::Io {
1787            operation: "remove abandoned artifact staging directory during pruning",
1788            path,
1789            source,
1790        })?;
1791        report.record_uncommitted_removal(bytes);
1792    }
1793    Ok(())
1794}
1795
1796fn staging_content_key(name: &OsStr) -> Option<&str> {
1797    let name = name.to_str()?;
1798    let (key, suffix) = name.split_once('-')?;
1799    (!suffix.is_empty() && key.len() == 64 && key.as_bytes().iter().all(u8::is_ascii_hexdigit))
1800        .then_some(key)
1801}
1802
1803fn cache_record(
1804    spec: &ArtifactCacheSpec,
1805    resolved: ResolvedKey,
1806    timings: ArtifactCacheTimings,
1807    maintenance: Option<ArtifactCacheMaintenance>,
1808) -> Result<ArtifactCacheRecord, ArtifactCacheError> {
1809    let entry = entry_directory(&namespace_directory(spec), resolved.key);
1810    let retention = RetainedCacheEntry::acquire(&entry).map_err(artifact_cache_fs_error)?;
1811    Ok(ArtifactCacheRecord {
1812        key: resolved.key,
1813        input_digest: resolved.input_digest,
1814        artifacts: spec
1815            .outputs
1816            .iter()
1817            .enumerate()
1818            .map(|(index, output)| ArtifactCacheArtifact {
1819                name: output.name.clone(),
1820                path: staged_output_path(&entry, index),
1821            })
1822            .collect(),
1823        timings,
1824        maintenance,
1825        _retention: retention,
1826    })
1827}
1828
1829fn create_staging_directory(
1830    namespace: &Path,
1831    key: InputDigest,
1832) -> Result<PathBuf, ArtifactCacheError> {
1833    let staging_root = namespace.join("staging");
1834    fs::create_dir_all(&staging_root).map_err(|source| ArtifactCacheError::Io {
1835        operation: "create artifact staging root",
1836        path: staging_root.clone(),
1837        source,
1838    })?;
1839    remove_same_key_staging(&staging_root, key)?;
1840    let sequence = STAGING_SEQUENCE.fetch_add(1, Ordering::Relaxed);
1841    let staging = staging_root.join(format!("{key}-{}-{sequence}", std::process::id()));
1842    fs::create_dir_all(staging.join("outputs")).map_err(|source| ArtifactCacheError::Io {
1843        operation: "create artifact transaction staging directory",
1844        path: staging.clone(),
1845        source,
1846    })?;
1847    Ok(staging)
1848}
1849
1850fn remove_same_key_staging(root: &Path, key: InputDigest) -> Result<(), ArtifactCacheError> {
1851    let prefix = format!("{key}-");
1852    let entries = fs::read_dir(root).map_err(|source| ArtifactCacheError::Io {
1853        operation: "read artifact staging root",
1854        path: root.to_owned(),
1855        source,
1856    })?;
1857    for entry in entries {
1858        let entry = entry.map_err(|source| ArtifactCacheError::Io {
1859            operation: "read artifact staging entry",
1860            path: root.to_owned(),
1861            source,
1862        })?;
1863        if entry.file_name().to_string_lossy().starts_with(&prefix) {
1864            remove_path_if_present(&entry.path()).map_err(|source| ArtifactCacheError::Io {
1865                operation: "remove abandoned artifact staging directory",
1866                path: entry.path(),
1867                source,
1868            })?;
1869        }
1870    }
1871    Ok(())
1872}
1873
1874fn staged_output_path(root: &Path, index: usize) -> PathBuf {
1875    root.join("outputs").join(format_output_index(index))
1876}
1877
1878fn format_output_index(index: usize) -> String {
1879    format!("{index:04}{OUTPUT_FILE_SUFFIX}")
1880}
1881
1882fn namespace_directory(spec: &ArtifactCacheSpec) -> PathBuf {
1883    namespace_directory_for(&spec.cache_root, &spec.namespace)
1884}
1885
1886fn namespace_directory_for(cache_root: &Path, namespace: &str) -> PathBuf {
1887    cache_root
1888        .join(".ic-testkit/artifact-sets/namespaces")
1889        .join(identifier_digest("artifact-cache-namespace-v1", namespace))
1890}
1891
1892fn entries_directory(namespace: &Path) -> PathBuf {
1893    namespace.join("entries")
1894}
1895
1896fn entry_directory(namespace: &Path, key: InputDigest) -> PathBuf {
1897    entries_directory(namespace).join(key.to_hex())
1898}
1899
1900fn coordination_lock_path(spec: &ArtifactCacheSpec) -> PathBuf {
1901    spec.cache_root
1902        .join(".ic-testkit/artifact-sets/locks/coordination")
1903        .join(format!(
1904            "{}.lock",
1905            identifier_digest("artifact-cache-coordination-v1", &spec.coordination_scope,)
1906        ))
1907}
1908
1909fn content_lock_path(spec: &ArtifactCacheSpec, key: InputDigest) -> PathBuf {
1910    content_lock_path_for_key(&spec.cache_root, &key.to_hex())
1911}
1912
1913fn content_lock_path_for_key(cache_root: &Path, key: &str) -> PathBuf {
1914    cache_root
1915        .join(".ic-testkit/artifact-sets/locks/content")
1916        .join(format!("{key}.lock"))
1917}
1918
1919fn namespace_lock_path(spec: &ArtifactCacheSpec) -> PathBuf {
1920    namespace_lock_path_for(&spec.cache_root, &spec.namespace)
1921}
1922
1923fn namespace_lock_path_for(cache_root: &Path, namespace: &str) -> PathBuf {
1924    cache_root
1925        .join(".ic-testkit/artifact-sets/locks/namespaces")
1926        .join(format!(
1927            "{}.lock",
1928            identifier_digest("artifact-cache-namespace-v1", namespace)
1929        ))
1930}
1931
1932fn identifier_digest(domain: &str, identifier: &str) -> String {
1933    digest_bytes(domain, identifier.as_bytes()).to_hex()
1934}
1935
1936fn artifact_cache_fs_error(error: CacheFsError) -> ArtifactCacheError {
1937    ArtifactCacheError::Io {
1938        operation: error.operation,
1939        path: error.path,
1940        source: error.source,
1941    }
1942}
1943
1944impl ArtifactOutputValidation {
1945    const fn cache_token(self) -> &'static str {
1946        match self {
1947            Self::RegularFile => "regular-file",
1948            Self::NonEmptyFile => "nonempty-file",
1949        }
1950    }
1951}
1952
1953impl std::fmt::Display for ArtifactCacheError {
1954    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1955        match self {
1956            Self::InvalidSpec { message } => {
1957                write!(formatter, "invalid artifact cache spec: {message}")
1958            }
1959            Self::Io {
1960                operation,
1961                path,
1962                source,
1963            } => write!(
1964                formatter,
1965                "failed to {operation} at {}: {source}",
1966                path.display()
1967            ),
1968            Self::InputsChangedDuringPreparation { before, after } => write!(
1969                formatter,
1970                "artifact inputs repeatedly changed during cache preparation: {before} -> {after}",
1971            ),
1972            Self::InputsChangedDuringAcquisition { before, after } => write!(
1973                formatter,
1974                "artifact inputs changed while the caller was building: {before} -> {after}",
1975            ),
1976            Self::CargoBuildInputsChanged {
1977                label,
1978                before,
1979                after,
1980            } => write!(
1981                formatter,
1982                "resolved Cargo build inputs `{label}` changed: {before} -> {after}",
1983            ),
1984            Self::CargoBuildInputRevalidation { label, source } => write!(
1985                formatter,
1986                "failed to revalidate resolved Cargo build inputs `{label}`: {source}",
1987            ),
1988            Self::InvalidOutputs { outputs } => write!(
1989                formatter,
1990                "artifact transaction has missing or invalid outputs: {}",
1991                outputs
1992                    .iter()
1993                    .map(|(name, path)| format!("{name} ({})", path.display()))
1994                    .collect::<Vec<_>>()
1995                    .join(", "),
1996            ),
1997            Self::UnknownOutput { name } => {
1998                write!(
1999                    formatter,
2000                    "artifact transaction has no output named `{name}`"
2001                )
2002            }
2003            Self::FailedTransactionCleanup {
2004                transaction_error,
2005                path,
2006                source,
2007            } => write!(
2008                formatter,
2009                "artifact transaction failed ({transaction_error}) and staging cleanup at {} also failed: {source}",
2010                path.display(),
2011            ),
2012        }
2013    }
2014}
2015
2016impl std::error::Error for ArtifactCacheError {
2017    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2018        match self {
2019            Self::Io { source, .. } | Self::FailedTransactionCleanup { source, .. } => Some(source),
2020            Self::CargoBuildInputRevalidation { source, .. } => Some(source),
2021            _ => None,
2022        }
2023    }
2024}
2025
2026#[cfg(test)]
2027mod tests;