canic-installer 0.24.1

Published installer and release-set tooling for Canic downstream 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
use crate::release_set::{
    config_path, configured_release_roles, dfx_call, dfx_root, emit_root_release_set_manifest,
    load_root_release_set_manifest, resolve_artifact_root, resume_root_bootstrap,
    root_release_set_manifest_path, stage_root_release_set, workspace_root,
};
use canic_core::protocol;
use serde::Deserialize;
use serde_json::Value;
use std::{
    env,
    path::Path,
    process::Command,
    thread,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

///
/// InstallRootOptions
///

#[derive(Clone, Debug)]
pub struct InstallRootOptions {
    pub root_canister: String,
    pub network: String,
    pub ready_timeout_seconds: u64,
}

///
/// BootstrapStatusSnapshot
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
struct BootstrapStatusSnapshot {
    ready: bool,
    phase: String,
    last_error: Option<String>,
}

///
/// InstallTimingSummary
///

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct InstallTimingSummary {
    create_canisters: Duration,
    build_all: Duration,
    emit_manifest: Duration,
    fabricate_cycles: Duration,
    install_root: Duration,
    stage_release_set: Duration,
    resume_bootstrap: Duration,
    wait_ready: Duration,
}

const LOCAL_ROOT_TARGET_CYCLES: u128 = 9_000_000_000_000_000;

impl InstallRootOptions {
    // Resolve the current local-root install options from args and environment.
    #[must_use]
    pub fn from_env_and_args() -> Self {
        Self {
            root_canister: env::args()
                .nth(1)
                .or_else(|| env::var("ROOT_CANISTER").ok())
                .unwrap_or_else(|| "root".to_string()),
            network: env::var("DFX_NETWORK").unwrap_or_else(|_| "local".to_string()),
            ready_timeout_seconds: env::var("READY_TIMEOUT_SECONDS")
                .ok()
                .and_then(|value| value.parse::<u64>().ok())
                .unwrap_or(120),
        }
    }
}

// Execute the local thin-root install flow against an already running replica.
pub fn install_root(options: InstallRootOptions) -> Result<(), Box<dyn std::error::Error>> {
    let workspace_root = workspace_root()?;
    let dfx_root = dfx_root()?;
    let total_started_at = Instant::now();
    let mut timings = InstallTimingSummary::default();

    println!("Installing root against DFX_NETWORK={}", options.network);
    require_dfx_running(&options.network)?;
    let mut create = Command::new("dfx");
    create
        .current_dir(&dfx_root)
        .args(["canister", "create", "--all", "-qq"]);
    let create_started_at = Instant::now();
    run_command(&mut create)?;
    timings.create_canisters = create_started_at.elapsed();

    let build_targets = local_install_build_targets(&workspace_root, &options.root_canister)?;
    let build_session_id = install_build_session_id();
    let build_started_at = Instant::now();
    run_dfx_build_targets(&dfx_root, &build_targets, &build_session_id)?;
    timings.build_all = build_started_at.elapsed();

    let emit_manifest_started_at = Instant::now();
    let manifest_path =
        emit_root_release_set_manifest(&workspace_root, &dfx_root, &options.network)?;
    timings.emit_manifest = emit_manifest_started_at.elapsed();

    timings.fabricate_cycles =
        maybe_fabricate_local_cycles(&dfx_root, &options.root_canister, &options.network)?;

    let mut install = Command::new("dfx");
    install.current_dir(&dfx_root).args([
        "canister",
        "install",
        &options.root_canister,
        "--mode=reinstall",
        "-y",
        "--argument",
        "(variant { Prime })",
    ]);
    let install_started_at = Instant::now();
    run_command(&mut install)?;
    timings.install_root = install_started_at.elapsed();

    let artifact_root = resolve_artifact_root(&dfx_root, &options.network)?;
    let manifest =
        load_root_release_set_manifest(&root_release_set_manifest_path(&artifact_root)?)?;
    assert_eq!(
        manifest_path,
        root_release_set_manifest_path(&artifact_root)?
    );
    let stage_started_at = Instant::now();
    stage_root_release_set(&dfx_root, &options.root_canister, &manifest)?;
    timings.stage_release_set = stage_started_at.elapsed();
    let resume_started_at = Instant::now();
    resume_root_bootstrap(&options.root_canister)?;
    timings.resume_bootstrap = resume_started_at.elapsed();
    let ready_started_at = Instant::now();
    let ready_result = wait_for_root_ready(&options.root_canister, options.ready_timeout_seconds);
    timings.wait_ready = ready_started_at.elapsed();
    if let Err(err) = ready_result {
        print_install_timing_summary(&timings, total_started_at.elapsed());
        return Err(err);
    }

    print_install_timing_summary(&timings, total_started_at.elapsed());
    println!("Root installed successfully");
    println!(
        "Smoke check: dfx canister call {} canic_ready",
        options.root_canister
    );
    Ok(())
}

// Resolve the local install build set from the root canister plus the
// configured ordinary roles owned by the root subnet.
fn local_install_build_targets(
    workspace_root: &Path,
    root_canister: &str,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
    let mut targets = vec![root_canister.to_string()];
    targets.extend(configured_release_roles(&config_path(workspace_root))?);
    Ok(targets)
}

// Run one `dfx build <canister>` call per configured local install target.
fn run_dfx_build_targets(
    dfx_root: &Path,
    targets: &[String],
    build_session_id: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    for target in targets {
        let mut command = dfx_build_target_command(dfx_root, target, build_session_id);
        run_command(&mut command)?;
    }

    Ok(())
}

// Spawn one local `dfx build <canister>` step without overriding the caller's
// selected build profile environment.
fn dfx_build_target_command(dfx_root: &Path, target: &str, build_session_id: &str) -> Command {
    let mut command = Command::new("dfx");
    command
        .current_dir(dfx_root)
        .env("CANIC_BUILD_CONTEXT_SESSION", build_session_id)
        .args(["build", "-qq", target]);
    command
}

fn install_build_session_id() -> String {
    let unique = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| duration.as_nanos());
    format!("install-root-{}-{unique}", std::process::id())
}

// Top up local root cycles only when the current balance is below the target floor.
fn maybe_fabricate_local_cycles(
    dfx_root: &Path,
    root_canister: &str,
    network: &str,
) -> Result<Duration, Box<dyn std::error::Error>> {
    if network != "local" {
        return Ok(Duration::ZERO);
    }

    let current_balance = root_cycle_balance(dfx_root, root_canister)?;
    let Some(fabricate_cycles) = required_local_cycle_topup(current_balance) else {
        println!(
            "Skipping local cycle fabrication for {root_canister}; balance {} already meets target {}",
            format_cycles(current_balance),
            format_cycles(LOCAL_ROOT_TARGET_CYCLES)
        );
        return Ok(Duration::ZERO);
    };

    println!(
        "Fabricating {} cycles locally for {root_canister} to reach target {} (current balance {})",
        format_cycles(fabricate_cycles),
        format_cycles(LOCAL_ROOT_TARGET_CYCLES),
        format_cycles(current_balance)
    );

    let mut fabricate = Command::new("dfx");
    fabricate.current_dir(dfx_root);
    fabricate.args([
        "ledger",
        "fabricate-cycles",
        "--canister",
        root_canister,
        "--cycles",
        &fabricate_cycles.to_string(),
    ]);
    let fabricate_started_at = Instant::now();
    let _ = run_command_allow_failure(&mut fabricate)?;

    Ok(fabricate_started_at.elapsed())
}

// Read the current root canister cycle balance from `dfx canister status`.
fn root_cycle_balance(
    dfx_root: &Path,
    root_canister: &str,
) -> Result<u128, Box<dyn std::error::Error>> {
    let output = Command::new("dfx")
        .current_dir(dfx_root)
        .args(["canister", "status", root_canister])
        .output()?;
    if !output.status.success() {
        return Err(format!("dfx canister status failed: {}", output.status).into());
    }

    let stdout = String::from_utf8(output.stdout)?;
    parse_canister_status_cycles(&stdout)
        .ok_or_else(|| "could not parse cycle balance from `dfx canister status` output".into())
}

// Parse the cycle balance from the human-readable `dfx canister status` output.
fn parse_canister_status_cycles(status_output: &str) -> Option<u128> {
    status_output
        .lines()
        .find_map(parse_canister_status_balance_line)
}

fn parse_canister_status_balance_line(line: &str) -> Option<u128> {
    let (label, value) = line.trim().split_once(':')?;
    let label = label.trim().to_ascii_lowercase();
    if label != "balance" && label != "cycle balance" {
        return None;
    }

    let digits = value
        .chars()
        .filter(char::is_ascii_digit)
        .collect::<String>();
    if digits.is_empty() {
        return None;
    }

    digits.parse::<u128>().ok()
}

// Return the local top-up delta needed to bring root up to the target cycle floor.
fn required_local_cycle_topup(current_balance: u128) -> Option<u128> {
    (current_balance < LOCAL_ROOT_TARGET_CYCLES)
        .then_some(LOCAL_ROOT_TARGET_CYCLES.saturating_sub(current_balance))
        .filter(|cycles| *cycles > 0)
}

fn format_cycles(value: u128) -> String {
    let digits = value.to_string();
    let mut out = String::with_capacity(digits.len() + (digits.len().saturating_sub(1) / 3));
    for (index, ch) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index).is_multiple_of(3) {
            out.push('_');
        }
        out.push(ch);
    }
    out
}

// Fail fast unless the requested DFX replica is already running.
fn require_dfx_running(network: &str) -> Result<(), Box<dyn std::error::Error>> {
    let result = Command::new("dfx").args(["ping", network]).output()?;
    if result.status.success() {
        return Ok(());
    }

    Err(format!(
        "dfx replica is not running for network '{network}'\nStart the target replica externally and rerun."
    )
    .into())
}

// Wait until root reports ready, printing periodic progress and diagnostics.
fn wait_for_root_ready(
    root_canister: &str,
    timeout_seconds: u64,
) -> Result<(), Box<dyn std::error::Error>> {
    let start = std::time::Instant::now();
    let mut next_report = 0_u64;

    println!("Waiting for {root_canister} to report canic_ready (timeout {timeout_seconds}s)");

    loop {
        if root_ready(root_canister)? {
            println!(
                "{root_canister} reported canic_ready after {}s",
                start.elapsed().as_secs()
            );
            return Ok(());
        }

        if let Some(status) = root_bootstrap_status(root_canister)?
            && let Some(last_error) = status.last_error.as_deref()
        {
            eprintln!(
                "root bootstrap reported failure during phase '{}' : {}",
                status.phase, last_error
            );
            eprintln!("Diagnostic: dfx canister call {root_canister} canic_bootstrap_status");
            print_raw_call(root_canister, protocol::CANIC_BOOTSTRAP_STATUS);
            eprintln!("Diagnostic: dfx canister call {root_canister} canic_subnet_registry");
            print_raw_call(root_canister, "canic_subnet_registry");
            eprintln!(
                "Diagnostic: dfx canister call {root_canister} canic_wasm_store_bootstrap_debug"
            );
            print_raw_call(root_canister, "canic_wasm_store_bootstrap_debug");
            eprintln!("Diagnostic: dfx canister call {root_canister} canic_wasm_store_overview");
            print_raw_call(root_canister, "canic_wasm_store_overview");
            eprintln!("Diagnostic: dfx canister call {root_canister} canic_log");
            print_recent_root_logs(root_canister);
            return Err(format!(
                "root bootstrap failed during phase '{}' : {}",
                status.phase, last_error
            )
            .into());
        }

        let elapsed = start.elapsed().as_secs();
        if elapsed >= timeout_seconds {
            eprintln!("root did not report canic_ready within {timeout_seconds}s");
            eprintln!("Diagnostic: dfx canister call {root_canister} canic_bootstrap_status");
            print_raw_call(root_canister, protocol::CANIC_BOOTSTRAP_STATUS);
            eprintln!("Diagnostic: dfx canister call {root_canister} canic_subnet_registry");
            print_raw_call(root_canister, "canic_subnet_registry");
            eprintln!(
                "Diagnostic: dfx canister call {root_canister} canic_wasm_store_bootstrap_debug"
            );
            print_raw_call(root_canister, "canic_wasm_store_bootstrap_debug");
            eprintln!("Diagnostic: dfx canister call {root_canister} canic_wasm_store_overview");
            print_raw_call(root_canister, "canic_wasm_store_overview");
            eprintln!("Diagnostic: dfx canister call {root_canister} canic_log");
            print_recent_root_logs(root_canister);
            return Err("root did not become ready".into());
        }

        if elapsed >= next_report {
            println!("Still waiting for {root_canister} canic_ready ({elapsed}s elapsed)");
            if let Some(status) = root_bootstrap_status(root_canister)? {
                match status.last_error.as_deref() {
                    Some(last_error) => println!(
                        "Current bootstrap status: phase={} ready={} error={}",
                        status.phase, status.ready, last_error
                    ),
                    None => println!(
                        "Current bootstrap status: phase={} ready={}",
                        status.phase, status.ready
                    ),
                }
            }
            if let Ok(registry_json) =
                dfx_call(root_canister, "canic_subnet_registry", None, Some("json"))
            {
                println!("Current subnet registry roles:");
                println!("  {}", registry_roles(&registry_json));
            }
            next_report = elapsed + 5;
        }

        thread::sleep(Duration::from_secs(1));
    }
}

// Return true once root reports `canic_ready == true`.
fn root_ready(root_canister: &str) -> Result<bool, Box<dyn std::error::Error>> {
    let output = dfx_call(root_canister, "canic_ready", None, Some("json"))?;
    let data = serde_json::from_str::<Value>(&output)?;
    Ok(parse_root_ready_value(&data))
}

// Return the current root bootstrap diagnostic state when the query is available.
fn root_bootstrap_status(
    root_canister: &str,
) -> Result<Option<BootstrapStatusSnapshot>, Box<dyn std::error::Error>> {
    let output = match dfx_call(
        root_canister,
        protocol::CANIC_BOOTSTRAP_STATUS,
        None,
        Some("json"),
    ) {
        Ok(output) => output,
        Err(err) => {
            let message = err.to_string();
            if message.contains("has no query method")
                || message.contains("method not found")
                || message.contains("Canister has no query method")
            {
                return Ok(None);
            }
            return Err(err);
        }
    };
    let data = serde_json::from_str::<Value>(&output)?;
    Ok(parse_bootstrap_status_value(&data))
}

// Accept both plain-bool and wrapped-result JSON shapes from `dfx --output json`.
fn parse_root_ready_value(data: &Value) -> bool {
    matches!(data, Value::Bool(true)) || matches!(data.get("Ok"), Some(Value::Bool(true)))
}

fn parse_bootstrap_status_value(data: &Value) -> Option<BootstrapStatusSnapshot> {
    serde_json::from_value::<BootstrapStatusSnapshot>(data.clone())
        .ok()
        .or_else(|| {
            data.get("Ok")
                .cloned()
                .and_then(|ok| serde_json::from_value::<BootstrapStatusSnapshot>(ok).ok())
        })
}

fn print_install_timing_summary(timings: &InstallTimingSummary, total: Duration) {
    println!("Install timing summary:");
    println!("{:<20} {:>10}", "phase", "elapsed");
    println!("{:<20} {:>10}", "--------------------", "----------");
    print_timing_row("create_canisters", timings.create_canisters);
    print_timing_row("build_all", timings.build_all);
    print_timing_row("emit_manifest", timings.emit_manifest);
    print_timing_row("fabricate_cycles", timings.fabricate_cycles);
    print_timing_row("install_root", timings.install_root);
    print_timing_row("stage_release_set", timings.stage_release_set);
    print_timing_row("resume_bootstrap", timings.resume_bootstrap);
    print_timing_row("wait_ready", timings.wait_ready);
    print_timing_row("total", total);
}

fn print_timing_row(label: &str, duration: Duration) {
    println!("{label:<20} {:>9.2}s", duration.as_secs_f64());
}

// Print recent structured root log entries without raw byte dumps.
fn print_recent_root_logs(root_canister: &str) {
    let page_args = r"(null, null, null, record { limit = 8; offset = 0 })";
    let Ok(logs_json) = dfx_call(root_canister, "canic_log", Some(page_args), Some("json")) else {
        return;
    };
    let Ok(data) = serde_json::from_str::<Value>(&logs_json) else {
        return;
    };
    let entries = data
        .get("Ok")
        .and_then(|ok| ok.get("entries"))
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();

    if entries.is_empty() {
        println!("  <no runtime log entries>");
        return;
    }

    for entry in entries.iter().rev() {
        let level = entry.get("level").and_then(Value::as_str).unwrap_or("Info");
        let topic = entry.get("topic").and_then(Value::as_str).unwrap_or("");
        let message = entry
            .get("message")
            .and_then(Value::as_str)
            .unwrap_or("")
            .replace('\n', "\\n");
        let topic_prefix = if topic.is_empty() {
            String::new()
        } else {
            format!("[{topic}] ")
        };
        println!("  {level} {topic_prefix}{message}");
    }
}

// Render the current subnet registry roles from one JSON response.
fn registry_roles(registry_json: &str) -> String {
    serde_json::from_str::<Value>(registry_json)
        .ok()
        .and_then(|data| {
            data.get("Ok").and_then(Value::as_array).map(|entries| {
                entries
                    .iter()
                    .filter_map(|entry| {
                        entry
                            .get("role")
                            .and_then(Value::as_str)
                            .map(str::to_string)
                    })
                    .collect::<Vec<_>>()
            })
        })
        .map_or_else(
            || "<unavailable>".to_string(),
            |roles| {
                if roles.is_empty() {
                    "<empty>".to_string()
                } else {
                    roles.join(", ")
                }
            },
        )
}

// Run one command and require a zero exit status.
fn run_command(command: &mut Command) -> Result<(), Box<dyn std::error::Error>> {
    let status = command.status()?;
    if status.success() {
        Ok(())
    } else {
        Err(format!("command failed: {status}").into())
    }
}

// Run one command and return its status without failing the caller on non-zero exit.
fn run_command_allow_failure(
    command: &mut Command,
) -> Result<std::process::ExitStatus, Box<dyn std::error::Error>> {
    Ok(command.status()?)
}

// Print one raw fallback `dfx canister call` result to stderr for diagnostics.
fn print_raw_call(root_canister: &str, method: &str) {
    let mut command = Command::new("dfx");
    if let Ok(root) = dfx_root() {
        command.current_dir(root);
    }
    let _ = command
        .args(["canister", "call", root_canister, method])
        .status();
}

#[cfg(test)]
mod tests {
    use super::{
        LOCAL_ROOT_TARGET_CYCLES, dfx_build_target_command, install_build_session_id,
        local_install_build_targets, parse_bootstrap_status_value, parse_canister_status_cycles,
        parse_root_ready_value, required_local_cycle_topup,
    };
    use serde_json::json;
    use std::{
        fs,
        path::{Path, PathBuf},
        time::{SystemTime, UNIX_EPOCH},
    };

    #[test]
    fn parse_root_ready_accepts_plain_true() {
        assert!(parse_root_ready_value(&json!(true)));
    }

    #[test]
    fn parse_root_ready_accepts_wrapped_ok_true() {
        assert!(parse_root_ready_value(&json!({ "Ok": true })));
    }

    #[test]
    fn parse_root_ready_rejects_false_shapes() {
        assert!(!parse_root_ready_value(&json!(false)));
        assert!(!parse_root_ready_value(&json!({ "Ok": false })));
        assert!(!parse_root_ready_value(&json!({ "Err": "nope" })));
    }

    #[test]
    fn parse_bootstrap_status_accepts_plain_record() {
        let status = parse_bootstrap_status_value(&json!({
            "ready": false,
            "phase": "root:init:create_canisters",
            "last_error": null
        }))
        .expect("plain bootstrap status must parse");

        assert!(!status.ready);
        assert_eq!(status.phase, "root:init:create_canisters");
        assert_eq!(status.last_error, None);
    }

    #[test]
    fn parse_bootstrap_status_accepts_wrapped_ok_record() {
        let status = parse_bootstrap_status_value(&json!({
            "Ok": {
                "ready": false,
                "phase": "failed",
                "last_error": "registry phase failed"
            }
        }))
        .expect("wrapped bootstrap status must parse");

        assert!(!status.ready);
        assert_eq!(status.phase, "failed");
        assert_eq!(status.last_error.as_deref(), Some("registry phase failed"));
    }

    #[test]
    fn parse_canister_status_cycles_accepts_balance_line() {
        let output = "\
Canister status call result for root.
Status: Running
Balance: 9_002_999_998_056_000 Cycles
Memory Size: 1_234_567 Bytes
";

        assert_eq!(
            parse_canister_status_cycles(output),
            Some(9_002_999_998_056_000)
        );
    }

    #[test]
    fn parse_canister_status_cycles_accepts_cycle_balance_line() {
        let output = "\
Canister status call result for root.
Cycle balance: 12_345 Cycles
";

        assert_eq!(parse_canister_status_cycles(output), Some(12_345));
    }

    #[test]
    fn required_local_cycle_topup_skips_when_balance_already_meets_target() {
        assert_eq!(required_local_cycle_topup(LOCAL_ROOT_TARGET_CYCLES), None);
        assert_eq!(
            required_local_cycle_topup(LOCAL_ROOT_TARGET_CYCLES + 1_000),
            None
        );
    }

    #[test]
    fn required_local_cycle_topup_returns_missing_delta_only() {
        assert_eq!(
            required_local_cycle_topup(3_000_000_000_000),
            Some(8_997_000_000_000_000)
        );
    }

    #[test]
    fn dfx_build_command_targets_one_canister_per_call() {
        let command = dfx_build_target_command(
            Path::new("/tmp/canic-dfx-root"),
            "user_hub",
            "install-root-test",
        );

        assert_eq!(command.get_program(), "dfx");
        assert_eq!(
            command
                .get_args()
                .map(|arg| arg.to_string_lossy().into_owned())
                .collect::<Vec<_>>(),
            ["build", "-qq", "user_hub"]
        );
        assert_eq!(
            command
                .get_current_dir()
                .map(|path| path.to_string_lossy().into_owned()),
            Some("/tmp/canic-dfx-root".to_string())
        );
        assert!(
            command
                .get_envs()
                .any(|(key, value)| key == "CANIC_BUILD_CONTEXT_SESSION" && value.is_some()),
            "dfx build must carry the shared build-session marker"
        );
    }

    #[test]
    fn install_build_session_id_is_prefixed_for_logs() {
        let session_id = install_build_session_id();
        assert!(session_id.starts_with("install-root-"));
    }

    #[test]
    fn local_install_build_targets_use_root_subnet_release_roles_only() {
        let workspace_root = write_temp_workspace_config(
            r#"
[subnets.prime.canisters.root]
kind = "root"

[subnets.prime.canisters.project_registry]
kind = "singleton"

[subnets.prime.canisters.user_hub]
kind = "singleton"

[subnets.extra.canisters.oracle_pokemon]
kind = "singleton"
"#,
        );

        let targets =
            local_install_build_targets(&workspace_root, "root").expect("targets must resolve");

        assert_eq!(
            targets,
            vec![
                "root".to_string(),
                "project_registry".to_string(),
                "user_hub".to_string()
            ]
        );
    }

    fn write_temp_workspace_config(config_source: &str) -> PathBuf {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock must be monotonic enough for test temp dir")
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "canic-install-root-test-{}-{unique}",
            std::process::id()
        ));
        fs::create_dir_all(root.join("canisters")).expect("temp canisters dir must be created");
        fs::write(root.join("canisters/canic.toml"), config_source)
            .expect("temp canic.toml must be written");
        root
    }
}