ic-testkit 0.8.9

PocketIC-oriented test utilities for IC canister tests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
use std::{
    collections::{HashMap, HashSet},
    marker::PhantomData,
    path::PathBuf,
    time::{Duration, Instant},
};

use super::wasm_cache::{
    SharedIncrementalTargetMaintenanceConfig, SharedIncrementalTargetMaintenanceOutcome,
    SharedIncrementalTargetPrunePolicy, WasmBuildBatchAttempt, WasmBuildBatchInputMetrics,
    WasmBuildBatchInputResolver, WasmBuildCacheMode, WasmBuildError, WasmBuildFailurePhase,
    WasmBuildFailureTimings, WasmBuildInputSnapshotState, WasmBuildOutcome,
    WasmBuildProgressConfig, WasmBuildProgressEvent, WasmBuildSessionState, WasmBuildSpec,
    WasmBuildTimings, WasmInputResolutionTimings, build_wasm_canisters_cached_in_batch,
    build_wasm_canisters_cached_in_batch_with_progress,
};

/// Orchestration shared by every entry in one independent Wasm build batch.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct WasmBuildBatchConfig {
    shared_incremental_maintenance: Option<SharedIncrementalTargetMaintenanceConfig>,
}

/// Caller-labeled specification for one exact Wasm batch entry.
///
/// The label is report and progress identity only; it does not alter the
/// underlying exact Wasm fingerprint or cache key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LabeledWasmBuildSpec {
    label: String,
    spec: WasmBuildSpec,
}

/// Ordered outcomes and failures from a collect-all Wasm build batch.
#[derive(Debug)]
pub struct WasmBuildBatchReport {
    entries: Vec<WasmBuildBatchEntry>,
    input_resolution: WasmBuildBatchInputMetrics,
    total: Duration,
}

/// Explicit cross-call input snapshot scoped to a caller-held source lease.
///
/// The session contains no global state. It may reuse successful Cargo/rustc
/// identity, metadata, input-discovery, and content-digest work while the
/// caller keeps the supplied write-exclusion guard alive and unchanged.
pub struct WasmBuildSession<'guard> {
    state: WasmBuildSessionState,
    _source_guard: PhantomData<&'guard ()>,
}

/// Immutable prepared Cargo input resolution shared by concurrent readers.
///
/// Preparation resolves the complete declared specification set while the
/// caller holds a genuine source write-exclusion guard. Reader batches may run
/// concurrently through `&self`, but cannot introduce specifications that
/// were not declared during preparation.
pub struct WasmBuildInputSnapshot<'guard> {
    state: WasmBuildInputSnapshotState,
    _source_guard: PhantomData<&'guard ()>,
}

/// Aggregate state retained by one explicit Wasm build session.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct WasmBuildSessionMetrics {
    snapshots: usize,
    snapshot_reuses: usize,
    invalidated: bool,
}

/// Preparation and reader-reuse counters for one immutable input snapshot.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct WasmBuildInputSnapshotMetrics {
    specifications: usize,
    input_resolution_runs: usize,
    input_resolution_reuses: usize,
    input_resolution_timings: WasmInputResolutionTimings,
    reader_reuses: usize,
    invalidated: bool,
}

/// One ordered caller-labeled result from a Wasm build batch.
#[derive(Debug)]
pub struct WasmBuildBatchEntry {
    index: usize,
    label: String,
    result: Result<WasmBuildOutcome, WasmBuildError>,
    failure: Option<WasmBuildFailureDetails>,
    entry_elapsed: Duration,
}

/// Structured phase and partial timings for one failed Wasm entry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WasmBuildFailureDetails {
    phase: WasmBuildFailurePhase,
    timings: WasmBuildFailureTimings,
}

/// One successful Wasm batch entry.
#[derive(Clone, Copy, Debug)]
pub struct WasmBuildBatchOutcomeEntry<'a> {
    index: usize,
    label: &'a str,
    outcome: &'a WasmBuildOutcome,
    entry_elapsed: Duration,
}

/// One failed Wasm batch entry with its retained wall-clock time.
#[derive(Clone, Copy, Debug)]
pub struct WasmBuildBatchFailure<'a> {
    index: usize,
    label: &'a str,
    error: &'a WasmBuildError,
    details: WasmBuildFailureDetails,
    entry_elapsed: Duration,
}

/// One integrated shared-target maintenance outcome from a Wasm batch.
#[derive(Clone, Copy, Debug)]
pub struct WasmBuildBatchMaintenanceEntry<'a> {
    index: usize,
    label: &'a str,
    outcome: &'a SharedIncrementalTargetMaintenanceOutcome,
}

/// Structural error that prevents a labeled Wasm batch from starting.
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum WasmBuildBatchContractError {
    /// An entry label was empty.
    EmptyLabel {
        /// Zero-based position of the invalid entry.
        index: usize,
    },
    /// Two entries used the same label.
    DuplicateLabel {
        /// Duplicated caller label.
        label: String,
        /// Position where the label first appeared.
        first_index: usize,
        /// Position where the label was repeated.
        duplicate_index: usize,
    },
    /// A source mutation invalidated the caller's immutable-source lease.
    SourceLeaseInvalidated,
    /// A prepared snapshot reader requested a specification absent at preparation.
    SpecificationNotPrepared {
        /// Zero-based position of the undeclared entry.
        index: usize,
        /// Caller-owned label of the undeclared entry.
        label: String,
    },
}

impl LabeledWasmBuildSpec {
    /// Attach a caller-owned stable label to one Wasm build specification.
    #[must_use]
    pub fn new(label: impl Into<String>, spec: WasmBuildSpec) -> Self {
        Self {
            label: label.into(),
            spec,
        }
    }

    /// Caller-owned report and progress label.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Underlying exact Wasm build specification.
    #[must_use]
    pub const fn spec(&self) -> &WasmBuildSpec {
        &self.spec
    }

    /// Consume the entry into its label and Wasm build specification.
    #[must_use]
    pub fn into_parts(self) -> (String, WasmBuildSpec) {
        (self.label, self.spec)
    }
}

impl<'guard> WasmBuildSession<'guard> {
    /// Assert source immutability and bind reuse to the supplied guard's lifetime.
    ///
    /// The guard must prevent mutation of every Cargo/rustc executable,
    /// manifest, configuration file, discovered source, declared additional
    /// input, and relevant environment value used by every specification sent
    /// through this session. The guard must remain held until the session is
    /// dropped. This method cannot verify the guard's provenance; supplying an
    /// unrelated value can permit stale cache reuse.
    #[must_use]
    pub fn assume_sources_immutable<Guard: ?Sized>(_source_write_guard: &'guard Guard) -> Self {
        Self {
            state: WasmBuildSessionState::new(),
            _source_guard: PhantomData,
        }
    }

    /// Build one sequential collect-all batch using retained immutable inputs.
    pub fn build_batch(
        &mut self,
        specs: &[LabeledWasmBuildSpec],
        config: WasmBuildBatchConfig,
    ) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
        build_wasm_canisters_cached_batch_with_session(specs, config, &mut self.state)
    }

    /// Build one observed sequential batch using retained immutable inputs.
    pub fn build_batch_with_progress<F>(
        &mut self,
        specs: &[LabeledWasmBuildSpec],
        batch_config: WasmBuildBatchConfig,
        progress_config: WasmBuildProgressConfig,
        observer: F,
    ) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
    where
        F: FnMut(WasmBuildBatchProgressEvent),
    {
        build_wasm_canisters_cached_batch_with_session_and_progress(
            specs,
            batch_config,
            progress_config,
            &mut self.state,
            observer,
        )
    }

    /// Current retained snapshot, reuse, and invalidation counters.
    #[must_use]
    pub const fn metrics(&self) -> WasmBuildSessionMetrics {
        WasmBuildSessionMetrics {
            snapshots: self.state.snapshot_count(),
            snapshot_reuses: self.state.snapshot_reuses(),
            invalidated: self.state.is_invalidated(),
        }
    }
}

impl WasmBuildSessionMetrics {
    /// Number of successful exact specification snapshots currently retained.
    #[must_use]
    pub const fn snapshots(self) -> usize {
        self.snapshots
    }

    /// Number of later entries resolved from a retained snapshot.
    #[must_use]
    pub const fn snapshot_reuses(self) -> usize {
        self.snapshot_reuses
    }

    /// Whether a detected source race permanently invalidated this session.
    #[must_use]
    pub const fn is_invalidated(self) -> bool {
        self.invalidated
    }
}

impl<'guard> WasmBuildInputSnapshot<'guard> {
    /// Resolve and freeze the complete specification set under a source lease.
    ///
    /// The guard must prevent mutation of every Cargo/rustc executable,
    /// manifest, configuration file, discovered source, declared additional
    /// input, and relevant environment value used by the supplied
    /// specifications. The type system cannot verify guard provenance.
    pub fn prepare_assuming_sources_immutable<Guard: ?Sized>(
        _source_write_guard: &'guard Guard,
        specs: &[WasmBuildSpec],
    ) -> Result<Self, WasmBuildError> {
        Ok(Self {
            state: WasmBuildInputSnapshotState::prepare(specs)?,
            _source_guard: PhantomData,
        })
    }

    /// Build one sequential collect-all batch from prepared inputs.
    ///
    /// Separate calls may run concurrently. Every exact specification must
    /// have been supplied to [`Self::prepare_assuming_sources_immutable`].
    pub fn build_batch(
        &self,
        specs: &[LabeledWasmBuildSpec],
        config: WasmBuildBatchConfig,
    ) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
        build_wasm_canisters_cached_batch_with_snapshot(specs, config, &self.state)
    }

    /// Build one observed sequential batch from prepared inputs.
    ///
    /// Separate calls may run concurrently and use independent observers.
    pub fn build_batch_with_progress<F>(
        &self,
        specs: &[LabeledWasmBuildSpec],
        batch_config: WasmBuildBatchConfig,
        progress_config: WasmBuildProgressConfig,
        observer: F,
    ) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
    where
        F: FnMut(WasmBuildBatchProgressEvent),
    {
        build_wasm_canisters_cached_batch_with_snapshot_and_progress(
            specs,
            batch_config,
            progress_config,
            &self.state,
            observer,
        )
    }

    /// Current preparation, reader-reuse, and invalidation metrics.
    #[must_use]
    pub fn metrics(&self) -> WasmBuildInputSnapshotMetrics {
        let preparation = self.state.preparation_metrics();
        WasmBuildInputSnapshotMetrics {
            specifications: self.state.specification_count(),
            input_resolution_runs: preparation.runs,
            input_resolution_reuses: preparation.reuses,
            input_resolution_timings: self.state.preparation_timings(),
            reader_reuses: self.state.reader_reuses(),
            invalidated: self.state.is_invalidated(),
        }
    }
}

impl WasmBuildInputSnapshotMetrics {
    /// Number of exact specifications captured during preparation.
    #[must_use]
    pub const fn specifications(self) -> usize {
        self.specifications
    }

    /// Number of workspace/toolchain resolution snapshots prepared.
    #[must_use]
    pub const fn input_resolution_runs(self) -> usize {
        self.input_resolution_runs
    }

    /// Number of prepared specifications sharing another resolution run.
    #[must_use]
    pub const fn input_resolution_reuses(self) -> usize {
        self.input_resolution_reuses
    }

    /// Complete tool, metadata, discovery, and hashing preparation timings.
    #[must_use]
    pub const fn input_resolution_timings(self) -> WasmInputResolutionTimings {
        self.input_resolution_timings
    }

    /// Cumulative exact specification resolutions served to readers.
    #[must_use]
    pub const fn reader_reuses(self) -> usize {
        self.reader_reuses
    }

    /// Whether any reader detected a violation of the source lease.
    #[must_use]
    pub const fn is_invalidated(self) -> bool {
        self.invalidated
    }
}

impl WasmBuildBatchEntry {
    /// Zero-based position in the supplied labeled specification slice.
    #[must_use]
    pub const fn index(&self) -> usize {
        self.index
    }

    /// Caller-owned stable label.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Structured success or failure for this entry.
    pub const fn result(&self) -> Result<&WasmBuildOutcome, &WasmBuildError> {
        self.result.as_ref()
    }

    /// Successful Wasm outcome, when this entry succeeded.
    #[must_use]
    pub fn outcome(&self) -> Option<&WasmBuildOutcome> {
        self.result.as_ref().ok()
    }

    /// Structured build failure, when this entry failed.
    #[must_use]
    pub fn error(&self) -> Option<&WasmBuildError> {
        self.result.as_ref().err()
    }

    /// Structured phase and partial timings when this entry failed.
    #[must_use]
    pub const fn failure_details(&self) -> Option<WasmBuildFailureDetails> {
        self.failure
    }

    /// Complete wall-clock time retained for this entry.
    #[must_use]
    pub const fn entry_elapsed(&self) -> Duration {
        self.entry_elapsed
    }

    /// Whether this entry completed successfully.
    #[must_use]
    pub const fn is_success(&self) -> bool {
        self.result.is_ok()
    }

    /// Consume the entry into its identity, result, optional failure details, and wall time.
    pub fn into_parts(
        self,
    ) -> (
        usize,
        String,
        Result<WasmBuildOutcome, WasmBuildError>,
        Option<WasmBuildFailureDetails>,
        Duration,
    ) {
        (
            self.index,
            self.label,
            self.result,
            self.failure,
            self.entry_elapsed,
        )
    }
}

impl WasmBuildFailureDetails {
    /// Primary acquisition phase that returned the failure.
    #[must_use]
    pub const fn phase(self) -> WasmBuildFailurePhase {
        self.phase
    }

    /// Partial phase timings retained before the failure returned.
    #[must_use]
    pub const fn timings(self) -> WasmBuildFailureTimings {
        self.timings
    }
}

impl<'a> WasmBuildBatchOutcomeEntry<'a> {
    /// Zero-based position in the supplied labeled specification slice.
    #[must_use]
    pub const fn index(self) -> usize {
        self.index
    }

    /// Caller-owned stable label.
    #[must_use]
    pub const fn label(self) -> &'a str {
        self.label
    }

    /// Successful Wasm build outcome.
    #[must_use]
    pub const fn outcome(self) -> &'a WasmBuildOutcome {
        self.outcome
    }

    /// Complete wall-clock time retained for this successful entry.
    #[must_use]
    pub const fn entry_elapsed(self) -> Duration {
        self.entry_elapsed
    }
}

impl<'a> WasmBuildBatchFailure<'a> {
    /// Zero-based position in the supplied specification slice.
    #[must_use]
    pub const fn index(self) -> usize {
        self.index
    }

    /// Caller-owned stable label.
    #[must_use]
    pub const fn label(self) -> &'a str {
        self.label
    }

    /// Structured acquisition failure.
    #[must_use]
    pub const fn error(self) -> &'a WasmBuildError {
        self.error
    }

    /// Primary acquisition phase that returned the failure.
    #[must_use]
    pub const fn phase(self) -> WasmBuildFailurePhase {
        self.details.phase
    }

    /// Partial phase timings retained before the failure returned.
    #[must_use]
    pub const fn timings(self) -> WasmBuildFailureTimings {
        self.details.timings
    }

    /// Complete wall-clock time retained for this failed entry.
    #[must_use]
    pub const fn entry_elapsed(self) -> Duration {
        self.entry_elapsed
    }
}

impl<'a> WasmBuildBatchMaintenanceEntry<'a> {
    /// Zero-based position in the supplied labeled specification slice.
    #[must_use]
    pub const fn index(self) -> usize {
        self.index
    }

    /// Caller-owned stable label.
    #[must_use]
    pub const fn label(self) -> &'a str {
        self.label
    }

    /// Structured shared-target maintenance outcome.
    #[must_use]
    pub const fn outcome(self) -> &'a SharedIncrementalTargetMaintenanceOutcome {
        self.outcome
    }
}

/// Aggregate counters and successful-acquisition timings for a Wasm build batch.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct WasmBuildBatchMetrics {
    specifications: usize,
    succeeded: usize,
    failed: usize,
    built: usize,
    reused: usize,
    input_resolution_runs: usize,
    input_resolution_reuses: usize,
    input_resolution_session_reuses: usize,
    input_resolution_prepared_reuses: usize,
    successful_timings: WasmBuildTimings,
    total: Duration,
}

/// Structured progress for an independent sequence of exact Wasm builds.
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum WasmBuildBatchProgressEvent {
    /// One independently resolved build specification is about to start.
    BuildStarted {
        /// Zero-based position in the supplied specification slice.
        index: usize,
        /// Caller-owned stable label.
        label: String,
        /// Total number of supplied specifications.
        total: usize,
    },
    /// Progress forwarded from one independent build.
    BuildProgress {
        /// Zero-based position in the supplied specification slice.
        index: usize,
        /// Caller-owned stable label.
        label: String,
        /// Event emitted by that build.
        event: WasmBuildProgressEvent,
    },
    /// One independent build completed successfully.
    BuildFinished {
        /// Zero-based position in the supplied specification slice.
        index: usize,
        /// Caller-owned stable label.
        label: String,
    },
    /// One independent build failed.
    BuildFailed {
        /// Zero-based position in the supplied specification slice.
        index: usize,
        /// Caller-owned stable label.
        label: String,
    },
}

impl WasmBuildBatchReport {
    /// Ordered labeled entries.
    #[must_use]
    pub fn entries(&self) -> &[WasmBuildBatchEntry] {
        &self.entries
    }

    /// Consume the report into its ordered labeled entries.
    #[must_use]
    pub fn into_entries(self) -> Vec<WasmBuildBatchEntry> {
        self.entries
    }

    /// Structured successful entries with labels and wall-clock times.
    pub fn outcomes(&self) -> impl Iterator<Item = WasmBuildBatchOutcomeEntry<'_>> {
        self.entries.iter().filter_map(|entry| {
            entry.outcome().map(|outcome| WasmBuildBatchOutcomeEntry {
                index: entry.index,
                label: &entry.label,
                outcome,
                entry_elapsed: entry.entry_elapsed,
            })
        })
    }

    /// Structured failed entries with labels and wall-clock times.
    pub fn failures(&self) -> impl Iterator<Item = WasmBuildBatchFailure<'_>> {
        self.entries.iter().filter_map(|entry| {
            entry.error().map(|error| WasmBuildBatchFailure {
                index: entry.index,
                label: &entry.label,
                error,
                details: entry
                    .failure
                    .expect("failed Wasm batch entry must retain failure details"),
                entry_elapsed: entry.entry_elapsed,
            })
        })
    }

    /// Labeled integrated shared-target maintenance outcomes.
    ///
    /// Batch-owned maintenance contributes at most one outcome for each
    /// distinct configured shared-target path.
    pub fn shared_incremental_maintenance_outcomes(
        &self,
    ) -> impl Iterator<Item = WasmBuildBatchMaintenanceEntry<'_>> {
        self.outcomes().filter_map(|entry| {
            entry
                .outcome
                .record()
                .shared_incremental_maintenance()
                .map(|outcome| WasmBuildBatchMaintenanceEntry {
                    index: entry.index,
                    label: entry.label,
                    outcome,
                })
        })
    }

    /// Complete wall-clock time for the sequential collect-all batch.
    #[must_use]
    pub const fn total(&self) -> Duration {
        self.total
    }

    /// Whether every specification completed successfully.
    #[must_use]
    pub fn is_success(&self) -> bool {
        self.entries.iter().all(WasmBuildBatchEntry::is_success)
    }

    /// Aggregate outcome, input-resolution reuse, and timing counters.
    #[must_use]
    pub fn metrics(&self) -> WasmBuildBatchMetrics {
        let mut metrics = WasmBuildBatchMetrics {
            specifications: self.entries.len(),
            input_resolution_runs: self.input_resolution.runs,
            input_resolution_reuses: self.input_resolution.reuses,
            input_resolution_session_reuses: self.input_resolution.session_reuses,
            input_resolution_prepared_reuses: self.input_resolution.prepared_reuses,
            total: self.total,
            ..WasmBuildBatchMetrics::default()
        };
        for entry in &self.entries {
            match &entry.result {
                Ok(outcome) => {
                    metrics.succeeded += 1;
                    if outcome.is_reused() {
                        metrics.reused += 1;
                    } else {
                        metrics.built += 1;
                    }
                    metrics.successful_timings = metrics
                        .successful_timings
                        .saturating_add(outcome.record().timings());
                }
                Err(_) => metrics.failed += 1,
            }
        }
        metrics
    }
}

impl WasmBuildBatchMetrics {
    /// Number of supplied specifications.
    #[must_use]
    pub const fn specifications(self) -> usize {
        self.specifications
    }

    /// Number of successful specifications.
    #[must_use]
    pub const fn succeeded(self) -> usize {
        self.succeeded
    }

    /// Number of failed specifications.
    #[must_use]
    pub const fn failed(self) -> usize {
        self.failed
    }

    /// Number of newly built Wasm artifact sets.
    #[must_use]
    pub const fn built(self) -> usize {
        self.built
    }

    /// Number of Wasm artifact sets reused from the exact cache.
    #[must_use]
    pub const fn reused(self) -> usize {
        self.reused
    }

    /// Number of workspace/toolchain input-resolution snapshots performed.
    #[must_use]
    pub const fn input_resolution_runs(self) -> usize {
        self.input_resolution_runs
    }

    /// Number of specifications resolved by reusing another batch snapshot.
    #[must_use]
    pub const fn input_resolution_reuses(self) -> usize {
        self.input_resolution_reuses
    }

    /// Number of specifications resolved from an explicit session snapshot.
    #[must_use]
    pub const fn input_resolution_session_reuses(self) -> usize {
        self.input_resolution_session_reuses
    }

    /// Number of specifications resolved from a prepared concurrent snapshot.
    #[must_use]
    pub const fn input_resolution_prepared_reuses(self) -> usize {
        self.input_resolution_prepared_reuses
    }

    /// Sum of timings from successful acquisitions.
    #[must_use]
    pub const fn successful_timings(self) -> WasmBuildTimings {
        self.successful_timings
    }

    /// Complete wall-clock time for the sequential batch.
    #[must_use]
    pub const fn total(self) -> Duration {
        self.total
    }
}

impl WasmBuildBatchConfig {
    /// Create batch orchestration without batch-owned target maintenance.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            shared_incremental_maintenance: None,
        }
    }

    /// Maintain each distinct shared target once through its first batch entry.
    #[must_use]
    pub const fn with_shared_incremental_target_maintenance(
        mut self,
        config: SharedIncrementalTargetMaintenanceConfig,
    ) -> Self {
        self.shared_incremental_maintenance = Some(config);
        self
    }

    /// Strictly maintain each distinct shared target at most once per interval.
    #[must_use]
    pub const fn with_shared_incremental_target_maintenance_at_most_every(
        self,
        policy: SharedIncrementalTargetPrunePolicy,
        minimum_interval: Duration,
    ) -> Self {
        self.with_shared_incremental_target_maintenance(
            SharedIncrementalTargetMaintenanceConfig::new(policy, minimum_interval),
        )
    }

    /// Batch-owned shared-target maintenance, when configured.
    #[must_use]
    pub const fn shared_incremental_target_maintenance(
        self,
    ) -> Option<SharedIncrementalTargetMaintenanceConfig> {
        self.shared_incremental_maintenance
    }
}

impl std::fmt::Display for WasmBuildBatchReport {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let metrics = self.metrics();
        write!(
            formatter,
            "builds={} succeeded={} failed={} built={} reused={} input_resolution_runs={} input_resolution_reuses={} input_resolution_session_reuses={} input_resolution_prepared_reuses={} successful_timings=({}) total={:?}",
            metrics.specifications(),
            metrics.succeeded(),
            metrics.failed(),
            metrics.built(),
            metrics.reused(),
            metrics.input_resolution_runs(),
            metrics.input_resolution_reuses(),
            metrics.input_resolution_session_reuses(),
            metrics.input_resolution_prepared_reuses(),
            metrics.successful_timings(),
            metrics.total(),
        )
    }
}

/// Build every Wasm specification as an independent Cargo invocation.
///
/// Specifications run sequentially and every result is retained. Each entry
/// keeps its own package set, profile arguments, feature resolution,
/// fingerprint, locks, and cache policy. Packages are never combined into one
/// Cargo command because doing so can unify shared dependency features.
pub fn build_wasm_canisters_cached_batch(
    specs: &[LabeledWasmBuildSpec],
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
    build_wasm_canisters_cached_batch_with_config(specs, WasmBuildBatchConfig::new())
}

/// Build an independent Wasm batch with shared batch orchestration.
///
/// Batch-owned maintenance is attached only to the first specification for
/// each distinct configured shared-target path. Isolated specifications are
/// unaffected. An entry mixing batch-owned and per-spec integrated maintenance
/// reports an indexed error without preventing later entries from running.
pub fn build_wasm_canisters_cached_batch_with_config(
    specs: &[LabeledWasmBuildSpec],
    config: WasmBuildBatchConfig,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
    build_wasm_canisters_cached_batch_internal(specs, config, None)
}

enum WasmBuildInputReuse<'reuse> {
    Session(&'reuse mut WasmBuildSessionState),
    Snapshot(&'reuse WasmBuildInputSnapshotState),
}

fn build_wasm_canisters_cached_batch_with_session(
    specs: &[LabeledWasmBuildSpec],
    config: WasmBuildBatchConfig,
    session: &mut WasmBuildSessionState,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
    build_wasm_canisters_cached_batch_internal(
        specs,
        config,
        Some(WasmBuildInputReuse::Session(session)),
    )
}

fn build_wasm_canisters_cached_batch_with_snapshot(
    specs: &[LabeledWasmBuildSpec],
    config: WasmBuildBatchConfig,
    snapshot: &WasmBuildInputSnapshotState,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
    build_wasm_canisters_cached_batch_internal(
        specs,
        config,
        Some(WasmBuildInputReuse::Snapshot(snapshot)),
    )
}

fn build_wasm_canisters_cached_batch_internal(
    specs: &[LabeledWasmBuildSpec],
    config: WasmBuildBatchConfig,
    reuse: Option<WasmBuildInputReuse<'_>>,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
    validate_batch_labels(specs)?;
    validate_input_reuse(specs, reuse.as_ref())?;
    let build_specs = specs
        .iter()
        .map(|labeled| labeled.spec.clone())
        .collect::<Vec<_>>();
    let mut resolver = match reuse {
        None => WasmBuildBatchInputResolver::new(&build_specs),
        Some(WasmBuildInputReuse::Session(session)) => {
            WasmBuildBatchInputResolver::with_session(&build_specs, session)
        }
        Some(WasmBuildInputReuse::Snapshot(snapshot)) => {
            WasmBuildBatchInputResolver::with_snapshot(&build_specs, snapshot)
        }
    };
    let mut report = build_wasm_batch(specs, config, |spec, index| {
        build_wasm_canisters_cached_in_batch(spec, index, &mut resolver)
    });
    report.input_resolution = resolver.metrics();
    Ok(report)
}

/// Build an independent Wasm batch while forwarding structured progress.
///
/// The same observation configuration is applied to every entry. Batch events
/// identify the originating specification without altering the standalone
/// build semantics.
pub fn build_wasm_canisters_cached_batch_with_progress<F>(
    specs: &[LabeledWasmBuildSpec],
    config: WasmBuildProgressConfig,
    observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
    F: FnMut(WasmBuildBatchProgressEvent),
{
    build_wasm_canisters_cached_batch_with_config_and_progress(
        specs,
        WasmBuildBatchConfig::new(),
        config,
        observer,
    )
}

/// Build a configured independent Wasm batch while forwarding structured progress.
pub fn build_wasm_canisters_cached_batch_with_config_and_progress<F>(
    specs: &[LabeledWasmBuildSpec],
    batch_config: WasmBuildBatchConfig,
    progress_config: WasmBuildProgressConfig,
    observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
    F: FnMut(WasmBuildBatchProgressEvent),
{
    build_wasm_canisters_cached_batch_with_progress_internal(
        specs,
        batch_config,
        progress_config,
        None,
        observer,
    )
}

fn build_wasm_canisters_cached_batch_with_session_and_progress<F>(
    specs: &[LabeledWasmBuildSpec],
    batch_config: WasmBuildBatchConfig,
    progress_config: WasmBuildProgressConfig,
    session: &mut WasmBuildSessionState,
    observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
    F: FnMut(WasmBuildBatchProgressEvent),
{
    build_wasm_canisters_cached_batch_with_progress_internal(
        specs,
        batch_config,
        progress_config,
        Some(WasmBuildInputReuse::Session(session)),
        observer,
    )
}

fn build_wasm_canisters_cached_batch_with_snapshot_and_progress<F>(
    specs: &[LabeledWasmBuildSpec],
    batch_config: WasmBuildBatchConfig,
    progress_config: WasmBuildProgressConfig,
    snapshot: &WasmBuildInputSnapshotState,
    observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
    F: FnMut(WasmBuildBatchProgressEvent),
{
    build_wasm_canisters_cached_batch_with_progress_internal(
        specs,
        batch_config,
        progress_config,
        Some(WasmBuildInputReuse::Snapshot(snapshot)),
        observer,
    )
}

fn build_wasm_canisters_cached_batch_with_progress_internal<F>(
    specs: &[LabeledWasmBuildSpec],
    batch_config: WasmBuildBatchConfig,
    progress_config: WasmBuildProgressConfig,
    reuse: Option<WasmBuildInputReuse<'_>>,
    mut observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
    F: FnMut(WasmBuildBatchProgressEvent),
{
    validate_batch_labels(specs)?;
    validate_input_reuse(specs, reuse.as_ref())?;
    let count = specs.len();
    let build_specs = specs
        .iter()
        .map(|labeled| labeled.spec.clone())
        .collect::<Vec<_>>();
    let mut resolver = match reuse {
        None => WasmBuildBatchInputResolver::new(&build_specs),
        Some(WasmBuildInputReuse::Session(session)) => {
            WasmBuildBatchInputResolver::with_session(&build_specs, session)
        }
        Some(WasmBuildInputReuse::Snapshot(snapshot)) => {
            WasmBuildBatchInputResolver::with_snapshot(&build_specs, snapshot)
        }
    };
    let mut report = build_wasm_batch(specs, batch_config, |spec, index| {
        let label = specs[index].label.clone();
        observer(WasmBuildBatchProgressEvent::BuildStarted {
            index,
            label: label.clone(),
            total: count,
        });
        let attempt = build_wasm_canisters_cached_in_batch_with_progress(
            spec,
            index,
            &mut resolver,
            progress_config,
            |event| {
                observer(WasmBuildBatchProgressEvent::BuildProgress {
                    index,
                    label: label.clone(),
                    event,
                });
            },
        );
        observer(match &attempt.result {
            Ok(_) => WasmBuildBatchProgressEvent::BuildFinished { index, label },
            Err(_) => WasmBuildBatchProgressEvent::BuildFailed { index, label },
        });
        attempt
    });
    report.input_resolution = resolver.metrics();
    Ok(report)
}

fn build_wasm_batch<F>(
    specs: &[LabeledWasmBuildSpec],
    config: WasmBuildBatchConfig,
    mut build: F,
) -> WasmBuildBatchReport
where
    F: FnMut(&WasmBuildSpec, usize) -> WasmBuildBatchAttempt,
{
    let started = Instant::now();
    let mut entries = Vec::with_capacity(specs.len());
    let mut maintenance = BatchMaintenanceTracker::new(config.shared_incremental_maintenance);
    for (index, labeled) in specs.iter().enumerate() {
        let entry_started = Instant::now();
        let spec = &labeled.spec;
        if config.shared_incremental_maintenance.is_some()
            && spec.shared_incremental_target_maintenance().is_some()
        {
            let elapsed = entry_started.elapsed();
            let attempt =
                WasmBuildBatchAttempt::invalid_spec(batch_maintenance_ownership_error(), elapsed);
            entries.push(WasmBuildBatchEntry {
                index,
                label: labeled.label.clone(),
                result: attempt.result,
                failure: Some(WasmBuildFailureDetails {
                    phase: attempt
                        .failure_phase
                        .expect("invalid batch entry must retain its failure phase"),
                    timings: attempt
                        .failure_timings
                        .expect("invalid batch entry must retain its failure timings"),
                }),
                entry_elapsed: elapsed,
            });
            continue;
        }
        let configured = maintenance.prepare_spec(spec);
        let attempt = build(configured.as_ref().unwrap_or(spec), index);
        let failure = attempt
            .failure_phase
            .zip(attempt.failure_timings)
            .map(|(phase, timings)| WasmBuildFailureDetails { phase, timings });
        entries.push(WasmBuildBatchEntry {
            index,
            label: labeled.label.clone(),
            result: attempt.result,
            failure,
            entry_elapsed: entry_started.elapsed(),
        });
    }
    WasmBuildBatchReport {
        entries,
        input_resolution: WasmBuildBatchInputMetrics::default(),
        total: started.elapsed(),
    }
}

fn validate_batch_labels(
    specs: &[LabeledWasmBuildSpec],
) -> Result<(), WasmBuildBatchContractError> {
    let mut labels = HashMap::with_capacity(specs.len());
    for (index, labeled) in specs.iter().enumerate() {
        if labeled.label.is_empty() {
            return Err(WasmBuildBatchContractError::EmptyLabel { index });
        }
        if let Some(first_index) = labels.get(labeled.label.as_str()) {
            return Err(WasmBuildBatchContractError::DuplicateLabel {
                label: labeled.label.clone(),
                first_index: *first_index,
                duplicate_index: index,
            });
        }
        labels.insert(labeled.label.as_str(), index);
    }
    Ok(())
}

fn validate_input_reuse(
    specs: &[LabeledWasmBuildSpec],
    reuse: Option<&WasmBuildInputReuse<'_>>,
) -> Result<(), WasmBuildBatchContractError> {
    match reuse {
        Some(WasmBuildInputReuse::Session(session)) if session.is_invalidated() => {
            Err(WasmBuildBatchContractError::SourceLeaseInvalidated)
        }
        Some(WasmBuildInputReuse::Snapshot(snapshot)) if snapshot.is_invalidated() => {
            Err(WasmBuildBatchContractError::SourceLeaseInvalidated)
        }
        Some(WasmBuildInputReuse::Snapshot(snapshot)) => {
            for (index, labeled) in specs.iter().enumerate() {
                if !snapshot.contains(&labeled.spec) {
                    return Err(WasmBuildBatchContractError::SpecificationNotPrepared {
                        index,
                        label: labeled.label.clone(),
                    });
                }
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

struct BatchMaintenanceTracker {
    config: Option<SharedIncrementalTargetMaintenanceConfig>,
    configured_targets: HashSet<PathBuf>,
}

impl BatchMaintenanceTracker {
    fn new(config: Option<SharedIncrementalTargetMaintenanceConfig>) -> Self {
        Self {
            config,
            configured_targets: HashSet::new(),
        }
    }

    fn prepare_spec(&mut self, spec: &WasmBuildSpec) -> Option<WasmBuildSpec> {
        let config = self.config?;
        debug_assert!(spec.shared_incremental_target_maintenance().is_none());
        let WasmBuildCacheMode::SharedIncremental { target_dir } = spec.cache_mode() else {
            return None;
        };
        if !self.configured_targets.insert(target_dir.clone()) {
            return None;
        }
        Some(
            spec.clone()
                .with_shared_incremental_target_maintenance(config),
        )
    }
}

fn batch_maintenance_ownership_error() -> WasmBuildError {
    WasmBuildError::InvalidSpec {
        message:
            "batch-owned shared-target maintenance cannot be combined with per-spec maintenance"
                .to_owned(),
    }
}

impl std::fmt::Display for WasmBuildBatchContractError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EmptyLabel { index } => {
                write!(formatter, "Wasm batch label at index {index} is empty")
            }
            Self::DuplicateLabel {
                label,
                first_index,
                duplicate_index,
            } => write!(
                formatter,
                "Wasm batch label {label:?} at index {duplicate_index} duplicates index {first_index}",
            ),
            Self::SourceLeaseInvalidated => formatter
                .write_str("Wasm build source lease was invalidated by a detected input mutation"),
            Self::SpecificationNotPrepared { index, label } => write!(
                formatter,
                "Wasm batch entry {label:?} at index {index} was not declared when the input snapshot was prepared",
            ),
        }
    }
}

impl std::error::Error for WasmBuildBatchContractError {}

#[cfg(test)]
mod tests;