Skip to main content

ic_testkit/artifacts/
wasm_cache.rs

1use serde_json::Value;
2use std::{
3    collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque},
4    ffi::{OsStr, OsString},
5    fs::{self, File},
6    io,
7    path::{Path, PathBuf},
8    process::{Child, Command, ExitStatus, Output, Stdio},
9    sync::{
10        Arc, RwLock,
11        atomic::{AtomicUsize, Ordering},
12        mpsc::{self, RecvTimeoutError},
13    },
14    thread,
15    time::{Duration, Instant, SystemTime},
16};
17use toml::Value as TomlValue;
18
19use crate::timing::saturating_add_optional_duration;
20
21use super::{
22    cache_fs::{
23        ArtifactCacheMaintenance, ArtifactCachePrunePolicy, ArtifactCachePruneReport, CacheFsError,
24        RetainedCacheEntry, cache_entry_last_used, cache_maintenance_due,
25        canonicalize_allow_missing, directory_logical_size,
26        ensure_cache_directory_tag as ensure_cache_tag, is_sha256_directory, lock_cache_file,
27        lock_cache_file_with_wait_observer, perform_scheduled_cache_maintenance,
28        prune_direct_child_directories, record_cache_entry_use as record_entry_use,
29        record_cache_maintenance, remove_path_if_present, remove_unretained_entry,
30    },
31    digest::{
32        InputDigest, InputHasher, LabeledPathDigestCache, copy_file_atomic, digest_bytes,
33        digest_file, digest_labeled_paths_composable, os_bytes, write_atomic,
34    },
35    wasm::wasm_path,
36};
37
38const CACHE_FORMAT_VERSION: &str = "ic-testkit-wasm-build-v1";
39const DEFAULT_TARGET: &str = "wasm32-unknown-unknown";
40const AUTOMATIC_ENVIRONMENT: &[&str] = &[
41    "CARGO_BUILD_RUSTC",
42    "CARGO_ENCODED_RUSTFLAGS",
43    "RUSTC",
44    "RUSTC_WRAPPER",
45    "RUSTC_WORKSPACE_WRAPPER",
46    "RUSTFLAGS",
47    "RUSTUP_TOOLCHAIN",
48];
49
50/// Complete caller-owned description of one cacheable Cargo Wasm build.
51///
52/// The selected package graph, sources, semantic workspace projection, Cargo
53/// configuration, Rust toolchain files, target, profile arguments, explicit
54/// child environment, selected inherited environment, and additional watched
55/// inputs contribute to the build fingerprint. The complete workspace
56/// manifest and lockfile remain conservative mutation-validation inputs.
57#[derive(Clone, Debug, Eq, PartialEq)]
58pub struct WasmBuildSpec {
59    workspace_root: PathBuf,
60    target_dir: PathBuf,
61    packages: Vec<String>,
62    profile_target_dir: String,
63    cargo_profile_args: Vec<OsString>,
64    extra_env: BTreeMap<OsString, OsString>,
65    inherited_env: BTreeSet<OsString>,
66    additional_inputs: Vec<PathBuf>,
67    target: String,
68    cargo_program: OsString,
69    rustc_program: OsString,
70    cache_mode: WasmBuildCacheMode,
71    prune_policy: Option<ArtifactCachePrunePolicy>,
72    prune_interval: Option<Duration>,
73    shared_incremental_maintenance_config: Option<SharedIncrementalTargetMaintenanceConfig>,
74}
75
76/// Failure handling for integrated shared incremental-target maintenance.
77#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
78pub enum SharedIncrementalTargetMaintenanceFailureMode {
79    /// Fail the Wasm acquisition when scheduled maintenance fails.
80    #[default]
81    Strict,
82    /// Preserve the acquisition and attach a structured failed-maintenance outcome.
83    BestEffort,
84}
85
86/// Scheduled shared incremental-target maintenance attached to a Wasm acquisition.
87#[derive(Clone, Copy, Debug, Eq, PartialEq)]
88pub struct SharedIncrementalTargetMaintenanceConfig {
89    policy: SharedIncrementalTargetPrunePolicy,
90    minimum_interval: Duration,
91    failure_mode: SharedIncrementalTargetMaintenanceFailureMode,
92}
93
94/// Cargo-target ownership mode for one exact cached Wasm build.
95#[non_exhaustive]
96#[derive(Clone, Debug, Eq, PartialEq)]
97pub enum WasmBuildCacheMode {
98    /// Build each exact fingerprint in its own content-addressed Cargo target.
99    Isolated,
100    /// Build misses in caller-owned shared Cargo incremental state, then cache final Wasm files.
101    SharedIncremental {
102        /// Mutable Cargo target directory shared across source fingerprints.
103        target_dir: PathBuf,
104    },
105}
106
107/// Whether a cacheable Wasm build ran Cargo or reused exact matching artifacts.
108#[derive(Clone, Debug, Eq, PartialEq)]
109pub enum WasmBuildOutcome {
110    /// Cargo ran and a new successful stamp was published.
111    Built(WasmBuildRecord),
112    /// Existing artifacts and their content-addressed stamp matched exactly.
113    Reused(WasmBuildRecord),
114}
115
116/// Details shared by built and reused Wasm outcomes.
117#[derive(Clone, Debug, Eq, PartialEq)]
118pub struct WasmBuildRecord {
119    fingerprint: InputDigest,
120    input_digest: InputDigest,
121    exact_cache_path: PathBuf,
122    _retention: RetainedCacheEntry,
123    artifacts: Vec<PathBuf>,
124    timings: WasmBuildTimings,
125    maintenance: Option<ArtifactCacheMaintenance>,
126    shared_incremental_maintenance: Option<SharedIncrementalTargetMaintenanceOutcome>,
127}
128
129/// Timings for cache coordination, input resolution, and Cargo execution.
130#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
131pub struct WasmBuildTimings {
132    lock_wait: Duration,
133    shared_incremental_lock_wait: Option<Duration>,
134    input_resolution: WasmInputResolutionTimings,
135    cargo_build: Option<Duration>,
136    cache_maintenance: Option<Duration>,
137    total: Duration,
138}
139
140/// Detailed timings for exact Wasm build-input resolution.
141#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
142pub struct WasmInputResolutionTimings {
143    tool_identity: Duration,
144    cargo_metadata: Duration,
145    input_discovery: Duration,
146    content_hashing: Duration,
147    total: Duration,
148}
149
150/// Primary phase in which one cacheable Wasm acquisition failed.
151#[non_exhaustive]
152#[derive(Clone, Copy, Debug, Eq, PartialEq)]
153pub enum WasmBuildFailurePhase {
154    /// The caller supplied an invalid build specification.
155    Specification,
156    /// Waiting for the exact-cache lock or preparing its directory.
157    ExactCacheCoordination,
158    /// Reading Cargo or rustc identity.
159    ToolIdentity,
160    /// Running or decoding Cargo metadata.
161    CargoMetadata,
162    /// Discovering selected source and configuration inputs.
163    InputDiscovery,
164    /// Hashing selected and conservative input contents.
165    ContentHashing,
166    /// Waiting for or preparing a shared incremental target.
167    SharedTargetCoordination,
168    /// Applying configured shared-target maintenance.
169    SharedTargetMaintenance,
170    /// Executing Cargo for the selected Wasm packages.
171    CargoBuild,
172    /// Validating, copying, stamping, or materializing Wasm artifacts.
173    ArtifactPublication,
174    /// Applying exact-cache retention after a successful acquisition.
175    ExactCacheMaintenance,
176    /// Removing an incomplete exact-cache entry after failure.
177    Cleanup,
178}
179
180/// Partial phase timings retained when a Wasm acquisition fails.
181#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
182pub struct WasmBuildFailureTimings {
183    exact_cache_coordination: Duration,
184    shared_target_coordination: Option<Duration>,
185    input_resolution: WasmInputResolutionTimings,
186    shared_target_maintenance: Option<Duration>,
187    cargo_build: Option<Duration>,
188    artifact_publication: Option<Duration>,
189    exact_cache_maintenance: Option<Duration>,
190    cleanup: Option<Duration>,
191    total: Duration,
192}
193
194/// Structured phase and partial timings for one failed Wasm entry.
195#[derive(Clone, Copy, Debug, Eq, PartialEq)]
196pub struct WasmBuildFailureDetails {
197    phase: WasmBuildFailurePhase,
198    timings: WasmBuildFailureTimings,
199}
200
201/// One exact local Cargo source or configuration input under a stable logical label.
202#[derive(Clone, Debug, Eq, PartialEq)]
203pub struct CargoBuildInput {
204    label: PathBuf,
205    path: PathBuf,
206}
207
208/// Resolved exact inputs and identity for one [`WasmBuildSpec`].
209///
210/// The snapshot can be resolved again after an external operation to detect
211/// source, configuration, toolchain, argument, or environment changes.
212#[derive(Clone, Debug, Eq, PartialEq)]
213pub struct ResolvedCargoBuildInputs {
214    fingerprint: InputDigest,
215    input_digest: InputDigest,
216    validation_digest: InputDigest,
217    inputs: Vec<CargoBuildInput>,
218    exclusions: Vec<PathBuf>,
219    timings: WasmInputResolutionTimings,
220}
221
222pub(super) enum WasmBuildInputReuse<'reuse> {
223    Session(&'reuse mut WasmBuildSessionState),
224    Snapshot(&'reuse WasmBuildInputSnapshotState),
225}
226
227pub(super) struct WasmBuildBatchInputResolver<'a, 'session> {
228    specs: &'a [WasmBuildSpec],
229    groups: Vec<BatchResolutionGroup>,
230    group_by_index: Vec<usize>,
231    resolved:
232        Vec<Option<Result<ResolvedCargoBuildInputs, (WasmBuildFailurePhase, WasmBuildError)>>>,
233    reuse: Option<WasmBuildInputReuse<'session>>,
234    metrics: WasmBuildBatchInputMetrics,
235}
236
237pub(super) struct WasmBuildSessionState {
238    snapshots: Vec<(WasmBuildSpec, ResolvedCargoBuildInputs)>,
239    digest_cache: LabeledPathDigestCache,
240    snapshot_reuses: usize,
241    invalidated: bool,
242}
243
244pub(super) struct WasmBuildInputSnapshotState {
245    snapshots: Vec<(WasmBuildSpec, ResolvedCargoBuildInputs)>,
246    preparation_metrics: WasmBuildBatchInputMetrics,
247    preparation_timings: WasmInputResolutionTimings,
248    reader_reuses: AtomicUsize,
249    invalidation: Arc<RwLock<bool>>,
250}
251
252// Keep the large failure-timing payload inline at this internal return boundary.
253pub(super) struct WasmBuildBatchAttempt {
254    pub(super) result: Result<WasmBuildOutcome, (WasmBuildError, WasmBuildFailureDetails)>,
255}
256
257struct BatchResolutionGroup {
258    indexes: Vec<usize>,
259}
260
261struct ResolvedLocalInputs {
262    validation_inputs: Vec<(PathBuf, PathBuf)>,
263    fingerprint: LocalInputFingerprint,
264}
265
266enum LocalInputFingerprint {
267    Conservative,
268    Projected {
269        inputs: Vec<(PathBuf, PathBuf)>,
270        workspace: InputDigest,
271    },
272}
273
274#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
275pub(super) struct WasmBuildBatchInputMetrics {
276    pub(super) runs: usize,
277    pub(super) reuses: usize,
278    pub(super) session_reuses: usize,
279    pub(super) prepared_reuses: usize,
280}
281
282#[derive(Eq, PartialEq)]
283struct BatchResolutionKey {
284    workspace_root: PathBuf,
285    cargo_program: OsString,
286    rustc_program: OsString,
287    metadata_arguments: Vec<OsString>,
288    environment: BTreeMap<OsString, Option<OsString>>,
289}
290
291/// Lock-coordinated disk-usage observation for a caller-owned shared Cargo target.
292#[derive(Clone, Debug, Eq, PartialEq)]
293pub struct SharedIncrementalTargetInspection {
294    target_dir: PathBuf,
295    logical_size_bytes: u64,
296    last_used: SystemTime,
297    lock_wait: Duration,
298}
299
300/// Whole-target retention limits for caller-owned shared Cargo state.
301///
302/// Unlike immutable fingerprint entries, a shared Cargo target has no safe
303/// per-entry LRU boundary. When either configured limit is exceeded,
304/// maintenance clears every other target child while preserving
305/// `ic-testkit`'s coordination metadata and the target root. Callers must not
306/// colocate unrelated data that needs to survive a clear.
307#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
308pub struct SharedIncrementalTargetPrunePolicy {
309    max_age: Option<Duration>,
310    max_size_bytes: Option<u64>,
311}
312
313/// Result of explicit shared Cargo target maintenance.
314#[derive(Clone, Debug, Eq, PartialEq)]
315pub struct SharedIncrementalTargetMaintenance {
316    target_dir: PathBuf,
317    logical_size_bytes_before: u64,
318    logical_size_bytes_after: u64,
319    last_used_before: SystemTime,
320    cleared: bool,
321    lock_wait: Duration,
322    maintenance: Duration,
323}
324
325/// Result of interval-limited shared Cargo target maintenance.
326#[non_exhaustive]
327#[derive(Clone, Debug, Eq, PartialEq)]
328pub enum SharedIncrementalTargetMaintenanceOutcome {
329    /// The configured shared target does not exist, so nothing was created or inspected.
330    Missing {
331        /// Configured target path. A missing path cannot necessarily be canonicalized.
332        target_dir: PathBuf,
333    },
334    /// A successful matching maintenance pass is still inside the requested interval.
335    Skipped {
336        /// Canonical shared Cargo target directory.
337        target_dir: PathBuf,
338        /// Time spent waiting for another process using the shared target.
339        lock_wait: Duration,
340        /// Time spent checking the small cross-process schedule marker.
341        schedule_check: Duration,
342    },
343    /// Retention was evaluated under the shared-target lock.
344    Performed {
345        /// Completed retention report.
346        maintenance: SharedIncrementalTargetMaintenance,
347        /// Time spent checking the small cross-process schedule marker.
348        schedule_check: Duration,
349    },
350    /// Integrated best-effort maintenance failed without invalidating the Wasm acquisition.
351    Failed {
352        /// Canonical shared Cargo target directory.
353        target_dir: PathBuf,
354        /// Time spent waiting for another process using the shared target.
355        lock_wait: Duration,
356        /// Rendered maintenance failure retained for diagnostics.
357        message: String,
358    },
359}
360
361/// Observation settings for one cacheable Wasm build.
362#[derive(Clone, Copy, Debug, Eq, PartialEq)]
363pub struct WasmBuildProgressConfig {
364    heartbeat_interval: Option<Duration>,
365    emit_cargo_output: bool,
366}
367
368/// Raw child-process stream attached to a Cargo progress event.
369#[derive(Clone, Copy, Debug, Eq, PartialEq)]
370pub enum WasmBuildOutputStream {
371    /// Cargo standard output.
372    Stdout,
373    /// Cargo standard error.
374    Stderr,
375}
376
377/// Final cache state reported by a successful observed build.
378#[derive(Clone, Copy, Debug, Eq, PartialEq)]
379pub enum WasmBuildProgressOutcome {
380    /// Cargo ran and exact artifacts were published.
381    Built,
382    /// Exact artifacts were reused without Cargo.
383    Reused,
384}
385
386/// Potentially long phase of one observed Wasm-cache acquisition.
387#[non_exhaustive]
388#[derive(Clone, Copy, Debug, Eq, PartialEq)]
389pub enum WasmBuildProgressPhase {
390    /// Waiting for exclusive ownership of the exact artifact cache.
391    ExactCacheLock,
392    /// Reading the Cargo executable identity.
393    CargoIdentity,
394    /// Reading the Rust compiler identity.
395    RustcIdentity,
396    /// Resolving Cargo's package graph.
397    CargoMetadata,
398    /// Discovering local source and configuration inputs.
399    InputDiscovery,
400    /// Hashing exact source and configuration contents.
401    ContentHashing,
402    /// Waiting for exclusive ownership of a shared incremental Cargo target.
403    SharedTargetLock,
404    /// Inspecting or clearing a shared incremental Cargo target.
405    SharedTargetMaintenance,
406    /// Compiling the selected Wasm packages.
407    CargoBuild,
408    /// Validating, copying, hashing, or stamping exact artifacts.
409    ArtifactPublication,
410    /// Applying retention to immutable exact-cache entries.
411    ExactCacheMaintenance,
412}
413
414/// Structured progress emitted by an observed cacheable Wasm build.
415#[non_exhaustive]
416#[derive(Clone, Debug, Eq, PartialEq)]
417pub enum WasmBuildProgressEvent {
418    /// One build/cache acquisition started.
419    Started,
420    /// One exact Cargo input-resolution pass completed.
421    InputsResolved {
422        /// Complete exact build fingerprint.
423        fingerprint: InputDigest,
424        /// Semantic selected-source/configuration digest.
425        input_digest: InputDigest,
426        /// Time spent on this resolution pass.
427        elapsed: Duration,
428    },
429    /// No reusable exact entry existed for this fingerprint.
430    CacheMiss {
431        /// Missing exact fingerprint.
432        fingerprint: InputDigest,
433    },
434    /// Exact artifacts were found and materialized when necessary.
435    CacheHit {
436        /// Reused exact fingerprint.
437        fingerprint: InputDigest,
438    },
439    /// The build is about to wait for a caller-owned shared Cargo target.
440    SharedTargetLockStarted {
441        /// Shared target selected by the build specification.
442        target_dir: PathBuf,
443    },
444    /// Exclusive shared-target ownership was acquired.
445    SharedTargetLockAcquired {
446        /// Canonical shared target directory.
447        target_dir: PathBuf,
448        /// Time spent waiting for another process.
449        wait: Duration,
450    },
451    /// Scheduled shared-target retention is about to be evaluated under lock.
452    SharedTargetMaintenanceStarted {
453        /// Canonical shared target selected by the build specification.
454        target_dir: PathBuf,
455    },
456    /// Scheduled shared-target retention completed or was skipped.
457    SharedTargetMaintenanceFinished {
458        /// Structured retention result attached to the successful acquisition.
459        outcome: SharedIncrementalTargetMaintenanceOutcome,
460    },
461    /// Cargo compilation started.
462    CargoStarted {
463        /// Cargo target receiving compilation state.
464        target_dir: PathBuf,
465    },
466    /// One raw Cargo output chunk was read without lossy UTF-8 conversion.
467    CargoOutput {
468        /// Child-process stream that produced the bytes.
469        stream: WasmBuildOutputStream,
470        /// Raw output bytes in per-stream read order.
471        bytes: Vec<u8>,
472    },
473    /// The current acquisition phase remained active without another event.
474    Heartbeat {
475        /// Phase that is still making or waiting for progress.
476        phase: WasmBuildProgressPhase,
477        /// Time elapsed since this phase started.
478        elapsed: Duration,
479    },
480    /// Cargo exited and all captured output was drained.
481    CargoFinished {
482        /// Whether Cargo reported success.
483        success: bool,
484        /// Portable exit code when the platform exposes one.
485        code: Option<i32>,
486        /// Complete Cargo execution duration.
487        elapsed: Duration,
488    },
489    /// The complete cacheable build operation succeeded.
490    Finished {
491        /// Whether Cargo ran or an exact entry was reused.
492        outcome: WasmBuildProgressOutcome,
493        /// Exact fingerprint selected by the operation.
494        fingerprint: InputDigest,
495        /// Total operation duration.
496        elapsed: Duration,
497    },
498}
499
500impl Default for WasmBuildProgressConfig {
501    fn default() -> Self {
502        Self {
503            heartbeat_interval: Some(Duration::from_secs(10)),
504            emit_cargo_output: true,
505        }
506    }
507}
508
509impl WasmBuildProgressConfig {
510    /// Observe acquisition progress and emit a heartbeat at least every ten quiet seconds.
511    #[must_use]
512    pub fn new() -> Self {
513        Self::default()
514    }
515
516    /// Select the maximum quiet interval between phase-aware heartbeat events.
517    ///
518    /// A zero interval is rejected before any build work begins.
519    #[must_use]
520    pub const fn with_heartbeat_interval(mut self, interval: Duration) -> Self {
521        self.heartbeat_interval = Some(interval);
522        self
523    }
524
525    /// Disable time-based heartbeats while retaining phase and output events.
526    #[must_use]
527    pub const fn without_heartbeats(mut self) -> Self {
528        self.heartbeat_interval = None;
529        self
530    }
531
532    /// Select whether raw Cargo stdout/stderr chunks are forwarded.
533    ///
534    /// Output is always captured for structured build failures.
535    #[must_use]
536    pub const fn with_cargo_output(mut self, emit: bool) -> Self {
537        self.emit_cargo_output = emit;
538        self
539    }
540
541    /// Configured heartbeat interval, or `None` when disabled.
542    #[must_use]
543    pub const fn heartbeat_interval(self) -> Option<Duration> {
544        self.heartbeat_interval
545    }
546
547    /// Whether raw Cargo output chunks are emitted to the observer.
548    #[must_use]
549    pub const fn emits_cargo_output(self) -> bool {
550        self.emit_cargo_output
551    }
552}
553
554struct ProgressReporter<'a> {
555    config: WasmBuildProgressConfig,
556    observer: Option<&'a mut dyn FnMut(WasmBuildProgressEvent)>,
557    last_event: Instant,
558    failure_phase: Option<WasmBuildFailurePhase>,
559    failure_timings: WasmBuildFailureTimings,
560}
561
562impl ProgressReporter<'_> {
563    fn silent() -> Self {
564        Self {
565            config: WasmBuildProgressConfig {
566                heartbeat_interval: None,
567                emit_cargo_output: false,
568            },
569            observer: None,
570            last_event: Instant::now(),
571            failure_phase: None,
572            failure_timings: WasmBuildFailureTimings::default(),
573        }
574    }
575
576    fn observed(
577        config: WasmBuildProgressConfig,
578        observer: &'_ mut dyn FnMut(WasmBuildProgressEvent),
579    ) -> ProgressReporter<'_> {
580        ProgressReporter {
581            config,
582            observer: Some(observer),
583            last_event: Instant::now(),
584            failure_phase: None,
585            failure_timings: WasmBuildFailureTimings::default(),
586        }
587    }
588
589    fn emit(&mut self, event: WasmBuildProgressEvent) {
590        if let Some(observer) = &mut self.observer {
591            observer(event);
592            self.last_event = Instant::now();
593        }
594    }
595
596    const fn is_observed(&self) -> bool {
597        self.observer.is_some()
598    }
599
600    fn heartbeat_due_in(&self) -> Option<Duration> {
601        self.config
602            .heartbeat_interval
603            .map(|interval| interval.saturating_sub(self.last_event.elapsed()))
604    }
605
606    fn emit_heartbeat(&mut self, phase: WasmBuildProgressPhase, elapsed: Duration) {
607        self.emit(WasmBuildProgressEvent::Heartbeat { phase, elapsed });
608    }
609
610    fn emit_heartbeat_if_due(&mut self, phase: WasmBuildProgressPhase, elapsed: Duration) {
611        if self.heartbeat_due_in() == Some(Duration::ZERO) {
612            self.emit_heartbeat(phase, elapsed);
613        }
614    }
615
616    fn run_phase<T, F>(&mut self, phase: WasmBuildProgressPhase, operation: F) -> T
617    where
618        T: Send,
619        F: FnOnce() -> T + Send,
620    {
621        let started = Instant::now();
622        self.begin_phase(progress_failure_phase(phase));
623        let result = if !self.is_observed() || self.config.heartbeat_interval.is_none() {
624            operation()
625        } else {
626            thread::scope(|scope| {
627                let (finished, completion) = mpsc::sync_channel(0);
628                let worker = scope.spawn(move || {
629                    let result = operation();
630                    let _ = finished.send(());
631                    result
632                });
633                loop {
634                    let wait = self
635                        .heartbeat_due_in()
636                        .expect("observed phase must have a heartbeat interval");
637                    match completion.recv_timeout(wait) {
638                        Ok(()) | Err(RecvTimeoutError::Disconnected) => {
639                            return worker
640                                .join()
641                                .unwrap_or_else(|panic| std::panic::resume_unwind(panic));
642                        }
643                        Err(RecvTimeoutError::Timeout) => {
644                            self.emit_heartbeat(phase, started.elapsed());
645                        }
646                    }
647                }
648            })
649        };
650        self.record_phase(progress_failure_phase(phase), started.elapsed());
651        result
652    }
653
654    const fn begin_phase(&mut self, phase: WasmBuildFailurePhase) {
655        self.failure_phase = Some(phase);
656    }
657
658    fn record_phase(&mut self, phase: WasmBuildFailurePhase, elapsed: Duration) {
659        self.failure_phase = Some(phase);
660        let timings = &mut self.failure_timings;
661        match phase {
662            WasmBuildFailurePhase::Specification => {}
663            WasmBuildFailurePhase::ExactCacheCoordination => {
664                timings.exact_cache_coordination =
665                    timings.exact_cache_coordination.saturating_add(elapsed);
666            }
667            WasmBuildFailurePhase::ToolIdentity => {
668                timings.input_resolution.tool_identity = timings
669                    .input_resolution
670                    .tool_identity
671                    .saturating_add(elapsed);
672                timings.input_resolution.total =
673                    timings.input_resolution.total.saturating_add(elapsed);
674            }
675            WasmBuildFailurePhase::CargoMetadata => {
676                timings.input_resolution.cargo_metadata = timings
677                    .input_resolution
678                    .cargo_metadata
679                    .saturating_add(elapsed);
680                timings.input_resolution.total =
681                    timings.input_resolution.total.saturating_add(elapsed);
682            }
683            WasmBuildFailurePhase::InputDiscovery => {
684                timings.input_resolution.input_discovery = timings
685                    .input_resolution
686                    .input_discovery
687                    .saturating_add(elapsed);
688                timings.input_resolution.total =
689                    timings.input_resolution.total.saturating_add(elapsed);
690            }
691            WasmBuildFailurePhase::ContentHashing => {
692                timings.input_resolution.content_hashing = timings
693                    .input_resolution
694                    .content_hashing
695                    .saturating_add(elapsed);
696                timings.input_resolution.total =
697                    timings.input_resolution.total.saturating_add(elapsed);
698            }
699            WasmBuildFailurePhase::SharedTargetCoordination => {
700                timings.shared_target_coordination = Some(
701                    timings
702                        .shared_target_coordination
703                        .unwrap_or_default()
704                        .saturating_add(elapsed),
705                );
706            }
707            WasmBuildFailurePhase::SharedTargetMaintenance => {
708                timings.shared_target_maintenance = Some(
709                    timings
710                        .shared_target_maintenance
711                        .unwrap_or_default()
712                        .saturating_add(elapsed),
713                );
714            }
715            WasmBuildFailurePhase::CargoBuild => {
716                timings.cargo_build = Some(
717                    timings
718                        .cargo_build
719                        .unwrap_or_default()
720                        .saturating_add(elapsed),
721                );
722            }
723            WasmBuildFailurePhase::ArtifactPublication => {
724                timings.artifact_publication = Some(
725                    timings
726                        .artifact_publication
727                        .unwrap_or_default()
728                        .saturating_add(elapsed),
729                );
730            }
731            WasmBuildFailurePhase::ExactCacheMaintenance => {
732                timings.exact_cache_maintenance = Some(
733                    timings
734                        .exact_cache_maintenance
735                        .unwrap_or_default()
736                        .saturating_add(elapsed),
737                );
738            }
739            WasmBuildFailurePhase::Cleanup => {
740                timings.cleanup = Some(timings.cleanup.unwrap_or_default().saturating_add(elapsed));
741            }
742        }
743    }
744
745    fn failure_details(&self, error: &WasmBuildError, total: Duration) -> WasmBuildFailureDetails {
746        let phase = self
747            .failure_phase
748            .unwrap_or_else(|| classify_unobserved_failure(error));
749        let mut timings = self.failure_timings;
750        timings.total = total;
751        WasmBuildFailureDetails { phase, timings }
752    }
753}
754
755const fn progress_failure_phase(phase: WasmBuildProgressPhase) -> WasmBuildFailurePhase {
756    match phase {
757        WasmBuildProgressPhase::ExactCacheLock => WasmBuildFailurePhase::ExactCacheCoordination,
758        WasmBuildProgressPhase::CargoIdentity | WasmBuildProgressPhase::RustcIdentity => {
759            WasmBuildFailurePhase::ToolIdentity
760        }
761        WasmBuildProgressPhase::CargoMetadata => WasmBuildFailurePhase::CargoMetadata,
762        WasmBuildProgressPhase::InputDiscovery => WasmBuildFailurePhase::InputDiscovery,
763        WasmBuildProgressPhase::ContentHashing => WasmBuildFailurePhase::ContentHashing,
764        WasmBuildProgressPhase::SharedTargetLock => WasmBuildFailurePhase::SharedTargetCoordination,
765        WasmBuildProgressPhase::SharedTargetMaintenance => {
766            WasmBuildFailurePhase::SharedTargetMaintenance
767        }
768        WasmBuildProgressPhase::CargoBuild => WasmBuildFailurePhase::CargoBuild,
769        WasmBuildProgressPhase::ArtifactPublication => WasmBuildFailurePhase::ArtifactPublication,
770        WasmBuildProgressPhase::ExactCacheMaintenance => {
771            WasmBuildFailurePhase::ExactCacheMaintenance
772        }
773    }
774}
775
776const fn classify_unobserved_failure(error: &WasmBuildError) -> WasmBuildFailurePhase {
777    match error {
778        WasmBuildError::InvalidSpec { .. } => WasmBuildFailurePhase::Specification,
779        WasmBuildError::CommandSpawn { phase, .. }
780        | WasmBuildError::CommandFailed { phase, .. } => match phase {
781            WasmBuildPhase::CargoIdentity | WasmBuildPhase::RustcIdentity => {
782                WasmBuildFailurePhase::ToolIdentity
783            }
784            WasmBuildPhase::CargoMetadata => WasmBuildFailurePhase::CargoMetadata,
785            WasmBuildPhase::CargoBuild => WasmBuildFailurePhase::CargoBuild,
786        },
787        WasmBuildError::InvalidMetadata { .. } => WasmBuildFailurePhase::CargoMetadata,
788        WasmBuildError::InvalidCargoConfiguration { .. } => WasmBuildFailurePhase::InputDiscovery,
789        WasmBuildError::MissingArtifacts { .. } => WasmBuildFailurePhase::ArtifactPublication,
790        WasmBuildError::InputsChangedDuringAcquisition { .. } => {
791            WasmBuildFailurePhase::ContentHashing
792        }
793        WasmBuildError::PreparedInputSnapshotInvalidated => {
794            WasmBuildFailurePhase::ArtifactPublication
795        }
796        WasmBuildError::FailedBuildCleanup { .. } => WasmBuildFailurePhase::Cleanup,
797        WasmBuildError::Io { .. } => WasmBuildFailurePhase::ExactCacheCoordination,
798    }
799}
800
801/// External phase associated with a cacheable Wasm build failure.
802#[non_exhaustive]
803#[derive(Clone, Copy, Debug, Eq, PartialEq)]
804pub enum WasmBuildPhase {
805    /// Resolving Cargo's package graph.
806    CargoMetadata,
807    /// Reading the Cargo executable identity.
808    CargoIdentity,
809    /// Reading the Rust compiler identity.
810    RustcIdentity,
811    /// Compiling the selected Wasm packages.
812    CargoBuild,
813}
814
815/// Structured failure from a cacheable Wasm build.
816#[non_exhaustive]
817#[derive(Debug)]
818pub enum WasmBuildError {
819    /// The caller supplied an incomplete or inconsistent specification.
820    InvalidSpec { message: String },
821    /// A filesystem operation failed.
822    Io {
823        operation: &'static str,
824        path: PathBuf,
825        source: io::Error,
826    },
827    /// An external command could not be launched.
828    CommandSpawn {
829        phase: WasmBuildPhase,
830        program: OsString,
831        source: io::Error,
832    },
833    /// An external command completed unsuccessfully.
834    CommandFailed {
835        phase: WasmBuildPhase,
836        status: ExitStatus,
837        stdout: String,
838        stderr: String,
839    },
840    /// Cargo metadata did not contain the expected package graph.
841    InvalidMetadata { message: String },
842    /// A discovered Cargo configuration could not be interpreted exactly.
843    InvalidCargoConfiguration { path: PathBuf, message: String },
844    /// Cargo succeeded without producing every declared Wasm artifact.
845    MissingArtifacts { paths: Vec<PathBuf> },
846    /// Declared inputs changed while acquiring or building Wasm artifacts.
847    InputsChangedDuringAcquisition {
848        before: InputDigest,
849        after: InputDigest,
850    },
851    /// Another concurrent reader invalidated the prepared input snapshot before publication.
852    PreparedInputSnapshotInvalidated,
853    /// A build failed and its incomplete fingerprint directory could not be removed.
854    FailedBuildCleanup {
855        build_error: Box<Self>,
856        path: PathBuf,
857        source: io::Error,
858    },
859}
860
861impl WasmBuildSpec {
862    /// Describe one Cargo build targeting `wasm32-unknown-unknown`.
863    ///
864    /// `profile_target_dir` is Cargo's output subdirectory, such as `debug`,
865    /// `release`, or the name supplied to `--profile`.
866    /// Relative `workspace_root` and exact `target_dir` paths are resolved from
867    /// the caller's working directory. Shared targets are workspace-relative.
868    #[must_use]
869    pub fn new(
870        workspace_root: &Path,
871        target_dir: &Path,
872        packages: &[&str],
873        profile_target_dir: &str,
874    ) -> Self {
875        Self {
876            workspace_root: workspace_root.to_owned(),
877            target_dir: target_dir.to_owned(),
878            packages: packages
879                .iter()
880                .map(|package| (*package).to_owned())
881                .collect(),
882            profile_target_dir: profile_target_dir.to_owned(),
883            cargo_profile_args: Vec::new(),
884            extra_env: BTreeMap::new(),
885            inherited_env: BTreeSet::new(),
886            additional_inputs: Vec::new(),
887            target: DEFAULT_TARGET.to_owned(),
888            cargo_program: std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()),
889            rustc_program: std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()),
890            cache_mode: WasmBuildCacheMode::Isolated,
891            prune_policy: None,
892            prune_interval: None,
893            shared_incremental_maintenance_config: None,
894        }
895    }
896
897    /// Set Cargo profile and feature arguments used for the build and fingerprint.
898    ///
899    /// `--target-dir` overrides are rejected during acquisition; target
900    /// directories are selected by this specification's cache configuration.
901    #[must_use]
902    pub fn with_cargo_profile_args<I, S>(mut self, arguments: I) -> Self
903    where
904        I: IntoIterator<Item = S>,
905        S: AsRef<OsStr>,
906    {
907        self.cargo_profile_args = arguments
908            .into_iter()
909            .map(|argument| argument.as_ref().to_owned())
910            .collect();
911        self
912    }
913
914    /// Set deterministic OS-native child-process environment overrides.
915    ///
916    /// `CARGO_TARGET_DIR` is owned by the cache configuration and cannot be
917    /// overridden here. Conflicting specifications fail before acquisition.
918    #[must_use]
919    pub fn with_extra_env<I, K, V>(mut self, environment: I) -> Self
920    where
921        I: IntoIterator<Item = (K, V)>,
922        K: Into<OsString>,
923        V: Into<OsString>,
924    {
925        self.extra_env = environment
926            .into_iter()
927            .map(|(key, value)| (key.into(), value.into()))
928            .collect();
929        self
930    }
931
932    /// Add ambient environment names whose current values affect the build.
933    ///
934    /// Common Rust and Cargo toolchain variables are included automatically.
935    /// Callers must declare application-specific variables read by build scripts.
936    #[must_use]
937    pub fn with_inherited_env<I, S>(mut self, names: I) -> Self
938    where
939        I: IntoIterator<Item = S>,
940        S: Into<OsString>,
941    {
942        self.inherited_env.extend(names.into_iter().map(Into::into));
943        self
944    }
945
946    /// Add files or directories not discoverable through Cargo's local dependency graph.
947    ///
948    /// Relative paths are resolved from the workspace root. Use this for build
949    /// script configuration, generated schemas, or other externally read inputs.
950    #[must_use]
951    pub fn with_additional_inputs<I, P>(mut self, paths: I) -> Self
952    where
953        I: IntoIterator<Item = P>,
954        P: Into<PathBuf>,
955    {
956        self.additional_inputs
957            .extend(paths.into_iter().map(Into::into));
958        self
959    }
960
961    /// Override the Cargo compilation target.
962    #[must_use]
963    pub fn with_target(mut self, target: &str) -> Self {
964        target.clone_into(&mut self.target);
965        self
966    }
967
968    /// Override the Cargo executable used by metadata, identity, and build commands.
969    #[must_use]
970    pub fn with_cargo_program(mut self, program: impl Into<OsString>) -> Self {
971        self.cargo_program = program.into();
972        self
973    }
974
975    /// Override the Rust compiler executable used to fingerprint the toolchain.
976    #[must_use]
977    pub fn with_rustc_program(mut self, program: impl Into<OsString>) -> Self {
978        self.rustc_program = program.into();
979        self
980    }
981
982    /// Build cache misses in one caller-owned shared Cargo incremental target.
983    ///
984    /// Exact final Wasm artifacts still live in the content-addressed cache.
985    /// The shared target is coordinated across processes but is never pruned
986    /// or removed by `ic-testkit` after a failed build.
987    #[must_use]
988    pub fn with_shared_incremental_target(mut self, target_dir: impl Into<PathBuf>) -> Self {
989        self.cache_mode = WasmBuildCacheMode::SharedIncremental {
990            target_dir: target_dir.into(),
991        };
992        self
993    }
994
995    /// Schedule caller-owned shared-target retention as part of acquisition.
996    ///
997    /// This option requires [`Self::with_shared_incremental_target`]. Every
998    /// acquisition coordinates through that target, including an exact hit,
999    /// so a missing target can be created and receive its first schedule
1000    /// marker immediately. Matching recent passes only check the marker; due
1001    /// passes reuse the acquisition's exact Cargo input resolution before
1002    /// evaluating retention. The structured result is attached to the build
1003    /// record and emitted through observed progress. Maintenance failures fail
1004    /// the acquisition and do not record a successful schedule marker.
1005    #[must_use]
1006    pub const fn with_shared_incremental_target_maintenance_at_most_every(
1007        mut self,
1008        policy: SharedIncrementalTargetPrunePolicy,
1009        minimum_interval: Duration,
1010    ) -> Self {
1011        self.shared_incremental_maintenance_config = Some(
1012            SharedIncrementalTargetMaintenanceConfig::new(policy, minimum_interval),
1013        );
1014        self
1015    }
1016
1017    /// Attach an explicit shared-target maintenance configuration.
1018    ///
1019    /// This is the configurable counterpart to
1020    /// [`Self::with_shared_incremental_target_maintenance_at_most_every`] and
1021    /// supports strict or best-effort failure handling.
1022    #[must_use]
1023    pub const fn with_shared_incremental_target_maintenance(
1024        mut self,
1025        config: SharedIncrementalTargetMaintenanceConfig,
1026    ) -> Self {
1027        self.shared_incremental_maintenance_config = Some(config);
1028        self
1029    }
1030
1031    /// Apply cache retention under the build operation's existing process lock.
1032    ///
1033    /// Maintenance is best-effort: its structured result is attached to the
1034    /// successful build record and cannot turn ready artifacts into a build
1035    /// failure. The active fingerprint is protected from this pruning pass.
1036    #[must_use]
1037    pub const fn with_prune_policy(mut self, policy: ArtifactCachePrunePolicy) -> Self {
1038        self.prune_policy = Some(policy);
1039        self.prune_interval = None;
1040        self
1041    }
1042
1043    /// Apply exact-entry retention at most once per `minimum_interval`.
1044    ///
1045    /// The active fingerprint remains protected. A zero interval is equivalent
1046    /// to [`Self::with_prune_policy`]. The interval covers attempted
1047    /// maintenance, including a nonfatal failed attempt. This schedule never
1048    /// owns or scans a caller-owned shared incremental Cargo target.
1049    #[must_use]
1050    pub const fn with_prune_policy_at_most_every(
1051        mut self,
1052        policy: ArtifactCachePrunePolicy,
1053        minimum_interval: Duration,
1054    ) -> Self {
1055        self.prune_policy = Some(policy);
1056        self.prune_interval = Some(minimum_interval);
1057        self
1058    }
1059
1060    /// Workspace containing the selected Cargo packages.
1061    #[must_use]
1062    pub fn workspace_root(&self) -> &Path {
1063        &self.workspace_root
1064    }
1065
1066    /// Cargo target directory containing artifacts, lock, and stamps.
1067    #[must_use]
1068    pub fn target_dir(&self) -> &Path {
1069        &self.target_dir
1070    }
1071
1072    /// Selected Cargo package names.
1073    #[must_use]
1074    pub fn packages(&self) -> &[String] {
1075        &self.packages
1076    }
1077
1078    /// Cargo-target ownership mode used for cache misses.
1079    #[must_use]
1080    pub const fn cache_mode(&self) -> &WasmBuildCacheMode {
1081        &self.cache_mode
1082    }
1083
1084    /// Exact-entry retention policy attached to this specification, when configured.
1085    #[must_use]
1086    pub const fn prune_policy(&self) -> Option<ArtifactCachePrunePolicy> {
1087        self.prune_policy
1088    }
1089
1090    /// Minimum interval between exact-entry retention attempts, when scheduled.
1091    #[must_use]
1092    pub const fn prune_interval(&self) -> Option<Duration> {
1093        self.prune_interval
1094    }
1095
1096    /// Shared incremental-target maintenance attached to this specification.
1097    #[must_use]
1098    pub const fn shared_incremental_target_maintenance(
1099        &self,
1100    ) -> Option<SharedIncrementalTargetMaintenanceConfig> {
1101        self.shared_incremental_maintenance_config
1102    }
1103}
1104
1105impl WasmBuildOutcome {
1106    /// Read the common build record.
1107    #[must_use]
1108    pub const fn record(&self) -> &WasmBuildRecord {
1109        match self {
1110            Self::Built(record) | Self::Reused(record) => record,
1111        }
1112    }
1113
1114    /// Report whether exact matching artifacts were reused.
1115    #[must_use]
1116    pub const fn is_reused(&self) -> bool {
1117        matches!(self, Self::Reused(_))
1118    }
1119}
1120
1121impl WasmBuildRecord {
1122    /// Exact build fingerprint used by the atomic cache stamp.
1123    #[must_use]
1124    pub const fn fingerprint(&self) -> InputDigest {
1125        self.fingerprint
1126    }
1127
1128    /// Semantic digest of selected package sources and configuration inputs.
1129    #[must_use]
1130    pub const fn input_digest(&self) -> InputDigest {
1131        self.input_digest
1132    }
1133
1134    /// Immutable content-addressed cache directory for this exact build.
1135    ///
1136    /// The directory is selected by the build fingerprint and contains the
1137    /// cached Wasm artifacts and their stamps. The record and its clones retain
1138    /// this entry against pruning until their last drop. A copied path alone
1139    /// does not retain ownership. Treat the contents as read-only.
1140    #[must_use]
1141    pub fn exact_cache_path(&self) -> &Path {
1142        &self.exact_cache_path
1143    }
1144
1145    /// Exact, read-only Wasm paths retained until this record and its clones drop.
1146    ///
1147    /// Keep a record alive throughout post-link processing and reading. Configured
1148    /// materialization destinations remain mutable and are not retained.
1149    #[must_use]
1150    pub fn artifacts(&self) -> &[PathBuf] {
1151        &self.artifacts
1152    }
1153
1154    /// Phase timings captured by the cacheable build operation.
1155    #[must_use]
1156    pub const fn timings(&self) -> WasmBuildTimings {
1157        self.timings
1158    }
1159
1160    /// Cache maintenance attempted under the build lock, when configured.
1161    #[must_use]
1162    pub const fn maintenance(&self) -> Option<&ArtifactCacheMaintenance> {
1163        self.maintenance.as_ref()
1164    }
1165
1166    /// Scheduled caller-owned shared-target maintenance, when configured.
1167    #[must_use]
1168    pub const fn shared_incremental_maintenance(
1169        &self,
1170    ) -> Option<&SharedIncrementalTargetMaintenanceOutcome> {
1171        self.shared_incremental_maintenance.as_ref()
1172    }
1173}
1174
1175impl WasmBuildTimings {
1176    /// Time spent waiting for the output-directory process lock.
1177    #[must_use]
1178    pub const fn lock_wait(self) -> Duration {
1179        self.lock_wait
1180    }
1181
1182    /// Time spent waiting for a shared incremental-target lock, when configured.
1183    #[must_use]
1184    pub const fn shared_incremental_lock_wait(self) -> Option<Duration> {
1185        self.shared_incremental_lock_wait
1186    }
1187
1188    /// Detailed tool, metadata, discovery, and hashing timings.
1189    #[must_use]
1190    pub const fn input_resolution(self) -> WasmInputResolutionTimings {
1191        self.input_resolution
1192    }
1193
1194    /// Time spent in `cargo build`, or `None` for a cache hit.
1195    #[must_use]
1196    pub const fn cargo_build(self) -> Option<Duration> {
1197        self.cargo_build
1198    }
1199
1200    /// Time spent on configured best-effort cache maintenance.
1201    #[must_use]
1202    pub const fn cache_maintenance(self) -> Option<Duration> {
1203        self.cache_maintenance
1204    }
1205
1206    /// Total operation duration, including lock coordination.
1207    #[must_use]
1208    pub const fn total(self) -> Duration {
1209        self.total
1210    }
1211
1212    pub(super) const fn saturating_add(self, other: Self) -> Self {
1213        let mut input_resolution = self.input_resolution;
1214        input_resolution.include(other.input_resolution);
1215        Self {
1216            lock_wait: self.lock_wait.saturating_add(other.lock_wait),
1217            shared_incremental_lock_wait: saturating_add_optional_duration(
1218                self.shared_incremental_lock_wait,
1219                other.shared_incremental_lock_wait,
1220            ),
1221            input_resolution,
1222            cargo_build: saturating_add_optional_duration(self.cargo_build, other.cargo_build),
1223            cache_maintenance: saturating_add_optional_duration(
1224                self.cache_maintenance,
1225                other.cache_maintenance,
1226            ),
1227            total: self.total.saturating_add(other.total),
1228        }
1229    }
1230}
1231
1232impl WasmInputResolutionTimings {
1233    /// Time spent reading Cargo and rustc identities.
1234    #[must_use]
1235    pub const fn tool_identity(self) -> Duration {
1236        self.tool_identity
1237    }
1238
1239    /// Time spent running and decoding `cargo metadata`.
1240    #[must_use]
1241    pub const fn cargo_metadata(self) -> Duration {
1242        self.cargo_metadata
1243    }
1244
1245    /// Time spent resolving packages, configuration, and watched paths.
1246    #[must_use]
1247    pub const fn input_discovery(self) -> Duration {
1248        self.input_discovery
1249    }
1250
1251    /// Time spent reading and hashing exact input contents.
1252    #[must_use]
1253    pub const fn content_hashing(self) -> Duration {
1254        self.content_hashing
1255    }
1256
1257    /// Complete input-resolution duration.
1258    #[must_use]
1259    pub const fn total(self) -> Duration {
1260        self.total
1261    }
1262
1263    const fn include(&mut self, other: Self) {
1264        self.tool_identity = self.tool_identity.saturating_add(other.tool_identity);
1265        self.cargo_metadata = self.cargo_metadata.saturating_add(other.cargo_metadata);
1266        self.input_discovery = self.input_discovery.saturating_add(other.input_discovery);
1267        self.content_hashing = self.content_hashing.saturating_add(other.content_hashing);
1268        self.total = self.total.saturating_add(other.total);
1269    }
1270}
1271
1272impl WasmBuildFailureDetails {
1273    pub(super) fn specification(total: Duration) -> Self {
1274        Self {
1275            phase: WasmBuildFailurePhase::Specification,
1276            timings: WasmBuildFailureTimings {
1277                total,
1278                ..WasmBuildFailureTimings::default()
1279            },
1280        }
1281    }
1282
1283    /// Primary acquisition phase that returned the failure.
1284    #[must_use]
1285    pub const fn phase(self) -> WasmBuildFailurePhase {
1286        self.phase
1287    }
1288
1289    /// Partial phase timings retained before the failure returned.
1290    #[must_use]
1291    pub const fn timings(self) -> WasmBuildFailureTimings {
1292        self.timings
1293    }
1294}
1295
1296impl WasmBuildFailureTimings {
1297    /// Time spent coordinating the exact artifact cache before failure.
1298    #[must_use]
1299    pub const fn exact_cache_coordination(self) -> Duration {
1300        self.exact_cache_coordination
1301    }
1302
1303    /// Time spent coordinating a shared incremental target, when reached.
1304    #[must_use]
1305    pub const fn shared_target_coordination(self) -> Option<Duration> {
1306        self.shared_target_coordination
1307    }
1308
1309    /// Partial Cargo/rustc identity, metadata, discovery, and hashing timings.
1310    #[must_use]
1311    pub const fn input_resolution(self) -> WasmInputResolutionTimings {
1312        self.input_resolution
1313    }
1314
1315    /// Time spent on shared-target maintenance, when reached.
1316    #[must_use]
1317    pub const fn shared_target_maintenance(self) -> Option<Duration> {
1318        self.shared_target_maintenance
1319    }
1320
1321    /// Time spent executing Cargo, including an unsuccessful execution.
1322    #[must_use]
1323    pub const fn cargo_build(self) -> Option<Duration> {
1324        self.cargo_build
1325    }
1326
1327    /// Time spent validating or publishing artifacts, when reached.
1328    #[must_use]
1329    pub const fn artifact_publication(self) -> Option<Duration> {
1330        self.artifact_publication
1331    }
1332
1333    /// Time spent on exact-cache maintenance, when reached.
1334    #[must_use]
1335    pub const fn exact_cache_maintenance(self) -> Option<Duration> {
1336        self.exact_cache_maintenance
1337    }
1338
1339    /// Explicit incomplete-entry cleanup time, when failure required it.
1340    #[must_use]
1341    pub const fn cleanup(self) -> Option<Duration> {
1342        self.cleanup
1343    }
1344
1345    /// Complete failed acquisition wall time.
1346    #[must_use]
1347    pub const fn total(self) -> Duration {
1348        self.total
1349    }
1350}
1351
1352impl CargoBuildInput {
1353    /// Stable checkout-independent label used while hashing this input.
1354    #[must_use]
1355    pub fn label(&self) -> &Path {
1356        &self.label
1357    }
1358
1359    /// Resolved file or directory read by the Cargo build.
1360    #[must_use]
1361    pub fn path(&self) -> &Path {
1362        &self.path
1363    }
1364}
1365
1366impl ResolvedCargoBuildInputs {
1367    /// Exact build fingerprint including Cargo inputs, tools, arguments, and environment.
1368    #[must_use]
1369    pub const fn fingerprint(&self) -> InputDigest {
1370        self.fingerprint
1371    }
1372
1373    /// Semantic digest of selected Cargo sources and workspace configuration.
1374    ///
1375    /// Unlike [`Self::validation_digest`], this may remain unchanged after an
1376    /// unrelated host-only workspace manifest or lockfile update.
1377    #[must_use]
1378    pub const fn input_digest(&self) -> InputDigest {
1379        self.input_digest
1380    }
1381
1382    /// Conservative digest of every raw source and configuration input.
1383    ///
1384    /// This digest is used for mutation guards. It may change while
1385    /// [`Self::input_digest`] and [`Self::fingerprint`] remain unchanged.
1386    #[must_use]
1387    pub const fn validation_digest(&self) -> InputDigest {
1388        self.validation_digest
1389    }
1390
1391    /// Stable logical labels and conservative resolved validation paths.
1392    #[must_use]
1393    pub fn inputs(&self) -> &[CargoBuildInput] {
1394        &self.inputs
1395    }
1396
1397    /// Generated-state roots excluded while recursively hashing local inputs.
1398    ///
1399    /// These exclusions are derived by `ic-testkit`; callers cannot add
1400    /// arbitrary exclusions through this snapshot.
1401    #[must_use]
1402    pub fn exclusions(&self) -> &[PathBuf] {
1403        &self.exclusions
1404    }
1405
1406    /// Timings for tool identity, metadata, discovery, and content hashing.
1407    #[must_use]
1408    pub const fn timings(&self) -> WasmInputResolutionTimings {
1409        self.timings
1410    }
1411
1412    /// Resolve `spec` again and report whether its exact identity is unchanged.
1413    pub fn is_current(&self, spec: &WasmBuildSpec) -> Result<bool, WasmBuildError> {
1414        resolve_cargo_build_inputs(spec).map(|current| current.fingerprint == self.fingerprint)
1415    }
1416
1417    /// Rehash the already discovered Cargo source/configuration set.
1418    ///
1419    /// This is cheaper than rerunning Cargo metadata and is intended for
1420    /// before/after guards around external artifact transformations. Resolve a
1421    /// new snapshot to observe tool, argument, environment, or dependency-graph
1422    /// identity changes between separate acquisitions.
1423    pub fn is_content_current(&self) -> Result<bool, WasmBuildError> {
1424        self.current_validation_digest()
1425            .map(|current| current == self.validation_digest)
1426    }
1427
1428    pub(super) fn current_validation_digest(&self) -> Result<InputDigest, WasmBuildError> {
1429        let inputs = self
1430            .inputs
1431            .iter()
1432            .map(|input| (input.label.clone(), input.path.clone()))
1433            .collect::<Vec<_>>();
1434        digest_labeled_paths_composable(
1435            "wasm-source-inputs-v1",
1436            &inputs,
1437            &self.exclusions,
1438            &mut LabeledPathDigestCache::default(),
1439        )
1440        .map_err(|source| WasmBuildError::Io {
1441            operation: "rehash resolved Cargo build inputs",
1442            path: self
1443                .inputs
1444                .first()
1445                .map_or_else(PathBuf::new, |input| input.path.clone()),
1446            source,
1447        })
1448    }
1449}
1450
1451impl WasmBuildSessionState {
1452    pub(super) fn new() -> Self {
1453        Self {
1454            snapshots: Vec::new(),
1455            digest_cache: LabeledPathDigestCache::default(),
1456            snapshot_reuses: 0,
1457            invalidated: false,
1458        }
1459    }
1460
1461    pub(super) const fn snapshot_count(&self) -> usize {
1462        self.snapshots.len()
1463    }
1464
1465    pub(super) const fn snapshot_reuses(&self) -> usize {
1466        self.snapshot_reuses
1467    }
1468
1469    pub(super) const fn is_invalidated(&self) -> bool {
1470        self.invalidated
1471    }
1472
1473    fn reuse(&mut self, spec: &WasmBuildSpec) -> Option<ResolvedCargoBuildInputs> {
1474        let (_, snapshot) = self
1475            .snapshots
1476            .iter()
1477            .find(|(candidate, _)| candidate == spec)?;
1478        self.snapshot_reuses = self.snapshot_reuses.saturating_add(1);
1479        let mut snapshot = snapshot.clone();
1480        snapshot.timings = WasmInputResolutionTimings::default();
1481        Some(snapshot)
1482    }
1483
1484    fn remember(&mut self, spec: &WasmBuildSpec, resolved: &ResolvedCargoBuildInputs) {
1485        if self
1486            .snapshots
1487            .iter()
1488            .any(|(candidate, _)| candidate == spec)
1489        {
1490            return;
1491        }
1492        let mut snapshot = resolved.clone();
1493        snapshot.timings = WasmInputResolutionTimings::default();
1494        self.snapshots.push((spec.clone(), snapshot));
1495    }
1496
1497    fn invalidate(&mut self) {
1498        self.snapshots.clear();
1499        self.digest_cache = LabeledPathDigestCache::default();
1500        self.invalidated = true;
1501    }
1502}
1503
1504impl WasmBuildInputSnapshotState {
1505    pub(super) fn prepare(specs: &[WasmBuildSpec]) -> Result<Self, WasmBuildError> {
1506        for spec in specs {
1507            validate_spec(spec)?;
1508        }
1509        let mut resolver = WasmBuildBatchInputResolver::new(specs, None);
1510        let mut snapshots = Vec::with_capacity(specs.len());
1511        let mut preparation_timings = WasmInputResolutionTimings::default();
1512        let mut progress = ProgressReporter::silent();
1513        for (index, spec) in specs.iter().enumerate() {
1514            let mut prepared_input = resolver.resolve(index, &mut progress)?;
1515            preparation_timings.include(prepared_input.timings);
1516            prepared_input.timings = WasmInputResolutionTimings::default();
1517            snapshots.push((spec.clone(), prepared_input));
1518        }
1519        Ok(Self {
1520            snapshots,
1521            preparation_metrics: resolver.metrics(),
1522            preparation_timings,
1523            reader_reuses: AtomicUsize::new(0),
1524            invalidation: Arc::new(RwLock::new(false)),
1525        })
1526    }
1527
1528    pub(super) fn contains(&self, spec: &WasmBuildSpec) -> bool {
1529        self.snapshots
1530            .iter()
1531            .any(|(candidate, _)| candidate == spec)
1532    }
1533
1534    fn reuse(&self, spec: &WasmBuildSpec) -> Option<ResolvedCargoBuildInputs> {
1535        let (_, snapshot) = self
1536            .snapshots
1537            .iter()
1538            .find(|(candidate, _)| candidate == spec)?;
1539        let mut current = self.reader_reuses.load(Ordering::Relaxed);
1540        loop {
1541            match self.reader_reuses.compare_exchange_weak(
1542                current,
1543                current.saturating_add(1),
1544                Ordering::Relaxed,
1545                Ordering::Relaxed,
1546            ) {
1547                Ok(_) => break,
1548                Err(observed) => current = observed,
1549            }
1550        }
1551        Some(snapshot.clone())
1552    }
1553
1554    pub(super) const fn specification_count(&self) -> usize {
1555        self.snapshots.len()
1556    }
1557
1558    pub(super) const fn preparation_metrics(&self) -> WasmBuildBatchInputMetrics {
1559        self.preparation_metrics
1560    }
1561
1562    pub(super) const fn preparation_timings(&self) -> WasmInputResolutionTimings {
1563        self.preparation_timings
1564    }
1565
1566    pub(super) fn reader_reuses(&self) -> usize {
1567        self.reader_reuses.load(Ordering::Relaxed)
1568    }
1569
1570    pub(super) fn is_invalidated(&self) -> bool {
1571        *self
1572            .invalidation
1573            .read()
1574            .unwrap_or_else(std::sync::PoisonError::into_inner)
1575    }
1576
1577    fn invalidate(&self) {
1578        *self
1579            .invalidation
1580            .write()
1581            .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
1582    }
1583
1584    fn invalidation(&self) -> Arc<RwLock<bool>> {
1585        Arc::clone(&self.invalidation)
1586    }
1587}
1588
1589impl<'a, 'session> WasmBuildBatchInputResolver<'a, 'session> {
1590    pub(super) fn new(
1591        specs: &'a [WasmBuildSpec],
1592        mut reuse: Option<WasmBuildInputReuse<'session>>,
1593    ) -> Self {
1594        let mut keys = Vec::<BatchResolutionKey>::new();
1595        let mut groups = Vec::<BatchResolutionGroup>::new();
1596        let mut group_by_index = Vec::with_capacity(specs.len());
1597        for (index, spec) in specs.iter().enumerate() {
1598            let key = BatchResolutionKey::for_spec(spec);
1599            let group = keys
1600                .iter()
1601                .position(|candidate| *candidate == key)
1602                .unwrap_or_else(|| {
1603                    keys.push(key);
1604                    groups.push(BatchResolutionGroup {
1605                        indexes: Vec::new(),
1606                    });
1607                    groups.len() - 1
1608                });
1609            groups[group].indexes.push(index);
1610            group_by_index.push(group);
1611        }
1612        let mut metrics = WasmBuildBatchInputMetrics::default();
1613        let resolved = specs
1614            .iter()
1615            .map(|spec| match reuse.as_mut() {
1616                Some(WasmBuildInputReuse::Session(session)) => {
1617                    let reused = session.reuse(spec);
1618                    if reused.is_some() {
1619                        metrics.session_reuses = metrics.session_reuses.saturating_add(1);
1620                    }
1621                    reused.map(Ok)
1622                }
1623                Some(WasmBuildInputReuse::Snapshot(snapshot)) => {
1624                    let reused = snapshot
1625                        .reuse(spec)
1626                        .expect("prepared input snapshot must contain every reader specification");
1627                    metrics.prepared_reuses = metrics.prepared_reuses.saturating_add(1);
1628                    Some(Ok(reused))
1629                }
1630                None => None,
1631            })
1632            .collect();
1633        Self {
1634            specs,
1635            groups,
1636            group_by_index,
1637            resolved,
1638            reuse,
1639            metrics,
1640        }
1641    }
1642
1643    pub(super) const fn metrics(&self) -> WasmBuildBatchInputMetrics {
1644        self.metrics
1645    }
1646
1647    pub(super) fn invalidate_source_lease(&mut self) {
1648        match self.reuse.as_mut() {
1649            Some(WasmBuildInputReuse::Session(session)) => {
1650                session.invalidate();
1651                // Every unresolved entry was captured before the detected source race,
1652                // including entries resolved only for this batch. Force later entries
1653                // through fresh discovery instead of consuming a now-stale snapshot.
1654                for resolved in &mut self.resolved {
1655                    *resolved = None;
1656                }
1657                self.reuse = None;
1658            }
1659            Some(WasmBuildInputReuse::Snapshot(snapshot)) => snapshot.invalidate(),
1660            None => {}
1661        }
1662    }
1663
1664    pub(super) const fn assumes_sources_immutable(&self) -> bool {
1665        self.reuse.is_some()
1666    }
1667
1668    pub(super) fn prepared_invalidation(&self) -> Option<Arc<RwLock<bool>>> {
1669        match self.reuse.as_ref() {
1670            Some(WasmBuildInputReuse::Snapshot(snapshot)) => Some(snapshot.invalidation()),
1671            _ => None,
1672        }
1673    }
1674
1675    fn resolve(
1676        &mut self,
1677        index: usize,
1678        progress: &mut ProgressReporter<'_>,
1679    ) -> Result<ResolvedCargoBuildInputs, WasmBuildError> {
1680        if self.resolved[index].is_none() {
1681            self.resolve_group(index, progress)?;
1682        }
1683        self.resolved[index]
1684            .take()
1685            .expect("resolved batch input must be populated")
1686            .map_err(|(phase, error)| {
1687                progress.begin_phase(phase);
1688                error
1689            })
1690    }
1691
1692    fn resolve_group(
1693        &mut self,
1694        active_index: usize,
1695        progress: &mut ProgressReporter<'_>,
1696    ) -> Result<(), WasmBuildError> {
1697        let total_started = Instant::now();
1698        let indexes = self.groups[self.group_by_index[active_index]]
1699            .indexes
1700            .clone();
1701        let active = &self.specs[active_index];
1702
1703        let (cargo_identity, rustc_identity, tool_identity) =
1704            resolve_tool_identity(active, progress)?;
1705
1706        let metadata_started = Instant::now();
1707        let metadata = progress.run_phase(WasmBuildProgressPhase::CargoMetadata, || {
1708            cargo_metadata(active)
1709        })?;
1710        let cargo_metadata = metadata_started.elapsed();
1711
1712        let (discovered, input_discovery) =
1713            self.discover_group_inputs(indexes, &metadata, progress);
1714
1715        let hashing_started = Instant::now();
1716        let mut batch_digest_cache = LabeledPathDigestCache::default();
1717        let digest_cache = match self.reuse.as_mut() {
1718            Some(WasmBuildInputReuse::Session(session)) => &mut session.digest_cache,
1719            _ => &mut batch_digest_cache,
1720        };
1721        let workspace_root = active.workspace_root.clone();
1722        let resolved_inputs = progress.run_phase(WasmBuildProgressPhase::ContentHashing, || {
1723            discovered
1724                .into_iter()
1725                .map(|(index, inputs, exclusions)| {
1726                    let result = digest_resolved_local_inputs(
1727                        &inputs,
1728                        &exclusions,
1729                        digest_cache,
1730                        &workspace_root,
1731                        "hash batched Wasm build inputs",
1732                        "hash batched semantic Wasm build inputs",
1733                    )
1734                    .map(|(input_digest, validation_digest)| {
1735                        (
1736                            inputs.validation_inputs,
1737                            exclusions,
1738                            input_digest,
1739                            validation_digest,
1740                        )
1741                    });
1742                    (index, result)
1743                })
1744                .collect::<Vec<_>>()
1745        });
1746        let content_hashing = hashing_started.elapsed();
1747        let timings = WasmInputResolutionTimings {
1748            tool_identity,
1749            cargo_metadata,
1750            input_discovery,
1751            content_hashing,
1752            total: total_started.elapsed(),
1753        };
1754        let resolved_count = resolved_inputs
1755            .iter()
1756            .filter(|(_, result)| result.is_ok())
1757            .count();
1758        self.metrics.runs += usize::from(resolved_count > 0);
1759        self.metrics.reuses += resolved_count.saturating_sub(1);
1760        let timing_index = resolved_inputs
1761            .iter()
1762            .find(|(index, result)| *index == active_index && result.is_ok())
1763            .or_else(|| resolved_inputs.iter().find(|(_, result)| result.is_ok()))
1764            .map(|(index, _)| *index);
1765        for (index, result) in resolved_inputs {
1766            let (inputs, exclusions, input_digest, validation_digest) = match result {
1767                Ok(resolved) => resolved,
1768                Err(error) => {
1769                    self.resolved[index] =
1770                        Some(Err((WasmBuildFailurePhase::ContentHashing, error)));
1771                    continue;
1772                }
1773            };
1774            let spec = &self.specs[index];
1775            let resolved = ResolvedCargoBuildInputs {
1776                fingerprint: finish_build_fingerprint(
1777                    spec,
1778                    &cargo_identity,
1779                    &rustc_identity,
1780                    input_digest,
1781                ),
1782                input_digest,
1783                validation_digest,
1784                inputs: inputs
1785                    .into_iter()
1786                    .map(|(label, path)| CargoBuildInput { label, path })
1787                    .collect(),
1788                exclusions,
1789                timings: if Some(index) == timing_index {
1790                    timings
1791                } else {
1792                    WasmInputResolutionTimings::default()
1793                },
1794            };
1795            if let Some(WasmBuildInputReuse::Session(session)) = self.reuse.as_mut() {
1796                session.remember(spec, &resolved);
1797            }
1798            self.resolved[index] = Some(Ok(resolved));
1799        }
1800        Ok(())
1801    }
1802
1803    fn discover_group_inputs(
1804        &mut self,
1805        indexes: Vec<usize>,
1806        metadata: &Value,
1807        progress: &mut ProgressReporter<'_>,
1808    ) -> (Vec<(usize, ResolvedLocalInputs, Vec<PathBuf>)>, Duration) {
1809        let started = Instant::now();
1810        let pending = indexes
1811            .into_iter()
1812            .filter(|index| {
1813                self.resolved[*index].is_none() && validate_spec(&self.specs[*index]).is_ok()
1814            })
1815            .collect::<Vec<_>>();
1816        let results = progress.run_phase(WasmBuildProgressPhase::InputDiscovery, || {
1817            pending
1818                .into_iter()
1819                .map(|index| {
1820                    let spec = &self.specs[index];
1821                    let result = (|| {
1822                        let inputs = resolve_local_inputs(spec, metadata)?;
1823                        validate_shared_incremental_target_boundary(
1824                            spec,
1825                            &inputs.validation_inputs,
1826                        )?;
1827                        let exclusions = source_exclusions(spec, &inputs.validation_inputs);
1828                        Ok::<_, WasmBuildError>((inputs, exclusions))
1829                    })();
1830                    (index, result)
1831                })
1832                .collect::<Vec<_>>()
1833        });
1834        let mut discovered = Vec::new();
1835        for (index, result) in results {
1836            match result {
1837                Ok((inputs, exclusions)) => discovered.push((index, inputs, exclusions)),
1838                Err(error) => {
1839                    self.resolved[index] =
1840                        Some(Err((WasmBuildFailurePhase::InputDiscovery, error)));
1841                }
1842            }
1843        }
1844        (discovered, started.elapsed())
1845    }
1846}
1847
1848fn resolve_tool_identity(
1849    spec: &WasmBuildSpec,
1850    progress: &mut ProgressReporter<'_>,
1851) -> Result<(Vec<u8>, Vec<u8>, Duration), WasmBuildError> {
1852    let started = Instant::now();
1853    let cargo_identity = progress.run_phase(WasmBuildProgressPhase::CargoIdentity, || {
1854        command_identity(
1855            spec,
1856            WasmBuildPhase::CargoIdentity,
1857            &spec.cargo_program,
1858            &["--version", "--verbose"],
1859        )
1860    })?;
1861    let rustc_program = spec
1862        .extra_env
1863        .get(OsStr::new("RUSTC"))
1864        .unwrap_or(&spec.rustc_program);
1865    let rustc_identity = progress.run_phase(WasmBuildProgressPhase::RustcIdentity, || {
1866        command_identity(spec, WasmBuildPhase::RustcIdentity, rustc_program, &["-vV"])
1867    })?;
1868    Ok((cargo_identity, rustc_identity, started.elapsed()))
1869}
1870
1871impl BatchResolutionKey {
1872    fn for_spec(spec: &WasmBuildSpec) -> Self {
1873        Self {
1874            workspace_root: spec.workspace_root.clone(),
1875            cargo_program: spec.cargo_program.clone(),
1876            rustc_program: spec
1877                .extra_env
1878                .get(OsStr::new("RUSTC"))
1879                .unwrap_or(&spec.rustc_program)
1880                .clone(),
1881            metadata_arguments: metadata_arguments(&spec.cargo_profile_args),
1882            environment: effective_environment(spec),
1883        }
1884    }
1885}
1886
1887impl SharedIncrementalTargetInspection {
1888    /// Canonical shared Cargo target directory that was inspected.
1889    #[must_use]
1890    pub fn target_dir(&self) -> &Path {
1891        &self.target_dir
1892    }
1893
1894    /// Logical bytes currently occupied by the complete shared target.
1895    #[must_use]
1896    pub const fn logical_size_bytes(&self) -> u64 {
1897        self.logical_size_bytes
1898    }
1899
1900    /// Most recent build use recorded by `ic-testkit`, or the directory mtime for older targets.
1901    #[must_use]
1902    pub const fn last_used(&self) -> SystemTime {
1903        self.last_used
1904    }
1905
1906    /// Time spent waiting for another process using the shared target.
1907    #[must_use]
1908    pub const fn lock_wait(&self) -> Duration {
1909        self.lock_wait
1910    }
1911}
1912
1913impl SharedIncrementalTargetPrunePolicy {
1914    /// Create an explicit policy without a clearing threshold.
1915    #[must_use]
1916    pub const fn new() -> Self {
1917        Self {
1918            max_age: None,
1919            max_size_bytes: None,
1920        }
1921    }
1922
1923    /// Clear shared Cargo state when its recorded use is older than `max_age`.
1924    #[must_use]
1925    pub const fn with_max_age(mut self, max_age: Duration) -> Self {
1926        self.max_age = Some(max_age);
1927        self
1928    }
1929
1930    /// Clear shared Cargo state when its logical size exceeds `bytes`.
1931    #[must_use]
1932    pub const fn with_max_size_bytes(mut self, bytes: u64) -> Self {
1933        self.max_size_bytes = Some(bytes);
1934        self
1935    }
1936
1937    /// Configured maximum time since recorded build use.
1938    #[must_use]
1939    pub const fn max_age(self) -> Option<Duration> {
1940        self.max_age
1941    }
1942
1943    /// Configured maximum logical target size.
1944    #[must_use]
1945    pub const fn max_size_bytes(self) -> Option<u64> {
1946        self.max_size_bytes
1947    }
1948
1949    fn maintenance_identity(self) -> String {
1950        format!(
1951            "age={:?};size={:?}",
1952            self.max_age.map(|duration| duration.as_nanos()),
1953            self.max_size_bytes
1954        )
1955    }
1956}
1957
1958impl SharedIncrementalTargetMaintenanceConfig {
1959    /// Schedule one strict retention pass at most once per interval.
1960    #[must_use]
1961    pub const fn new(
1962        policy: SharedIncrementalTargetPrunePolicy,
1963        minimum_interval: Duration,
1964    ) -> Self {
1965        Self {
1966            policy,
1967            minimum_interval,
1968            failure_mode: SharedIncrementalTargetMaintenanceFailureMode::Strict,
1969        }
1970    }
1971
1972    /// Select whether an integrated maintenance failure fails the acquisition.
1973    #[must_use]
1974    pub const fn with_failure_mode(
1975        mut self,
1976        failure_mode: SharedIncrementalTargetMaintenanceFailureMode,
1977    ) -> Self {
1978        self.failure_mode = failure_mode;
1979        self
1980    }
1981
1982    /// Configured whole-target retention policy.
1983    #[must_use]
1984    pub const fn policy(self) -> SharedIncrementalTargetPrunePolicy {
1985        self.policy
1986    }
1987
1988    /// Minimum interval between successful matching maintenance passes.
1989    #[must_use]
1990    pub const fn minimum_interval(self) -> Duration {
1991        self.minimum_interval
1992    }
1993
1994    /// Configured maintenance failure handling.
1995    #[must_use]
1996    pub const fn failure_mode(self) -> SharedIncrementalTargetMaintenanceFailureMode {
1997        self.failure_mode
1998    }
1999}
2000
2001impl SharedIncrementalTargetMaintenance {
2002    /// Canonical shared Cargo target directory maintained under lock.
2003    #[must_use]
2004    pub fn target_dir(&self) -> &Path {
2005        &self.target_dir
2006    }
2007
2008    /// Logical bytes observed before applying the policy.
2009    #[must_use]
2010    pub const fn logical_size_bytes_before(&self) -> u64 {
2011        self.logical_size_bytes_before
2012    }
2013
2014    /// Logical bytes retained after applying the policy.
2015    #[must_use]
2016    pub const fn logical_size_bytes_after(&self) -> u64 {
2017        self.logical_size_bytes_after
2018    }
2019
2020    /// Most recent build use observed before applying the policy.
2021    #[must_use]
2022    pub const fn last_used_before(&self) -> SystemTime {
2023        self.last_used_before
2024    }
2025
2026    /// Whether a configured limit caused the mutable target contents to be cleared.
2027    #[must_use]
2028    pub const fn was_cleared(&self) -> bool {
2029        self.cleared
2030    }
2031
2032    /// Time spent waiting for another process using the shared target.
2033    #[must_use]
2034    pub const fn lock_wait(&self) -> Duration {
2035        self.lock_wait
2036    }
2037
2038    /// Time spent measuring and, when required, clearing the target.
2039    #[must_use]
2040    pub const fn maintenance(&self) -> Duration {
2041        self.maintenance
2042    }
2043}
2044
2045impl std::fmt::Display for SharedIncrementalTargetMaintenance {
2046    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2047        write!(
2048            formatter,
2049            "target={} action={} bytes={}=>{} lock={:?} maintenance={:?}",
2050            self.target_dir.display(),
2051            if self.cleared { "cleared" } else { "retained" },
2052            self.logical_size_bytes_before,
2053            self.logical_size_bytes_after,
2054            self.lock_wait,
2055            self.maintenance,
2056        )
2057    }
2058}
2059
2060impl SharedIncrementalTargetMaintenanceOutcome {
2061    /// Configured or canonical target associated with this result.
2062    #[must_use]
2063    pub fn target_dir(&self) -> &Path {
2064        match self {
2065            Self::Missing { target_dir }
2066            | Self::Skipped { target_dir, .. }
2067            | Self::Failed { target_dir, .. } => target_dir,
2068            Self::Performed { maintenance, .. } => maintenance.target_dir(),
2069        }
2070    }
2071
2072    /// Completed maintenance report, when retention was evaluated.
2073    #[must_use]
2074    pub const fn maintenance(&self) -> Option<&SharedIncrementalTargetMaintenance> {
2075        match self {
2076            Self::Performed { maintenance, .. } => Some(maintenance),
2077            Self::Missing { .. } | Self::Skipped { .. } | Self::Failed { .. } => None,
2078        }
2079    }
2080
2081    /// Whether retention was evaluated during this call.
2082    #[must_use]
2083    pub const fn was_performed(&self) -> bool {
2084        matches!(self, Self::Performed { .. })
2085    }
2086
2087    /// Time spent waiting for another process, when the target existed.
2088    #[must_use]
2089    pub const fn lock_wait(&self) -> Option<Duration> {
2090        match self {
2091            Self::Missing { .. } => None,
2092            Self::Skipped { lock_wait, .. } | Self::Failed { lock_wait, .. } => Some(*lock_wait),
2093            Self::Performed { maintenance, .. } => Some(maintenance.lock_wait()),
2094        }
2095    }
2096
2097    /// Time spent checking the schedule marker, when the target existed.
2098    #[must_use]
2099    pub const fn schedule_check(&self) -> Option<Duration> {
2100        match self {
2101            Self::Missing { .. } | Self::Failed { .. } => None,
2102            Self::Skipped { schedule_check, .. } | Self::Performed { schedule_check, .. } => {
2103                Some(*schedule_check)
2104            }
2105        }
2106    }
2107
2108    /// Rendered integrated maintenance failure, when best-effort handling preserved acquisition.
2109    #[must_use]
2110    pub fn failure_message(&self) -> Option<&str> {
2111        match self {
2112            Self::Failed { message, .. } => Some(message),
2113            Self::Missing { .. } | Self::Skipped { .. } | Self::Performed { .. } => None,
2114        }
2115    }
2116}
2117
2118impl std::fmt::Display for SharedIncrementalTargetMaintenanceOutcome {
2119    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2120        match self {
2121            Self::Missing { target_dir } => {
2122                write!(formatter, "target={} action=missing", target_dir.display())
2123            }
2124            Self::Skipped {
2125                target_dir,
2126                lock_wait,
2127                schedule_check,
2128            } => write!(
2129                formatter,
2130                "target={} action=skipped lock={lock_wait:?} schedule={schedule_check:?}",
2131                target_dir.display(),
2132            ),
2133            Self::Performed {
2134                maintenance,
2135                schedule_check,
2136            } => write!(formatter, "{maintenance} schedule={schedule_check:?}"),
2137            Self::Failed {
2138                target_dir,
2139                lock_wait,
2140                message,
2141            } => write!(
2142                formatter,
2143                "target={} action=failed lock={lock_wait:?} error={message}",
2144                target_dir.display(),
2145            ),
2146        }
2147    }
2148}
2149
2150impl std::fmt::Display for WasmBuildTimings {
2151    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2152        write!(
2153            formatter,
2154            "total={:?} lock={:?} shared_lock={:?} inputs={:?} cargo={:?} maintenance={:?}",
2155            self.total,
2156            self.lock_wait,
2157            self.shared_incremental_lock_wait,
2158            self.input_resolution.total,
2159            self.cargo_build,
2160            self.cache_maintenance,
2161        )
2162    }
2163}
2164
2165impl std::fmt::Display for WasmBuildOutcome {
2166    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2167        let state = if self.is_reused() { "reused" } else { "built" };
2168        write!(
2169            formatter,
2170            "{state} fingerprint={} artifacts={} {}",
2171            self.record().fingerprint,
2172            self.record().artifacts.len(),
2173            self.record().timings,
2174        )?;
2175        if let Some(maintenance) = self.record().shared_incremental_maintenance() {
2176            write!(formatter, " shared_maintenance=({maintenance})")?;
2177        }
2178        Ok(())
2179    }
2180}
2181
2182/// Resolve the exact Cargo source, configuration, toolchain, argument, and environment identity.
2183///
2184/// This performs the same resolution used before and after cached Wasm builds
2185/// without running `cargo build`.
2186pub fn resolve_cargo_build_inputs(
2187    spec: &WasmBuildSpec,
2188) -> Result<ResolvedCargoBuildInputs, WasmBuildError> {
2189    validate_spec(spec)?;
2190    build_fingerprint(spec)
2191}
2192
2193/// Inspect one configured shared Cargo target under its build coordination lock.
2194///
2195/// Returns `None` without creating anything when the caller-owned target does
2196/// not exist. This operation never removes Cargo state.
2197pub fn inspect_shared_incremental_target(
2198    spec: &WasmBuildSpec,
2199) -> Result<Option<SharedIncrementalTargetInspection>, WasmBuildError> {
2200    if !shared_incremental_target_exists(spec, "inspect shared incremental Cargo target")? {
2201        return Ok(None);
2202    }
2203
2204    let (_lock, lock_wait, canonical) = lock_shared_incremental_target(spec)?;
2205    let logical_size_bytes =
2206        directory_logical_size(&canonical).map_err(|source| WasmBuildError::Io {
2207            operation: "measure shared incremental Cargo target",
2208            path: canonical.clone(),
2209            source,
2210        })?;
2211    let last_used = cache_entry_last_used(&canonical).map_err(|source| WasmBuildError::Io {
2212        operation: "read shared incremental Cargo target use time",
2213        path: canonical.clone(),
2214        source,
2215    })?;
2216    Ok(Some(SharedIncrementalTargetInspection {
2217        target_dir: canonical,
2218        logical_size_bytes,
2219        last_used,
2220        lock_wait,
2221    }))
2222}
2223
2224/// Apply explicit whole-target retention to caller-owned shared Cargo state.
2225///
2226/// Returns `None` without creating anything when the target does not exist.
2227/// Policy evaluation and any clearing occur under the same cross-process lock
2228/// used by shared-incremental builds. The target root, `CACHEDIR.TAG`, and
2229/// `.ic-testkit` lock metadata are preserved, so another process cannot enter
2230/// through a replacement lock while maintenance is active.
2231/// Every other target child is removed when a limit is exceeded; unrelated
2232/// data that must survive must not be colocated there. Exact Cargo input
2233/// resolution first rejects targets overlapping source or configuration.
2234///
2235/// This function is never called automatically by exact Wasm acquisitions.
2236/// Consumers retain ownership of when mutable incremental state may be lost.
2237pub fn maintain_shared_incremental_target(
2238    spec: &WasmBuildSpec,
2239    policy: SharedIncrementalTargetPrunePolicy,
2240) -> Result<Option<SharedIncrementalTargetMaintenance>, WasmBuildError> {
2241    if !shared_incremental_target_exists(
2242        spec,
2243        "inspect shared incremental Cargo target before maintenance",
2244    )? {
2245        return Ok(None);
2246    }
2247
2248    // Reuse the exact build resolver so destructive maintenance cannot act on
2249    // a target that overlaps Cargo sources, configuration, or additional
2250    // inputs. The target itself is excluded as generated state during hashing.
2251    let _ = resolve_cargo_build_inputs(spec)?;
2252    let (_lock, lock_wait, canonical) = lock_shared_incremental_target(spec)?;
2253    maintain_shared_incremental_target_locked(&canonical, policy, lock_wait).map(Some)
2254}
2255
2256/// Apply whole-target retention at most once per interval across processes.
2257///
2258/// The schedule marker is checked under the same lock used by shared Cargo
2259/// builds. A matching successful pass inside `minimum_interval` returns
2260/// [`SharedIncrementalTargetMaintenanceOutcome::Skipped`] without resolving
2261/// Cargo inputs or traversing the target. Missing targets are not created.
2262/// Changing the policy makes maintenance immediately due, and a zero interval
2263/// always evaluates retention.
2264///
2265/// Due maintenance performs exact Cargo input resolution before inspecting or
2266/// clearing the target. Failures are returned and are not recorded as a
2267/// successful pass, so an unsafe configuration cannot be hidden by the
2268/// schedule.
2269pub fn maintain_shared_incremental_target_at_most_every(
2270    spec: &WasmBuildSpec,
2271    policy: SharedIncrementalTargetPrunePolicy,
2272    minimum_interval: Duration,
2273) -> Result<SharedIncrementalTargetMaintenanceOutcome, WasmBuildError> {
2274    let target_dir =
2275        shared_incremental_target(spec).ok_or_else(|| WasmBuildError::InvalidSpec {
2276            message: "shared incremental target is not configured".to_owned(),
2277        })?;
2278    if !shared_incremental_target_exists(
2279        spec,
2280        "inspect shared incremental Cargo target before scheduled maintenance",
2281    )? {
2282        return Ok(SharedIncrementalTargetMaintenanceOutcome::Missing { target_dir });
2283    }
2284
2285    let (_lock, lock_wait, canonical) = lock_shared_incremental_target(spec)?;
2286    let schedule = schedule_shared_incremental_target_maintenance(
2287        &canonical,
2288        policy,
2289        minimum_interval,
2290        lock_wait,
2291    )?;
2292    let schedule = match schedule {
2293        SharedIncrementalTargetMaintenanceSchedule::Skipped(outcome) => return Ok(outcome),
2294        SharedIncrementalTargetMaintenanceSchedule::Due(due) => due,
2295    };
2296
2297    // Keep the schedule decision and maintenance in one critical section so
2298    // concurrent test binaries cannot all perform the same expensive scan.
2299    let _ = resolve_cargo_build_inputs(spec)?;
2300    perform_due_shared_incremental_target_maintenance(&canonical, policy, lock_wait, schedule)
2301}
2302
2303enum SharedIncrementalTargetMaintenanceSchedule {
2304    Skipped(SharedIncrementalTargetMaintenanceOutcome),
2305    Due(DueSharedIncrementalTargetMaintenance),
2306}
2307
2308struct DueSharedIncrementalTargetMaintenance {
2309    schedule_root: PathBuf,
2310    maintenance_identity: String,
2311    schedule_check: Duration,
2312}
2313
2314fn schedule_shared_incremental_target_maintenance(
2315    canonical: &Path,
2316    policy: SharedIncrementalTargetPrunePolicy,
2317    minimum_interval: Duration,
2318    lock_wait: Duration,
2319) -> Result<SharedIncrementalTargetMaintenanceSchedule, WasmBuildError> {
2320    let schedule_root = canonical.join(".ic-testkit");
2321    let maintenance_identity = policy.maintenance_identity();
2322    let schedule_started = Instant::now();
2323    let due = cache_maintenance_due(
2324        &schedule_root,
2325        Some(minimum_interval),
2326        &maintenance_identity,
2327    )
2328    .map_err(wasm_cache_fs_error)?;
2329    let schedule_check = schedule_started.elapsed();
2330    if !due {
2331        return Ok(SharedIncrementalTargetMaintenanceSchedule::Skipped(
2332            SharedIncrementalTargetMaintenanceOutcome::Skipped {
2333                target_dir: canonical.to_owned(),
2334                lock_wait,
2335                schedule_check,
2336            },
2337        ));
2338    }
2339    Ok(SharedIncrementalTargetMaintenanceSchedule::Due(
2340        DueSharedIncrementalTargetMaintenance {
2341            schedule_root,
2342            maintenance_identity,
2343            schedule_check,
2344        },
2345    ))
2346}
2347
2348fn perform_due_shared_incremental_target_maintenance(
2349    canonical: &Path,
2350    policy: SharedIncrementalTargetPrunePolicy,
2351    lock_wait: Duration,
2352    due: DueSharedIncrementalTargetMaintenance,
2353) -> Result<SharedIncrementalTargetMaintenanceOutcome, WasmBuildError> {
2354    let DueSharedIncrementalTargetMaintenance {
2355        schedule_root,
2356        maintenance_identity,
2357        schedule_check,
2358    } = due;
2359    let maintenance = maintain_shared_incremental_target_locked(canonical, policy, lock_wait)?;
2360    record_cache_maintenance(&schedule_root, &maintenance_identity).map_err(wasm_cache_fs_error)?;
2361    Ok(SharedIncrementalTargetMaintenanceOutcome::Performed {
2362        maintenance,
2363        schedule_check,
2364    })
2365}
2366
2367fn maintain_shared_incremental_target_locked(
2368    canonical: &Path,
2369    policy: SharedIncrementalTargetPrunePolicy,
2370    lock_wait: Duration,
2371) -> Result<SharedIncrementalTargetMaintenance, WasmBuildError> {
2372    let started = Instant::now();
2373    let logical_size_bytes_before =
2374        directory_logical_size(canonical).map_err(|source| WasmBuildError::Io {
2375            operation: "measure shared incremental Cargo target before maintenance",
2376            path: canonical.to_owned(),
2377            source,
2378        })?;
2379    let last_used_before =
2380        cache_entry_last_used(canonical).map_err(|source| WasmBuildError::Io {
2381            operation: "read shared incremental Cargo target use time before maintenance",
2382            path: canonical.to_owned(),
2383            source,
2384        })?;
2385    let expired = policy.max_age.is_some_and(|max_age| {
2386        SystemTime::now()
2387            .duration_since(last_used_before)
2388            .is_ok_and(|age| age > max_age)
2389    });
2390    let oversized = policy
2391        .max_size_bytes
2392        .is_some_and(|max_size_bytes| logical_size_bytes_before > max_size_bytes);
2393    let cleared = expired || oversized;
2394    if cleared {
2395        clear_shared_incremental_target_contents(canonical)?;
2396        record_cache_entry_use(canonical)?;
2397    }
2398    let logical_size_bytes_after = if cleared {
2399        directory_logical_size(canonical).map_err(|source| WasmBuildError::Io {
2400            operation: "measure shared incremental Cargo target after maintenance",
2401            path: canonical.to_owned(),
2402            source,
2403        })?
2404    } else {
2405        logical_size_bytes_before
2406    };
2407    Ok(SharedIncrementalTargetMaintenance {
2408        target_dir: canonical.to_owned(),
2409        logical_size_bytes_before,
2410        logical_size_bytes_after,
2411        last_used_before,
2412        cleared,
2413        lock_wait,
2414        maintenance: started.elapsed(),
2415    })
2416}
2417
2418fn clear_shared_incremental_target_contents(target_dir: &Path) -> Result<(), WasmBuildError> {
2419    let entries = fs::read_dir(target_dir).map_err(|source| WasmBuildError::Io {
2420        operation: "read shared incremental Cargo target for maintenance",
2421        path: target_dir.to_owned(),
2422        source,
2423    })?;
2424    for entry in entries {
2425        let path = entry
2426            .map_err(|source| WasmBuildError::Io {
2427                operation: "read shared incremental Cargo target entry for maintenance",
2428                path: target_dir.to_owned(),
2429                source,
2430            })?
2431            .path();
2432        let preserved = path
2433            .file_name()
2434            .is_some_and(|name| name == ".ic-testkit" || name == "CACHEDIR.TAG");
2435        if !preserved {
2436            remove_path_if_present(&path).map_err(|source| WasmBuildError::Io {
2437                operation: "clear shared incremental Cargo target entry",
2438                path,
2439                source,
2440            })?;
2441        }
2442    }
2443    Ok(())
2444}
2445
2446/// Build or reuse one exact set of Cargo Wasm artifacts.
2447///
2448/// The operation takes an exclusive process lock scoped to `target_dir`, then
2449/// fingerprints all declared inputs. A cache hit requires both a matching
2450/// atomic stamp and every expected nonempty Wasm output. Ordinary warm hits
2451/// revalidate inputs before returning and reject mutations during acquisition.
2452/// Explicit immutable-source sessions and prepared readers skip that warm
2453/// revalidation under their source-lease contract. Failed or interrupted
2454/// builds never publish a successful stamp.
2455pub fn build_wasm_canisters_cached(
2456    spec: &WasmBuildSpec,
2457) -> Result<WasmBuildOutcome, WasmBuildError> {
2458    build_wasm_canisters_cached_internal(spec, &mut ProgressReporter::silent(), None)
2459}
2460
2461pub(super) fn build_wasm_canisters_cached_in_batch(
2462    spec: &WasmBuildSpec,
2463    index: usize,
2464    resolver: &mut WasmBuildBatchInputResolver<'_, '_>,
2465) -> WasmBuildBatchAttempt {
2466    let started = Instant::now();
2467    let mut progress = ProgressReporter::silent();
2468    let result = build_wasm_canisters_cached_internal(spec, &mut progress, Some((resolver, index)));
2469    if result
2470        .as_ref()
2471        .is_err_and(WasmBuildError::indicates_input_change)
2472    {
2473        resolver.invalidate_source_lease();
2474    }
2475    batch_result(result, &progress, started.elapsed())
2476}
2477
2478/// Build or reuse one exact Wasm set while streaming structured progress.
2479///
2480/// Cargo output remains captured for [`WasmBuildError::CommandFailed`] and is
2481/// additionally forwarded as raw chunks when enabled. Potentially long input
2482/// resolution, lock waits, maintenance, Cargo, and publication phases emit
2483/// periodic heartbeats, so a legitimate acquisition need not appear stalled.
2484/// Observer panics propagate after joining active phase work, terminating the
2485/// Cargo child when applicable, and preserving normal cleanup.
2486pub fn build_wasm_canisters_cached_with_progress<F>(
2487    spec: &WasmBuildSpec,
2488    config: WasmBuildProgressConfig,
2489    mut observer: F,
2490) -> Result<WasmBuildOutcome, WasmBuildError>
2491where
2492    F: FnMut(WasmBuildProgressEvent),
2493{
2494    if config.heartbeat_interval == Some(Duration::ZERO) {
2495        return Err(WasmBuildError::InvalidSpec {
2496            message: "Wasm build progress heartbeat interval must be greater than zero".to_owned(),
2497        });
2498    }
2499    build_wasm_canisters_cached_internal(
2500        spec,
2501        &mut ProgressReporter::observed(config, &mut observer),
2502        None,
2503    )
2504}
2505
2506pub(super) fn build_wasm_canisters_cached_in_batch_with_progress<F>(
2507    spec: &WasmBuildSpec,
2508    index: usize,
2509    resolver: &mut WasmBuildBatchInputResolver<'_, '_>,
2510    config: WasmBuildProgressConfig,
2511    mut observer: F,
2512) -> WasmBuildBatchAttempt
2513where
2514    F: FnMut(WasmBuildProgressEvent),
2515{
2516    if config.heartbeat_interval == Some(Duration::ZERO) {
2517        return WasmBuildBatchAttempt {
2518            result: Err((
2519                WasmBuildError::InvalidSpec {
2520                    message: "Wasm build progress heartbeat interval must be greater than zero"
2521                        .to_owned(),
2522                },
2523                WasmBuildFailureDetails::specification(Duration::ZERO),
2524            )),
2525        };
2526    }
2527    let started = Instant::now();
2528    let mut progress = ProgressReporter::observed(config, &mut observer);
2529    let result = build_wasm_canisters_cached_internal(spec, &mut progress, Some((resolver, index)));
2530    if result
2531        .as_ref()
2532        .is_err_and(WasmBuildError::indicates_input_change)
2533    {
2534        resolver.invalidate_source_lease();
2535    }
2536    batch_result(result, &progress, started.elapsed())
2537}
2538
2539fn batch_result(
2540    result: Result<WasmBuildOutcome, WasmBuildError>,
2541    progress: &ProgressReporter<'_>,
2542    total: Duration,
2543) -> WasmBuildBatchAttempt {
2544    WasmBuildBatchAttempt {
2545        result: result.map_err(|error| {
2546            let details = progress.failure_details(&error, total);
2547            (error, details)
2548        }),
2549    }
2550}
2551
2552fn batch_source_assumptions(
2553    batch_resolution: Option<&(&mut WasmBuildBatchInputResolver<'_, '_>, usize)>,
2554) -> (bool, Option<Arc<RwLock<bool>>>) {
2555    batch_resolution.map_or((false, None), |(resolver, _)| {
2556        (
2557            resolver.assumes_sources_immutable(),
2558            resolver.prepared_invalidation(),
2559        )
2560    })
2561}
2562
2563fn build_wasm_canisters_cached_internal(
2564    spec: &WasmBuildSpec,
2565    progress: &mut ProgressReporter<'_>,
2566    mut batch_resolution: Option<(&mut WasmBuildBatchInputResolver<'_, '_>, usize)>,
2567) -> Result<WasmBuildOutcome, WasmBuildError> {
2568    let total_started = Instant::now();
2569    validate_spec(spec)?;
2570    let (assumes_sources_immutable, prepared_invalidation) =
2571        batch_source_assumptions(batch_resolution.as_ref());
2572    progress.emit(WasmBuildProgressEvent::Started);
2573    if spec.shared_incremental_maintenance_config.is_some() {
2574        let outcome = build_wasm_canisters_cached_with_scheduled_shared_maintenance(
2575            spec,
2576            total_started,
2577            progress,
2578            batch_resolution.take(),
2579        )?;
2580        emit_finished_progress(&outcome, progress);
2581        return Ok(outcome);
2582    }
2583    let (cache_lock, first_lock_wait) =
2584        lock_wasm_build_cache_with_progress(&spec.target_dir, progress)?;
2585    ensure_cache_directory_tag(&spec.target_dir)?;
2586
2587    let resolved = resolve_initial_inputs(spec, batch_resolution.take(), progress)?;
2588    let isolated_acquisition =
2589        WasmAcquisitionContext::isolated(prepared_invalidation.clone(), assumes_sources_immutable);
2590    if let Some(outcome) = try_reuse_wasm_artifacts(
2591        spec,
2592        &resolved,
2593        first_lock_wait,
2594        &isolated_acquisition,
2595        total_started,
2596        progress,
2597    )? {
2598        emit_finished_progress(&outcome, progress);
2599        return Ok(outcome);
2600    }
2601    progress.emit(WasmBuildProgressEvent::CacheMiss {
2602        fingerprint: resolved.fingerprint,
2603    });
2604
2605    let outcome = match &spec.cache_mode {
2606        WasmBuildCacheMode::Isolated => {
2607            let cache_entry = cache_entry_directory(spec, resolved.fingerprint);
2608            build_wasm_cache_miss(
2609                spec,
2610                resolved,
2611                first_lock_wait,
2612                isolated_acquisition,
2613                cache_entry,
2614                total_started,
2615                progress,
2616            )
2617        }
2618        WasmBuildCacheMode::SharedIncremental { .. } => {
2619            drop(cache_lock);
2620            build_wasm_with_shared_incremental(
2621                spec,
2622                resolved,
2623                first_lock_wait,
2624                assumes_sources_immutable,
2625                prepared_invalidation,
2626                total_started,
2627                progress,
2628            )
2629        }
2630    }?;
2631    emit_finished_progress(&outcome, progress);
2632    Ok(outcome)
2633}
2634
2635fn build_wasm_with_shared_incremental(
2636    spec: &WasmBuildSpec,
2637    resolved: ResolvedCargoBuildInputs,
2638    first_lock_wait: Duration,
2639    assumes_sources_immutable: bool,
2640    prepared_invalidation: Option<Arc<RwLock<bool>>>,
2641    total_started: Instant,
2642    progress: &mut ProgressReporter<'_>,
2643) -> Result<WasmBuildOutcome, WasmBuildError> {
2644    let (shared_lock, shared_lock_wait, shared_target) =
2645        lock_shared_incremental_target_with_progress(spec, progress)?;
2646    let (_cache_lock, second_lock_wait) =
2647        lock_wasm_build_cache_with_progress(&spec.target_dir, progress)?;
2648    ensure_cache_directory_tag(&spec.target_dir)?;
2649
2650    let current = if assumes_sources_immutable {
2651        resolved
2652    } else {
2653        let mut current = resolve_inputs_with_progress(spec, progress)?;
2654        current.timings.include(resolved.timings);
2655        current
2656    };
2657    let lock_wait = first_lock_wait.saturating_add(second_lock_wait);
2658    let shared_incremental = WasmAcquisitionContext::shared(
2659        shared_lock_wait,
2660        None,
2661        prepared_invalidation,
2662        assumes_sources_immutable,
2663    );
2664    if let Some(outcome) = try_reuse_wasm_artifacts(
2665        spec,
2666        &current,
2667        lock_wait,
2668        &shared_incremental,
2669        total_started,
2670        progress,
2671    )? {
2672        return Ok(outcome);
2673    }
2674
2675    let outcome = build_wasm_cache_miss(
2676        spec,
2677        current,
2678        lock_wait,
2679        shared_incremental,
2680        shared_target,
2681        total_started,
2682        progress,
2683    );
2684    drop(shared_lock);
2685    outcome
2686}
2687
2688fn build_wasm_canisters_cached_with_scheduled_shared_maintenance(
2689    spec: &WasmBuildSpec,
2690    total_started: Instant,
2691    progress: &mut ProgressReporter<'_>,
2692    batch_resolution: Option<(&mut WasmBuildBatchInputResolver<'_, '_>, usize)>,
2693) -> Result<WasmBuildOutcome, WasmBuildError> {
2694    let (assumes_sources_immutable, prepared_invalidation) =
2695        batch_source_assumptions(batch_resolution.as_ref());
2696    let (_shared_lock, shared_lock_wait, shared_target) =
2697        lock_shared_incremental_target_with_progress(spec, progress)?;
2698    let (_cache_lock, lock_wait) = lock_wasm_build_cache_with_progress(&spec.target_dir, progress)?;
2699    ensure_cache_directory_tag(&spec.target_dir)?;
2700
2701    // Resolution under both locks proves the target boundary once for the
2702    // scheduled retention pass and the following exact-cache acquisition.
2703    let resolved = resolve_initial_inputs(spec, batch_resolution, progress)?;
2704    let shared_maintenance = perform_configured_shared_incremental_target_maintenance(
2705        spec,
2706        &shared_target,
2707        shared_lock_wait,
2708        progress,
2709    )?;
2710    let shared_incremental = WasmAcquisitionContext::shared(
2711        shared_lock_wait,
2712        Some(shared_maintenance),
2713        prepared_invalidation,
2714        assumes_sources_immutable,
2715    );
2716    if let Some(outcome) = try_reuse_wasm_artifacts(
2717        spec,
2718        &resolved,
2719        lock_wait,
2720        &shared_incremental,
2721        total_started,
2722        progress,
2723    )? {
2724        return Ok(outcome);
2725    }
2726    progress.emit(WasmBuildProgressEvent::CacheMiss {
2727        fingerprint: resolved.fingerprint,
2728    });
2729    build_wasm_cache_miss(
2730        spec,
2731        resolved,
2732        lock_wait,
2733        shared_incremental,
2734        shared_target,
2735        total_started,
2736        progress,
2737    )
2738}
2739
2740fn perform_configured_shared_incremental_target_maintenance(
2741    spec: &WasmBuildSpec,
2742    shared_target: &Path,
2743    lock_wait: Duration,
2744    progress: &mut ProgressReporter<'_>,
2745) -> Result<SharedIncrementalTargetMaintenanceOutcome, WasmBuildError> {
2746    let config = spec
2747        .shared_incremental_maintenance_config
2748        .expect("configured shared-target maintenance must have settings");
2749    progress.emit(WasmBuildProgressEvent::SharedTargetMaintenanceStarted {
2750        target_dir: shared_target.to_owned(),
2751    });
2752    let result = progress.run_phase(WasmBuildProgressPhase::SharedTargetMaintenance, || {
2753        let schedule = schedule_shared_incremental_target_maintenance(
2754            shared_target,
2755            config.policy,
2756            config.minimum_interval,
2757            lock_wait,
2758        )?;
2759        match schedule {
2760            SharedIncrementalTargetMaintenanceSchedule::Skipped(outcome) => Ok(outcome),
2761            SharedIncrementalTargetMaintenanceSchedule::Due(due) => {
2762                perform_due_shared_incremental_target_maintenance(
2763                    shared_target,
2764                    config.policy,
2765                    lock_wait,
2766                    due,
2767                )
2768            }
2769        }
2770    });
2771    let outcome = integrated_shared_maintenance_result(config, shared_target, lock_wait, result)?;
2772    progress.emit(WasmBuildProgressEvent::SharedTargetMaintenanceFinished {
2773        outcome: outcome.clone(),
2774    });
2775    Ok(outcome)
2776}
2777
2778fn integrated_shared_maintenance_result(
2779    config: SharedIncrementalTargetMaintenanceConfig,
2780    shared_target: &Path,
2781    lock_wait: Duration,
2782    result: Result<SharedIncrementalTargetMaintenanceOutcome, WasmBuildError>,
2783) -> Result<SharedIncrementalTargetMaintenanceOutcome, WasmBuildError> {
2784    match result {
2785        Ok(outcome) => Ok(outcome),
2786        Err(error)
2787            if config.failure_mode == SharedIncrementalTargetMaintenanceFailureMode::BestEffort =>
2788        {
2789            Ok(SharedIncrementalTargetMaintenanceOutcome::Failed {
2790                target_dir: shared_target.to_owned(),
2791                lock_wait,
2792                message: error.to_string(),
2793            })
2794        }
2795        Err(error) => Err(error),
2796    }
2797}
2798
2799fn resolve_inputs_with_progress(
2800    spec: &WasmBuildSpec,
2801    progress: &mut ProgressReporter<'_>,
2802) -> Result<ResolvedCargoBuildInputs, WasmBuildError> {
2803    let resolved = build_fingerprint_with_progress(spec, progress)?;
2804    progress.emit(WasmBuildProgressEvent::InputsResolved {
2805        fingerprint: resolved.fingerprint,
2806        input_digest: resolved.input_digest,
2807        elapsed: resolved.timings.total,
2808    });
2809    Ok(resolved)
2810}
2811
2812fn resolve_initial_inputs(
2813    spec: &WasmBuildSpec,
2814    batch_resolution: Option<(&mut WasmBuildBatchInputResolver<'_, '_>, usize)>,
2815    progress: &mut ProgressReporter<'_>,
2816) -> Result<ResolvedCargoBuildInputs, WasmBuildError> {
2817    let resolved = if let Some((resolver, index)) = batch_resolution {
2818        resolver.resolve(index, progress)?
2819    } else {
2820        build_fingerprint_with_progress(spec, progress)?
2821    };
2822    progress.emit(WasmBuildProgressEvent::InputsResolved {
2823        fingerprint: resolved.fingerprint,
2824        input_digest: resolved.input_digest,
2825        elapsed: resolved.timings.total,
2826    });
2827    Ok(resolved)
2828}
2829
2830fn emit_finished_progress(outcome: &WasmBuildOutcome, progress: &mut ProgressReporter<'_>) {
2831    let state = if outcome.is_reused() {
2832        progress.emit(WasmBuildProgressEvent::CacheHit {
2833            fingerprint: outcome.record().fingerprint,
2834        });
2835        WasmBuildProgressOutcome::Reused
2836    } else {
2837        WasmBuildProgressOutcome::Built
2838    };
2839    progress.emit(WasmBuildProgressEvent::Finished {
2840        outcome: state,
2841        fingerprint: outcome.record().fingerprint,
2842        elapsed: outcome.record().timings.total,
2843    });
2844}
2845
2846#[derive(Clone, Debug, Default)]
2847struct WasmAcquisitionContext {
2848    assumes_sources_immutable: bool,
2849    lock_wait: Option<Duration>,
2850    maintenance: Option<SharedIncrementalTargetMaintenanceOutcome>,
2851    prepared_invalidation: Option<Arc<RwLock<bool>>>,
2852}
2853
2854impl WasmAcquisitionContext {
2855    fn isolated(
2856        prepared_invalidation: Option<Arc<RwLock<bool>>>,
2857        assumes_sources_immutable: bool,
2858    ) -> Self {
2859        Self {
2860            assumes_sources_immutable,
2861            prepared_invalidation,
2862            ..Self::default()
2863        }
2864    }
2865
2866    const fn shared(
2867        lock_wait: Duration,
2868        maintenance: Option<SharedIncrementalTargetMaintenanceOutcome>,
2869        prepared_invalidation: Option<Arc<RwLock<bool>>>,
2870        assumes_sources_immutable: bool,
2871    ) -> Self {
2872        Self {
2873            assumes_sources_immutable,
2874            lock_wait: Some(lock_wait),
2875            maintenance,
2876            prepared_invalidation,
2877        }
2878    }
2879
2880    fn lock_prepared_publication(
2881        &self,
2882    ) -> Result<Option<std::sync::RwLockReadGuard<'_, bool>>, WasmBuildError> {
2883        let guard = self.prepared_invalidation.as_deref().map(|invalidation| {
2884            invalidation
2885                .read()
2886                .unwrap_or_else(std::sync::PoisonError::into_inner)
2887        });
2888        if guard.as_deref().is_some_and(|invalidated| *invalidated) {
2889            return Err(WasmBuildError::PreparedInputSnapshotInvalidated);
2890        }
2891        Ok(guard)
2892    }
2893}
2894
2895fn try_reuse_wasm_artifacts(
2896    spec: &WasmBuildSpec,
2897    resolved: &ResolvedCargoBuildInputs,
2898    lock_wait: Duration,
2899    shared_incremental: &WasmAcquisitionContext,
2900    total_started: Instant,
2901    progress: &mut ProgressReporter<'_>,
2902) -> Result<Option<WasmBuildOutcome>, WasmBuildError> {
2903    let _publication_guard = shared_incremental.lock_prepared_publication()?;
2904    let fingerprint = resolved.fingerprint;
2905    let artifacts = expected_artifacts(spec, &spec.target_dir);
2906    let cache_entry = cache_entry_directory(spec, fingerprint);
2907    let artifacts_match = progress.run_phase(WasmBuildProgressPhase::ArtifactPublication, || {
2908        artifact_set_matches(&artifacts, fingerprint)
2909    });
2910    if artifacts_match {
2911        ensure_exact_cache_entry(spec, &artifacts, &cache_entry, fingerprint, progress)?;
2912    } else {
2913        let cached_artifacts = expected_artifacts(spec, &cache_entry);
2914        let cached_artifacts_match = progress
2915            .run_phase(WasmBuildProgressPhase::ArtifactPublication, || {
2916                artifact_set_matches(&cached_artifacts, fingerprint)
2917            });
2918        if !cached_artifacts_match {
2919            return Ok(None);
2920        }
2921        progress.run_phase(WasmBuildProgressPhase::ArtifactPublication, || {
2922            materialize_artifacts(&cached_artifacts, &artifacts, fingerprint)?;
2923            record_cache_entry_use(&cache_entry)
2924        })?;
2925    }
2926    let input_resolution = validate_reused_inputs(spec, resolved, shared_incremental, progress)?;
2927    Ok(Some(WasmBuildOutcome::Reused(complete_build_record(
2928        spec,
2929        BuildRecordInput {
2930            fingerprint,
2931            input_digest: resolved.input_digest,
2932            lock_wait,
2933            shared_incremental: shared_incremental.clone(),
2934            input_resolution,
2935            cargo_build: None,
2936            active_entry: &cache_entry,
2937        },
2938        total_started,
2939        progress,
2940    )?)))
2941}
2942
2943fn validate_reused_inputs(
2944    spec: &WasmBuildSpec,
2945    resolved: &ResolvedCargoBuildInputs,
2946    context: &WasmAcquisitionContext,
2947    progress: &mut ProgressReporter<'_>,
2948) -> Result<WasmInputResolutionTimings, WasmBuildError> {
2949    let mut timings = resolved.timings;
2950    if !context.assumes_sources_immutable {
2951        let verified = verify_resolved_inputs(spec, resolved, progress)?;
2952        timings.include(verified.timings);
2953    }
2954    Ok(timings)
2955}
2956
2957fn verify_resolved_inputs(
2958    spec: &WasmBuildSpec,
2959    resolved: &ResolvedCargoBuildInputs,
2960    progress: &mut ProgressReporter<'_>,
2961) -> Result<ResolvedCargoBuildInputs, WasmBuildError> {
2962    let verified = resolve_inputs_with_progress(spec, progress)?;
2963    for (before, after) in [
2964        (resolved.validation_digest, verified.validation_digest),
2965        (resolved.fingerprint, verified.fingerprint),
2966    ] {
2967        if before != after {
2968            return Err(WasmBuildError::InputsChangedDuringAcquisition { before, after });
2969        }
2970    }
2971    Ok(verified)
2972}
2973
2974fn ensure_exact_cache_entry(
2975    spec: &WasmBuildSpec,
2976    artifacts: &[PathBuf],
2977    cache_entry: &Path,
2978    fingerprint: InputDigest,
2979    progress: &mut ProgressReporter<'_>,
2980) -> Result<(), WasmBuildError> {
2981    let cached_artifacts = expected_artifacts(spec, cache_entry);
2982    let entry_is_current =
2983        progress.run_phase(WasmBuildProgressPhase::ArtifactPublication, || {
2984            if artifact_set_matches(&cached_artifacts, fingerprint) {
2985                record_cache_entry_use(cache_entry)?;
2986                Ok::<_, WasmBuildError>(true)
2987            } else {
2988                Ok(false)
2989            }
2990        })?;
2991    if entry_is_current {
2992        return Ok(());
2993    }
2994    progress.run_phase(WasmBuildProgressPhase::ArtifactPublication, || {
2995        remove_unretained_entry(cache_entry).map_err(wasm_cache_fs_error)?;
2996        create_dir_all(
2997            cache_entry,
2998            "create content-addressed Cargo target directory",
2999        )
3000    })?;
3001    let incomplete = IncompleteBuildDirectory::new(cache_entry.to_owned());
3002    let result = progress.run_phase(WasmBuildProgressPhase::ArtifactPublication, || {
3003        copy_wasm_artifacts(artifacts, &cached_artifacts)?;
3004        publish_artifact_stamps(&cached_artifacts, fingerprint)?;
3005        record_cache_entry_use(cache_entry)
3006    });
3007    match result {
3008        Ok(()) => {
3009            incomplete.preserve();
3010            Ok(())
3011        }
3012        Err(build_error) => Err(cleanup_failed_fingerprint_build(
3013            build_error,
3014            incomplete,
3015            progress,
3016        )),
3017    }
3018}
3019
3020fn build_wasm_cache_miss(
3021    spec: &WasmBuildSpec,
3022    resolved: ResolvedCargoBuildInputs,
3023    lock_wait: Duration,
3024    shared_incremental: WasmAcquisitionContext,
3025    cargo_target_dir: PathBuf,
3026    total_started: Instant,
3027    progress: &mut ProgressReporter<'_>,
3028) -> Result<WasmBuildOutcome, WasmBuildError> {
3029    let fingerprint = resolved.fingerprint;
3030    let mut input_resolution = resolved.timings;
3031    let artifacts = expected_artifacts(spec, &spec.target_dir);
3032    let cache_entry = cache_entry_directory(spec, fingerprint);
3033    let preparation_started = Instant::now();
3034    progress.begin_phase(WasmBuildFailurePhase::ArtifactPublication);
3035    let preparation_result = (|| {
3036        remove_unretained_entry(&cache_entry).map_err(wasm_cache_fs_error)?;
3037        create_dir_all(
3038            &cache_entry,
3039            "create content-addressed Cargo target directory",
3040        )
3041    })();
3042    progress.record_phase(
3043        WasmBuildFailurePhase::ArtifactPublication,
3044        preparation_started.elapsed(),
3045    );
3046    preparation_result?;
3047    let incomplete_directory = IncompleteBuildDirectory::new(cache_entry.clone());
3048    let build_result = (|| {
3049        if matches!(
3050            spec.cache_mode,
3051            WasmBuildCacheMode::SharedIncremental { .. }
3052        ) {
3053            record_cache_entry_use(&cargo_target_dir)?;
3054        }
3055        let build_started = Instant::now();
3056        progress.begin_phase(WasmBuildFailurePhase::CargoBuild);
3057        let cargo_result = run_cargo_build(spec, &cargo_target_dir, progress);
3058        let cargo_build = build_started.elapsed();
3059        progress.record_phase(WasmBuildFailurePhase::CargoBuild, cargo_build);
3060        cargo_result?;
3061        let built_artifacts = expected_artifacts(spec, &cargo_target_dir);
3062        let validation_started = Instant::now();
3063        progress.begin_phase(WasmBuildFailurePhase::ArtifactPublication);
3064        let missing = missing_artifacts(&built_artifacts);
3065        progress.record_phase(
3066            WasmBuildFailurePhase::ArtifactPublication,
3067            validation_started.elapsed(),
3068        );
3069        if !missing.is_empty() {
3070            return Err(WasmBuildError::MissingArtifacts { paths: missing });
3071        }
3072
3073        let verified = verify_resolved_inputs(spec, &resolved, progress)?;
3074        input_resolution.include(verified.timings);
3075
3076        // Publication is the prepared snapshot's linearization boundary. A
3077        // reader that reaches it first may finish publishing; invalidation
3078        // takes the write side of this lock and therefore precedes every later
3079        // reader without racing a successful stamp into existence.
3080        let publication_guard = shared_incremental.lock_prepared_publication()?;
3081
3082        let cached_artifacts = expected_artifacts(spec, &cache_entry);
3083        progress.run_phase(WasmBuildProgressPhase::ArtifactPublication, || {
3084            if cargo_target_dir != cache_entry {
3085                copy_wasm_artifacts(&built_artifacts, &cached_artifacts)?;
3086            }
3087            publish_artifact_stamps(&cached_artifacts, fingerprint)?;
3088            materialize_artifacts(&cached_artifacts, &artifacts, fingerprint)?;
3089            record_cache_entry_use(&cache_entry)
3090        })?;
3091        drop(publication_guard);
3092
3093        Ok(WasmBuildOutcome::Built(complete_build_record(
3094            spec,
3095            BuildRecordInput {
3096                fingerprint,
3097                input_digest: resolved.input_digest,
3098                lock_wait,
3099                shared_incremental,
3100                input_resolution,
3101                cargo_build: Some(cargo_build),
3102                active_entry: &cache_entry,
3103            },
3104            total_started,
3105            progress,
3106        )?))
3107    })();
3108    finish_fingerprint_build(build_result, incomplete_directory, progress)
3109}
3110
3111/// Prune fingerprint-specific Cargo target directories under `target_dir`.
3112///
3113/// Pruning uses the same exclusive process lock as builds. Entries older than
3114/// the configured age are removed first, then least-recently-used entries are
3115/// removed until the configured logical byte limit is met. Only direct child
3116/// directories with SHA-256 fingerprint names are eligible; caller-facing
3117/// artifacts and unrelated target contents are never removed.
3118/// Entries owned by live build records are skipped until their last owner drops.
3119pub fn prune_wasm_build_cache(
3120    target_dir: &Path,
3121    policy: ArtifactCachePrunePolicy,
3122) -> Result<ArtifactCachePruneReport, WasmBuildError> {
3123    let (_lock_file, _) = lock_wasm_build_cache(target_dir)?;
3124    ensure_cache_directory_tag(target_dir)?;
3125
3126    prune_wasm_build_cache_locked(target_dir, policy, None)
3127}
3128
3129struct BuildRecordInput<'a> {
3130    fingerprint: InputDigest,
3131    input_digest: InputDigest,
3132    lock_wait: Duration,
3133    shared_incremental: WasmAcquisitionContext,
3134    input_resolution: WasmInputResolutionTimings,
3135    cargo_build: Option<Duration>,
3136    active_entry: &'a Path,
3137}
3138
3139fn complete_build_record(
3140    spec: &WasmBuildSpec,
3141    input: BuildRecordInput<'_>,
3142    total_started: Instant,
3143    progress: &mut ProgressReporter<'_>,
3144) -> Result<WasmBuildRecord, WasmBuildError> {
3145    let retention = progress.run_phase(WasmBuildProgressPhase::ArtifactPublication, || {
3146        RetainedCacheEntry::acquire(input.active_entry).map_err(wasm_cache_fs_error)
3147    })?;
3148    let (maintenance, cache_maintenance) = spec.prune_policy.map_or((None, None), |policy| {
3149        progress.run_phase(WasmBuildProgressPhase::ExactCacheMaintenance, || {
3150            let cache_root = spec.target_dir.join(".ic-testkit/wasm-targets");
3151            let identity = policy.maintenance_identity();
3152            perform_scheduled_cache_maintenance(&cache_root, spec.prune_interval, &identity, || {
3153                prune_wasm_build_cache_locked(&spec.target_dir, policy, Some(input.active_entry))
3154                    .map_err(|error| error.to_string())
3155            })
3156        })
3157    });
3158    Ok(WasmBuildRecord {
3159        fingerprint: input.fingerprint,
3160        input_digest: input.input_digest,
3161        exact_cache_path: input.active_entry.to_owned(),
3162        artifacts: expected_artifacts(spec, input.active_entry),
3163        _retention: retention,
3164        timings: WasmBuildTimings {
3165            lock_wait: input.lock_wait,
3166            shared_incremental_lock_wait: input.shared_incremental.lock_wait,
3167            input_resolution: input.input_resolution,
3168            cargo_build: input.cargo_build,
3169            cache_maintenance,
3170            total: total_started.elapsed(),
3171        },
3172        maintenance,
3173        shared_incremental_maintenance: input.shared_incremental.maintenance,
3174    })
3175}
3176
3177fn prune_wasm_build_cache_locked(
3178    target_dir: &Path,
3179    policy: ArtifactCachePrunePolicy,
3180    protected_entry: Option<&Path>,
3181) -> Result<ArtifactCachePruneReport, WasmBuildError> {
3182    let cache_root = target_dir.join(".ic-testkit/wasm-targets");
3183    prune_direct_child_directories(&cache_root, policy, protected_entry, is_sha256_directory)
3184        .map_err(wasm_cache_fs_error)
3185}
3186
3187struct IncompleteBuildDirectory {
3188    path: PathBuf,
3189    armed: bool,
3190}
3191
3192impl IncompleteBuildDirectory {
3193    const fn new(path: PathBuf) -> Self {
3194        Self { path, armed: true }
3195    }
3196
3197    fn preserve(mut self) {
3198        self.armed = false;
3199    }
3200
3201    fn cleanup(mut self) -> io::Result<()> {
3202        let result = remove_path_if_present(&self.path);
3203        if result.is_ok() {
3204            self.armed = false;
3205        }
3206        result
3207    }
3208}
3209
3210impl Drop for IncompleteBuildDirectory {
3211    fn drop(&mut self) {
3212        if self.armed {
3213            let _ = remove_path_if_present(&self.path);
3214        }
3215    }
3216}
3217
3218fn finish_fingerprint_build(
3219    result: Result<WasmBuildOutcome, WasmBuildError>,
3220    incomplete_directory: IncompleteBuildDirectory,
3221    progress: &mut ProgressReporter<'_>,
3222) -> Result<WasmBuildOutcome, WasmBuildError> {
3223    match result {
3224        Ok(outcome) => {
3225            incomplete_directory.preserve();
3226            Ok(outcome)
3227        }
3228        Err(build_error) => Err(cleanup_failed_fingerprint_build(
3229            build_error,
3230            incomplete_directory,
3231            progress,
3232        )),
3233    }
3234}
3235
3236fn cleanup_failed_fingerprint_build(
3237    build_error: WasmBuildError,
3238    incomplete_directory: IncompleteBuildDirectory,
3239    progress: &mut ProgressReporter<'_>,
3240) -> WasmBuildError {
3241    let path = incomplete_directory.path.clone();
3242    let primary_phase = progress.failure_phase;
3243    let cleanup_started = Instant::now();
3244    let cleanup = incomplete_directory.cleanup();
3245    progress.record_phase(WasmBuildFailurePhase::Cleanup, cleanup_started.elapsed());
3246    match cleanup {
3247        Ok(()) => {
3248            progress.failure_phase = primary_phase;
3249            build_error
3250        }
3251        Err(source) => WasmBuildError::FailedBuildCleanup {
3252            build_error: Box::new(build_error),
3253            path,
3254            source,
3255        },
3256    }
3257}
3258
3259fn lock_wasm_build_cache(target_dir: &Path) -> Result<(File, Duration), WasmBuildError> {
3260    create_dir_all(target_dir, "create Cargo target directory")?;
3261    let lock_path = target_dir.join(".ic-testkit/wasm-build.lock");
3262    lock_cache_file(&lock_path).map_err(wasm_cache_fs_error)
3263}
3264
3265fn lock_wasm_build_cache_with_progress(
3266    target_dir: &Path,
3267    progress: &mut ProgressReporter<'_>,
3268) -> Result<(File, Duration), WasmBuildError> {
3269    progress.begin_phase(WasmBuildFailurePhase::ExactCacheCoordination);
3270    create_dir_all(target_dir, "create Cargo target directory")?;
3271    let lock_path = target_dir.join(".ic-testkit/wasm-build.lock");
3272    lock_cache_file_with_progress(&lock_path, WasmBuildProgressPhase::ExactCacheLock, progress)
3273}
3274
3275fn lock_shared_incremental_target(
3276    spec: &WasmBuildSpec,
3277) -> Result<(File, Duration, PathBuf), WasmBuildError> {
3278    lock_shared_incremental_target_internal(spec, None)
3279}
3280
3281fn lock_shared_incremental_target_with_progress(
3282    spec: &WasmBuildSpec,
3283    progress: &mut ProgressReporter<'_>,
3284) -> Result<(File, Duration, PathBuf), WasmBuildError> {
3285    let target_dir = shared_incremental_target(spec)
3286        .expect("validated shared acquisition must have a shared Cargo target");
3287    progress.emit(WasmBuildProgressEvent::SharedTargetLockStarted { target_dir });
3288    let (lock, wait, canonical) = lock_shared_incremental_target_internal(spec, Some(progress))?;
3289    progress.emit(WasmBuildProgressEvent::SharedTargetLockAcquired {
3290        target_dir: canonical.clone(),
3291        wait,
3292    });
3293    Ok((lock, wait, canonical))
3294}
3295
3296fn lock_shared_incremental_target_internal(
3297    spec: &WasmBuildSpec,
3298    mut progress: Option<&mut ProgressReporter<'_>>,
3299) -> Result<(File, Duration, PathBuf), WasmBuildError> {
3300    if let Some(progress) = progress.as_deref_mut() {
3301        progress.begin_phase(WasmBuildFailurePhase::SharedTargetCoordination);
3302    }
3303    let target_dir =
3304        shared_incremental_target(spec).ok_or_else(|| WasmBuildError::InvalidSpec {
3305            message: "shared incremental target is not configured".to_owned(),
3306        })?;
3307    create_dir_all(
3308        &target_dir,
3309        "create shared incremental Cargo target directory",
3310    )?;
3311    ensure_cache_tag(&target_dir).map_err(wasm_cache_fs_error)?;
3312    let canonical = target_dir
3313        .canonicalize()
3314        .map_err(|source| WasmBuildError::Io {
3315            operation: "resolve shared incremental Cargo target directory",
3316            path: target_dir.clone(),
3317            source,
3318        })?;
3319    let lock_path = canonical.join(".ic-testkit/wasm-incremental.lock");
3320    let (lock, wait) = if let Some(progress) = progress {
3321        lock_cache_file_with_progress(
3322            &lock_path,
3323            WasmBuildProgressPhase::SharedTargetLock,
3324            progress,
3325        )?
3326    } else {
3327        lock_cache_file(&lock_path).map_err(wasm_cache_fs_error)?
3328    };
3329    Ok((lock, wait, canonical))
3330}
3331
3332fn lock_cache_file_with_progress(
3333    lock_path: &Path,
3334    phase: WasmBuildProgressPhase,
3335    progress: &mut ProgressReporter<'_>,
3336) -> Result<(File, Duration), WasmBuildError> {
3337    let failure_phase = progress_failure_phase(phase);
3338    let started = Instant::now();
3339    progress.begin_phase(failure_phase);
3340    let result = if !progress.is_observed() || progress.config.heartbeat_interval.is_none() {
3341        lock_cache_file(lock_path).map_err(wasm_cache_fs_error)
3342    } else {
3343        let heartbeat_interval = progress
3344            .config
3345            .heartbeat_interval
3346            .expect("observed cache lock must have a heartbeat interval");
3347        lock_cache_file_with_wait_observer(lock_path, heartbeat_interval, |elapsed| {
3348            progress.emit_heartbeat_if_due(phase, elapsed);
3349        })
3350        .map_err(wasm_cache_fs_error)
3351    };
3352    progress.record_phase(failure_phase, started.elapsed());
3353    result
3354}
3355
3356fn ensure_cache_directory_tag(target_dir: &Path) -> Result<(), WasmBuildError> {
3357    ensure_cache_tag(target_dir).map_err(wasm_cache_fs_error)
3358}
3359
3360fn record_cache_entry_use(path: &Path) -> Result<(), WasmBuildError> {
3361    record_entry_use(path).map_err(wasm_cache_fs_error)
3362}
3363
3364fn wasm_cache_fs_error(error: CacheFsError) -> WasmBuildError {
3365    WasmBuildError::Io {
3366        operation: error.operation,
3367        path: error.path,
3368        source: error.source,
3369    }
3370}
3371
3372fn validate_spec(spec: &WasmBuildSpec) -> Result<(), WasmBuildError> {
3373    if spec.packages.is_empty() {
3374        return Err(WasmBuildError::InvalidSpec {
3375            message: "at least one Cargo package is required".to_owned(),
3376        });
3377    }
3378    if spec.profile_target_dir.is_empty() {
3379        return Err(WasmBuildError::InvalidSpec {
3380            message: "Cargo profile target directory must not be empty".to_owned(),
3381        });
3382    }
3383    if spec.target.is_empty() {
3384        return Err(WasmBuildError::InvalidSpec {
3385            message: "Cargo compilation target must not be empty".to_owned(),
3386        });
3387    }
3388    if spec.extra_env.contains_key(OsStr::new("CARGO_TARGET_DIR"))
3389        || spec.cargo_profile_args.iter().any(|argument| {
3390            argument == OsStr::new("--target-dir")
3391                || argument.as_encoded_bytes().starts_with(b"--target-dir=")
3392        })
3393    {
3394        return Err(WasmBuildError::InvalidSpec {
3395            message: "Cargo target directories are owned by the build specification; use target_dir or with_shared_incremental_target instead of command overrides".to_owned(),
3396        });
3397    }
3398    if matches!(
3399        &spec.cache_mode,
3400        WasmBuildCacheMode::SharedIncremental { target_dir } if target_dir.as_os_str().is_empty()
3401    ) {
3402        return Err(WasmBuildError::InvalidSpec {
3403            message: "shared incremental Cargo target directory must not be empty".to_owned(),
3404        });
3405    }
3406    if spec.shared_incremental_maintenance_config.is_some()
3407        && !matches!(
3408            spec.cache_mode,
3409            WasmBuildCacheMode::SharedIncremental { .. }
3410        )
3411    {
3412        return Err(WasmBuildError::InvalidSpec {
3413            message:
3414                "scheduled shared-target maintenance requires a shared incremental Cargo target"
3415                    .to_owned(),
3416        });
3417    }
3418    Ok(())
3419}
3420
3421fn build_fingerprint(spec: &WasmBuildSpec) -> Result<ResolvedCargoBuildInputs, WasmBuildError> {
3422    build_fingerprint_with_progress(spec, &mut ProgressReporter::silent())
3423}
3424
3425fn build_fingerprint_with_progress(
3426    spec: &WasmBuildSpec,
3427    progress: &mut ProgressReporter<'_>,
3428) -> Result<ResolvedCargoBuildInputs, WasmBuildError> {
3429    let total_started = Instant::now();
3430    let (cargo_identity, rustc_identity, tool_identity) = resolve_tool_identity(spec, progress)?;
3431
3432    let metadata_started = Instant::now();
3433    let metadata = progress.run_phase(WasmBuildProgressPhase::CargoMetadata, || {
3434        cargo_metadata(spec)
3435    })?;
3436    let cargo_metadata = metadata_started.elapsed();
3437
3438    let discovery_started = Instant::now();
3439    let (inputs, exclusions) =
3440        progress.run_phase(WasmBuildProgressPhase::InputDiscovery, || {
3441            let inputs = resolve_local_inputs(spec, &metadata)?;
3442            validate_shared_incremental_target_boundary(spec, &inputs.validation_inputs)?;
3443            let exclusions = source_exclusions(spec, &inputs.validation_inputs);
3444            Ok::<_, WasmBuildError>((inputs, exclusions))
3445        })?;
3446    let input_discovery = discovery_started.elapsed();
3447
3448    let hashing_started = Instant::now();
3449    let (input_digest, validation_digest) =
3450        progress.run_phase(WasmBuildProgressPhase::ContentHashing, || {
3451            let mut cache = LabeledPathDigestCache::default();
3452            digest_resolved_local_inputs(
3453                &inputs,
3454                &exclusions,
3455                &mut cache,
3456                &spec.workspace_root,
3457                "hash Wasm build inputs",
3458                "hash semantic Wasm build inputs",
3459            )
3460        })?;
3461    let content_hashing = hashing_started.elapsed();
3462
3463    let fingerprint =
3464        finish_build_fingerprint(spec, &cargo_identity, &rustc_identity, input_digest);
3465    Ok(ResolvedCargoBuildInputs {
3466        fingerprint,
3467        input_digest,
3468        validation_digest,
3469        inputs: inputs
3470            .validation_inputs
3471            .into_iter()
3472            .map(|(label, path)| CargoBuildInput { label, path })
3473            .collect(),
3474        exclusions,
3475        timings: WasmInputResolutionTimings {
3476            tool_identity,
3477            cargo_metadata,
3478            input_discovery,
3479            content_hashing,
3480            total: total_started.elapsed(),
3481        },
3482    })
3483}
3484
3485fn finish_build_fingerprint(
3486    spec: &WasmBuildSpec,
3487    cargo_identity: &[u8],
3488    rustc_identity: &[u8],
3489    input_digest: InputDigest,
3490) -> InputDigest {
3491    let mut hasher = InputHasher::new(CACHE_FORMAT_VERSION);
3492    let mut packages = spec.packages.clone();
3493    packages.sort();
3494    packages.dedup();
3495    for package in packages {
3496        hasher.field("package", package.as_bytes());
3497    }
3498    hasher.field("target", spec.target.as_bytes());
3499    hasher.field("profile-target-dir", spec.profile_target_dir.as_bytes());
3500    for argument in &spec.cargo_profile_args {
3501        hasher.field("cargo-argument", &os_bytes(argument));
3502    }
3503    for (key, value) in effective_environment(spec) {
3504        hasher.field("environment-key", &os_bytes(&key));
3505        if let Some(value) = value {
3506            hasher.field("environment-value", &os_bytes(&value));
3507        } else {
3508            hasher.field("environment-unset", b"");
3509        }
3510    }
3511    hasher.field("cargo-identity", cargo_identity);
3512    hasher.field("rustc-identity", rustc_identity);
3513    hasher.field("source-input-digest", input_digest.as_bytes());
3514    hasher.finish()
3515}
3516
3517fn command_identity(
3518    spec: &WasmBuildSpec,
3519    phase: WasmBuildPhase,
3520    program: &OsStr,
3521    arguments: &[&str],
3522) -> Result<Vec<u8>, WasmBuildError> {
3523    let mut command = Command::new(program);
3524    command.current_dir(&spec.workspace_root).args(arguments);
3525    apply_command_environment(&mut command, spec);
3526    let output = command
3527        .output()
3528        .map_err(|source| WasmBuildError::CommandSpawn {
3529            phase,
3530            program: program.to_owned(),
3531            source,
3532        })?;
3533    ensure_command_success(phase, output).map(|output| {
3534        let mut identity = output.stdout;
3535        identity.extend_from_slice(&output.stderr);
3536        identity
3537    })
3538}
3539
3540fn cargo_metadata(spec: &WasmBuildSpec) -> Result<Value, WasmBuildError> {
3541    let mut command = Command::new(&spec.cargo_program);
3542    command
3543        .current_dir(&spec.workspace_root)
3544        .args(["metadata", "--format-version", "1"]);
3545    for argument in metadata_arguments(&spec.cargo_profile_args) {
3546        command.arg(argument);
3547    }
3548    apply_command_environment(&mut command, spec);
3549    let output = command
3550        .output()
3551        .map_err(|source| WasmBuildError::CommandSpawn {
3552            phase: WasmBuildPhase::CargoMetadata,
3553            program: spec.cargo_program.clone(),
3554            source,
3555        })?;
3556    let output = ensure_command_success(WasmBuildPhase::CargoMetadata, output)?;
3557    serde_json::from_slice(&output.stdout).map_err(|error| WasmBuildError::InvalidMetadata {
3558        message: format!("Cargo metadata was not valid JSON: {error}"),
3559    })
3560}
3561
3562fn metadata_arguments(arguments: &[OsString]) -> Vec<OsString> {
3563    let mut selected = Vec::new();
3564    let mut arguments = arguments.iter();
3565    while let Some(argument) = arguments.next() {
3566        let argument_text = argument.to_string_lossy();
3567        match argument_text.as_ref() {
3568            "--all-features" | "--no-default-features" | "--locked" | "--offline" | "--frozen" => {
3569                selected.push(argument.clone());
3570            }
3571            "--features" | "-F" | "--filter-platform" => {
3572                selected.push(argument.clone());
3573                if let Some(value) = arguments.next() {
3574                    selected.push(value.clone());
3575                }
3576            }
3577            _ if argument_text.starts_with("--features=")
3578                || argument_text.starts_with("-F")
3579                || argument_text.starts_with("--filter-platform=") =>
3580            {
3581                selected.push(argument.clone());
3582            }
3583            _ => {}
3584        }
3585    }
3586    selected
3587}
3588
3589#[derive(Clone)]
3590struct MetadataPackage {
3591    id: String,
3592    name: String,
3593    version: String,
3594    manifest_path: PathBuf,
3595    is_local: bool,
3596    source: Option<String>,
3597    semantic_fields: Vec<(&'static str, Option<String>)>,
3598}
3599
3600const SEMANTIC_PACKAGE_FIELDS: &[&str] = &[
3601    "authors",
3602    "default_run",
3603    "description",
3604    "documentation",
3605    "edition",
3606    "homepage",
3607    "license",
3608    "license_file",
3609    "links",
3610    "metadata",
3611    "name",
3612    "readme",
3613    "repository",
3614    "rust_version",
3615    "version",
3616];
3617
3618struct LockedPackageIdentity {
3619    name: String,
3620    version: String,
3621    source: String,
3622    checksum: Option<String>,
3623}
3624
3625fn resolve_local_inputs(
3626    spec: &WasmBuildSpec,
3627    metadata: &Value,
3628) -> Result<ResolvedLocalInputs, WasmBuildError> {
3629    let packages = metadata_packages(metadata)?;
3630    let mut selected_ids = selected_package_ids(spec, metadata, &packages)?;
3631    let dependencies = metadata_dependencies(metadata)?;
3632    let mut closure = BTreeSet::new();
3633    while let Some(id) = selected_ids.pop_front() {
3634        if !closure.insert(id.clone()) {
3635            continue;
3636        }
3637        if let Some(deps) = dependencies.get(&id) {
3638            selected_ids.extend(deps.iter().cloned());
3639        }
3640    }
3641
3642    let workspace_root = metadata
3643        .get("workspace_root")
3644        .and_then(Value::as_str)
3645        .map_or_else(|| spec.workspace_root.clone(), PathBuf::from);
3646    let projection = semantic_workspace_projection(metadata, &packages, &closure, &workspace_root)?;
3647    let mut validation_inputs = workspace_configuration_inputs(spec, &workspace_root)?;
3648    append_package_inputs(&mut validation_inputs, &packages, closure, &workspace_root)?;
3649    append_additional_inputs(&mut validation_inputs, spec, &workspace_root);
3650    let fingerprint = projection.map_or(LocalInputFingerprint::Conservative, |workspace| {
3651        LocalInputFingerprint::Projected {
3652            inputs: validation_inputs
3653                .iter()
3654                .filter(|(label, _)| !is_broad_workspace_input(label))
3655                .cloned()
3656                .collect(),
3657            workspace,
3658        }
3659    });
3660    Ok(ResolvedLocalInputs {
3661        validation_inputs,
3662        fingerprint,
3663    })
3664}
3665
3666fn metadata_packages(metadata: &Value) -> Result<HashMap<String, MetadataPackage>, WasmBuildError> {
3667    let packages_value = metadata
3668        .get("packages")
3669        .and_then(Value::as_array)
3670        .ok_or_else(|| invalid_metadata("Cargo metadata has no package array"))?;
3671    let mut packages = HashMap::new();
3672    for value in packages_value {
3673        let source = optional_string(value, "source")?;
3674        let package = MetadataPackage {
3675            id: required_string(value, "id")?,
3676            name: required_string(value, "name")?,
3677            version: required_string(value, "version")?,
3678            manifest_path: PathBuf::from(required_string(value, "manifest_path")?),
3679            is_local: value.get("source").is_some_and(Value::is_null),
3680            source,
3681            semantic_fields: SEMANTIC_PACKAGE_FIELDS
3682                .iter()
3683                .map(|field| (*field, value.get(*field).map(Value::to_string)))
3684                .collect(),
3685        };
3686        packages.insert(package.id.clone(), package);
3687    }
3688    Ok(packages)
3689}
3690
3691fn selected_package_ids(
3692    spec: &WasmBuildSpec,
3693    metadata: &Value,
3694    packages: &HashMap<String, MetadataPackage>,
3695) -> Result<VecDeque<String>, WasmBuildError> {
3696    let workspace_members = metadata
3697        .get("workspace_members")
3698        .and_then(Value::as_array)
3699        .ok_or_else(|| invalid_metadata("Cargo metadata has no workspace member array"))?
3700        .iter()
3701        .filter_map(Value::as_str)
3702        .collect::<HashSet<_>>();
3703    let mut selected_ids = VecDeque::new();
3704    for requested in &spec.packages {
3705        let matches = packages
3706            .values()
3707            .filter(|package| {
3708                package.name == *requested && workspace_members.contains(package.id.as_str())
3709            })
3710            .map(|package| package.id.clone())
3711            .collect::<Vec<_>>();
3712        match matches.as_slice() {
3713            [id] => selected_ids.push_back(id.clone()),
3714            [] => {
3715                return Err(WasmBuildError::InvalidSpec {
3716                    message: format!("Cargo workspace contains no package named `{requested}`"),
3717                });
3718            }
3719            _ => {
3720                return Err(WasmBuildError::InvalidSpec {
3721                    message: format!("Cargo workspace package name `{requested}` is ambiguous"),
3722                });
3723            }
3724        }
3725    }
3726    Ok(selected_ids)
3727}
3728
3729fn metadata_dependencies(metadata: &Value) -> Result<HashMap<String, Vec<String>>, WasmBuildError> {
3730    let mut dependencies = HashMap::<String, Vec<String>>::new();
3731    let nodes = metadata
3732        .pointer("/resolve/nodes")
3733        .and_then(Value::as_array)
3734        .ok_or_else(|| invalid_metadata("Cargo metadata has no resolved dependency nodes"))?;
3735    for node in nodes {
3736        let id = required_string(node, "id")?;
3737        let deps = node
3738            .get("deps")
3739            .and_then(Value::as_array)
3740            .ok_or_else(|| invalid_metadata("Cargo metadata dependency node has no deps array"))?
3741            .iter()
3742            .map(|dependency| required_string(dependency, "pkg"))
3743            .collect::<Result<Vec<_>, _>>()?;
3744        dependencies.insert(id, deps);
3745    }
3746    Ok(dependencies)
3747}
3748
3749fn semantic_workspace_projection(
3750    metadata: &Value,
3751    packages: &HashMap<String, MetadataPackage>,
3752    closure: &BTreeSet<String>,
3753    workspace_root: &Path,
3754) -> Result<Option<InputDigest>, WasmBuildError> {
3755    // A workspace-root or external local package cannot be separated from the
3756    // broad root safely; `None` keeps the complete-input fingerprint.
3757    let locked_packages = locked_package_identities(workspace_root)?;
3758    let mut identities = HashMap::new();
3759    for id in closure {
3760        let package = packages
3761            .get(id)
3762            .ok_or_else(|| invalid_metadata(&format!("resolved package `{id}` is missing")))?;
3763        let Some(identity) = semantic_package_identity(package, workspace_root, &locked_packages)
3764        else {
3765            return Ok(None);
3766        };
3767        identities.insert(id.as_str(), identity);
3768    }
3769
3770    let nodes = metadata
3771        .pointer("/resolve/nodes")
3772        .and_then(Value::as_array)
3773        .ok_or_else(|| invalid_metadata("Cargo metadata has no resolved dependency nodes"))?;
3774    let nodes_by_id = nodes
3775        .iter()
3776        .map(|node| Ok((required_string(node, "id")?, node)))
3777        .collect::<Result<HashMap<_, _>, WasmBuildError>>()?;
3778    let mut projected_packages = closure
3779        .iter()
3780        .map(|id| {
3781            let package = packages
3782                .get(id)
3783                .expect("selected package closure was validated above");
3784            let identity = identities[id.as_str()];
3785            let node = nodes_by_id.get(id).copied().ok_or_else(|| {
3786                invalid_metadata(&format!("resolved package `{id}` has no dependency node"))
3787            })?;
3788            let projection = semantic_package_projection(package, node, &identities)?;
3789            Ok::<_, WasmBuildError>((identity, projection))
3790        })
3791        .collect::<Result<Vec<_>, _>>()?;
3792    projected_packages.sort_by_key(|(identity, _)| *identity);
3793
3794    let root_manifest = workspace_root.join("Cargo.toml");
3795    let root_contents =
3796        fs::read_to_string(&root_manifest).map_err(|source| WasmBuildError::Io {
3797            operation: "read workspace manifest for semantic projection",
3798            path: root_manifest.clone(),
3799            source,
3800        })?;
3801    let root = toml::from_str::<TomlValue>(&root_contents).map_err(|error| {
3802        invalid_metadata(&format!(
3803            "workspace manifest could not be projected as TOML: {error}"
3804        ))
3805    })?;
3806
3807    let mut hasher = InputHasher::new("wasm-semantic-workspace-projection-v1");
3808    for (identity, projection) in projected_packages {
3809        hasher.field("package-identity", identity.as_bytes());
3810        hasher.field("package-projection", projection.as_bytes());
3811    }
3812    hash_toml_setting(&mut hasher, "cargo-features", root.get("cargo-features"));
3813    hash_toml_setting(&mut hasher, "profile", root.get("profile"));
3814    let workspace = root.get("workspace").and_then(TomlValue::as_table);
3815    hash_toml_setting(
3816        &mut hasher,
3817        "workspace-resolver",
3818        workspace.and_then(|table| table.get("resolver")),
3819    );
3820    hash_toml_setting(
3821        &mut hasher,
3822        "workspace-lints",
3823        workspace.and_then(|table| table.get("lints")),
3824    );
3825    Ok(Some(hasher.finish()))
3826}
3827
3828fn locked_package_identities(
3829    workspace_root: &Path,
3830) -> Result<Vec<LockedPackageIdentity>, WasmBuildError> {
3831    let lockfile = workspace_root.join("Cargo.lock");
3832    let contents = match fs::read_to_string(&lockfile) {
3833        Ok(contents) => contents,
3834        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
3835        Err(source) => {
3836            return Err(WasmBuildError::Io {
3837                operation: "read Cargo lockfile for semantic projection",
3838                path: lockfile,
3839                source,
3840            });
3841        }
3842    };
3843    let lock = toml::from_str::<TomlValue>(&contents).map_err(|error| {
3844        invalid_metadata(&format!(
3845            "Cargo lockfile could not be projected as TOML: {error}"
3846        ))
3847    })?;
3848    let Some(packages) = lock.get("package").and_then(TomlValue::as_array) else {
3849        return Ok(Vec::new());
3850    };
3851    packages
3852        .iter()
3853        .filter_map(|package| {
3854            let Some(table) = package.as_table() else {
3855                return Some(Err(invalid_metadata(
3856                    "Cargo lockfile package entry is not a table",
3857                )));
3858            };
3859            let source = table.get("source")?.as_str().map(str::to_owned);
3860            Some(
3861                source
3862                    .ok_or_else(|| {
3863                        invalid_metadata("Cargo lockfile package source is not a string")
3864                    })
3865                    .and_then(|source| {
3866                        Ok(LockedPackageIdentity {
3867                            name: required_toml_string(table, "name", "Cargo lockfile package")?,
3868                            version: required_toml_string(
3869                                table,
3870                                "version",
3871                                "Cargo lockfile package",
3872                            )?,
3873                            source,
3874                            checksum: optional_toml_string(
3875                                table,
3876                                "checksum",
3877                                "Cargo lockfile package",
3878                            )?,
3879                        })
3880                    }),
3881            )
3882        })
3883        .collect()
3884}
3885
3886fn required_toml_string(
3887    table: &toml::Table,
3888    field: &str,
3889    context: &str,
3890) -> Result<String, WasmBuildError> {
3891    table
3892        .get(field)
3893        .and_then(TomlValue::as_str)
3894        .map(str::to_owned)
3895        .ok_or_else(|| invalid_metadata(&format!("{context} `{field}` is missing or not a string")))
3896}
3897
3898fn optional_toml_string(
3899    table: &toml::Table,
3900    field: &str,
3901    context: &str,
3902) -> Result<Option<String>, WasmBuildError> {
3903    match table.get(field) {
3904        None => Ok(None),
3905        Some(TomlValue::String(value)) => Ok(Some(value.clone())),
3906        Some(_) => Err(invalid_metadata(&format!(
3907            "{context} `{field}` is not a string"
3908        ))),
3909    }
3910}
3911
3912fn semantic_package_identity(
3913    package: &MetadataPackage,
3914    workspace_root: &Path,
3915    locked_packages: &[LockedPackageIdentity],
3916) -> Option<InputDigest> {
3917    let mut hasher = InputHasher::new("wasm-semantic-package-identity-v1");
3918    hasher.field("name", package.name.as_bytes());
3919    hasher.field("version", package.version.as_bytes());
3920    if package.is_local {
3921        let manifest = package.manifest_path.strip_prefix(workspace_root).ok()?;
3922        let package_root = package.manifest_path.parent()?;
3923        if package_root == workspace_root {
3924            return None;
3925        }
3926        hasher.field("local-manifest", &os_bytes(manifest.as_os_str()));
3927    } else {
3928        let metadata_source = package.source.as_deref()?;
3929        let locked = locked_packages.iter().find(|locked| {
3930            locked.name == package.name
3931                && locked.version == package.version
3932                && locked.source == metadata_source
3933        })?;
3934        match locked.source.as_str() {
3935            source if source.starts_with("registry+") && locked.checksum.is_some() => {}
3936            source if source.starts_with("git+") && source.contains('#') => {}
3937            _ => return None,
3938        }
3939        hasher.field("external-package-id", package.id.as_bytes());
3940        hasher.field("external-source", locked.source.as_bytes());
3941        hasher.field(
3942            "external-checksum",
3943            locked.checksum.as_deref().unwrap_or_default().as_bytes(),
3944        );
3945    }
3946    Some(hasher.finish())
3947}
3948
3949fn semantic_package_projection(
3950    package: &MetadataPackage,
3951    node: &Value,
3952    identities: &HashMap<&str, InputDigest>,
3953) -> Result<InputDigest, WasmBuildError> {
3954    // These are the effective package values Cargo can expose to compilation
3955    // through CARGO_PKG_* variables. Local manifests and external checksums
3956    // cover the remaining package definition.
3957    let mut hasher = InputHasher::new("wasm-semantic-package-projection-v1");
3958    for (field, value) in &package.semantic_fields {
3959        hasher.field("package-field-name", field.as_bytes());
3960        match value {
3961            Some(value) => hasher.field("package-field-value", value.as_bytes()),
3962            None => hasher.field("package-field-missing", b""),
3963        }
3964    }
3965
3966    let mut features = node
3967        .get("features")
3968        .and_then(Value::as_array)
3969        .ok_or_else(|| invalid_metadata("Cargo metadata dependency node has no features array"))?
3970        .iter()
3971        .map(|feature| {
3972            feature.as_str().map(str::to_owned).ok_or_else(|| {
3973                invalid_metadata("Cargo metadata dependency feature is not a string")
3974            })
3975        })
3976        .collect::<Result<Vec<_>, _>>()?;
3977    features.sort();
3978    for feature in features {
3979        hasher.field("enabled-feature", feature.as_bytes());
3980    }
3981
3982    let mut dependencies = node
3983        .get("deps")
3984        .and_then(Value::as_array)
3985        .ok_or_else(|| invalid_metadata("Cargo metadata dependency node has no deps array"))?
3986        .iter()
3987        .map(|dependency| {
3988            let name = required_string(dependency, "name")?;
3989            let package_id = required_string(dependency, "pkg")?;
3990            let identity = identities
3991                .get(package_id.as_str())
3992                .copied()
3993                .ok_or_else(|| {
3994                    invalid_metadata(&format!(
3995                        "dependency `{package_id}` is outside the selected package closure"
3996                    ))
3997                })?;
3998            let kinds = dependency
3999                .get("dep_kinds")
4000                .ok_or_else(|| invalid_metadata("Cargo metadata dependency has no kind array"))?
4001                .to_string();
4002            Ok::<_, WasmBuildError>((name, identity, kinds))
4003        })
4004        .collect::<Result<Vec<_>, _>>()?;
4005    dependencies.sort();
4006    for (name, identity, kinds) in dependencies {
4007        hasher.field("dependency-name", name.as_bytes());
4008        hasher.field("dependency-identity", identity.as_bytes());
4009        hasher.field("dependency-kinds", kinds.as_bytes());
4010    }
4011    Ok(hasher.finish())
4012}
4013
4014fn hash_toml_setting(hasher: &mut InputHasher, label: &str, value: Option<&TomlValue>) {
4015    hasher.field("workspace-setting-name", label.as_bytes());
4016    match value {
4017        Some(value) => hasher.field("workspace-setting-value", value.to_string().as_bytes()),
4018        None => hasher.field("workspace-setting-missing", b""),
4019    }
4020}
4021
4022fn is_broad_workspace_input(label: &Path) -> bool {
4023    label == Path::new("workspace/Cargo.toml") || label == Path::new("workspace/Cargo.lock")
4024}
4025
4026fn digest_resolved_local_inputs(
4027    inputs: &ResolvedLocalInputs,
4028    exclusions: &[PathBuf],
4029    cache: &mut LabeledPathDigestCache,
4030    error_path: &Path,
4031    validation_operation: &'static str,
4032    semantic_operation: &'static str,
4033) -> Result<(InputDigest, InputDigest), WasmBuildError> {
4034    let validation_digest = digest_labeled_paths_composable(
4035        "wasm-source-inputs-v1",
4036        &inputs.validation_inputs,
4037        exclusions,
4038        cache,
4039    )
4040    .map_err(|source| WasmBuildError::Io {
4041        operation: validation_operation,
4042        path: error_path.to_owned(),
4043        source,
4044    })?;
4045    let input_digest = semantic_input_digest(inputs, validation_digest, exclusions, cache)
4046        .map_err(|source| WasmBuildError::Io {
4047            operation: semantic_operation,
4048            path: error_path.to_owned(),
4049            source,
4050        })?;
4051    Ok((input_digest, validation_digest))
4052}
4053
4054fn semantic_input_digest(
4055    inputs: &ResolvedLocalInputs,
4056    validation_digest: InputDigest,
4057    exclusions: &[PathBuf],
4058    cache: &mut LabeledPathDigestCache,
4059) -> io::Result<InputDigest> {
4060    let LocalInputFingerprint::Projected {
4061        inputs: fingerprint_inputs,
4062        workspace,
4063    } = &inputs.fingerprint
4064    else {
4065        return Ok(validation_digest);
4066    };
4067    let path_digest = digest_labeled_paths_composable(
4068        "wasm-source-inputs-v1",
4069        fingerprint_inputs,
4070        exclusions,
4071        cache,
4072    )?;
4073    let mut hasher = InputHasher::new("wasm-semantic-source-inputs-v1");
4074    hasher.field("path-input-digest", path_digest.as_bytes());
4075    hasher.field("workspace-projection", workspace.as_bytes());
4076    Ok(hasher.finish())
4077}
4078
4079fn workspace_configuration_inputs(
4080    spec: &WasmBuildSpec,
4081    workspace_root: &Path,
4082) -> Result<Vec<(PathBuf, PathBuf)>, WasmBuildError> {
4083    let mut inputs = Vec::new();
4084    add_if_present(
4085        &mut inputs,
4086        "workspace/Cargo.toml",
4087        workspace_root.join("Cargo.toml"),
4088    );
4089    add_if_present(
4090        &mut inputs,
4091        "workspace/Cargo.lock",
4092        workspace_root.join("Cargo.lock"),
4093    );
4094    add_if_present(
4095        &mut inputs,
4096        "workspace/rust-toolchain.toml",
4097        workspace_root.join("rust-toolchain.toml"),
4098    );
4099    add_if_present(
4100        &mut inputs,
4101        "workspace/rust-toolchain",
4102        workspace_root.join("rust-toolchain"),
4103    );
4104    append_cargo_configuration_inputs(&mut inputs, spec, workspace_root)?;
4105    Ok(inputs)
4106}
4107
4108fn append_cargo_configuration_inputs(
4109    inputs: &mut Vec<(PathBuf, PathBuf)>,
4110    spec: &WasmBuildSpec,
4111    workspace_root: &Path,
4112) -> Result<(), WasmBuildError> {
4113    let invocation_root =
4114        spec.workspace_root
4115            .canonicalize()
4116            .map_err(|source| WasmBuildError::Io {
4117                operation: "resolve Cargo invocation directory",
4118                path: spec.workspace_root.clone(),
4119                source,
4120            })?;
4121    let canonical_workspace =
4122        workspace_root
4123            .canonicalize()
4124            .map_err(|source| WasmBuildError::Io {
4125                operation: "resolve Cargo workspace directory",
4126                path: workspace_root.to_owned(),
4127                source,
4128            })?;
4129
4130    let mut roots = invocation_root
4131        .ancestors()
4132        .filter_map(|directory| effective_cargo_config(&directory.join(".cargo")))
4133        .collect::<Vec<_>>();
4134    if let Some(cargo_home) = effective_cargo_home(spec, &invocation_root)
4135        && let Some(config) = effective_cargo_config(&cargo_home)
4136    {
4137        roots.push(config);
4138    }
4139
4140    let mut visited = BTreeSet::new();
4141    for config in roots {
4142        append_cargo_configuration_tree(
4143            inputs,
4144            &config,
4145            &canonical_workspace,
4146            &mut visited,
4147            false,
4148        )?;
4149    }
4150    Ok(())
4151}
4152
4153fn effective_cargo_config(directory: &Path) -> Option<PathBuf> {
4154    let extensionless = directory.join("config");
4155    if extensionless.exists() {
4156        return Some(extensionless);
4157    }
4158    let toml = directory.join("config.toml");
4159    toml.exists().then_some(toml)
4160}
4161
4162fn effective_cargo_home(spec: &WasmBuildSpec, invocation_root: &Path) -> Option<PathBuf> {
4163    if let Some(cargo_home) = command_environment_value(spec, "CARGO_HOME") {
4164        let cargo_home = PathBuf::from(cargo_home);
4165        return Some(if cargo_home.is_absolute() {
4166            cargo_home
4167        } else {
4168            invocation_root.join(cargo_home)
4169        });
4170    }
4171
4172    default_home_directory(spec).map(|home| {
4173        let home = if home.is_absolute() {
4174            home
4175        } else {
4176            invocation_root.join(home)
4177        };
4178        home.join(".cargo")
4179    })
4180}
4181
4182#[cfg(windows)]
4183fn default_home_directory(spec: &WasmBuildSpec) -> Option<PathBuf> {
4184    command_environment_value(spec, "USERPROFILE")
4185        .or_else(|| command_environment_value(spec, "HOME"))
4186        .map(PathBuf::from)
4187}
4188
4189#[cfg(not(windows))]
4190fn default_home_directory(spec: &WasmBuildSpec) -> Option<PathBuf> {
4191    command_environment_value(spec, "HOME").map(PathBuf::from)
4192}
4193
4194fn command_environment_value(spec: &WasmBuildSpec, name: &str) -> Option<OsString> {
4195    spec.extra_env
4196        .get(OsStr::new(name))
4197        .cloned()
4198        .or_else(|| std::env::var_os(name))
4199}
4200
4201fn append_cargo_configuration_tree(
4202    inputs: &mut Vec<(PathBuf, PathBuf)>,
4203    config: &Path,
4204    workspace_root: &Path,
4205    visited: &mut BTreeSet<PathBuf>,
4206    optional: bool,
4207) -> Result<(), WasmBuildError> {
4208    let canonical = match config.canonicalize() {
4209        Ok(canonical) => canonical,
4210        Err(error) if optional && error.kind() == io::ErrorKind::NotFound => return Ok(()),
4211        Err(source) => {
4212            return Err(WasmBuildError::Io {
4213                operation: "resolve Cargo configuration",
4214                path: config.to_owned(),
4215                source,
4216            });
4217        }
4218    };
4219    if !visited.insert(canonical.clone()) {
4220        return Ok(());
4221    }
4222
4223    let contents = fs::read_to_string(&canonical).map_err(|source| WasmBuildError::Io {
4224        operation: "read Cargo configuration",
4225        path: canonical.clone(),
4226        source,
4227    })?;
4228    let configuration = toml::from_str::<TomlValue>(&contents).map_err(|error| {
4229        WasmBuildError::InvalidCargoConfiguration {
4230            path: canonical.clone(),
4231            message: error.to_string(),
4232        }
4233    })?;
4234    inputs.push((
4235        cargo_configuration_label(&canonical, workspace_root),
4236        canonical.clone(),
4237    ));
4238
4239    let Some(include) = configuration.get("include") else {
4240        return Ok(());
4241    };
4242    let parent = canonical
4243        .parent()
4244        .ok_or_else(|| WasmBuildError::InvalidCargoConfiguration {
4245            path: canonical.clone(),
4246            message: "configuration path has no parent directory".to_owned(),
4247        })?;
4248    for (included, optional) in cargo_configuration_includes(include, &canonical)? {
4249        let included = if included.is_absolute() {
4250            included
4251        } else {
4252            parent.join(included)
4253        };
4254        append_cargo_configuration_tree(inputs, &included, workspace_root, visited, optional)?;
4255    }
4256    Ok(())
4257}
4258
4259fn cargo_configuration_includes(
4260    include: &TomlValue,
4261    config: &Path,
4262) -> Result<Vec<(PathBuf, bool)>, WasmBuildError> {
4263    let values = match include {
4264        TomlValue::Array(values) => values.as_slice(),
4265        value => std::slice::from_ref(value),
4266    };
4267    values
4268        .iter()
4269        .map(|value| match value {
4270            TomlValue::String(path) => Ok((PathBuf::from(path), false)),
4271            TomlValue::Table(table) => {
4272                let path = table
4273                    .get("path")
4274                    .and_then(TomlValue::as_str)
4275                    .ok_or_else(|| {
4276                        invalid_cargo_configuration(
4277                            config,
4278                            "Cargo configuration include table requires a string `path`",
4279                        )
4280                    })?;
4281                let optional = table
4282                    .get("optional")
4283                    .map(|value| {
4284                        value.as_bool().ok_or_else(|| {
4285                            invalid_cargo_configuration(
4286                                config,
4287                                "Cargo configuration include `optional` must be a boolean",
4288                            )
4289                        })
4290                    })
4291                    .transpose()?
4292                    .unwrap_or(false);
4293                Ok((PathBuf::from(path), optional))
4294            }
4295            _ => Err(invalid_cargo_configuration(
4296                config,
4297                "Cargo configuration `include` must contain paths or include tables",
4298            )),
4299        })
4300        .collect()
4301}
4302
4303fn cargo_configuration_label(config: &Path, workspace_root: &Path) -> PathBuf {
4304    if let Ok(relative) = config.strip_prefix(workspace_root) {
4305        return PathBuf::from("cargo-config/workspace").join(relative);
4306    }
4307    let location = digest_bytes("cargo-config-location-v1", &os_bytes(config.as_os_str()));
4308    PathBuf::from("cargo-config/external").join(location.to_hex())
4309}
4310
4311fn invalid_cargo_configuration(path: &Path, message: &str) -> WasmBuildError {
4312    WasmBuildError::InvalidCargoConfiguration {
4313        path: path.to_owned(),
4314        message: message.to_owned(),
4315    }
4316}
4317
4318fn append_package_inputs(
4319    inputs: &mut Vec<(PathBuf, PathBuf)>,
4320    packages: &HashMap<String, MetadataPackage>,
4321    closure: BTreeSet<String>,
4322    workspace_root: &Path,
4323) -> Result<(), WasmBuildError> {
4324    for id in closure {
4325        let Some(package) = packages.get(&id) else {
4326            return Err(invalid_metadata(&format!(
4327                "resolved package `{id}` is missing"
4328            )));
4329        };
4330        if !package.is_local {
4331            continue;
4332        }
4333        let root = package.manifest_path.parent().ok_or_else(|| {
4334            invalid_metadata(&format!(
4335                "package `{}` manifest has no parent",
4336                package.name
4337            ))
4338        })?;
4339        let relative_manifest = package
4340            .manifest_path
4341            .strip_prefix(workspace_root)
4342            .unwrap_or(&package.manifest_path);
4343        let label = PathBuf::from(format!("package/{}@{}", package.name, package.version))
4344            .join(relative_manifest.parent().unwrap_or_else(|| Path::new(".")));
4345        inputs.push((label, root.to_owned()));
4346    }
4347    Ok(())
4348}
4349
4350fn append_additional_inputs(
4351    inputs: &mut Vec<(PathBuf, PathBuf)>,
4352    spec: &WasmBuildSpec,
4353    workspace_root: &Path,
4354) {
4355    for additional in &spec.additional_inputs {
4356        let path = if additional.is_absolute() {
4357            additional.clone()
4358        } else {
4359            workspace_root.join(additional)
4360        };
4361        inputs.push((PathBuf::from("additional").join(additional), path));
4362    }
4363}
4364
4365fn source_exclusions(spec: &WasmBuildSpec, inputs: &[(PathBuf, PathBuf)]) -> Vec<PathBuf> {
4366    let mut exclusions = vec![
4367        spec.target_dir.clone(),
4368        spec.workspace_root.join("target"),
4369        spec.workspace_root.join(".git"),
4370    ];
4371    if let Some(shared_target) = shared_incremental_target(spec) {
4372        exclusions.push(shared_target);
4373    }
4374    for (_, path) in inputs {
4375        if path.is_dir() {
4376            exclusions.push(path.join("target"));
4377            exclusions.push(path.join(".git"));
4378        }
4379    }
4380    exclusions
4381}
4382
4383fn validate_shared_incremental_target_boundary(
4384    spec: &WasmBuildSpec,
4385    inputs: &[(PathBuf, PathBuf)],
4386) -> Result<(), WasmBuildError> {
4387    let Some(shared_target) = shared_incremental_target(spec) else {
4388        return Ok(());
4389    };
4390    let shared_target =
4391        canonicalize_allow_missing(&shared_target).map_err(|source| WasmBuildError::Io {
4392            operation: "resolve shared incremental Cargo target boundary",
4393            path: shared_target.clone(),
4394            source,
4395        })?;
4396    let exact_entries = spec.target_dir.join(".ic-testkit/wasm-targets");
4397    let exact_entries =
4398        canonicalize_allow_missing(&exact_entries).map_err(|source| WasmBuildError::Io {
4399            operation: "resolve exact Wasm cache boundary",
4400            path: exact_entries,
4401            source,
4402        })?;
4403    // Maintenance preserves only the shared target's direct metadata child.
4404    // An exact cache elsewhere beneath that target would lose retained entries.
4405    if shared_target.starts_with(&exact_entries)
4406        || (exact_entries.starts_with(&shared_target)
4407            && !exact_entries.starts_with(shared_target.join(".ic-testkit")))
4408    {
4409        return Err(WasmBuildError::InvalidSpec {
4410            message: "shared incremental target must not overlap removable exact Wasm cache state"
4411                .to_owned(),
4412        });
4413    }
4414    let resolved_inputs = inputs
4415        .iter()
4416        .map(|(_, input)| {
4417            let canonical = input.canonicalize().map_err(|source| WasmBuildError::Io {
4418                operation: "resolve Cargo input boundary",
4419                path: input.clone(),
4420                source,
4421            })?;
4422            let metadata = fs::metadata(&canonical).map_err(|source| WasmBuildError::Io {
4423                operation: "inspect Cargo input boundary",
4424                path: canonical.clone(),
4425                source,
4426            })?;
4427            Ok((canonical, metadata.is_dir()))
4428        })
4429        .collect::<Result<Vec<_>, WasmBuildError>>()?;
4430    let safe_generated_roots = std::iter::once(spec.target_dir.clone())
4431        .chain(std::iter::once(spec.workspace_root.join("target")))
4432        .chain(
4433            inputs
4434                .iter()
4435                .filter(|(_, path)| path.is_dir())
4436                .map(|(_, path)| path.join("target")),
4437        )
4438        .filter_map(|path| canonicalize_allow_missing(&path).ok())
4439        .filter(|root| {
4440            !resolved_inputs
4441                .iter()
4442                .any(|(input, _is_directory)| input.starts_with(root))
4443        })
4444        .collect::<Vec<_>>();
4445    if safe_generated_roots
4446        .iter()
4447        .any(|root| shared_target.starts_with(root))
4448    {
4449        return Ok(());
4450    }
4451
4452    for (input, is_directory) in resolved_inputs {
4453        if shared_target == input
4454            || (is_directory && shared_target.starts_with(&input))
4455            || input.starts_with(&shared_target)
4456        {
4457            return Err(WasmBuildError::InvalidSpec {
4458                message: format!(
4459                    "shared incremental target {} must not overlap exact Cargo inputs unless it is inside a generated target directory",
4460                    shared_target.display()
4461                ),
4462            });
4463        }
4464    }
4465    Ok(())
4466}
4467
4468pub(super) fn shared_incremental_target(spec: &WasmBuildSpec) -> Option<PathBuf> {
4469    let WasmBuildCacheMode::SharedIncremental { target_dir } = &spec.cache_mode else {
4470        return None;
4471    };
4472    Some(if target_dir.is_absolute() {
4473        target_dir.clone()
4474    } else {
4475        spec.workspace_root.join(target_dir)
4476    })
4477}
4478
4479fn shared_incremental_target_exists(
4480    spec: &WasmBuildSpec,
4481    operation: &'static str,
4482) -> Result<bool, WasmBuildError> {
4483    let target_dir =
4484        shared_incremental_target(spec).ok_or_else(|| WasmBuildError::InvalidSpec {
4485            message: "shared incremental target is not configured".to_owned(),
4486        })?;
4487    match fs::symlink_metadata(&target_dir) {
4488        Ok(metadata) if metadata.is_dir() => Ok(true),
4489        Ok(_) => Err(WasmBuildError::InvalidSpec {
4490            message: format!(
4491                "shared incremental Cargo target {} must be a directory",
4492                target_dir.display()
4493            ),
4494        }),
4495        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
4496        Err(source) => Err(WasmBuildError::Io {
4497            operation,
4498            path: target_dir,
4499            source,
4500        }),
4501    }
4502}
4503
4504fn effective_environment(spec: &WasmBuildSpec) -> BTreeMap<OsString, Option<OsString>> {
4505    let mut names = spec.inherited_env.clone();
4506    names.extend(AUTOMATIC_ENVIRONMENT.iter().map(OsString::from));
4507    let mut environment = names
4508        .into_iter()
4509        .map(|name| {
4510            let value = std::env::var_os(&name);
4511            (name, value)
4512        })
4513        .collect::<BTreeMap<_, _>>();
4514    for (key, value) in &spec.extra_env {
4515        environment.insert(key.clone(), Some(value.clone()));
4516    }
4517    environment
4518}
4519
4520fn apply_command_environment(command: &mut Command, spec: &WasmBuildSpec) {
4521    for (key, value) in &spec.extra_env {
4522        command.env(key, value);
4523    }
4524}
4525
4526fn run_cargo_build(
4527    spec: &WasmBuildSpec,
4528    build_target_dir: &Path,
4529    progress: &mut ProgressReporter<'_>,
4530) -> Result<(), WasmBuildError> {
4531    let absolute_target_dir =
4532        canonicalize_allow_missing(build_target_dir).map_err(|source| WasmBuildError::Io {
4533            operation: "resolve Cargo build target directory",
4534            path: build_target_dir.to_owned(),
4535            source,
4536        })?;
4537    let mut command = Command::new(&spec.cargo_program);
4538    command
4539        .current_dir(&spec.workspace_root)
4540        .env("CARGO_TARGET_DIR", absolute_target_dir)
4541        .args(["build", "--target", &spec.target])
4542        .args(&spec.cargo_profile_args);
4543    apply_command_environment(&mut command, spec);
4544    for package in &spec.packages {
4545        command.args(["-p", package]);
4546    }
4547
4548    if !progress.is_observed() {
4549        let output = command
4550            .output()
4551            .map_err(|source| WasmBuildError::CommandSpawn {
4552                phase: WasmBuildPhase::CargoBuild,
4553                program: spec.cargo_program.clone(),
4554                source,
4555            })?;
4556        return ensure_command_success(WasmBuildPhase::CargoBuild, output).map(|_| ());
4557    }
4558
4559    run_observed_cargo_build(spec, build_target_dir, command, progress)
4560}
4561
4562fn run_observed_cargo_build(
4563    spec: &WasmBuildSpec,
4564    build_target_dir: &Path,
4565    mut command: Command,
4566    progress: &mut ProgressReporter<'_>,
4567) -> Result<(), WasmBuildError> {
4568    command.stdout(Stdio::piped()).stderr(Stdio::piped());
4569    let started = Instant::now();
4570    let child = command
4571        .spawn()
4572        .map_err(|source| WasmBuildError::CommandSpawn {
4573            phase: WasmBuildPhase::CargoBuild,
4574            program: spec.cargo_program.clone(),
4575            source,
4576        })?;
4577    let mut child = ObservedChild::new(child);
4578    progress.emit(WasmBuildProgressEvent::CargoStarted {
4579        target_dir: build_target_dir.to_owned(),
4580    });
4581
4582    let stdout = child
4583        .child_mut()
4584        .stdout
4585        .take()
4586        .expect("Cargo stdout must be piped");
4587    let stderr = child
4588        .child_mut()
4589        .stderr
4590        .take()
4591        .expect("Cargo stderr must be piped");
4592    let (sender, chunks) = mpsc::channel();
4593    let stdout_sender = sender.clone();
4594    let stdout_reader = thread::spawn(move || {
4595        read_process_output(stdout, WasmBuildOutputStream::Stdout, stdout_sender)
4596    });
4597    let stderr_reader =
4598        thread::spawn(move || read_process_output(stderr, WasmBuildOutputStream::Stderr, sender));
4599
4600    let captured = capture_observed_cargo_output(chunks, progress, started);
4601
4602    let status = child.wait().map_err(|source| WasmBuildError::Io {
4603        operation: "wait for observed cargo build",
4604        path: PathBuf::from(&spec.cargo_program),
4605        source,
4606    })?;
4607    join_output_reader(
4608        stdout_reader,
4609        "read observed cargo stdout",
4610        &spec.cargo_program,
4611    )?;
4612    join_output_reader(
4613        stderr_reader,
4614        "read observed cargo stderr",
4615        &spec.cargo_program,
4616    )?;
4617    let elapsed = started.elapsed();
4618    progress.emit(WasmBuildProgressEvent::CargoFinished {
4619        success: status.success(),
4620        code: status.code(),
4621        elapsed,
4622    });
4623
4624    ensure_command_success(
4625        WasmBuildPhase::CargoBuild,
4626        Output {
4627            status,
4628            stdout: captured.stdout,
4629            stderr: captured.stderr,
4630        },
4631    )
4632    .map(|_| ())
4633}
4634
4635struct CapturedProcessOutput {
4636    stdout: Vec<u8>,
4637    stderr: Vec<u8>,
4638}
4639
4640fn capture_observed_cargo_output(
4641    chunks: mpsc::Receiver<ProcessOutputChunk>,
4642    progress: &mut ProgressReporter<'_>,
4643    started: Instant,
4644) -> CapturedProcessOutput {
4645    let mut stdout = Vec::new();
4646    let mut stderr = Vec::new();
4647    loop {
4648        let message = match progress.heartbeat_due_in() {
4649            Some(wait) => match chunks.recv_timeout(wait) {
4650                Ok(chunk) => Some(chunk),
4651                Err(RecvTimeoutError::Timeout) => {
4652                    progress.emit_heartbeat(WasmBuildProgressPhase::CargoBuild, started.elapsed());
4653                    None
4654                }
4655                Err(RecvTimeoutError::Disconnected) => break,
4656            },
4657            None => match chunks.recv() {
4658                Ok(chunk) => Some(chunk),
4659                Err(_) => break,
4660            },
4661        };
4662        let Some(chunk) = message else {
4663            continue;
4664        };
4665        match chunk.stream {
4666            WasmBuildOutputStream::Stdout => stdout.extend_from_slice(&chunk.bytes),
4667            WasmBuildOutputStream::Stderr => stderr.extend_from_slice(&chunk.bytes),
4668        }
4669        if progress.config.emit_cargo_output {
4670            progress.emit(WasmBuildProgressEvent::CargoOutput {
4671                stream: chunk.stream,
4672                bytes: chunk.bytes,
4673            });
4674        }
4675    }
4676    CapturedProcessOutput { stdout, stderr }
4677}
4678
4679#[derive(Debug)]
4680struct ProcessOutputChunk {
4681    stream: WasmBuildOutputStream,
4682    bytes: Vec<u8>,
4683}
4684
4685fn read_process_output<R: io::Read>(
4686    mut reader: R,
4687    stream: WasmBuildOutputStream,
4688    sender: mpsc::Sender<ProcessOutputChunk>,
4689) -> io::Result<()> {
4690    let mut buffer = [0_u8; 8 * 1024];
4691    loop {
4692        let count = match reader.read(&mut buffer) {
4693            Ok(count) => count,
4694            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
4695            Err(error) => return Err(error),
4696        };
4697        if count == 0 {
4698            return Ok(());
4699        }
4700        if sender
4701            .send(ProcessOutputChunk {
4702                stream,
4703                bytes: buffer[..count].to_vec(),
4704            })
4705            .is_err()
4706        {
4707            return Ok(());
4708        }
4709    }
4710}
4711
4712fn join_output_reader(
4713    reader: thread::JoinHandle<io::Result<()>>,
4714    operation: &'static str,
4715    cargo_program: &OsStr,
4716) -> Result<(), WasmBuildError> {
4717    let result = reader.join().map_err(|_| WasmBuildError::Io {
4718        operation,
4719        path: PathBuf::from(cargo_program),
4720        source: io::Error::other("Cargo output reader panicked"),
4721    })?;
4722    result.map_err(|source| WasmBuildError::Io {
4723        operation,
4724        path: PathBuf::from(cargo_program),
4725        source,
4726    })
4727}
4728
4729struct ObservedChild(Option<Child>);
4730
4731impl ObservedChild {
4732    const fn new(child: Child) -> Self {
4733        Self(Some(child))
4734    }
4735
4736    const fn child_mut(&mut self) -> &mut Child {
4737        self.0.as_mut().expect("observed child must be present")
4738    }
4739
4740    fn wait(&mut self) -> io::Result<ExitStatus> {
4741        let status = self.child_mut().wait()?;
4742        self.0.take();
4743        Ok(status)
4744    }
4745}
4746
4747impl Drop for ObservedChild {
4748    fn drop(&mut self) {
4749        if let Some(mut child) = self.0.take() {
4750            let _ = child.kill();
4751            let _ = child.wait();
4752        }
4753    }
4754}
4755
4756fn ensure_command_success(phase: WasmBuildPhase, output: Output) -> Result<Output, WasmBuildError> {
4757    if output.status.success() {
4758        return Ok(output);
4759    }
4760    Err(WasmBuildError::CommandFailed {
4761        phase,
4762        status: output.status,
4763        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
4764        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
4765    })
4766}
4767
4768fn expected_artifacts(spec: &WasmBuildSpec, target_dir: &Path) -> Vec<PathBuf> {
4769    let mut packages = spec.packages.iter().map(String::as_str).collect::<Vec<_>>();
4770    packages.sort_unstable();
4771    packages.dedup();
4772    packages
4773        .into_iter()
4774        .map(|package| {
4775            if spec.target == DEFAULT_TARGET {
4776                wasm_path(target_dir, package, &spec.profile_target_dir)
4777            } else {
4778                target_dir
4779                    .join(&spec.target)
4780                    .join(&spec.profile_target_dir)
4781                    .join(format!("{package}.wasm"))
4782            }
4783        })
4784        .collect()
4785}
4786
4787fn cache_entry_directory(spec: &WasmBuildSpec, fingerprint: InputDigest) -> PathBuf {
4788    spec.target_dir
4789        .join(".ic-testkit/wasm-targets")
4790        .join(fingerprint.to_hex())
4791}
4792
4793fn artifact_set_matches(artifacts: &[PathBuf], fingerprint: InputDigest) -> bool {
4794    artifacts.iter().all(|path| {
4795        fs::metadata(path).is_ok_and(|metadata| metadata.is_file() && metadata.len() > 0)
4796            && cache_stamp_matches(path, fingerprint)
4797    })
4798}
4799
4800fn missing_artifacts(artifacts: &[PathBuf]) -> Vec<PathBuf> {
4801    artifacts
4802        .iter()
4803        .filter(|path| {
4804            fs::metadata(path).map_or(true, |metadata| !metadata.is_file() || metadata.len() == 0)
4805        })
4806        .cloned()
4807        .collect()
4808}
4809
4810fn cache_stamp_matches(artifact: &Path, fingerprint: InputDigest) -> bool {
4811    let stamp_path = artifact_stamp_path(artifact);
4812    let Ok(expected) = artifact_stamp_contents(artifact, fingerprint) else {
4813        return false;
4814    };
4815    fs::read_to_string(stamp_path).is_ok_and(|stamp| stamp == expected)
4816}
4817
4818fn artifact_stamp_path(artifact: &Path) -> PathBuf {
4819    let mut name = artifact
4820        .file_name()
4821        .map_or_else(|| OsString::from("artifact"), OsString::from);
4822    name.push(".ic-testkit-build");
4823    artifact.with_file_name(name)
4824}
4825
4826fn artifact_stamp_contents(artifact: &Path, fingerprint: InputDigest) -> io::Result<String> {
4827    let (_, artifact_digest) = digest_file("wasm-artifact-v1", artifact)?;
4828    Ok(format!(
4829        "{CACHE_FORMAT_VERSION}\nbuild-sha256:{fingerprint}\nartifact-sha256:{artifact_digest}\n"
4830    ))
4831}
4832
4833fn publish_artifact_stamps(
4834    artifacts: &[PathBuf],
4835    fingerprint: InputDigest,
4836) -> Result<(), WasmBuildError> {
4837    for artifact in artifacts {
4838        let stamp_path = artifact_stamp_path(artifact);
4839        let stamp = artifact_stamp_contents(artifact, fingerprint).map_err(|source| {
4840            WasmBuildError::Io {
4841                operation: "hash built Wasm artifact",
4842                path: artifact.clone(),
4843                source,
4844            }
4845        })?;
4846        write_atomic(&stamp_path, stamp.as_bytes()).map_err(|source| WasmBuildError::Io {
4847            operation: "publish Wasm build stamp",
4848            path: stamp_path,
4849            source,
4850        })?;
4851    }
4852    Ok(())
4853}
4854
4855fn materialize_artifacts(
4856    cached_artifacts: &[PathBuf],
4857    artifacts: &[PathBuf],
4858    fingerprint: InputDigest,
4859) -> Result<(), WasmBuildError> {
4860    for (cached, artifact) in cached_artifacts.iter().zip(artifacts) {
4861        copy_file_atomic(cached, artifact).map_err(|source| WasmBuildError::Io {
4862            operation: "publish Wasm artifact",
4863            path: artifact.clone(),
4864            source,
4865        })?;
4866    }
4867    publish_artifact_stamps(artifacts, fingerprint)
4868}
4869
4870fn copy_wasm_artifacts(
4871    source_artifacts: &[PathBuf],
4872    cached_artifacts: &[PathBuf],
4873) -> Result<(), WasmBuildError> {
4874    for (source, cached) in source_artifacts.iter().zip(cached_artifacts) {
4875        copy_file_atomic(source, cached).map_err(|source_error| WasmBuildError::Io {
4876            operation: "cache shared-incremental Wasm artifact",
4877            path: cached.clone(),
4878            source: source_error,
4879        })?;
4880    }
4881    Ok(())
4882}
4883
4884fn create_dir_all(path: &Path, operation: &'static str) -> Result<(), WasmBuildError> {
4885    fs::create_dir_all(path).map_err(|source| WasmBuildError::Io {
4886        operation,
4887        path: path.to_owned(),
4888        source,
4889    })
4890}
4891
4892fn add_if_present(inputs: &mut Vec<(PathBuf, PathBuf)>, label: &str, path: PathBuf) {
4893    if path.exists() {
4894        inputs.push((PathBuf::from(label), path));
4895    }
4896}
4897
4898fn required_string(value: &Value, field: &str) -> Result<String, WasmBuildError> {
4899    value
4900        .get(field)
4901        .and_then(Value::as_str)
4902        .map(str::to_owned)
4903        .ok_or_else(|| invalid_metadata(&format!("Cargo metadata field `{field}` is missing")))
4904}
4905
4906fn optional_string(value: &Value, field: &str) -> Result<Option<String>, WasmBuildError> {
4907    match value.get(field) {
4908        None | Some(Value::Null) => Ok(None),
4909        Some(Value::String(value)) => Ok(Some(value.clone())),
4910        Some(_) => Err(invalid_metadata(&format!(
4911            "Cargo metadata field `{field}` is not a string or null"
4912        ))),
4913    }
4914}
4915
4916fn invalid_metadata(message: &str) -> WasmBuildError {
4917    WasmBuildError::InvalidMetadata {
4918        message: message.to_owned(),
4919    }
4920}
4921
4922impl WasmBuildError {
4923    fn indicates_input_change(&self) -> bool {
4924        match self {
4925            Self::InputsChangedDuringAcquisition { .. } => true,
4926            Self::FailedBuildCleanup { build_error, .. } => build_error.indicates_input_change(),
4927            _ => false,
4928        }
4929    }
4930}
4931
4932impl std::fmt::Display for WasmBuildPhase {
4933    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4934        formatter.write_str(match self {
4935            Self::CargoMetadata => "cargo metadata",
4936            Self::CargoIdentity => "Cargo identity",
4937            Self::RustcIdentity => "Rust compiler identity",
4938            Self::CargoBuild => "cargo build",
4939        })
4940    }
4941}
4942
4943impl std::fmt::Display for WasmBuildProgressPhase {
4944    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4945        formatter.write_str(match self {
4946            Self::ExactCacheLock => "exact cache lock",
4947            Self::CargoIdentity => "Cargo identity",
4948            Self::RustcIdentity => "Rust compiler identity",
4949            Self::CargoMetadata => "Cargo metadata",
4950            Self::InputDiscovery => "input discovery",
4951            Self::ContentHashing => "content hashing",
4952            Self::SharedTargetLock => "shared target lock",
4953            Self::SharedTargetMaintenance => "shared target maintenance",
4954            Self::CargoBuild => "Cargo build",
4955            Self::ArtifactPublication => "artifact publication",
4956            Self::ExactCacheMaintenance => "exact cache maintenance",
4957        })
4958    }
4959}
4960
4961impl std::fmt::Display for WasmBuildError {
4962    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4963        match self {
4964            Self::InvalidSpec { message } => {
4965                write!(formatter, "invalid Wasm build spec: {message}")
4966            }
4967            Self::Io {
4968                operation,
4969                path,
4970                source,
4971            } => write!(
4972                formatter,
4973                "failed to {operation} at {}: {source}",
4974                path.display()
4975            ),
4976            Self::CommandSpawn {
4977                phase,
4978                program,
4979                source,
4980            } => write!(
4981                formatter,
4982                "failed to launch {phase} using `{}`: {source}",
4983                program.to_string_lossy(),
4984            ),
4985            Self::CommandFailed {
4986                phase,
4987                status,
4988                stdout,
4989                stderr,
4990            } => write!(
4991                formatter,
4992                "{phase} failed with {status}\nstdout:\n{stdout}\nstderr:\n{stderr}",
4993            ),
4994            Self::InvalidMetadata { message } => {
4995                write!(formatter, "invalid Cargo metadata: {message}")
4996            }
4997            Self::InvalidCargoConfiguration { path, message } => write!(
4998                formatter,
4999                "invalid Cargo configuration at {}: {message}",
5000                path.display(),
5001            ),
5002            Self::MissingArtifacts { paths } => write!(
5003                formatter,
5004                "cargo build succeeded without producing: {}",
5005                paths
5006                    .iter()
5007                    .map(|path| path.display().to_string())
5008                    .collect::<Vec<_>>()
5009                    .join(", "),
5010            ),
5011            Self::InputsChangedDuringAcquisition { before, after } => write!(
5012                formatter,
5013                "Wasm inputs changed during artifact acquisition: {before} -> {after}",
5014            ),
5015            Self::PreparedInputSnapshotInvalidated => formatter.write_str(
5016                "the prepared Wasm input snapshot was invalidated before artifact publication",
5017            ),
5018            Self::FailedBuildCleanup {
5019                build_error,
5020                path,
5021                source,
5022            } => write!(
5023                formatter,
5024                "Wasm build failed ({build_error}) and its incomplete target directory at {} could not be removed: {source}",
5025                path.display(),
5026            ),
5027        }
5028    }
5029}
5030
5031impl std::error::Error for WasmBuildError {
5032    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
5033        match self {
5034            Self::Io { source, .. }
5035            | Self::CommandSpawn { source, .. }
5036            | Self::FailedBuildCleanup { source, .. } => Some(source),
5037            _ => None,
5038        }
5039    }
5040}
5041
5042#[cfg(test)]
5043mod tests;