canic-host 0.109.15

Host-side App build and desired-state Fleet reconciliation library for Canic workspaces
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
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
//! Module: fleet_ensure::generate
//!
//! Responsibility: compile high-level Fleet policy plus explicit live identities into desired state.
//! Does not own: artifact builds, identity invention, paid effects, or convergence.
//! Boundary: release artifacts are local authority; every retained Principal is explicit and live-verified.

#[cfg(test)]
mod tests;

use crate::{
    canister_protocol::query_with_candid,
    component_topology::{
        PlannedFleetSubnetRootTopology, PlannedFleetSubnetRootTopologyInput,
        RootComponentAdmissionInput, plan_initial_fleet_topology,
    },
    durable_io::{RegularFileReadError, read_optional_regular_bytes},
    fleet_ensure::model::{
        DesiredCanister, DesiredCanisterInit, DesiredCanisterKind, DesiredComponentGroupPlacement,
        DesiredFleet, DesiredFleetBootstrap, DesiredFleetBootstrapRoot, DesiredFleetProtocol,
        DesiredPresence, FLEET_ENSURE_SCHEMA_VERSION,
    },
    fleet_ensure::ops::root_owned_lifecycle,
    icp::IcpCli,
    icp_config::resolve_icp_build_network_from_root,
    network::resolve_canonical_network_id_from_root,
    release_build::validate_finalized_release_build_manifest,
    release_set::{
        AppConfigSnapshot, CanicInfrastructureArtifactEntry, CanicInfrastructureRole,
        load_persisted_application_artifact_union,
        load_persisted_canic_infrastructure_artifact_manifest,
        load_persisted_current_release_set_manifest,
    },
    subnet_catalog::load_mainnet_subnet_catalog,
};
use candid::{Nat, Principal};
use canic_core::{
    cdk::types::Cycles,
    control_plane_support::config::ComponentDeploymentConfiguration,
    dto::fleet_subnet_root::FleetSubnetRootAuthority,
    dto::pool::{CanisterPoolResponse, CanisterPoolStatusRequest},
    ids::{
        BuildNetwork, ComponentGroupDeploymentId, ComponentSpecId, CyclesFundingBudget,
        FleetAdmissionPolicyTemplate, FleetBinding, FleetCoordinatorBinding,
        FleetCoordinatorRootFundingPolicy, FleetFundingProfile, FleetKey, FleetRegistryAuthority,
        FleetSubnetCanisterPoolConfig, FleetSubnetRootBinding, FleetSubnetRootFundingAuthority,
        FleetSubnetRootFundingPolicy, FleetSubnetRootLimits, FleetSubnetWasmStoreAuthority,
        ReleaseBuildId, SubnetId,
    },
    protocol,
    shared_support::fleet_admission_policy::compile_fleet_admission_policy_template,
};
use ic_query::subnet_catalog::SubnetSpecialization;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};
use thiserror::Error as ThisError;

const MAX_GENERATOR_INPUT_BYTES: usize = 1024 * 1024;
const MAINNET_CYCLES_LEDGER: &str = "um5iw-rqaaa-aaaaq-qaaba-cai";
const GENERATED_RETAINED_MATERIAL_CYCLE_THRESHOLD: u128 = 1_000_000;
const GENERATED_RETAINED_MAXIMUM_OBSERVATION_BURN_CYCLES: u128 = 10_000_000;
const GENERATED_RETAINED_MAXIMUM_UPDATE_BURN_CYCLES: u128 = 100_000_000_000;

/// Exact local and live inputs for one no-effect desired-state generation.
pub struct FleetGenerateRequest<'a> {
    pub app_config: &'a Path,
    pub environment: &'a str,
    pub fleet: &'a str,
    pub icp_executable: &'a str,
    pub release_build_id: ReleaseBuildId,
    pub root: &'a Path,
    pub seed: &'a Path,
    pub source: &'a Path,
}

/// Generated desired state plus its explicit observation summary.
pub struct GeneratedDesiredFleet {
    pub desired: DesiredFleet,
    pub observed_canisters: usize,
    pub observed_controlled_cycles: u128,
    pub release_build_id: ReleaseBuildId,
}

/// Typed no-effect Fleet generation failure.
#[derive(Debug, ThisError)]
pub enum FleetGenerateError {
    #[error("failed to read Fleet generator input {path}: {source}")]
    Read {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Fleet generator input is not a safe regular file: {path} ({reason})")]
    UnsafeInput { path: PathBuf, reason: &'static str },

    #[error("Fleet generator input is too large: {path} ({actual} bytes; maximum {maximum})")]
    TooLarge {
        actual: usize,
        maximum: usize,
        path: PathBuf,
    },

    #[error("failed to decode Fleet generator input {path}: {source}")]
    Decode {
        path: PathBuf,
        #[source]
        source: toml::de::Error,
    },

    #[error("unsupported Fleet generator {kind} schema {actual}; expected 1")]
    Schema { actual: u32, kind: &'static str },

    #[error("invalid Fleet generator authority: {0}")]
    Authority(String),

    #[error("Fleet identity seed and policy topology differ: {0}")]
    SeedTopology(String),

    #[error("retained canister {canister} is unavailable: {reason}")]
    CanisterUnavailable { canister: String, reason: String },

    #[error(
        "retained canister {canister} controller set differs: actual {actual:?}, expected {expected:?}"
    )]
    ControllerMismatch {
        actual: Vec<String>,
        canister: String,
        expected: Vec<String>,
    },

    #[error("retained canister {canister} is on Subnet {actual}, expected {expected}")]
    SubnetMismatch {
        actual: String,
        canister: String,
        expected: String,
    },

    #[error("release authority is invalid: {0}")]
    Release(String),

    #[error("artifact Candid sidecar is missing or changed: {0}")]
    Candid(String),

    #[error("system clock is before the Unix epoch")]
    Clock,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct FleetSource {
    schema_version: u32,
    funding_profile: FleetFundingProfile,
    operator: String,
    admission: AdmissionSource,
    coordinator: CoordinatorSource,
    fleet_subnet_roots: Vec<RootSource>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct AdmissionSource {
    principals: Vec<String>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CoordinatorSource {
    subnet: ExplicitSubnetSource,
    creation_funding: CyclesCreationSource,
    root_funding: CoordinatorFundingSource,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ExplicitSubnetSource {
    kind: String,
    subnet: String,
    acknowledge_fiduciary_cost: bool,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CyclesCreationSource {
    kind: String,
    #[serde(deserialize_with = "Cycles::from_config")]
    cycles: Cycles,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CoordinatorFundingSource {
    #[serde(deserialize_with = "Cycles::from_config")]
    minimum_reserve_cycles: Cycles,
    window_secs: u64,
    #[serde(deserialize_with = "Cycles::from_config")]
    maximum_cycles: Cycles,
    maximum_automatic_grants: u32,
    #[serde(deserialize_with = "Cycles::from_config")]
    maximum_automatic_cycles: Cycles,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RootSource {
    placement_subnet: String,
    #[serde(default)]
    acknowledge_fiduciary_cost: bool,
    #[serde(default)]
    component_group_placements: BTreeMap<ComponentGroupDeploymentId, Vec<u32>>,
    component_admissions: BTreeMap<ComponentSpecId, u32>,
    canister_pool: PoolSource,
    root_funding: RootFundingSource,
    limits: LimitsSource,
    root_creation_funding: CyclesCreationSource,
    wasm_store_creation_funding: CyclesCreationSource,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct PoolSource {
    minimum_size: u32,
    maximum_size: u32,
    #[serde(deserialize_with = "Cycles::from_config")]
    canister_cycles: Cycles,
    #[serde(default)]
    imports: Vec<String>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RootFundingSource {
    #[serde(deserialize_with = "Cycles::from_config")]
    request_threshold: Cycles,
    #[serde(deserialize_with = "Cycles::from_config")]
    target_balance: Cycles,
    cooldown_secs: u64,
    window_secs: u64,
    #[serde(deserialize_with = "Cycles::from_config")]
    maximum_cycles: Cycles,
    maximum_automatic_grants: u32,
    #[serde(deserialize_with = "Cycles::from_config")]
    maximum_automatic_cycles: Cycles,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct LimitsSource {
    maximum_component_instances: u32,
    maximum_registry_bytes: u64,
    maximum_wasm_store_bytes: u64,
    maximum_group_placements: u32,
    cycles_funding: CyclesFundingSource,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CyclesFundingSource {
    window_secs: u64,
    #[serde(deserialize_with = "Cycles::from_config")]
    maximum_cycles: Cycles,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct EstateSeed {
    schema_version: u32,
    fleet_id: canic_core::ids::FleetId,
    coordinator: String,
    #[serde(default)]
    treasury: Option<TreasurySeed>,
    #[serde(default = "mainnet_cycles_ledger")]
    cycles_ledger: String,
    roots: Vec<RootSeed>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
struct TreasurySeed {
    principal: String,
    subnet: String,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RootSeed {
    placement_subnet: String,
    root: String,
    store: String,
    #[serde(default)]
    pool_imports: Vec<String>,
}

#[derive(Clone)]
struct ObservedCanister {
    cycles: u128,
    module_sha256: Option<String>,
    subnet: String,
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct WasmStoreIdentityRelationship {
    authority: canic_core::ids::FleetRegistryAuthority,
    placement_subnet: SubnetId,
    fleet_subnet_root: Principal,
    wasm_store: Principal,
}

impl From<&FleetSubnetWasmStoreAuthority> for WasmStoreIdentityRelationship {
    fn from(value: &FleetSubnetWasmStoreAuthority) -> Self {
        Self {
            authority: value.authority.clone(),
            placement_subnet: value.placement_subnet,
            fleet_subnet_root: value.fleet_subnet_root,
            wasm_store: value.wasm_store,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct RootIdentityRelationship {
    authority: canic_core::ids::FleetRegistryAuthority,
    placement_subnet: SubnetId,
    fleet_subnet_root: Principal,
}

impl From<&FleetSubnetRootBinding> for RootIdentityRelationship {
    fn from(value: &FleetSubnetRootBinding) -> Self {
        Self {
            authority: value.authority.clone(),
            placement_subnet: value.placement_subnet,
            fleet_subnet_root: value.fleet_subnet_root,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct RootDesiredPolicy {
    component_admissions: Vec<canic_core::ids::ComponentSpecAdmission>,
    component_topology_digest: canic_core::ids::ComponentTopologyDigest,
    funding: FleetSubnetRootFundingAuthority,
    installation_controller: Principal,
    limits: FleetSubnetRootLimits,
}

impl From<&FleetSubnetRootAuthority> for RootDesiredPolicy {
    fn from(value: &FleetSubnetRootAuthority) -> Self {
        Self {
            component_admissions: value.binding.component_admissions.clone(),
            component_topology_digest: value.binding.component_topology_digest,
            funding: value.binding.funding.clone(),
            installation_controller: value.wasm_store_authority.installation_controller,
            limits: value.binding.limits.clone(),
        }
    }
}

struct ExpectedRootEstateAuthority {
    coordinator: FleetCoordinatorBinding,
    root: RootIdentityRelationship,
    store: WasmStoreIdentityRelationship,
}

struct RootEstateAuthorityRequest<'a, 'request> {
    app: &'a canic_core::ids::AppId,
    generation: &'a FleetGenerateRequest<'request>,
    root_candid: &'a Path,
    root_wasm_sha256: &'a str,
    seed: &'a EstateSeed,
    source: &'a FleetSource,
    topology: &'a crate::component_topology::PlannedFleetTopology,
}

struct EstateObservationRequest<'a, 'request> {
    app: &'a canic_core::ids::AppId,
    generation: &'a FleetGenerateRequest<'request>,
    operator: Principal,
    root_candid: &'a Path,
    root_wasm_sha256: &'a str,
    seed: &'a EstateSeed,
    source: &'a FleetSource,
    topology: &'a crate::component_topology::PlannedFleetTopology,
}

#[derive(candid::CandidType)]
enum RootEstateStatusRequest {
    FleetAuthority,
    Pool(CanisterPoolStatusRequest),
}

#[derive(candid::CandidType, Deserialize)]
enum RootEstateStatusResponse {
    FleetAuthority(Box<FleetSubnetRootAuthority>),
    Pool(Box<CanisterPoolResponse>),
}

/// Generate one exact low-level desired document without issuing an IC update.
#[expect(
    clippy::too_many_lines,
    reason = "generation keeps one visible fail-closed authority-validation sequence"
)]
pub fn generate_desired_fleet(
    request: &FleetGenerateRequest<'_>,
) -> Result<GeneratedDesiredFleet, FleetGenerateError> {
    let source: FleetSource = load_toml(request.source, "source")?;
    let seed: EstateSeed = load_toml(request.seed, "seed")?;
    require_schema(source.schema_version, "source")?;
    require_schema(seed.schema_version, "seed")?;
    validate_identity_seed(&source, &seed)?;
    require_cycles_creation(&source.coordinator.creation_funding, "Coordinator")?;
    if source.coordinator.subnet.kind != "explicit" {
        return Err(FleetGenerateError::Authority(
            "Coordinator Subnet must be an exact explicit protected Subnet".to_string(),
        ));
    }
    let operator = parse_principal("operator", &source.operator)?;
    parse_subnet("Coordinator", &source.coordinator.subnet.subnet)?;
    let config = AppConfigSnapshot::load(request.app_config)
        .map_err(|error| FleetGenerateError::Authority(error.to_string()))?;
    let deployment_configuration = ComponentDeploymentConfiguration::compile(config.model())
        .map_err(|error| FleetGenerateError::Authority(error.to_string()))?;
    let admission_principals = source
        .admission
        .principals
        .iter()
        .map(|value| parse_principal("Fleet admission", value))
        .collect::<Result<Vec<_>, _>>()?;
    let admission: FleetAdmissionPolicyTemplate =
        compile_fleet_admission_policy_template(admission_principals, Vec::new())
            .map_err(|error| FleetGenerateError::Authority(error.to_string()))?;
    let root_inputs = source
        .fleet_subnet_roots
        .iter()
        .map(|root| {
            Ok(PlannedFleetSubnetRootTopologyInput {
                placement_subnet: parse_subnet("Fleet Subnet Root", &root.placement_subnet)?,
                component_admissions: root
                    .component_admissions
                    .iter()
                    .map(
                        |(component_spec, maximum_root_instances)| RootComponentAdmissionInput {
                            component_spec: component_spec.clone(),
                            maximum_root_instances: *maximum_root_instances,
                        },
                    )
                    .collect(),
                limits: root_limits(root),
            })
        })
        .collect::<Result<Vec<_>, FleetGenerateError>>()?;
    let topology = plan_initial_fleet_topology(config.model(), root_inputs)
        .map_err(|error| FleetGenerateError::Authority(error.to_string()))?;
    let (infrastructure, complete) = release_authority(request, config.component_topology())?;
    if complete.manifest.infrastructure_artifact_manifest_sha256 != infrastructure.digest {
        return Err(FleetGenerateError::Release(
            "complete release set does not bind its infrastructure manifest".to_string(),
        ));
    }
    let coordinator_artifact = artifact(
        &infrastructure.manifest.entries,
        CanicInfrastructureRole::FleetCoordinator,
    )?;
    let root_artifact = artifact(
        &infrastructure.manifest.entries,
        CanicInfrastructureRole::FleetSubnetRoot,
    )?;
    let store_artifact = artifact(
        &infrastructure.manifest.entries,
        CanicInfrastructureRole::WasmStore,
    )?;
    let coordinator_candid = candid_sidecar(request.root, coordinator_artifact)?;
    let root_candid = candid_sidecar(request.root, root_artifact)?;
    let store_candid = candid_sidecar(request.root, store_artifact)?;
    let root_candid_path = request.root.join(&root_candid);
    let observed = observe_estate(&EstateObservationRequest {
        app: config.model().app_id(),
        generation: request,
        operator,
        root_candid: &root_candid_path,
        root_wasm_sha256: &root_artifact.wasm_sha256_hex,
        seed: &seed,
        source: &source,
        topology: &topology,
    })?;
    let treasury = seed
        .treasury
        .as_ref()
        .map_or(seed.coordinator.as_str(), |treasury| {
            treasury.principal.as_str()
        });
    if !observed.contains_key(treasury) {
        return Err(FleetGenerateError::Authority(
            "treasury must be the seeded Coordinator or another explicitly seeded controlled canister"
                .to_string(),
        ));
    }
    let ledger_fee_cycles = observe_ledger_fee(request, &seed.cycles_ledger)?;
    let desired = compile_desired(CompileDesiredRequest {
        request,
        source: &source,
        seed: &seed,
        admission,
        app: config.model().app_id().clone(),
        deployment_configuration,
        topology,
        coordinator_artifact,
        root_artifact,
        store_artifact,
        coordinator_candid: &coordinator_candid,
        root_candid: &root_candid,
        store_candid: &store_candid,
        observed: &observed,
        treasury,
        ledger_fee_cycles,
    })?;
    let observed_controlled_cycles = observed.values().try_fold(0_u128, |total, canister| {
        total.checked_add(canister.cycles).ok_or_else(|| {
            FleetGenerateError::Authority("observed controlled cycle total overflowed".to_string())
        })
    })?;
    Ok(GeneratedDesiredFleet {
        desired,
        observed_canisters: observed.len(),
        observed_controlled_cycles,
        release_build_id: request.release_build_id,
    })
}

struct CompileDesiredRequest<'a> {
    request: &'a FleetGenerateRequest<'a>,
    source: &'a FleetSource,
    seed: &'a EstateSeed,
    admission: FleetAdmissionPolicyTemplate,
    app: canic_core::ids::AppId,
    deployment_configuration: ComponentDeploymentConfiguration,
    topology: crate::component_topology::PlannedFleetTopology,
    coordinator_artifact: &'a CanicInfrastructureArtifactEntry,
    root_artifact: &'a CanicInfrastructureArtifactEntry,
    store_artifact: &'a CanicInfrastructureArtifactEntry,
    coordinator_candid: &'a str,
    root_candid: &'a str,
    store_candid: &'a str,
    observed: &'a BTreeMap<String, ObservedCanister>,
    treasury: &'a str,
    ledger_fee_cycles: u128,
}

struct RootGenerationBinding<'a> {
    source: &'a RootSource,
    seed: &'a RootSeed,
    planned: &'a PlannedFleetSubnetRootTopology,
}

fn bind_root_generation_inputs<'a>(
    sources: &'a [RootSource],
    seeds: &'a [RootSeed],
    planned_roots: &'a [PlannedFleetSubnetRootTopology],
) -> Result<Vec<RootGenerationBinding<'a>>, FleetGenerateError> {
    let mut sources_by_subnet = BTreeMap::new();
    for source in sources {
        let placement = parse_subnet("Fleet policy Root", &source.placement_subnet)?;
        if sources_by_subnet.insert(placement, source).is_some() {
            return Err(FleetGenerateError::SeedTopology(format!(
                "Fleet policy repeats Root placement Subnet {placement}"
            )));
        }
    }
    let mut seeds_by_subnet = BTreeMap::new();
    for seed in seeds {
        let placement = parse_subnet("Fleet identity-seed Root", &seed.placement_subnet)?;
        if seeds_by_subnet.insert(placement, seed).is_some() {
            return Err(FleetGenerateError::SeedTopology(format!(
                "Fleet identity seed repeats Root placement Subnet {placement}"
            )));
        }
    }
    let mut planned_by_subnet = BTreeMap::new();
    for planned in planned_roots {
        if planned_by_subnet
            .insert(planned.placement_subnet, planned)
            .is_some()
        {
            return Err(FleetGenerateError::SeedTopology(format!(
                "compiled topology repeats Root placement Subnet {}",
                planned.placement_subnet
            )));
        }
    }
    let source_subnets = sources_by_subnet.keys().copied().collect::<BTreeSet<_>>();
    let seed_subnets = seeds_by_subnet.keys().copied().collect::<BTreeSet<_>>();
    let planned_subnets = planned_by_subnet.keys().copied().collect::<BTreeSet<_>>();
    if source_subnets != seed_subnets || source_subnets != planned_subnets {
        return Err(FleetGenerateError::SeedTopology(
            "Fleet policy, identity-seed and compiled Root placement Subnet sets differ"
                .to_string(),
        ));
    }
    Ok(planned_by_subnet
        .into_iter()
        .map(|(placement, planned)| RootGenerationBinding {
            source: sources_by_subnet[&placement],
            seed: seeds_by_subnet[&placement],
            planned,
        })
        .collect())
}

#[expect(
    clippy::too_many_lines,
    reason = "one compiler constructs the complete canonical desired document"
)]
fn compile_desired(input: CompileDesiredRequest<'_>) -> Result<DesiredFleet, FleetGenerateError> {
    let mut canisters = Vec::new();
    canisters.push(infrastructure_canister(
        "coordinator",
        DesiredCanisterKind::Coordinator,
        Some(DesiredCanisterInit::Coordinator),
        &input.seed.coordinator,
        None,
        &input.source.operator,
        &input.source.coordinator.subnet.subnet,
        input.source.coordinator.creation_funding.cycles.to_u128(),
        input
            .source
            .coordinator
            .root_funding
            .minimum_reserve_cycles
            .to_u128(),
        input.coordinator_artifact,
    ));
    let mut bootstrap_roots = Vec::new();
    let mut placements = Vec::new();
    let root_bindings = bind_root_generation_inputs(
        &input.source.fleet_subnet_roots,
        &input.seed.roots,
        &input.topology.fleet_subnet_roots,
    )?;
    for (index, binding) in root_bindings.into_iter().enumerate() {
        let RootGenerationBinding {
            source,
            seed,
            planned,
        } = binding;
        require_cycles_creation(&source.root_creation_funding, "Fleet Subnet Root")?;
        require_cycles_creation(&source.wasm_store_creation_funding, "Wasm Store")?;
        let root_name = format!("root-{index}");
        let store_name = format!("store-{index}");
        canisters.push(infrastructure_canister(
            &root_name,
            DesiredCanisterKind::Root,
            Some(DesiredCanisterInit::Root {
                root: root_name.clone(),
            }),
            &seed.root,
            Some("coordinator"),
            &input.source.operator,
            &source.placement_subnet,
            source.root_creation_funding.cycles.to_u128(),
            source.root_funding.request_threshold.to_u128(),
            input.root_artifact,
        ));
        let mut store = infrastructure_canister(
            &store_name,
            DesiredCanisterKind::Store,
            Some(DesiredCanisterInit::Store {
                root: root_name.clone(),
            }),
            &seed.store,
            Some(&root_name),
            &input.source.operator,
            &source.placement_subnet,
            source.wasm_store_creation_funding.cycles.to_u128(),
            0,
            input.store_artifact,
        );
        store.controllers.push(seed.root.clone());
        store.controllers.sort();
        canisters.push(store);
        let mut pool_names = Vec::new();
        for (pool_index, pool) in seed.pool_imports.iter().enumerate() {
            let name = format!("root-{index}-pool-{pool_index}");
            pool_names.push(name.clone());
            canisters.push(DesiredCanister {
                canic_init: None,
                controllers: vec![seed.root.clone()],
                drain: None,
                initial_cycles: source.canister_pool.canister_cycles.to_u128().to_string(),
                init_arg: None,
                init_candid: None,
                kind: DesiredCanisterKind::Pool,
                minimum_cycles: source.canister_pool.canister_cycles.to_u128().to_string(),
                name,
                parent: Some(root_name.clone()),
                presence: DesiredPresence::Present,
                principal: Some(pool.clone()),
                protocol_binding: None,
                replace: false,
                subnet: source.placement_subnet.clone(),
                wasm: None,
            });
        }
        if seed.pool_imports != source.canister_pool.imports
            && !source.canister_pool.imports.is_empty()
        {
            return Err(FleetGenerateError::SeedTopology(format!(
                "Root {} pool imports differ between policy source and identity seed",
                source.placement_subnet
            )));
        }
        bootstrap_roots.push(DesiredFleetBootstrapRoot {
            canister_pool_imports: pool_names,
            component_admissions: planned.component_admissions.clone(),
            component_topology_digest: planned.component_topology_digest,
            funding: root_funding(input.source.funding_profile, &source.root_funding),
            limits: root_limits(source),
            placement_subnet: planned.placement_subnet,
            root: root_name.clone(),
            store: store_name,
        });
        for (deployment, ordinals) in &source.component_group_placements {
            for ordinal in ordinals {
                placements.push(DesiredComponentGroupPlacement {
                    deployment: deployment.to_string(),
                    ordinal: *ordinal,
                    root: root_name.clone(),
                });
            }
        }
    }
    if input.treasury != input.seed.coordinator {
        let treasury_observation = input
            .observed
            .get(input.treasury)
            .expect("verified treasury observation");
        canisters.push(DesiredCanister {
            canic_init: None,
            controllers: vec![input.source.operator.clone()],
            drain: None,
            initial_cycles: "0".to_string(),
            init_arg: None,
            init_candid: None,
            kind: DesiredCanisterKind::Auxiliary,
            minimum_cycles: "0".to_string(),
            name: "treasury".to_string(),
            parent: None,
            presence: DesiredPresence::Present,
            principal: Some(input.treasury.to_string()),
            protocol_binding: None,
            replace: false,
            subnet: treasury_observation.subnet.clone(),
            wasm: None,
        });
    }
    let app_config = relative_path(input.request.root, input.request.app_config)?;
    let app = input.app.clone();
    Ok(DesiredFleet {
        bootstrap: Some(DesiredFleetBootstrap {
            admission: input.admission,
            app,
            canonical_network_id: canonical_network_id(input.request, input.source)?,
            component_deployment_configuration: input.deployment_configuration,
            coordinator: "coordinator".to_string(),
            coordinator_subnet: parse_subnet(
                "Coordinator",
                &input.source.coordinator.subnet.subnet,
            )?,
            fleet_id: input.seed.fleet_id,
            release_build_id: input.request.release_build_id,
            root_funding: Some(coordinator_funding(
                input.source.funding_profile,
                &input.source.coordinator.root_funding,
            )),
            roots: bootstrap_roots,
        }),
        canisters,
        cycles_ledger: input.seed.cycles_ledger.clone(),
        environment: input.request.environment.to_string(),
        fleet: input.request.fleet.to_string(),
        ledger_fee_cycles: input.ledger_fee_cycles.to_string(),
        // Generated retained estates bind every paid canister to an observed Principal.
        // A missing seeded identity fails closed, so this contract cannot create a canister.
        management_creation_fee_cycles: "0".to_string(),
        material_cycle_threshold: GENERATED_RETAINED_MATERIAL_CYCLE_THRESHOLD.to_string(),
        maximum_observation_burn_cycles: GENERATED_RETAINED_MAXIMUM_OBSERVATION_BURN_CYCLES
            .to_string(),
        maximum_stalled_observations: 8,
        maximum_update_burn_cycles: GENERATED_RETAINED_MAXIMUM_UPDATE_BURN_CYCLES.to_string(),
        operator: input.source.operator.clone(),
        protocol: Some(DesiredFleetProtocol {
            app_config,
            component_group_placements: placements,
            coordinator_candid: input.coordinator_candid.to_string(),
            root_candid: input.root_candid.to_string(),
            store_candid: input.store_candid.to_string(),
        }),
        protocol_steps: Vec::new(),
        schema_version: FLEET_ENSURE_SCHEMA_VERSION,
        treasury: input.treasury.to_string(),
    })
}

fn observe_ledger_fee(
    request: &FleetGenerateRequest<'_>,
    cycles_ledger: &str,
) -> Result<u128, FleetGenerateError> {
    parse_principal("Cycles Ledger", cycles_ledger)?;
    let icp = IcpCli::new(
        request.icp_executable,
        Some(request.environment.to_string()),
    )
    .with_cwd(request.root.to_path_buf());
    let value: Nat = icp
        .canister_query_candid(cycles_ledger, "icrc1_fee", &(), None)
        .map_err(|error| {
            FleetGenerateError::Authority(format!(
                "failed to observe the exact Cycles Ledger fee: {error}"
            ))
        })?;
    let rendered = value.to_string();
    u128::try_from(value.0).map_err(|_| {
        FleetGenerateError::Authority(format!(
            "live Cycles Ledger fee exceeds the supported cycle range: {rendered}"
        ))
    })
}

#[expect(
    clippy::too_many_lines,
    reason = "one observation boundary validates identity, controllers, placement, and cycles together"
)]
fn observe_estate(
    input: &EstateObservationRequest<'_, '_>,
) -> Result<BTreeMap<String, ObservedCanister>, FleetGenerateError> {
    let EstateObservationRequest {
        app,
        generation: request,
        operator,
        root_candid,
        root_wasm_sha256,
        seed,
        source,
        topology,
    } = input;
    let icp = IcpCli::new(
        request.icp_executable,
        Some(request.environment.to_string()),
    )
    .with_cwd(request.root.to_path_buf());
    let active = icp
        .identity_principal_text()
        .map_err(|error| FleetGenerateError::Authority(error.to_string()))?;
    if active != operator.to_text() {
        return Err(FleetGenerateError::Authority(format!(
            "active identity {active} differs from protected operator {operator}"
        )));
    }
    let network = resolve_icp_build_network_from_root(request.root, request.environment)
        .map_err(|error| FleetGenerateError::Authority(error.to_string()))?;
    let catalog = if network == BuildNetwork::Ic {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|_| FleetGenerateError::Clock)?
            .as_secs();
        Some(
            load_mainnet_subnet_catalog(request.root, now)
                .map_err(|error| FleetGenerateError::Authority(error.to_string()))?,
        )
    } else {
        None
    };
    if let Some(catalog) = &catalog {
        require_fiduciary_acknowledgement(
            &catalog.catalog,
            &source.coordinator.subnet.subnet,
            source.coordinator.subnet.acknowledge_fiduciary_cost,
            "Coordinator",
        )?;
        for root in &source.fleet_subnet_roots {
            require_fiduciary_acknowledgement(
                &catalog.catalog,
                &root.placement_subnet,
                root.acknowledge_fiduciary_cost,
                "Fleet Subnet Root",
            )?;
        }
    }
    let mut expected = BTreeMap::new();
    insert_expected_canister(
        &mut expected,
        seed.coordinator.clone(),
        (
            source.coordinator.subnet.subnet.clone(),
            vec![source.operator.clone()],
        ),
        "Coordinator",
    )?;
    if let Some(treasury) = &seed.treasury
        && treasury.principal != seed.coordinator
    {
        insert_expected_canister(
            &mut expected,
            treasury.principal.clone(),
            (treasury.subnet.clone(), vec![source.operator.clone()]),
            "treasury",
        )?;
    }
    for root in &seed.roots {
        insert_expected_canister(
            &mut expected,
            root.root.clone(),
            (root.placement_subnet.clone(), vec![source.operator.clone()]),
            "Fleet Subnet Root",
        )?;
    }
    let mut observed = BTreeMap::new();
    for (canister, (expected_subnet, required_controllers)) in expected {
        parse_principal("retained canister", &canister)?;
        let status = icp.canister_status_report(&canister).map_err(|error| {
            FleetGenerateError::CanisterUnavailable {
                canister: canister.clone(),
                reason: error.to_string(),
            }
        })?;
        let controllers = status
            .settings
            .map(|settings| settings.controllers)
            .unwrap_or_default();
        require_exact_controllers(&canister, controllers, required_controllers)?;
        let subnet = if let Some(catalog) = &catalog {
            catalog
                .catalog
                .resolve_canister_route(&status.id)
                .map_err(|error| FleetGenerateError::Authority(error.to_string()))?
                .subnet
                .to_text()
        } else {
            expected_subnet.clone()
        };
        if subnet != expected_subnet {
            return Err(FleetGenerateError::SubnetMismatch {
                actual: subnet,
                canister,
                expected: expected_subnet,
            });
        }
        let cycles = status
            .cycles
            .as_deref()
            .unwrap_or("0")
            .replace('_', "")
            .parse::<u128>()
            .map_err(|_| FleetGenerateError::Authority("invalid live cycle balance".to_string()))?;
        if observed
            .insert(
                status.id.clone(),
                ObservedCanister {
                    cycles,
                    module_sha256: status
                        .module_hash
                        .map(|hash| hash.trim_start_matches("0x").to_ascii_lowercase()),
                    subnet,
                },
            )
            .is_some()
        {
            return Err(FleetGenerateError::SeedTopology(format!(
                "retained identity {} is assigned to more than one role",
                status.id
            )));
        }
    }
    observe_root_owned_pool_assets(
        &icp,
        &RootEstateAuthorityRequest {
            app,
            generation: request,
            root_candid,
            root_wasm_sha256,
            seed,
            source,
            topology,
        },
        &mut observed,
    )?;
    Ok(observed)
}

fn require_root_estate_authority(
    root: &str,
    actual: &FleetSubnetRootAuthority,
    expected: &ExpectedRootEstateAuthority,
) -> Result<(), FleetGenerateError> {
    if actual.binding.authority.binding != expected.coordinator {
        return Err(FleetGenerateError::SeedTopology(format!(
            "Root {root} live Coordinator authority differs from protected policy"
        )));
    }
    if RootIdentityRelationship::from(&actual.binding) != expected.root {
        return Err(FleetGenerateError::SeedTopology(format!(
            "Root {root} live identity or placement differs from the identity seed"
        )));
    }
    if WasmStoreIdentityRelationship::from(&actual.wasm_store_authority) != expected.store {
        return Err(FleetGenerateError::SeedTopology(format!(
            "Root {root} live Store relationship differs from the identity seed"
        )));
    }
    Ok(())
}

fn require_root_policy_convergence(
    root: &str,
    actual: &RootDesiredPolicy,
    expected: &RootDesiredPolicy,
    observed_module_sha256: Option<&str>,
    desired_module_sha256: &str,
) -> Result<(), FleetGenerateError> {
    if actual != expected && observed_module_sha256 == Some(desired_module_sha256) {
        return Err(FleetGenerateError::SeedTopology(format!(
            "Root {root} policy differs but its current module cannot converge that init-only drift without a reinstall"
        )));
    }
    Ok(())
}

fn require_fiduciary_acknowledgement(
    catalog: &ic_query::subnet_catalog::ValidatedSubnetCatalog,
    subnet: &str,
    acknowledged: bool,
    role: &str,
) -> Result<(), FleetGenerateError> {
    let info = catalog.subnet_by_principal(subnet).ok_or_else(|| {
        FleetGenerateError::Authority(format!(
            "{role} Subnet {subnet} is absent from validated Registry evidence"
        ))
    })?;
    let fiduciary = info.subnet_specialization == SubnetSpecialization::Fiduciary;
    if fiduciary != acknowledged {
        return Err(FleetGenerateError::Authority(format!(
            "{role} Subnet {subnet} Fiduciary cost acknowledgement differs from validated Registry classification"
        )));
    }
    Ok(())
}

#[expect(
    clippy::too_many_lines,
    reason = "bounded Root inventory observation validates one complete authority tuple and page stream"
)]
fn observe_root_owned_pool_assets(
    icp: &IcpCli,
    request: &RootEstateAuthorityRequest<'_, '_>,
    observed: &mut BTreeMap<String, ObservedCanister>,
) -> Result<(), FleetGenerateError> {
    let expected_network = canonical_network_id(request.generation, request.source)?;
    let expected_fleet = request.seed.fleet_id;
    let expected_coordinator = parse_principal("Fleet Coordinator", &request.seed.coordinator)?;
    let expected_coordinator_subnet = parse_subnet(
        "Fleet Coordinator",
        &request.source.coordinator.subnet.subnet,
    )?;
    for root in &request.seed.roots {
        let source_root = request
            .source
            .fleet_subnet_roots
            .iter()
            .find(|candidate| candidate.placement_subnet == root.placement_subnet)
            .ok_or_else(|| {
                FleetGenerateError::SeedTopology(format!(
                    "Root {} has no policy source",
                    root.placement_subnet
                ))
            })?;
        let planned = request
            .topology
            .fleet_subnet_roots
            .iter()
            .find(|candidate| candidate.placement_subnet.to_string() == root.placement_subnet)
            .ok_or_else(|| {
                FleetGenerateError::SeedTopology(format!(
                    "Root {} has no compiled topology authority",
                    root.placement_subnet
                ))
            })?;
        let expected = std::iter::once(root.store.as_str())
            .chain(root.pool_imports.iter().map(String::as_str))
            .collect::<std::collections::BTreeSet<_>>();
        let root_principal = parse_principal("Fleet Subnet Root", &root.root)?;
        let response: RootEstateStatusResponse = query_with_candid(
            icp,
            request.root_candid,
            root_principal,
            protocol::CANIC_STATUS,
            &RootEstateStatusRequest::FleetAuthority,
        )
        .map_err(|error| FleetGenerateError::CanisterUnavailable {
            canister: root.root.clone(),
            reason: format!("protected Root authority observation failed: {error}"),
        })?;
        let RootEstateStatusResponse::FleetAuthority(authority) = response else {
            return Err(FleetGenerateError::SeedTopology(format!(
                "Root {} returned the wrong authority projection",
                root.root
            )));
        };
        let expected_coordinator = FleetCoordinatorBinding {
            fleet: FleetBinding {
                fleet: FleetKey {
                    canonical_network_id: expected_network,
                    fleet_id: expected_fleet,
                },
                app: request.app.clone(),
            },
            coordinator_subnet: expected_coordinator_subnet,
            coordinator: expected_coordinator,
        };
        let expected_registry_authority = FleetRegistryAuthority {
            binding: expected_coordinator.clone(),
            epoch: authority.binding.authority.epoch,
        };
        let expected_authority = ExpectedRootEstateAuthority {
            coordinator: expected_coordinator,
            root: RootIdentityRelationship {
                authority: expected_registry_authority.clone(),
                placement_subnet: planned.placement_subnet,
                fleet_subnet_root: root_principal,
            },
            store: WasmStoreIdentityRelationship {
                authority: expected_registry_authority,
                placement_subnet: planned.placement_subnet,
                fleet_subnet_root: root_principal,
                wasm_store: parse_principal("Wasm Store", &root.store)?,
            },
        };
        require_root_estate_authority(&root.root, &authority, &expected_authority)?;
        let expected_policy = RootDesiredPolicy {
            component_admissions: planned.component_admissions.clone(),
            component_topology_digest: planned.component_topology_digest,
            funding: root_funding(request.source.funding_profile, &source_root.root_funding),
            installation_controller: parse_principal("operator", &request.source.operator)?,
            limits: planned.limits.clone(),
        };
        require_root_policy_convergence(
            &root.root,
            &RootDesiredPolicy::from(authority.as_ref()),
            &expected_policy,
            observed
                .get(&root.root)
                .and_then(|value| value.module_sha256.as_deref()),
            request.root_wasm_sha256,
        )?;
        let mut found = BTreeMap::new();
        let mut start_after = None;
        loop {
            let response: RootEstateStatusResponse = query_with_candid(
                icp,
                request.root_candid,
                root_principal,
                protocol::CANIC_STATUS,
                &RootEstateStatusRequest::Pool(CanisterPoolStatusRequest {
                    start_after,
                    limit: 256,
                }),
            )
            .map_err(|error| FleetGenerateError::CanisterUnavailable {
                canister: root.root.clone(),
                reason: format!("protected Root pool observation failed: {error}"),
            })?;
            let RootEstateStatusResponse::Pool(page) = response else {
                return Err(FleetGenerateError::SeedTopology(format!(
                    "Root {} returned the wrong pool projection",
                    root.root
                )));
            };
            if page.config != authority.binding.limits.canister_pool {
                return Err(FleetGenerateError::SeedTopology(format!(
                    "Root {} live pool policy conflicts with its retained authority",
                    root.root
                )));
            }
            for asset in page.entries {
                let principal = asset.canister_id.to_text();
                if !expected.contains(principal.as_str()) {
                    return Err(FleetGenerateError::SeedTopology(format!(
                        "Root {} retains unseeded controlled pool asset {principal}",
                        root.root
                    )));
                }
                if principal == root.store
                    && root_owned_lifecycle(DesiredCanisterKind::Store, &asset.status).is_none()
                {
                    return Err(FleetGenerateError::SeedTopology(format!(
                        "Root {} does not retain {} as its exact Store",
                        root.root, root.store
                    )));
                }
                if principal != root.store
                    && root_owned_lifecycle(DesiredCanisterKind::Pool, &asset.status).is_none()
                {
                    return Err(FleetGenerateError::SeedTopology(format!(
                        "Root {} pool identity {principal} is outside the retained bootstrap/workload lifecycle",
                        root.root
                    )));
                }
                if found.insert(principal, asset.cycles.to_u128()).is_some() {
                    return Err(FleetGenerateError::SeedTopology(format!(
                        "Root {} repeats a pool identity",
                        root.root
                    )));
                }
            }
            let next = page.next_start_after;
            if next.is_none() {
                break;
            }
            if next == start_after {
                return Err(FleetGenerateError::SeedTopology(format!(
                    "Root {} pool cursor did not advance",
                    root.root
                )));
            }
            start_after = next;
        }
        for principal in expected {
            let cycles = found.get(principal).copied().ok_or_else(|| {
                FleetGenerateError::SeedTopology(format!(
                    "Root {} does not retain seeded identity {principal}",
                    root.root
                ))
            })?;
            if let Some(entry) = observed.get(principal) {
                if entry.cycles != cycles {
                    return Err(FleetGenerateError::Authority(format!(
                        "Root-owned and direct cycle observations differ for {principal}"
                    )));
                }
            } else {
                observed.insert(
                    principal.to_string(),
                    ObservedCanister {
                        cycles,
                        module_sha256: None,
                        subnet: root.placement_subnet.clone(),
                    },
                );
            }
        }
    }
    Ok(())
}

fn validate_identity_seed(
    source: &FleetSource,
    seed: &EstateSeed,
) -> Result<(), FleetGenerateError> {
    let mut identities = BTreeSet::new();
    insert_seed_identity(&mut identities, "Coordinator", &seed.coordinator)?;
    if let Some(treasury) = &seed.treasury {
        parse_subnet("treasury", &treasury.subnet)?;
        if treasury.principal != seed.coordinator {
            insert_seed_identity(&mut identities, "treasury", &treasury.principal)?;
        } else if treasury.subnet != source.coordinator.subnet.subnet {
            return Err(FleetGenerateError::SeedTopology(
                "Coordinator treasury Subnet differs from Coordinator placement".to_string(),
            ));
        }
    }
    let source_roots = source
        .fleet_subnet_roots
        .iter()
        .map(|root| root.placement_subnet.as_str())
        .collect::<BTreeSet<_>>();
    let seed_roots = seed
        .roots
        .iter()
        .map(|root| root.placement_subnet.as_str())
        .collect::<BTreeSet<_>>();
    if source_roots.len() != source.fleet_subnet_roots.len()
        || seed_roots.len() != seed.roots.len()
        || source_roots != seed_roots
    {
        return Err(FleetGenerateError::SeedTopology(
            "Root placement Subnet sets differ or contain duplicates".to_string(),
        ));
    }
    for root in &seed.roots {
        let source_root = source
            .fleet_subnet_roots
            .iter()
            .find(|candidate| candidate.placement_subnet == root.placement_subnet)
            .expect("validated Root placement");
        insert_seed_identity(&mut identities, "Fleet Subnet Root", &root.root)?;
        insert_seed_identity(&mut identities, "Wasm Store", &root.store)?;
        for pool in &root.pool_imports {
            insert_seed_identity(&mut identities, "pool import", pool)?;
        }
        if !source_root.canister_pool.imports.is_empty()
            && source_root.canister_pool.imports != root.pool_imports
        {
            return Err(FleetGenerateError::SeedTopology(format!(
                "Root {} pool imports differ between policy source and identity seed",
                root.placement_subnet
            )));
        }
    }
    Ok(())
}

fn insert_seed_identity(
    identities: &mut BTreeSet<String>,
    role: &str,
    principal: &str,
) -> Result<(), FleetGenerateError> {
    parse_principal(role, principal)?;
    if !identities.insert(principal.to_string()) {
        return Err(FleetGenerateError::SeedTopology(format!(
            "Principal {principal} is assigned to more than one retained role"
        )));
    }
    Ok(())
}

fn insert_expected_canister(
    expected: &mut BTreeMap<String, (String, Vec<String>)>,
    principal: String,
    authority: (String, Vec<String>),
    role: &str,
) -> Result<(), FleetGenerateError> {
    if expected.insert(principal.clone(), authority).is_some() {
        return Err(FleetGenerateError::SeedTopology(format!(
            "{role} Principal {principal} is assigned more than once"
        )));
    }
    Ok(())
}

fn require_exact_controllers(
    canister: &str,
    mut actual: Vec<String>,
    mut expected: Vec<String>,
) -> Result<(), FleetGenerateError> {
    actual.sort();
    expected.sort();
    if actual != expected {
        return Err(FleetGenerateError::ControllerMismatch {
            actual,
            canister: canister.to_string(),
            expected,
        });
    }
    Ok(())
}

fn release_authority(
    request: &FleetGenerateRequest<'_>,
    component_topology: &canic_core::control_plane_support::config::ComponentTopology,
) -> Result<
    (
        crate::release_set::PersistedCanicInfrastructureArtifactManifest,
        crate::release_set::PersistedCurrentReleaseSetManifest,
    ),
    FleetGenerateError,
> {
    let complete =
        load_persisted_current_release_set_manifest(request.root, request.release_build_id)
            .map_err(|error| FleetGenerateError::Release(error.to_string()))?;
    validate_finalized_release_build_manifest(
        request.root,
        request.release_build_id,
        &complete.path,
    )
    .map_err(|error| FleetGenerateError::Release(error.to_string()))?;
    let infrastructure = load_persisted_canic_infrastructure_artifact_manifest(
        request.root,
        request.release_build_id,
    )
    .map_err(|error| FleetGenerateError::Release(error.to_string()))?;
    let application = load_persisted_application_artifact_union(
        request.root,
        component_topology,
        request.release_build_id,
    )
    .map_err(|error| FleetGenerateError::Release(error.to_string()))?;
    if complete.manifest.application_artifact_union_sha256 != application.digest {
        return Err(FleetGenerateError::Release(
            "complete release set does not bind its application artifact union".to_string(),
        ));
    }
    Ok((infrastructure, complete))
}

#[expect(
    clippy::too_many_arguments,
    reason = "single constructor makes every authority-bearing desired canister field explicit"
)]
fn infrastructure_canister(
    name: &str,
    kind: DesiredCanisterKind,
    canic_init: Option<DesiredCanisterInit>,
    principal: &str,
    parent: Option<&str>,
    operator: &str,
    subnet: &str,
    initial_cycles: u128,
    minimum_cycles: u128,
    artifact: &CanicInfrastructureArtifactEntry,
) -> DesiredCanister {
    DesiredCanister {
        canic_init,
        controllers: vec![operator.to_string()],
        drain: None,
        initial_cycles: initial_cycles.to_string(),
        init_arg: None,
        init_candid: None,
        kind,
        minimum_cycles: minimum_cycles.to_string(),
        name: name.to_string(),
        parent: parent.map(str::to_string),
        presence: DesiredPresence::Present,
        principal: Some(principal.to_string()),
        protocol_binding: None,
        replace: false,
        subnet: subnet.to_string(),
        wasm: Some(artifact.wasm_relative_path.clone()),
    }
}

fn coordinator_funding(
    profile: FleetFundingProfile,
    source: &CoordinatorFundingSource,
) -> FleetCoordinatorRootFundingPolicy {
    FleetCoordinatorRootFundingPolicy {
        funding_profile: profile,
        minimum_reserve_cycles: source.minimum_reserve_cycles.clone(),
        budget: CyclesFundingBudget {
            window_secs: source.window_secs,
            maximum_cycles: source.maximum_cycles.clone(),
        },
        maximum_automatic_grants: source.maximum_automatic_grants,
        maximum_automatic_cycles: source.maximum_automatic_cycles.clone(),
    }
}

fn root_funding(
    profile: FleetFundingProfile,
    source: &RootFundingSource,
) -> FleetSubnetRootFundingAuthority {
    FleetSubnetRootFundingAuthority {
        root_funding: FleetSubnetRootFundingPolicy {
            funding_profile: profile,
            request_threshold: source.request_threshold.clone(),
            target_balance: source.target_balance.clone(),
            cooldown_secs: source.cooldown_secs,
            budget: CyclesFundingBudget {
                window_secs: source.window_secs,
                maximum_cycles: source.maximum_cycles.clone(),
            },
            maximum_automatic_grants: source.maximum_automatic_grants,
            maximum_automatic_cycles: source.maximum_automatic_cycles.clone(),
        },
        icp_refill: None,
    }
}

fn root_limits(source: &RootSource) -> FleetSubnetRootLimits {
    FleetSubnetRootLimits {
        maximum_component_instances: source.limits.maximum_component_instances,
        maximum_registry_bytes: source.limits.maximum_registry_bytes,
        maximum_wasm_store_bytes: source.limits.maximum_wasm_store_bytes,
        canister_pool: FleetSubnetCanisterPoolConfig {
            minimum_size: source.canister_pool.minimum_size,
            maximum_size: source.canister_pool.maximum_size,
            canister_cycles: source.canister_pool.canister_cycles.clone(),
        },
        cycles_funding: CyclesFundingBudget {
            window_secs: source.limits.cycles_funding.window_secs,
            maximum_cycles: source.limits.cycles_funding.maximum_cycles.clone(),
        },
        maximum_group_placements: source.limits.maximum_group_placements,
    }
}

fn artifact(
    entries: &[CanicInfrastructureArtifactEntry],
    role: CanicInfrastructureRole,
) -> Result<&CanicInfrastructureArtifactEntry, FleetGenerateError> {
    entries
        .iter()
        .find(|entry| entry.role == role)
        .ok_or_else(|| FleetGenerateError::Release(format!("missing {role:?} artifact")))
}

fn candid_sidecar(
    root: &Path,
    artifact: &CanicInfrastructureArtifactEntry,
) -> Result<String, FleetGenerateError> {
    let wasm = root.join(&artifact.wasm_relative_path);
    let path = wasm.with_extension("did");
    let bytes = match read_optional_regular_bytes(&path) {
        Ok(Some(bytes)) => bytes,
        Ok(None) => {
            return Err(FleetGenerateError::Candid(format!(
                "{} is missing",
                path.display()
            )));
        }
        Err(RegularFileReadError::NotRegular) => {
            return Err(FleetGenerateError::Candid(format!(
                "{} is not a regular no-follow file",
                path.display()
            )));
        }
        Err(RegularFileReadError::Io(error)) => {
            return Err(FleetGenerateError::Candid(format!(
                "{}: {error}",
                path.display()
            )));
        }
        #[cfg(not(unix))]
        Err(RegularFileReadError::UnsupportedPlatform) => {
            return Err(FleetGenerateError::Candid(format!(
                "{} cannot be read without following links on this platform",
                path.display()
            )));
        }
    };
    let actual: [u8; 32] = Sha256::digest(bytes).into();
    if actual != artifact.candid_sha256 {
        return Err(FleetGenerateError::Candid(format!(
            "{} digest differs from release authority",
            path.display()
        )));
    }
    relative_path(root, &path)
}

fn relative_path(root: &Path, path: &Path) -> Result<String, FleetGenerateError> {
    path.strip_prefix(root)
        .map_err(|_| {
            FleetGenerateError::Authority(format!("path is outside workspace: {}", path.display()))
        })?
        .to_str()
        .map(str::to_string)
        .ok_or_else(|| {
            FleetGenerateError::Authority(format!("path is not UTF-8: {}", path.display()))
        })
}

fn canonical_network_id(
    request: &FleetGenerateRequest<'_>,
    _source: &FleetSource,
) -> Result<canic_core::ids::CanonicalNetworkId, FleetGenerateError> {
    resolve_canonical_network_id_from_root(request.root, request.environment)
        .map_err(|error| FleetGenerateError::Authority(error.to_string()))
}

fn load_toml<T: for<'de> Deserialize<'de>>(
    path: &Path,
    _kind: &'static str,
) -> Result<T, FleetGenerateError> {
    let bytes = match read_optional_regular_bytes(path) {
        Ok(Some(bytes)) => bytes,
        Ok(None) => {
            return Err(FleetGenerateError::Read {
                path: path.to_path_buf(),
                source: std::io::Error::new(std::io::ErrorKind::NotFound, "input is missing"),
            });
        }
        Err(RegularFileReadError::Io(source)) => {
            return Err(FleetGenerateError::Read {
                path: path.to_path_buf(),
                source,
            });
        }
        Err(RegularFileReadError::NotRegular) => {
            return Err(FleetGenerateError::UnsafeInput {
                path: path.to_path_buf(),
                reason: "path is not a regular no-follow file",
            });
        }
        #[cfg(not(unix))]
        Err(RegularFileReadError::UnsupportedPlatform) => {
            return Err(FleetGenerateError::UnsafeInput {
                path: path.to_path_buf(),
                reason: "no-follow reads are unsupported on this platform",
            });
        }
    };
    if bytes.len() > MAX_GENERATOR_INPUT_BYTES {
        return Err(FleetGenerateError::TooLarge {
            actual: bytes.len(),
            maximum: MAX_GENERATOR_INPUT_BYTES,
            path: path.to_path_buf(),
        });
    }
    toml::from_slice(&bytes).map_err(|source| FleetGenerateError::Decode {
        path: path.to_path_buf(),
        source,
    })
}

const fn require_schema(actual: u32, kind: &'static str) -> Result<(), FleetGenerateError> {
    if actual == 1 {
        Ok(())
    } else {
        Err(FleetGenerateError::Schema { actual, kind })
    }
}

fn require_cycles_creation(
    source: &CyclesCreationSource,
    owner: &str,
) -> Result<(), FleetGenerateError> {
    if source.kind == "cycles" && source.cycles.to_u128() > 0 {
        Ok(())
    } else {
        Err(FleetGenerateError::Authority(format!(
            "{owner} fresh creation must use a positive exact cycles amount"
        )))
    }
}

fn parse_principal(field: &str, value: &str) -> Result<Principal, FleetGenerateError> {
    Principal::from_text(value).map_err(|error| {
        FleetGenerateError::Authority(format!("invalid {field} Principal: {error}"))
    })
}

fn parse_subnet(field: &str, value: &str) -> Result<SubnetId, FleetGenerateError> {
    parse_principal(field, value).map(SubnetId::from_principal)
}

fn mainnet_cycles_ledger() -> String {
    MAINNET_CYCLES_LEDGER.to_string()
}