canic-host 0.109.5

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
//! Module: fleet_install_plan::initial_placement_policy
//!
//! Responsibility: purely validate complete initial Component Group placement assignments.
//! Does not own: file paths, serialization, durable publication, artifact projection, or effects.
//! Boundary: compiled deployment/service policy plus planned roots yields acceptance or typed error.

use super::model::FreshFleetSubnetRootPlanV1;
use std::collections::BTreeMap;

use canic_core::{
    bootstrap::compiled::ConfigModel,
    cdk::types::Cycles,
    control_plane_support::config::{
        ComponentDeploymentPurpose, ComponentGroupDeploymentSpec, FleetServiceTopology,
    },
    ids::{ComponentGroupDeploymentId, ComponentSpecId, FleetServiceId, SubnetId},
};
use thiserror::Error as ThisError;

#[derive(Clone, Copy)]
pub(super) enum InitialPoolCyclesPolicy {
    Enforce,
    RetainHistorical,
}

#[derive(Debug, ThisError)]
pub(super) enum InitialPlacementPolicyError {
    #[error("{0}")]
    Configuration(String),

    #[error("root {root} assignments are not strictly canonical")]
    NonCanonicalRootAssignments { root: SubnetId },

    #[error("root {root} exceeds maximum_group_placements")]
    RootPlacementLimitExceeded { root: SubnetId },

    #[error("root {root} references unknown deployment '{deployment}'")]
    UnknownDeployment {
        root: SubnetId,
        deployment: ComponentGroupDeploymentId,
    },

    #[error("deployment '{deployment}' ordinal {ordinal} is outside its initial placement set")]
    OrdinalOutsideInitialSet {
        deployment: ComponentGroupDeploymentId,
        ordinal: u32,
    },

    #[error("deployment '{deployment}' ordinal {ordinal} is assigned more than once")]
    DuplicateAssignment {
        deployment: ComponentGroupDeploymentId,
        ordinal: u32,
    },

    #[error("{subject} count overflowed")]
    CountOverflow { subject: &'static str },

    #[error("{subject} count does not fit u32")]
    CountDoesNotFitU32 { subject: &'static str },

    #[error("root {root} initial Components exceed protected root capacity")]
    RootComponentCapacityExceeded { root: SubnetId },

    #[error(
        "root {root} initial atomic Component batch requires {required} Ready prepaid Canisters but its configured minimum/import target is {available}"
    )]
    ReadyAssetCapacityExceeded {
        root: SubnetId,
        required: u32,
        available: u32,
    },

    #[error(
        "root {root} pool assets provide {configured} each but an initial Component requires {required}"
    )]
    PoolAssetCyclesInsufficient {
        root: SubnetId,
        configured: Cycles,
        required: Cycles,
    },

    #[error("root {root} does not admit Component Spec '{component_spec}'")]
    MissingComponentAdmission {
        root: SubnetId,
        component_spec: ComponentSpecId,
    },

    #[error("root {root} exceeds admission for Component Spec '{component_spec}'")]
    ComponentAdmissionExceeded {
        root: SubnetId,
        component_spec: ComponentSpecId,
    },

    #[error("deployment '{deployment}' does not assign every initial ordinal exactly once")]
    IncompleteDeploymentAssignments {
        deployment: ComponentGroupDeploymentId,
    },

    #[error("deployment '{deployment}' violates its root density or spread policy")]
    DeploymentPlacementPolicy {
        deployment: ComponentGroupDeploymentId,
    },

    #[error("Fleet service '{service}' violates its root density or spread policy")]
    ServicePlacementPolicy { service: FleetServiceId },
}

pub(super) fn validate_initial_component_group_assignments(
    config: &ConfigModel,
    roots: &[FreshFleetSubnetRootPlanV1],
) -> Result<BTreeMap<SubnetId, u32>, InitialPlacementPolicyError> {
    validate_initial_component_group_assignments_with_pool_policy(
        config,
        roots,
        InitialPoolCyclesPolicy::Enforce,
    )
}

pub(super) fn validate_historical_component_group_assignments(
    config: &ConfigModel,
    roots: &[FreshFleetSubnetRootPlanV1],
) -> Result<BTreeMap<SubnetId, u32>, InitialPlacementPolicyError> {
    validate_initial_component_group_assignments_with_pool_policy(
        config,
        roots,
        InitialPoolCyclesPolicy::RetainHistorical,
    )
}

fn validate_initial_component_group_assignments_with_pool_policy(
    config: &ConfigModel,
    roots: &[FreshFleetSubnetRootPlanV1],
    pool_cycles_policy: InitialPoolCyclesPolicy,
) -> Result<BTreeMap<SubnetId, u32>, InitialPlacementPolicyError> {
    let configuration = config
        .compile_component_deployment_configuration()
        .map_err(|error| InitialPlacementPolicyError::Configuration(error.to_string()))?;
    let deployments = &configuration
        .deployment_topology
        .component_group_deployments;
    let mut assignments = BTreeMap::<
        (ComponentGroupDeploymentId, u32),
        (SubnetId, &ComponentGroupDeploymentSpec),
    >::new();
    let mut service_roots = BTreeMap::<FleetServiceId, BTreeMap<SubnetId, u32>>::new();
    let mut component_counts = BTreeMap::<SubnetId, u32>::new();

    for root in roots {
        validate_root_assignment_order(root)?;
        let component_count = validate_root_initial_assignment_capacity(
            config,
            root,
            deployments,
            pool_cycles_policy,
            &mut assignments,
            &mut service_roots,
        )?;
        component_counts.insert(root.placement_subnet, component_count);
    }

    for deployment in deployments {
        validate_deployment_assignment(deployment, &assignments)?;
    }
    validate_service_assignments(&configuration.fleet_service_topology, &service_roots)?;
    Ok(component_counts)
}

fn validate_root_assignment_order(
    root: &FreshFleetSubnetRootPlanV1,
) -> Result<(), InitialPlacementPolicyError> {
    let assignments_are_sorted = root.component_group_placements.is_sorted();
    let assignments_are_unique = root
        .component_group_placements
        .windows(2)
        .all(|window| window[0] != window[1]);
    if !assignments_are_sorted || !assignments_are_unique {
        return Err(InitialPlacementPolicyError::NonCanonicalRootAssignments {
            root: root.placement_subnet,
        });
    }
    if root.component_group_placements.len() > root.limits.maximum_group_placements as usize {
        return Err(InitialPlacementPolicyError::RootPlacementLimitExceeded {
            root: root.placement_subnet,
        });
    }
    Ok(())
}

fn validate_root_initial_assignment_capacity<'a>(
    config: &ConfigModel,
    root: &FreshFleetSubnetRootPlanV1,
    deployments: &'a [ComponentGroupDeploymentSpec],
    pool_cycles_policy: InitialPoolCyclesPolicy,
    assignments: &mut BTreeMap<
        (ComponentGroupDeploymentId, u32),
        (SubnetId, &'a ComponentGroupDeploymentSpec),
    >,
    service_roots: &mut BTreeMap<FleetServiceId, BTreeMap<SubnetId, u32>>,
) -> Result<u32, InitialPlacementPolicyError> {
    let mut component_counts = BTreeMap::<ComponentSpecId, u32>::new();
    let mut component_count = 0_u32;
    let mut required_asset_cycles = Cycles::default();
    for assignment in &root.component_group_placements {
        let deployment = deployments
            .binary_search_by(|candidate| candidate.deployment.cmp(&assignment.deployment))
            .ok()
            .map(|index| &deployments[index])
            .ok_or_else(|| InitialPlacementPolicyError::UnknownDeployment {
                root: root.placement_subnet,
                deployment: assignment.deployment.clone(),
            })?;
        if assignment.ordinal >= deployment.initial_placements {
            return Err(InitialPlacementPolicyError::OrdinalOutsideInitialSet {
                deployment: assignment.deployment.clone(),
                ordinal: assignment.ordinal,
            });
        }
        if assignments
            .insert(
                (assignment.deployment.clone(), assignment.ordinal),
                (root.placement_subnet, deployment),
            )
            .is_some()
        {
            return Err(InitialPlacementPolicyError::DuplicateAssignment {
                deployment: assignment.deployment.clone(),
                ordinal: assignment.ordinal,
            });
        }
        component_count = component_count
            .checked_add(u32::try_from(deployment.members.len()).map_err(|_| {
                InitialPlacementPolicyError::CountDoesNotFitU32 {
                    subject: "deployment member",
                }
            })?)
            .ok_or(InitialPlacementPolicyError::CountOverflow {
                subject: "root Component",
            })?;
        for member in &deployment.members {
            let initial_cycles = config
                .component_specs
                .get(&member.component_spec)
                .map(|component| component.initial_cycles.clone())
                .ok_or_else(|| {
                    InitialPlacementPolicyError::Configuration(format!(
                        "unknown Component Spec '{}' in compiled deployment",
                        member.component_spec
                    ))
                })?;
            required_asset_cycles = required_asset_cycles.max(initial_cycles);
        }
        record_member_capacity(root, deployment, &mut component_counts, service_roots)?;
    }
    if component_count > root.limits.maximum_component_instances {
        return Err(InitialPlacementPolicyError::RootComponentCapacityExceeded {
            root: root.placement_subnet,
        });
    }
    validate_initial_pool_capacity(
        root,
        component_count,
        required_asset_cycles,
        pool_cycles_policy,
    )?;
    validate_component_admissions(root, component_counts)?;
    Ok(component_count)
}

fn record_member_capacity(
    root: &FreshFleetSubnetRootPlanV1,
    deployment: &ComponentGroupDeploymentSpec,
    component_counts: &mut BTreeMap<ComponentSpecId, u32>,
    service_roots: &mut BTreeMap<FleetServiceId, BTreeMap<SubnetId, u32>>,
) -> Result<(), InitialPlacementPolicyError> {
    for member in &deployment.members {
        let count = component_counts
            .entry(member.component_spec.clone())
            .or_default();
        *count = count
            .checked_add(1)
            .ok_or(InitialPlacementPolicyError::CountOverflow {
                subject: "root Component Spec",
            })?;
        if let ComponentDeploymentPurpose::FleetServiceMember { service, .. } = &member.purpose {
            let count = service_roots
                .entry(service.clone())
                .or_default()
                .entry(root.placement_subnet)
                .or_default();
            *count = count
                .checked_add(1)
                .ok_or(InitialPlacementPolicyError::CountOverflow {
                    subject: "Fleet-service member",
                })?;
        }
    }
    Ok(())
}

fn validate_initial_pool_capacity(
    root: &FreshFleetSubnetRootPlanV1,
    component_count: u32,
    required_asset_cycles: Cycles,
    pool_cycles_policy: InitialPoolCyclesPolicy,
) -> Result<(), InitialPlacementPolicyError> {
    let imported_assets = u32::try_from(root.canister_pool_imports.len()).map_err(|_| {
        InitialPlacementPolicyError::CountDoesNotFitU32 {
            subject: "root Canister pool import",
        }
    })?;
    let automatic_ready_target = root.limits.canister_pool.minimum_size.max(imported_assets);
    if component_count > automatic_ready_target {
        return Err(InitialPlacementPolicyError::ReadyAssetCapacityExceeded {
            root: root.placement_subnet,
            required: component_count,
            available: automatic_ready_target,
        });
    }
    if matches!(pool_cycles_policy, InitialPoolCyclesPolicy::Enforce)
        && root.limits.canister_pool.canister_cycles < required_asset_cycles
    {
        return Err(InitialPlacementPolicyError::PoolAssetCyclesInsufficient {
            root: root.placement_subnet,
            configured: root.limits.canister_pool.canister_cycles.clone(),
            required: required_asset_cycles,
        });
    }
    Ok(())
}

fn validate_component_admissions(
    root: &FreshFleetSubnetRootPlanV1,
    component_counts: BTreeMap<ComponentSpecId, u32>,
) -> Result<(), InitialPlacementPolicyError> {
    for (component_spec, count) in component_counts {
        let admission = root
            .component_admissions
            .binary_search_by(|admission| admission.component_spec.cmp(&component_spec))
            .ok()
            .map(|index| &root.component_admissions[index])
            .ok_or_else(|| InitialPlacementPolicyError::MissingComponentAdmission {
                root: root.placement_subnet,
                component_spec: component_spec.clone(),
            })?;
        if count > admission.maximum_root_instances {
            return Err(InitialPlacementPolicyError::ComponentAdmissionExceeded {
                root: root.placement_subnet,
                component_spec,
            });
        }
    }
    Ok(())
}

fn validate_deployment_assignment(
    deployment: &ComponentGroupDeploymentSpec,
    assignments: &BTreeMap<
        (ComponentGroupDeploymentId, u32),
        (SubnetId, &ComponentGroupDeploymentSpec),
    >,
) -> Result<(), InitialPlacementPolicyError> {
    let matching = assignments
        .iter()
        .filter(|((candidate, _), _)| candidate == &deployment.deployment)
        .collect::<Vec<_>>();
    let ordinals_are_exact = matching
        .iter()
        .map(|((_, ordinal), _)| *ordinal)
        .eq(0..deployment.initial_placements);
    if matching.len() != deployment.initial_placements as usize || !ordinals_are_exact {
        return Err(
            InitialPlacementPolicyError::IncompleteDeploymentAssignments {
                deployment: deployment.deployment.clone(),
            },
        );
    }
    let mut root_counts = BTreeMap::<SubnetId, u32>::new();
    for (_, (root, _)) in matching {
        let count = root_counts.entry(*root).or_default();
        *count = count
            .checked_add(1)
            .ok_or(InitialPlacementPolicyError::CountOverflow {
                subject: "deployment root",
            })?;
    }
    let density_is_valid = root_counts
        .values()
        .all(|count| *count <= deployment.placement.maximum_per_root);
    let required_roots = deployment
        .initial_placements
        .min(deployment.placement.minimum_distinct_roots) as usize;
    if !density_is_valid || root_counts.len() < required_roots {
        return Err(InitialPlacementPolicyError::DeploymentPlacementPolicy {
            deployment: deployment.deployment.clone(),
        });
    }
    Ok(())
}

fn validate_service_assignments(
    topology: &FleetServiceTopology,
    service_roots: &BTreeMap<FleetServiceId, BTreeMap<SubnetId, u32>>,
) -> Result<(), InitialPlacementPolicyError> {
    for target in &topology.targets {
        let roots = service_roots
            .get(&target.service)
            .cloned()
            .unwrap_or_default();
        let density_is_valid = roots
            .values()
            .all(|count| *count <= target.placement.maximum_members_per_root);
        let members = roots.values().try_fold(0_u32, |total, count| {
            total
                .checked_add(*count)
                .ok_or(InitialPlacementPolicyError::CountOverflow {
                    subject: "Fleet-service member",
                })
        })?;
        let required_roots = members.min(target.placement.minimum_distinct_roots) as usize;
        if !density_is_valid || roots.len() < required_roots {
            return Err(InitialPlacementPolicyError::ServicePlacementPolicy {
                service: target.service.clone(),
            });
        }
    }
    Ok(())
}