canic-host 0.100.99

Host-side App build, Fleet install, deployment, and release-set 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
//! Module: install_root::fleet_subnet_root_install
//!
//! Responsibility: create, install, and independently verify every planned Fleet Subnet Root.
//! Does not own: local Wasm Store bootstrap, Fleet Registry registration, or runtime activation.
//! Boundary: roots are installed serially from canonical plan order; uncertain paid effects remain
//! in explicit durable in-flight phases and are observed rather than blindly replayed.

use super::{
    commands::prepare_creation_result,
    fleet_subnet_root_install_journal::{
        FleetSubnetRootInstallJournal, FleetSubnetRootInstallPhase,
        PlanFleetSubnetRootInstallRequest, ResolvedFleetSubnetRootInstall, begin_root_creation,
        begin_root_install, begin_wasm_store_creation, begin_wasm_store_install,
        create_result_path, expected_root_authority, expected_wasm_store_authority,
        plan_fleet_subnet_root_install, record_infrastructure_verified, record_root_created,
        record_root_installed, record_wasm_store_created, record_wasm_store_installed,
        validate_live_root_activation_status, wasm_store_create_result_path,
    },
    operations::{
        CreationEffectRequest, EffectAction, InstallArtifact, InstallEffectRequest,
        execute_or_observe_creation, execute_or_observe_install, observe_controllers, query_no_arg,
        require_expected_module_hash, resolve_install_artifact,
    },
};
use crate::{
    fleet_install_plan::PersistedFleetInstallPlan,
    icp::LocalReplicaTarget,
    release_set::{
        AppConfigSnapshot, CanicInfrastructureRole,
        load_persisted_canic_infrastructure_artifact_manifest,
    },
};
use candid::Principal;
use canic_core::{
    dto::{
        fleet_activation::FleetActivationStatusResponse,
        fleet_subnet_root::{
            FleetSubnetRootAuthority, FleetSubnetRootInitArgs, FleetSubnetWasmStoreInitArgs,
        },
    },
    ids::FleetSubnetWasmStoreAuthority,
    protocol,
};
use std::path::{Path, PathBuf};
use thiserror::Error as ThisError;

const MAX_ROOT_TRANSITIONS: usize = 12;
const ROOT_INSTALL_ARGS_FILE: &str = "root-install-args.bin";
const WASM_STORE_INSTALL_ARGS_FILE: &str = "wasm-store-install-args.bin";

#[derive(Debug, ThisError)]
#[error(
    "Fleet Subnet Root creation outcome on {placement_subnet} is unknown; no second paid creation was attempted. Inspect durable result {result_path} and retry after the original ICP command has settled: {detail}"
)]
struct RootCreationOutcomeUnknownError {
    placement_subnet: canic_core::ids::SubnetId,
    result_path: PathBuf,
    detail: String,
}

#[derive(Debug, ThisError)]
#[error(
    "Wasm Store creation outcome on {placement_subnet} is unknown; no second paid creation was attempted. Inspect durable result {result_path} and retry after the original ICP command has settled: {detail}"
)]
struct WasmStoreCreationOutcomeUnknownError {
    placement_subnet: canic_core::ids::SubnetId,
    result_path: PathBuf,
    detail: String,
}

#[derive(Debug, ThisError)]
enum RootInstallStateError {
    #[error("Fleet Subnet Root activation status differs from exact Prepared install authority")]
    ActivationStatusMismatch,

    #[error("Fleet Subnet Root protected authority query differs from exact planned binding")]
    AuthorityMismatch,

    #[error("Wasm Store protected authority query differs from exact planned binding")]
    WasmStoreAuthorityMismatch,

    #[error("Wasm Store temporary controllers differ from installer-plus-root authority")]
    WasmStoreTemporaryControllersMismatch,

    #[error("Fleet Subnet Root installation exceeded its bounded phase transitions")]
    TransitionBoundExceeded,
}

pub(super) fn install_and_verify_fleet_subnet_roots(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&LocalReplicaTarget>,
    config_path: &Path,
    fleet_install_plan: &PersistedFleetInstallPlan,
    coordinator: Principal,
    install_operation_id: [u8; 32],
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfigSnapshot::load(config_path)?;
    let component_topology = config.model().compile_component_topology()?;
    let infrastructure_manifest = load_persisted_canic_infrastructure_artifact_manifest(
        icp_root,
        fleet_install_plan.plan.release_build_id,
    )?;
    let root_artifact = resolve_install_artifact(
        icp_root,
        &infrastructure_manifest,
        CanicInfrastructureRole::FleetSubnetRoot,
        fleet_install_plan.plan.release_build_id,
    )?;
    let wasm_store_artifact = resolve_install_artifact(
        icp_root,
        &infrastructure_manifest,
        CanicInfrastructureRole::WasmStore,
        fleet_install_plan.plan.release_build_id,
    )?;
    let mut roots = Vec::with_capacity(fleet_install_plan.plan.fleet_subnet_roots.len());

    for root_plan in &fleet_install_plan.plan.fleet_subnet_roots {
        let current = plan_fleet_subnet_root_install(PlanFleetSubnetRootInstallRequest {
            fleet_install_plan,
            infrastructure_manifest: &infrastructure_manifest,
            coordinator,
            install_operation_id,
            component_topology: component_topology.clone(),
            root_plan,
        })?;
        roots.push(drive_root_install(
            icp_root,
            environment,
            local_replica,
            &root_artifact,
            &wasm_store_artifact,
            current,
        )?);
    }

    let bindings = roots
        .iter()
        .map(|authority| authority.binding.clone())
        .collect::<Vec<_>>();
    component_topology.validate_fleet_subnet_root_bindings(&bindings)?;
    Ok(())
}

fn drive_root_install(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&LocalReplicaTarget>,
    root_artifact: &InstallArtifact,
    wasm_store_artifact: &InstallArtifact,
    mut current: ResolvedFleetSubnetRootInstall,
) -> Result<FleetSubnetRootAuthority, Box<dyn std::error::Error>> {
    for _ in 0..MAX_ROOT_TRANSITIONS {
        current = match current.journal.phase {
            FleetSubnetRootInstallPhase::Planned => {
                prepare_creation_result(&create_result_path(&current.path), "Fleet Subnet Root")?;
                begin_root_creation(&current)?
            }
            FleetSubnetRootInstallPhase::RootCreationInFlight => {
                recover_or_create_root(icp_root, environment, local_replica, &current)?
            }
            FleetSubnetRootInstallPhase::RootCreated => {
                prepare_creation_result(
                    &wasm_store_create_result_path(&current.path),
                    "Wasm Store",
                )?;
                let installation_controller =
                    active_installation_controller(icp_root, environment, local_replica)?;
                begin_wasm_store_creation(&current, installation_controller)?
            }
            FleetSubnetRootInstallPhase::WasmStoreCreationInFlight => {
                recover_or_create_wasm_store(icp_root, environment, local_replica, &current)?
            }
            FleetSubnetRootInstallPhase::WasmStoreCreated => begin_wasm_store_install(&current)?,
            FleetSubnetRootInstallPhase::WasmStoreInstallInFlight => recover_or_install_wasm_store(
                icp_root,
                environment,
                local_replica,
                wasm_store_artifact,
                &current,
            )?,
            FleetSubnetRootInstallPhase::WasmStoreInstalled => begin_root_install(&current)?,
            FleetSubnetRootInstallPhase::RootInstallInFlight => recover_or_install_root(
                icp_root,
                environment,
                local_replica,
                root_artifact,
                &current,
            )?,
            FleetSubnetRootInstallPhase::RootInstalled => {
                verify_and_record_infrastructure(icp_root, environment, local_replica, &current)?
            }
            FleetSubnetRootInstallPhase::InfrastructureVerified
            | FleetSubnetRootInstallPhase::StoreAdoptionInFlight
            | FleetSubnetRootInstallPhase::StoreAdopted
            | FleetSubnetRootInstallPhase::StoreStaging
            | FleetSubnetRootInstallPhase::StoreStaged
            | FleetSubnetRootInstallPhase::StoreBootstrapInFlight
            | FleetSubnetRootInstallPhase::StoreBootstrapped
            | FleetSubnetRootInstallPhase::StoreVerified
            | FleetSubnetRootInstallPhase::RegistryJoinInFlight
            | FleetSubnetRootInstallPhase::RegistryJoined
            | FleetSubnetRootInstallPhase::RegistryJoinVerified
            | FleetSubnetRootInstallPhase::RegistrySyncInFlight
            | FleetSubnetRootInstallPhase::RegistrySynchronized
            | FleetSubnetRootInstallPhase::RegistrySyncVerified
            | FleetSubnetRootInstallPhase::RegistryMirrorActivationInFlight
            | FleetSubnetRootInstallPhase::RegistryMirrorActivated
            | FleetSubnetRootInstallPhase::RegistryMirrorActivationVerified
            | FleetSubnetRootInstallPhase::ComponentRegistryPreparationInFlight
            | FleetSubnetRootInstallPhase::ComponentRegistryPrepared
            | FleetSubnetRootInstallPhase::ComponentRegistryPreparationVerified
            | FleetSubnetRootInstallPhase::RootActivationPreparationInFlight
            | FleetSubnetRootInstallPhase::RootActivationPrepared
            | FleetSubnetRootInstallPhase::RootActivationInFlight
            | FleetSubnetRootInstallPhase::RootActivated
            | FleetSubnetRootInstallPhase::RootActivationVerified => {
                let (authority, _) = verify_live_infrastructure(
                    icp_root,
                    environment,
                    local_replica,
                    &current.path,
                    &current.journal,
                )?;
                return Ok(authority);
            }
        };
    }
    Err(RootInstallStateError::TransitionBoundExceeded.into())
}

fn recover_or_create_root(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&LocalReplicaTarget>,
    current: &ResolvedFleetSubnetRootInstall,
) -> Result<ResolvedFleetSubnetRootInstall, Box<dyn std::error::Error>> {
    let result_path = create_result_path(&current.path);
    let evidence = execute_or_observe_creation(CreationEffectRequest {
        icp_root,
        environment,
        local_replica,
        result_path: &result_path,
        subject: "Fleet Subnet Root",
        placement_subnet: current.journal.root_plan.placement_subnet,
        funding: &current.journal.root_plan.root_creation_funding,
        controllers: &[],
        action: EffectAction::from_advanced(current.advanced),
        expected_module_hash: current.journal.expected_root_module_hash,
    })?;
    let Some(fleet_subnet_root) = evidence.canister else {
        return Err(RootCreationOutcomeUnknownError {
            placement_subnet: current.journal.root_plan.placement_subnet,
            result_path,
            detail: evidence.command_error.unwrap_or_else(|| {
                "the journal is already creation_in_flight and has no recoverable principal"
                    .to_string()
            }),
        }
        .into());
    };
    record_root_created(current, fleet_subnet_root).map_err(Into::into)
}

fn recover_or_install_root(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&LocalReplicaTarget>,
    artifact: &InstallArtifact,
    current: &ResolvedFleetSubnetRootInstall,
) -> Result<ResolvedFleetSubnetRootInstall, Box<dyn std::error::Error>> {
    let fleet_subnet_root = current
        .journal
        .fleet_subnet_root
        .expect("validated InstallInFlight journal retains its root");
    let args_path = current.path.with_file_name(ROOT_INSTALL_ARGS_FILE);
    let module_hash = execute_or_observe_install(
        InstallEffectRequest {
            icp_root,
            environment,
            local_replica,
            subject: "Fleet Subnet Root",
            canister: fleet_subnet_root,
            wasm_path: &artifact.wasm_path,
            args_path: &args_path,
            expected_module_hash: current.journal.expected_root_module_hash,
            action: EffectAction::from_advanced(current.advanced),
        },
        || root_install_args(&current.journal),
    )?;
    record_root_installed(current, module_hash).map_err(Into::into)
}

fn recover_or_create_wasm_store(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&LocalReplicaTarget>,
    current: &ResolvedFleetSubnetRootInstall,
) -> Result<ResolvedFleetSubnetRootInstall, Box<dyn std::error::Error>> {
    let result_path = wasm_store_create_result_path(&current.path);
    let controllers = temporary_store_controllers(&current.journal);
    let evidence = execute_or_observe_creation(CreationEffectRequest {
        icp_root,
        environment,
        local_replica,
        result_path: &result_path,
        subject: "Wasm Store",
        placement_subnet: current.journal.root_plan.placement_subnet,
        funding: &current.journal.root_plan.wasm_store_creation_funding,
        controllers: &controllers,
        action: EffectAction::from_advanced(current.advanced),
        expected_module_hash: current.journal.expected_wasm_store_module_hash,
    })?;
    let Some(wasm_store) = evidence.canister else {
        return Err(WasmStoreCreationOutcomeUnknownError {
            placement_subnet: current.journal.root_plan.placement_subnet,
            result_path,
            detail: evidence.command_error.unwrap_or_else(|| {
                "the journal is already wasm_store_creation_in_flight and has no recoverable principal"
                    .to_string()
            }),
        }
        .into());
    };
    let observed_controllers = observe_controllers(
        &super::install_icp(icp_root, environment, local_replica),
        wasm_store,
    )?;
    if observed_controllers != temporary_store_controllers(&current.journal) {
        return Err(RootInstallStateError::WasmStoreTemporaryControllersMismatch.into());
    }
    record_wasm_store_created(current, wasm_store).map_err(Into::into)
}

fn active_installation_controller(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&LocalReplicaTarget>,
) -> Result<Principal, Box<dyn std::error::Error>> {
    let text =
        super::install_icp(icp_root, environment, local_replica).identity_principal_text()?;
    let controller = Principal::from_text(text.trim())?;
    Ok(controller)
}

fn temporary_store_controllers(journal: &FleetSubnetRootInstallJournal) -> Vec<Principal> {
    let mut controllers = vec![
        journal
            .installation_controller
            .expect("Wasm Store creation intent retains its installation controller"),
        journal
            .fleet_subnet_root
            .expect("Wasm Store creation intent retains its root"),
    ];
    controllers.sort();
    controllers.dedup();
    controllers
}

fn recover_or_install_wasm_store(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&LocalReplicaTarget>,
    artifact: &InstallArtifact,
    current: &ResolvedFleetSubnetRootInstall,
) -> Result<ResolvedFleetSubnetRootInstall, Box<dyn std::error::Error>> {
    let wasm_store = current
        .journal
        .wasm_store
        .expect("validated WasmStoreInstallInFlight journal retains its Store");
    let args_path = current.path.with_file_name(WASM_STORE_INSTALL_ARGS_FILE);
    let module_hash = execute_or_observe_install(
        InstallEffectRequest {
            icp_root,
            environment,
            local_replica,
            subject: "Wasm Store",
            canister: wasm_store,
            wasm_path: &artifact.wasm_path,
            args_path: &args_path,
            expected_module_hash: current.journal.expected_wasm_store_module_hash,
            action: EffectAction::from_advanced(current.advanced),
        },
        || wasm_store_install_args(&current.journal),
    )?;
    record_wasm_store_installed(current, module_hash).map_err(Into::into)
}

fn verify_and_record_infrastructure(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&LocalReplicaTarget>,
    current: &ResolvedFleetSubnetRootInstall,
) -> Result<ResolvedFleetSubnetRootInstall, Box<dyn std::error::Error>> {
    let (root_authority, wasm_store_authority) = verify_live_infrastructure(
        icp_root,
        environment,
        local_replica,
        &current.path,
        &current.journal,
    )?;
    record_infrastructure_verified(current, root_authority, wasm_store_authority)
        .map_err(Into::into)
}

fn verify_live_infrastructure(
    icp_root: &Path,
    environment: &str,
    local_replica: Option<&LocalReplicaTarget>,
    journal_path: &Path,
    journal: &FleetSubnetRootInstallJournal,
) -> Result<(FleetSubnetRootAuthority, FleetSubnetWasmStoreAuthority), Box<dyn std::error::Error>> {
    let fleet_subnet_root = journal
        .fleet_subnet_root
        .expect("installed root journal retains its principal");
    let icp = super::install_icp(icp_root, environment, local_replica);
    require_expected_module_hash(
        &icp,
        fleet_subnet_root,
        journal.expected_root_module_hash,
        "Fleet Subnet Root",
    )?;

    let expected = expected_root_authority(journal)?;
    let status = query_no_arg::<FleetActivationStatusResponse>(
        &icp,
        fleet_subnet_root,
        protocol::CANIC_FLEET_ACTIVATION_STATUS,
    )?;
    validate_live_root_activation_status(journal_path, journal, &status)
        .map_err(|_| RootInstallStateError::ActivationStatusMismatch)?;
    let observed = query_no_arg::<FleetSubnetRootAuthority>(
        &icp,
        fleet_subnet_root,
        protocol::CANIC_FLEET_SUBNET_ROOT_AUTHORITY,
    )?;
    if observed != expected {
        return Err(RootInstallStateError::AuthorityMismatch.into());
    }
    let direct_store_verification_required = matches!(
        journal.phase,
        FleetSubnetRootInstallPhase::RootInstalled
            | FleetSubnetRootInstallPhase::InfrastructureVerified
    );
    if !direct_store_verification_required {
        return Ok((expected.clone(), expected.wasm_store_authority));
    }
    let wasm_store = journal
        .wasm_store
        .expect("installed infrastructure journal retains its Store");
    require_expected_module_hash(
        &icp,
        wasm_store,
        journal.expected_wasm_store_module_hash,
        "Wasm Store",
    )?;
    let store_status = query_no_arg::<FleetActivationStatusResponse>(
        &icp,
        wasm_store,
        protocol::CANIC_FLEET_ACTIVATION_STATUS,
    )?;
    validate_live_root_activation_status(journal_path, journal, &store_status)
        .map_err(|_| RootInstallStateError::ActivationStatusMismatch)?;
    let expected_store = expected_wasm_store_authority(journal)?;
    let observed_controllers = observe_controllers(&icp, wasm_store)?;
    if observed_controllers != temporary_store_controllers(journal) {
        return Err(RootInstallStateError::WasmStoreTemporaryControllersMismatch.into());
    }
    let observed_store = query_no_arg::<FleetSubnetWasmStoreAuthority>(
        &icp,
        wasm_store,
        protocol::CANIC_FLEET_SUBNET_WASM_STORE_AUTHORITY,
    )?;
    if observed_store != expected_store {
        return Err(RootInstallStateError::WasmStoreAuthorityMismatch.into());
    }
    Ok((expected, expected_store))
}

fn root_install_args(
    journal: &FleetSubnetRootInstallJournal,
) -> Result<FleetSubnetRootInitArgs, Box<dyn std::error::Error>> {
    Ok(FleetSubnetRootInitArgs {
        authority: expected_root_authority(journal)?,
        install_id: journal.install_operation_id,
        canister_pool_imports: journal.root_plan.canister_pool_imports.clone(),
    })
}

fn wasm_store_install_args(
    journal: &FleetSubnetRootInstallJournal,
) -> Result<FleetSubnetWasmStoreInitArgs, Box<dyn std::error::Error>> {
    Ok(FleetSubnetWasmStoreInitArgs {
        authority: expected_wasm_store_authority(journal)?,
        install_id: journal.install_operation_id,
    })
}