zc2 0.0.47

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
//! One backend choice for every container path (zc#578).
//!
//! The Atelier job CLI, the deploy / Spaces `ContainerRuntime` and the share
//! workers used to run `docker` directly, whatever [`super::select`] said. They
//! now ask this module, which resolves the active backend ONCE per process
//! (preference -> probe -> chosen, every reason kept for `zc doctor`) and turns
//! a Docker-shaped argv into the real command line:
//!
//! | chosen | the command |
//! |---|---|
//! | Docker | `docker <args>`, byte for byte |
//! | LXC | `<incus\|lxc> exec zakuro-sandbox -- nerdctl <args>` (nerdctl takes the docker flags for run, stop, rm, inspect, logs, pull, ps) |
//!
//! A host with neither is an error naming what to install, never a silent
//! host process; Docker used directly is a choice (`ZAKURO_RUNTIME_PREFER=docker`
//! or no Incus), reported by `zc doctor`.
//!
//! A `scan` test (`no_container_engine_is_spawned_outside_the_sandbox_layer`)
//! fails when a `Command::new("docker")` appears outside this module's layer
//! and its allow-list, so a new path cannot skip the choice again.

use std::process::Command;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use super::docker::{DockerCli, DockerRuntime};
use super::lxc::{self, LxcRuntime};
use super::{Probe, Runtime, RuntimeKind, Selection};

/// How a Docker-shaped argv becomes a process.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Engine {
    /// `docker …`.
    Docker,
    /// `<cli> exec <instance> -- nerdctl …` into the shared sandbox (T1).
    Nerdctl { cli: String, instance: String },
    /// `limactl shell --workdir / <instance> -- sudo nerdctl …` inside the
    /// zc-owned Lima VM (macOS).
    Lima { limactl: String, instance: String },
    /// `colima ssh -p <profile> -- docker …` inside the zc-created Colima
    /// profile (macOS). Never the host's Docker CLI or context.
    Colima { colima: String, profile: String },
}

impl Engine {
    /// The engine a [`Selection`] chose; `None` when nothing isolating is
    /// available. Lima and Colima are reached inside their VM, never through
    /// the host's Docker (that would put the job on Docker Desktop).
    pub fn from_selection(sel: &Selection, lxc_cli: &str) -> Option<Engine> {
        Some(match sel.chosen? {
            RuntimeKind::Lxc => Engine::Nerdctl {
                cli: lxc_cli.to_string(),
                instance: lxc::SANDBOX.to_string(),
            },
            RuntimeKind::Lima => Engine::Lima {
                limactl: super::lima::binary(),
                instance: super::lima::LimaRuntime::shell().instance().to_string(),
            },
            RuntimeKind::Colima => Engine::Colima {
                colima: super::colima::ColimaShell::binary(),
                profile: super::colima::ColimaRuntime::shell().profile().to_string(),
            },
            _ => Engine::Docker,
        })
    }

    /// `(program, args)` running `args` (a docker argv WITHOUT the leading
    /// `docker`). A leading `--config <dir>` (a private registry-login dir)
    /// becomes `DOCKER_CONFIG` for nerdctl, which has no such flag.
    pub fn invocation(&self, args: &[String]) -> (String, Vec<String>) {
        match self {
            Engine::Docker => ("docker".to_string(), args.to_vec()),
            Engine::Nerdctl { cli, instance } => {
                let mut a = vec!["exec".to_string(), instance.clone(), "--".to_string()];
                a.extend(nerdctl_tail(args));
                (cli.clone(), a)
            }
            Engine::Lima { limactl, instance } => {
                let mut a = ["shell", "--workdir", "/", instance.as_str(), "--", "sudo"]
                    .map(String::from)
                    .to_vec();
                a.extend(nerdctl_tail(args));
                (limactl.clone(), a)
            }
            Engine::Colima { colima, profile } => {
                let mut a = ["ssh", "-p", profile.as_str(), "--", "docker"]
                    .map(String::from)
                    .to_vec();
                a.extend(args.iter().cloned());
                (colima.clone(), a)
            }
        }
    }

    pub fn is_lxc(&self) -> bool {
        matches!(self, Engine::Nerdctl { .. })
    }

    pub fn describe(&self) -> String {
        match self {
            Engine::Docker => "docker".to_string(),
            Engine::Nerdctl { cli, instance } => format!("{cli} sandbox {instance} (nerdctl)"),
            Engine::Lima { instance, .. } => format!("Lima VM {instance} (nerdctl)"),
            Engine::Colima { profile, .. } => {
                format!("Colima profile {profile} (docker in the VM)")
            }
        }
    }
}

/// `nerdctl <args>` as the words after the "run this in the sandbox" prefix.
/// A leading `--config <dir>` (a private registry-login dir) becomes
/// `DOCKER_CONFIG` for nerdctl, which has no such flag.
fn nerdctl_tail(args: &[String]) -> Vec<String> {
    let mut a = Vec::new();
    let rest = match args {
        [flag, dir, rest @ ..] if flag == "--config" => {
            a.push("env".into());
            a.push(format!("DOCKER_CONFIG={dir}"));
            rest
        }
        _ => args,
    };
    match detached_rm_run(rest) {
        // nerdctl refuses `run -d --rm` ("flags -d and --rm cannot be
        // specified together"). Run it without `--rm` and remove a stale
        // container of the same name first, which is what `--rm` left behind
        // for Docker: the name is free again.
        Some((name, run)) => {
            a.extend(
                [
                    "sh",
                    "-c",
                    r#"nerdctl rm -f "$1" >/dev/null 2>&1; shift; exec nerdctl "$@""#,
                    "sh",
                ]
                .map(String::from),
            );
            a.push(name);
            a.extend(run);
        }
        None => {
            a.push("nerdctl".into());
            a.extend(rest.iter().cloned());
        }
    }
    a
}

/// A detached `run` that also asks for `--rm`: its container name and the
/// argv without `--rm`. `None` for anything else.
fn detached_rm_run(args: &[String]) -> Option<(String, Vec<String>)> {
    if args.first().map(String::as_str) != Some("run") {
        return None;
    }
    let detached = args.iter().any(|a| a == "-d" || a == "--detach");
    let rm = args.iter().any(|a| a == "--rm");
    if !(detached && rm) {
        return None;
    }
    let name = args
        .iter()
        .position(|a| a == "--name")
        .and_then(|i| args.get(i + 1))?
        .clone();
    Some((
        name,
        args.iter().filter(|a| *a != "--rm").cloned().collect(),
    ))
}

/// The outcome of the once-per-process backend choice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolved {
    pub selection: Selection,
    /// The SHARED tier (T1: deployments, share workers, Atelier jobs).
    pub engine: Option<Engine>,
    /// Why the shared engine was chosen (or why there is none).
    pub shared_reason: String,
    /// The JOB tier (T2) is an ephemeral LXC instance per job: an LXC CLI
    /// probed OK. Otherwise foreign jobs run on the shared engine.
    pub jobs_per_instance: bool,
    pub jobs_reason: String,
}

/// The shared-tier choice with its reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Choice {
    pub engine: Option<Engine>,
    pub reason: String,
}

/// Did the owner explicitly ask for the LXC sandbox as the shared tier?
/// `ZAKURO_SANDBOX_SHARED=lxc`, or `ZAKURO_RUNTIME_PREFER` set and listing
/// `lxc` before `docker`. Never the default: a host that has LXD installed
/// keeps running its long-lived services on Docker until the owner opts in.
pub fn shared_lxc_requested(get: &dyn Fn(&str) -> Option<String>) -> Option<String> {
    let clean = |k: &str| {
        get(k)
            .map(|v| v.trim().to_ascii_lowercase())
            .filter(|v| !v.is_empty())
    };
    if clean("ZAKURO_SANDBOX_SHARED").as_deref() == Some("lxc") {
        return Some("ZAKURO_SANDBOX_SHARED=lxc".to_string());
    }
    let prefer = clean("ZAKURO_RUNTIME_PREFER")?;
    let first = prefer
        .split(',')
        .filter_map(RuntimeKind::parse)
        .find(|k| matches!(k, RuntimeKind::Lxc | RuntimeKind::Docker))?;
    (first == RuntimeKind::Lxc).then(|| format!("ZAKURO_RUNTIME_PREFER={prefer}"))
}

/// The shared tier on Linux, from the two probes: Docker when it probes OK,
/// unless the owner asked for LXC ([`shared_lxc_requested`]); LXC when Docker
/// is absent (the only isolating option, not a downgrade); else none.
pub fn resolve_shared(
    get: &dyn Fn(&str) -> Option<String>,
    lxc_probe: &Probe,
    docker_probe: &Probe,
    lxc_cli: &str,
) -> Choice {
    let lxc = || Engine::Nerdctl {
        cli: lxc_cli.to_string(),
        instance: lxc::SANDBOX.to_string(),
    };
    let ok = |e: Engine, why: String| Choice {
        engine: Some(e),
        reason: why,
    };
    if let Some(ask) = shared_lxc_requested(get) {
        if lxc_probe.available {
            return ok(lxc(), format!("LXC sandbox, asked for by {ask}"));
        }
        if docker_probe.available {
            return ok(
                Engine::Docker,
                format!("Docker ({ask} asked for LXC, but: {})", lxc_probe.detail),
            );
        }
    } else {
        if docker_probe.available {
            return ok(
                Engine::Docker,
                "Docker (default; opt in to the LXC sandbox with ZAKURO_SANDBOX_SHARED=lxc)".into(),
            );
        }
        if lxc_probe.available {
            return ok(
                lxc(),
                format!(
                    "LXC sandbox (Docker is unavailable: {})",
                    docker_probe.detail
                ),
            );
        }
    }
    Choice {
        engine: None,
        reason: no_backend_message(&Selection {
            chosen: None,
            tried: vec![lxc_probe.clone(), docker_probe.clone()],
        }),
    }
}

/// The job tier: an ephemeral instance per job when an LXC CLI probes OK and
/// `ZAKURO_SANDBOX_ISOLATION` is not `shared`; else the shared engine (Docker
/// with limits), reported as the fallback.
pub fn resolve_jobs(
    get: &dyn Fn(&str) -> Option<String>,
    lxc_probe: &Probe,
    shared: &Choice,
) -> (bool, String) {
    let iso = get("ZAKURO_SANDBOX_ISOLATION")
        .map(|v| v.trim().to_ascii_lowercase())
        .filter(|v| !v.is_empty());
    match iso.as_deref() {
        Some("shared") => (
            false,
            "shared engine (ZAKURO_SANDBOX_ISOLATION=shared)".to_string(),
        ),
        None | Some("job") if lxc_probe.available => (
            true,
            format!("ephemeral LXC instance per job ({})", lxc_probe.detail),
        ),
        None | Some("job") => (
            false,
            format!(
                "FALLBACK: shared engine with limits, no per-job instance ({})",
                lxc_probe.detail
            ),
        ),
        Some(other) => (
            false,
            format!("ZAKURO_SANDBOX_ISOLATION={other:?} is not one of job, shared; using the shared engine ({})", shared.reason),
        ),
    }
}

/// Why no container can be started, with what to install and the explicit
/// escape (`ZAKURO_SHARE_RUNTIME=host`, share workers only).
pub fn no_backend_message(sel: &Selection) -> String {
    let mut m = String::from("no isolating container backend on this host");
    let reasons: Vec<String> = sel
        .tried
        .iter()
        .map(|p| format!("{}: {}", p.kind.as_str(), p.detail))
        .collect();
    if !reasons.is_empty() {
        m.push_str(&format!(" ({})", reasons.join("; ")));
    }
    m.push_str(
        ". Install Incus (`apt install incus && incus admin init --minimal`; LXD works too) \
         or Docker, or run on the host with no isolation: ZAKURO_SHARE_RUNTIME=host \
         (owner's own work only)",
    );
    m
}

/// How long a failed resolution is reused before the backends are probed again
/// (a successful one is kept for the process: the agent restarts to change it).
const RETRY_AFTER: Duration = Duration::from_secs(30);

fn cache() -> &'static Mutex<Option<(Instant, Arc<Resolved>)>> {
    static C: Mutex<Option<(Instant, Arc<Resolved>)>> = Mutex::new(None);
    &C
}

/// The active backend, resolved on first use. Probes through
/// [`super::probe_host`] (the same preference and probes `zc doctor` shows).
pub fn active() -> Arc<Resolved> {
    let mut g = cache().lock().unwrap_or_else(|p| p.into_inner());
    if let Some((at, r)) = g.as_ref() {
        if r.engine.is_some() || at.elapsed() < RETRY_AFTER {
            return r.clone();
        }
    }
    let r = Arc::new(resolve_host(&|k| std::env::var(k).ok()));
    *g = Some((Instant::now(), r.clone()));
    r
}

/// Docker through the deploy reconciler's own `docker version` probe (the
/// same reasons and next step `zc doctor` shows).
fn docker_probe() -> Probe {
    let p = crate::broker::deploy::runtime_probe();
    let detail = match p.next_step() {
        Some(step) => format!("{} ({step})", p.detail),
        None => p.detail.clone(),
    };
    Probe {
        kind: RuntimeKind::Docker,
        available: p.available,
        detail,
    }
}

/// Probe this host and resolve both tiers. Linux: the two probes feed
/// [`resolve_shared`] and [`resolve_jobs`]. Elsewhere: the preference-ordered
/// [`super::probe_host`] (Lima, Colima, Docker) is the shared tier, and there is
/// no per-job instance.
fn resolve_host(get: &dyn Fn(&str) -> Option<String>) -> Resolved {
    if !cfg!(target_os = "linux") {
        let selection = super::probe_host();
        let engine = Engine::from_selection(&selection, lxc::cli_binary());
        let reason = match &engine {
            Some(e) => format!("{} (first available in the preference order)", e.describe()),
            None => no_backend_message(&selection),
        };
        return Resolved {
            selection,
            engine,
            shared_reason: reason,
            jobs_per_instance: false,
            jobs_reason: "no per-job instance off Linux; shared engine with limits".into(),
        };
    }
    let lxc_probe = lxc::LxcRuntime::shell().probe();
    let docker_probe = docker_probe();
    let shared = resolve_shared(get, &lxc_probe, &docker_probe, lxc::cli_binary());
    let (jobs_per_instance, jobs_reason) = resolve_jobs(get, &lxc_probe, &shared);
    let chosen = shared.engine.as_ref().map(|e| {
        if e.is_lxc() {
            RuntimeKind::Lxc
        } else {
            RuntimeKind::Docker
        }
    });
    Resolved {
        selection: Selection {
            chosen,
            tried: vec![lxc_probe, docker_probe],
        },
        engine: shared.engine,
        shared_reason: shared.reason,
        jobs_per_instance,
        jobs_reason,
    }
}

/// Is there a backend to run containers in?
pub fn available() -> bool {
    active().engine.is_some()
}

/// The sandbox instance exists (T1 reads nothing from one that was never made).
pub fn sandbox_exists() -> bool {
    matches!(LxcRuntime::shell().state(), Ok(Some(_)))
}

/// Make the T1 sandbox ready (created, budgeted, containerd inside): once per
/// process, and again every [`REENSURE`] so a sandbox deleted by hand comes
/// back. Serialised across processes.
fn prepare(engine: &Engine) -> Result<(), String> {
    const REENSURE: Duration = Duration::from_secs(300);
    if matches!(engine, Engine::Docker) {
        return Ok(());
    }
    static LAST: Mutex<Option<Instant>> = Mutex::new(None);
    let mut last = LAST.lock().unwrap_or_else(|p| p.into_inner());
    if last.is_some_and(|t| t.elapsed() < REENSURE) {
        return Ok(());
    }
    let _g = super::lock::provision_lock(Duration::from_secs(900))?;
    match engine {
        Engine::Nerdctl { .. } => LxcRuntime::shell().ensure()?,
        Engine::Lima { .. } => super::lima::LimaRuntime::shell().ensure()?,
        Engine::Colima { .. } => super::colima::ColimaRuntime::shell().ensure()?,
        Engine::Docker => {}
    }
    *last = Some(Instant::now());
    Ok(())
}

/// A ready-to-spawn command running the docker-shaped `args` on the active
/// backend. `Err` names why nothing can run.
pub fn command(args: &[String]) -> Result<Command, String> {
    let r = active();
    let engine = r
        .engine
        .as_ref()
        .ok_or_else(|| no_backend_message(&r.selection))?;
    prepare(engine)?;
    Ok(build(engine, args))
}

/// [`command`] without creating or touching the sandbox: for reads that must
/// not provision anything (`Ok(None)` when the sandbox does not exist).
pub fn command_if_present(args: &[String]) -> Result<Option<Command>, String> {
    let r = active();
    let engine = r
        .engine
        .as_ref()
        .ok_or_else(|| no_backend_message(&r.selection))?;
    if engine.is_lxc() && !sandbox_exists() {
        return Ok(None);
    }
    Ok(Some(build(engine, args)))
}

fn build(engine: &Engine, args: &[String]) -> Command {
    let (prog, rest) = engine.invocation(args);
    let mut c = Command::new(prog);
    c.args(rest);
    c
}

/// Run the docker-shaped `args`; trimmed stdout, or trimmed stderr as the
/// error. The shape of the old per-module `docker()` helpers.
pub fn run(args: &[&str]) -> Result<String, String> {
    let argv: Vec<String> = args.iter().map(|a| a.to_string()).collect();
    let out = command(&argv)?
        .output()
        .map_err(|e| format!("container runtime not available: {e}"))?;
    if out.status.success() {
        Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
    } else {
        let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
        Err(if stderr.is_empty() {
            format!(
                "container command {} failed",
                args.first().copied().unwrap_or("")
            )
        } else {
            stderr
        })
    }
}

/// [`DockerCli`] on the active backend: argv `["docker", …]` as the
/// [`DockerRuntime`] builds it.
pub struct EngineShell;

impl DockerCli for EngineShell {
    fn run(&self, argv: &[String]) -> Result<String, String> {
        let rest = match argv.split_first() {
            Some((first, rest)) if first == "docker" => rest,
            _ => argv,
        };
        let out = command(rest)?
            .output()
            .map_err(|e| format!("container runtime not available: {e}"))?;
        if out.status.success() {
            Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
        } else {
            Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
        }
    }
}

/// The [`Runtime`] of the active backend: the LXC sandbox backend (ports
/// proxied, mounts shared in), the Lima or Colima VM backend, or Docker.
/// `Err` when there is none.
pub fn runtime() -> Result<Arc<dyn Runtime>, String> {
    let r = active();
    match r.engine {
        Some(Engine::Nerdctl { .. }) => Ok(Arc::new(LxcRuntime::shell())),
        Some(Engine::Lima { .. }) => Ok(Arc::new(super::lima::LimaRuntime::shell())),
        Some(Engine::Colima { .. }) => Ok(Arc::new(super::colima::ColimaRuntime::shell())),
        Some(Engine::Docker) => Ok(Arc::new(DockerRuntime::new(Arc::new(EngineShell)))),
        None => Err(no_backend_message(&r.selection)),
    }
}

/// The per-job instance manager (T2), sized once from the environment.
pub fn ephemeral() -> &'static super::ephemeral::Ephemeral {
    static E: std::sync::OnceLock<super::ephemeral::Ephemeral> = std::sync::OnceLock::new();
    E.get_or_init(|| super::ephemeral::Ephemeral::from_env(&|k| std::env::var(k).ok()))
}

/// Every running workload's share of the node budget on the active backend:
/// the labelled containers (in the shared sandbox, on LXC) plus, on LXC, every
/// per-job instance's own budget key. Reads nothing from a sandbox that was
/// never created (and does not create it).
pub fn allocations() -> Result<Vec<super::Allocation>, String> {
    let lxc = active().engine.as_ref().is_some_and(|e| e.is_lxc());
    let mut all = if lxc && !sandbox_exists() {
        Vec::new()
    } else {
        let args = super::docker::allocations_args();
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        super::docker::parse_allocations(&run(&args)?)
    };
    // Per-job instances hold their share whatever the shared tier is.
    if active().jobs_per_instance {
        all.extend(ephemeral().allocations()?);
    }
    Ok(all)
}

/// Which tier a foreign job (a Spaces lease) starts in on this engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tier {
    /// A container on the active backend (Docker, or the shared sandbox).
    Shared,
    /// Its own ephemeral instance (T2). Only the LXC backend has one.
    PerJob,
}

/// [`Tier::PerJob`] when an LXC CLI probed OK and the owner did not say
/// `shared` ([`resolve_jobs`]); [`Tier::Shared`] otherwise (including when
/// there is no backend: the start itself reports that).
pub fn active_job_tier() -> Tier {
    if active().jobs_per_instance {
        Tier::PerJob
    } else {
        Tier::Shared
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn lima_and_colima_run_inside_their_vm_never_on_host_docker() {
        let run: Vec<String> = ["run", "--rm", "-d", "--name", "w1", "img"]
            .map(String::from)
            .to_vec();
        let lima = Engine::Lima {
            limactl: "/opt/homebrew/bin/limactl".into(),
            instance: "zakuro".into(),
        };
        let (p, a) = lima.invocation(&run);
        assert_eq!(p, "/opt/homebrew/bin/limactl");
        assert_eq!(
            &a[..7],
            &["shell", "--workdir", "/", "zakuro", "--", "sudo", "sh"].map(String::from)
        );
        assert!(!a.contains(&"--rm".to_string()), "{a:?}");
        let (p, a) = lima.invocation(&["ps".to_string()]);
        assert_eq!(
            (p.as_str(), a.last().unwrap().as_str()),
            ("/opt/homebrew/bin/limactl", "ps")
        );
        assert_eq!(a[a.len() - 2], "nerdctl");

        let colima = Engine::Colima {
            colima: "colima".into(),
            profile: "zakuro".into(),
        };
        let (p, a) = colima.invocation(&run);
        assert_eq!(p, "colima");
        assert_eq!(
            &a[..5],
            &["ssh", "-p", "zakuro", "--", "docker"].map(String::from)
        );
        assert_eq!(&a[5..], &run[..], "docker in the VM keeps --rm");
    }

    #[test]
    fn nerdctl_never_gets_run_with_both_d_and_rm() {
        let e = Engine::Nerdctl {
            cli: "lxc".into(),
            instance: "zakuro-sandbox".into(),
        };
        let run: Vec<String> = ["run", "--rm", "-d", "--name", "w1", "img"]
            .map(String::from)
            .to_vec();
        let (prog, a) = e.invocation(&run);
        assert_eq!(prog, "lxc");
        assert!(!a.contains(&"--rm".to_string()), "{a:?}");
        let tail: Vec<&str> = a.iter().map(String::as_str).collect();
        assert_eq!(&tail[..4], &["exec", "zakuro-sandbox", "--", "sh"]);
        assert_eq!(
            &tail[tail.len() - 6..],
            &["w1", "run", "-d", "--name", "w1", "img"]
        );
        // Docker keeps `--rm`; a foreground `run --rm` and other verbs are untouched.
        assert_eq!(Engine::Docker.invocation(&run).1, run);
        let fg: Vec<String> = ["run", "--rm", "img"].map(String::from).to_vec();
        assert_eq!(e.invocation(&fg).1.last().unwrap(), "img");
        assert!(e.invocation(&fg).1.contains(&"--rm".to_string()));
    }
    use super::*;

    fn sel(chosen: Option<RuntimeKind>) -> Selection {
        Selection {
            chosen,
            tried: vec![
                Probe {
                    kind: RuntimeKind::Lxc,
                    available: chosen == Some(RuntimeKind::Lxc),
                    detail: "incus is not installed".into(),
                },
                Probe {
                    kind: RuntimeKind::Docker,
                    available: chosen == Some(RuntimeKind::Docker),
                    detail: "docker daemon is not responding".into(),
                },
            ],
        }
    }

    fn v(a: &[&str]) -> Vec<String> {
        a.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn docker_is_the_docker_cli_byte_for_byte() {
        let e = Engine::from_selection(&sel(Some(RuntimeKind::Docker)), "incus").unwrap();
        assert_eq!(e, Engine::Docker);
        let args = v(&["run", "-d", "--cpus", "1", "img"]);
        assert_eq!(e.invocation(&args), ("docker".to_string(), args));
        // A --config login dir is passed through untouched.
        let cfg = v(&["--config", "/tmp/d", "pull", "img"]);
        assert_eq!(e.invocation(&cfg).1, cfg);
    }

    #[test]
    fn lxc_runs_the_same_argv_under_nerdctl_in_the_sandbox() {
        let e = Engine::from_selection(&sel(Some(RuntimeKind::Lxc)), "lxc").unwrap();
        assert!(e.is_lxc());
        let (prog, a) = e.invocation(&v(&["inspect", "-f", "{{.State.Running}}", "c"]));
        assert_eq!(prog, "lxc");
        assert_eq!(
            a,
            v(&[
                "exec",
                "zakuro-sandbox",
                "--",
                "nerdctl",
                "inspect",
                "-f",
                "{{.State.Running}}",
                "c"
            ])
        );
        // nerdctl has no --config: the login dir becomes DOCKER_CONFIG.
        let (_, a) = e.invocation(&v(&["--config", "/d/cfg", "pull", "img"]));
        assert_eq!(
            a,
            v(&[
                "exec",
                "zakuro-sandbox",
                "--",
                "env",
                "DOCKER_CONFIG=/d/cfg",
                "nerdctl",
                "pull",
                "img"
            ])
        );
    }

    #[test]
    fn nothing_available_is_no_engine_and_the_message_names_the_way_out() {
        assert_eq!(Engine::from_selection(&sel(None), "incus"), None);
        let m = no_backend_message(&sel(None));
        assert!(m.contains("lxc: incus is not installed"), "{m}");
        assert!(m.contains("docker: docker daemon is not responding"), "{m}");
        assert!(m.contains("apt install incus"), "{m}");
        assert!(m.contains("ZAKURO_SHARE_RUNTIME=host"), "{m}");
    }

    #[test]
    fn lima_and_colima_selections_are_their_vm_engines_not_host_docker() {
        let lima = Selection {
            chosen: Some(RuntimeKind::Lima),
            tried: vec![],
        };
        assert!(matches!(
            Engine::from_selection(&lima, "incus"),
            Some(Engine::Lima { .. })
        ));
        let colima = Selection {
            chosen: Some(RuntimeKind::Colima),
            tried: vec![],
        };
        assert!(matches!(
            Engine::from_selection(&colima, "incus"),
            Some(Engine::Colima { .. })
        ));
        let docker = Selection {
            chosen: Some(RuntimeKind::Docker),
            tried: vec![],
        };
        assert_eq!(
            Engine::from_selection(&docker, "incus"),
            Some(Engine::Docker)
        );
    }

    fn probe(kind: RuntimeKind, ok: bool) -> Probe {
        Probe {
            kind,
            available: ok,
            detail: if ok { "ok".into() } else { "down".into() },
        }
    }

    fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
        move |k| {
            pairs
                .iter()
                .find(|(ek, _)| *ek == k)
                .map(|(_, v)| v.to_string())
        }
    }

    /// `(shared engine, jobs per instance)` for the injected probes and env.
    fn matrix(lxc_ok: bool, docker_ok: bool, e: &[(&str, &str)]) -> (Option<Engine>, bool) {
        let g = env(e);
        let l = probe(RuntimeKind::Lxc, lxc_ok);
        let c = resolve_shared(&g, &l, &probe(RuntimeKind::Docker, docker_ok), "incus");
        let (jobs, _) = resolve_jobs(&g, &l, &c);
        (c.engine, jobs)
    }

    fn lxc_engine() -> Option<Engine> {
        Some(Engine::Nerdctl {
            cli: "incus".into(),
            instance: "zakuro-sandbox".into(),
        })
    }

    #[test]
    fn resolution_matrix_docker_only() {
        assert_eq!(matrix(false, true, &[]), (Some(Engine::Docker), false));
        // Asking for LXC without it falls back to Docker, saying why.
        let g = env(&[("ZAKURO_SANDBOX_SHARED", "lxc")]);
        let c = resolve_shared(
            &g,
            &probe(RuntimeKind::Lxc, false),
            &probe(RuntimeKind::Docker, true),
            "incus",
        );
        assert_eq!(c.engine, Some(Engine::Docker));
        assert!(
            c.reason.contains("asked for LXC, but: down"),
            "{}",
            c.reason
        );
    }

    #[test]
    fn resolution_matrix_lxc_only() {
        // Docker absent: LXC is the only isolating option, not a downgrade.
        let (e, jobs) = matrix(true, false, &[]);
        assert_eq!(e, lxc_engine());
        assert!(jobs);
        let g = env(&[]);
        let c = resolve_shared(
            &g,
            &probe(RuntimeKind::Lxc, true),
            &probe(RuntimeKind::Docker, false),
            "incus",
        );
        assert!(c.reason.contains("Docker is unavailable"), "{}", c.reason);
    }

    #[test]
    fn resolution_matrix_both_without_a_preference_keeps_long_lived_work_on_docker() {
        let (e, jobs) = matrix(true, true, &[]);
        assert_eq!(
            e,
            Some(Engine::Docker),
            "an LXD host is not moved by an upgrade"
        );
        assert!(jobs, "foreign jobs still get their own instance");
        // A preference that lists docker first, or only docker, changes nothing.
        for p in ["docker,lxc", "docker", "podman", ""] {
            assert_eq!(
                matrix(true, true, &[("ZAKURO_RUNTIME_PREFER", p)]).0,
                Some(Engine::Docker),
                "{p:?}"
            );
        }
        assert_eq!(
            matrix(true, true, &[("ZAKURO_SANDBOX_SHARED", "docker")]).0,
            Some(Engine::Docker)
        );
    }

    #[test]
    fn resolution_matrix_both_with_an_explicit_lxc_choice() {
        for e in [
            &[("ZAKURO_RUNTIME_PREFER", "lxc,docker")][..],
            &[("ZAKURO_RUNTIME_PREFER", "incus")][..],
            &[("ZAKURO_RUNTIME_PREFER", " LXD , docker ")][..],
            &[("ZAKURO_SANDBOX_SHARED", "LXC")][..],
        ] {
            assert_eq!(matrix(true, true, e), (lxc_engine(), true), "{e:?}");
        }
        let g = env(&[("ZAKURO_RUNTIME_PREFER", "lxc,docker")]);
        let c = resolve_shared(
            &g,
            &probe(RuntimeKind::Lxc, true),
            &probe(RuntimeKind::Docker, true),
            "incus",
        );
        assert!(
            c.reason
                .contains("asked for by ZAKURO_RUNTIME_PREFER=lxc,docker"),
            "{}",
            c.reason
        );
    }

    #[test]
    fn resolution_matrix_neither_names_what_to_install() {
        let (e, jobs) = matrix(false, false, &[]);
        assert_eq!((e, jobs), (None, false));
        let g = env(&[]);
        let c = resolve_shared(
            &g,
            &probe(RuntimeKind::Lxc, false),
            &probe(RuntimeKind::Docker, false),
            "incus",
        );
        assert!(
            c.reason.contains("apt install incus")
                && c.reason.contains("ZAKURO_SHARE_RUNTIME=host"),
            "{}",
            c.reason
        );
    }

    #[test]
    fn the_job_tier_follows_the_lxc_probe_and_the_isolation_setting() {
        let docker = Choice {
            engine: Some(Engine::Docker),
            reason: "d".into(),
        };
        let up = probe(RuntimeKind::Lxc, true);
        let down = probe(RuntimeKind::Lxc, false);
        let g = env(&[]);
        assert!(resolve_jobs(&g, &up, &docker).0);
        let (per, why) = resolve_jobs(&g, &down, &docker);
        assert!(
            !per && why.starts_with("FALLBACK: shared engine with limits"),
            "{why}"
        );
        let shared = env(&[("ZAKURO_SANDBOX_ISOLATION", " Shared ")]);
        assert!(!resolve_jobs(&shared, &up, &docker).0);
        let job = env(&[("ZAKURO_SANDBOX_ISOLATION", "job")]);
        assert!(resolve_jobs(&job, &up, &docker).0);
        let bad = env(&[("ZAKURO_SANDBOX_ISOLATION", "vm")]);
        let (per, why) = resolve_jobs(&bad, &up, &docker);
        assert!(!per && why.contains("not one of job, shared"), "{why}");
    }

    fn rust_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
        for entry in std::fs::read_dir(dir).unwrap() {
            let p = entry.unwrap().path();
            if p.is_dir() {
                rust_files(&p, out);
            } else if p.extension().is_some_and(|e| e == "rs") {
                out.push(p);
            }
        }
    }

    /// Files that may spawn a container engine themselves, and why. Everything
    /// else asks [`command`] / [`run`], so a new path cannot skip the backend
    /// choice (the same idea as the `/peer/*` guard in `broker::peer`).
    const ALLOWED: &[(&str, &str)] = &[
        (
            "src/sandbox/",
            "the sandbox layer itself (backends, probes, this engine)",
        ),
        (
            "src/vpn/",
            "the WireGuard sidecar is a Docker container by design",
        ),
        (
            "src/mesh.rs",
            "the local static dev mesh (`zc mesh up`) is Docker-only",
        ),
        ("src/exec/", "`zc exec` runs a user-named Docker command"),
        ("src/common/mod.rs", "legacy `zc build` docker-compose verb"),
        (
            "src/hub_allocation/mod.rs",
            "`docker info` host-memory probe for a hub offer",
        ),
        (
            "src/broker/deploy/runtime.rs",
            "the Docker probe that `sandbox::probe_host` and `zc doctor` read",
        ),
    ];

    /// A line that spawns a container-engine binary directly.
    fn spawns_engine(line: &str) -> bool {
        let t = line.trim_start();
        !t.starts_with("//")
            && [
                "docker", "nerdctl", "podman", "lxc", "incus", "colima", "limactl",
            ]
            .iter()
            .any(|b| line.contains(&format!("Command::new(\"{b}\")")))
    }

    #[test]
    fn no_container_engine_is_spawned_outside_the_sandbox_layer() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let mut files = Vec::new();
        rust_files(&root.join("src"), &mut files);
        assert!(files.len() > 20, "source scan found too few files");
        let mut offenders = Vec::new();
        for f in &files {
            let rel = f.strip_prefix(root).unwrap().to_string_lossy().to_string();
            if ALLOWED.iter().any(|(p, _)| rel.starts_with(p)) {
                continue;
            }
            for (i, line) in std::fs::read_to_string(f).unwrap().lines().enumerate() {
                if spawns_engine(line) {
                    offenders.push(format!("{rel}:{}: {}", i + 1, line.trim()));
                }
            }
        }
        assert!(
            offenders.is_empty(),
            "a container engine is spawned outside src/sandbox/ and the allow-list: go through \
             sandbox::engine::command / run so the chosen backend (Incus or Docker) is used \
             (zc#578):\n{}",
            offenders.join("\n")
        );
    }

    #[test]
    fn the_scan_flags_a_direct_engine_spawn_and_spares_comments() {
        assert!(spawns_engine(
            r#"    let out = Command::new("docker").args(a).output();"#
        ));
        assert!(spawns_engine(r#"std::process::Command::new("nerdctl")"#));
        assert!(spawns_engine(r#"Command::new("incus")"#));
        assert!(!spawns_engine(
            r#"    // Command::new("docker") + captured stdout"#
        ));
        assert!(!spawns_engine(r#"Command::new("git")"#));
        for (p, why) in ALLOWED {
            assert!(!why.is_empty(), "{p} needs a reason");
        }
    }
}