Skip to main content

greengate_runtime/
cluster.rs

1//! A `platform=any` gate run on the homelab cluster, as one Kubernetes Job
2//! (ADR-0016).
3//!
4//! A trusted manifest marks a gate whose verdict does not depend on the
5//! platform (`platform=any`) and says `set executor cluster`; the machine
6//! names a kubeconfig and an image pinned by digest. Then the gate runs in a
7//! pod instead of on this laptop, and takes no host slot (ADR-0014).
8//!
9//! **The cluster proves only passes.** The verdict is read from what
10//! Kubernetes recorded — the Job's `Complete` condition, each container's
11//! exit code, `fetch`'s termination message naming the tree, the pod's
12//! `imageID` — never from the logs. Anything else, a failure of the gate
13//! included, re-runs the gate here, unchanged, and the local outcome is the
14//! verdict: a gate never fails because of the cluster. Each such fallback
15//! appends `<epoch> <gate> <reason>` to `amont/cluster.log` in the common git
16//! directory.
17//!
18//! A pass is recorded under its own identity
19//! ([`crate::gate_identity::cluster_token`]) in its own ref
20//! ([`crate::gate_stamp::CLUSTER_REF`]) and never as a local token: the
21//! hooks consult [`proved`] so a cluster-derived pass never reaches the
22//! commit marker, a push stamp or the laptop's attestation.
23//!
24//! Every `kubectl` call goes through `--kubeconfig <path>` (never the default
25//! context), with stdin null — except the one `exec -i` that streams the
26//! bundle — and under one deadline taken before the Job is created.
27
28use std::collections::BTreeSet;
29use std::path::{Path, PathBuf};
30use std::process::{Command, Stdio};
31use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
32use std::sync::Mutex;
33use std::time::{Duration, Instant};
34
35use crate::json_read::Value;
36use crate::manifest::{External, Kind};
37
38mod detached;
39pub(crate) use detached::{collect, settled_lines, status_lines, stop_pending};
40pub use detached::{collect_command, detach, wanted, Ask, Detached};
41
42/// [`collect`] for the hooks and `amont stamps`, which run in every repository:
43/// only where the manifest declares a `platform=any` gate, the only kind a
44/// Workflow can hold a pass for, so a repository without one pays nothing.
45pub fn collect_if_declared(manifest: &crate::manifest::Manifest) {
46    if manifest.externals.iter().any(is_platform_any) {
47        collect();
48    }
49}
50
51/// The node the gate pods run on, and the names the homelab contract fixes.
52const NODE: &str = "talos-wk-3-gpu";
53const PRIORITY_CLASS: &str = "gate-batch";
54const PULL_SECRET: &str = "forgejo-registry-pull";
55const JOB_PREFIX: &str = "amont-gate-slot-";
56const CACHE_PREFIX: &str = "gate-cache-";
57const TEMP_REF_PREFIX: &str = "refs/amont/cluster/";
58/// The platform a cluster pass is recorded under.
59pub(crate) const PLATFORM: &str = "x86_64-linux";
60/// The main container's memory, request equal to limit, and CPU limit.
61const MEMORY: &str = "4Gi";
62const CPU_LIMIT: &str = "2";
63/// One short kubectl call: its own request timeout plus room for the exec
64/// credential plugin. Never more than the time left.
65const CALL_SECS: u64 = 20;
66/// The shared budget for deleting live Jobs when amont is interrupted.
67const CANCEL_SECS: u64 = 10;
68/// The bound on a quiet clean-up by label after a `create` timed out.
69const LABEL_DELETE_SECS: u64 = 5;
70/// The label every Job carries, valued by its run ([`run_label`]).
71const RUN_LABEL_KEY: &str = "amont.run";
72const POLL: Duration = Duration::from_millis(500);
73const MIB: u64 = 1024 * 1024;
74
75/// Passes the cluster proved in this process, by (check id, tree): run there,
76/// or reused from a cluster token. Such a pass never becomes a local token,
77/// stamp or attestation for that tree.
78static PROVED: Mutex<BTreeSet<(String, String)>> = Mutex::new(BTreeSet::new());
79/// Set once the apiserver did not answer: the later gates of this hook
80/// process run here without asking it again.
81static UNREACHABLE: AtomicBool = AtomicBool::new(false);
82/// A misconfiguration is said once per run, not once per gate.
83static WARNED: AtomicBool = AtomicBool::new(false);
84/// An unreachable apiserver is said once per run; each gate still logs it.
85static UNREACHABLE_SAID: AtomicBool = AtomicBool::new(false);
86/// What an interrupt must clean up, by run.
87static LIVE: Mutex<Vec<LiveRun>> = Mutex::new(Vec::new());
88/// Serialises writes of the cluster note: concurrent gates of one stage each
89/// read, merge and rewrite it.
90static STAMP_LOCK: Mutex<()> = Mutex::new(());
91static SEQ: AtomicU64 = AtomicU64::new(0);
92/// Temporary manifest files of detached submissions, for an interrupt to
93/// delete. Files only: a detached Workflow outlives amont on purpose.
94static TEMP_FILES: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
95
96fn track_temp_file(path: &Path) {
97    TEMP_FILES
98        .lock()
99        .unwrap_or_else(|p| p.into_inner())
100        .push(path.to_path_buf());
101}
102
103fn untrack_temp_file(path: &Path) {
104    TEMP_FILES
105        .lock()
106        .unwrap_or_else(|p| p.into_inner())
107        .retain(|p| p != path);
108}
109
110/// Did the cluster prove the check `id` on `tree` in this process?
111pub fn proved(id: &str, tree: &str) -> bool {
112    PROVED
113        .lock()
114        .unwrap_or_else(|p| p.into_inner())
115        .contains(&(id.to_string(), tree.to_string()))
116}
117
118/// Did the cluster prove the check `id` on any tree in this process? For a
119/// caller that covers several trees at once (an attestation of a push).
120pub fn proved_anywhere(id: &str) -> bool {
121    PROVED
122        .lock()
123        .unwrap_or_else(|p| p.into_inner())
124        .iter()
125        .any(|(i, _)| i == id)
126}
127
128/// Did the cluster prove the check `id` on the index's tree? Spawns nothing
129/// unless the cluster proved `id` somewhere; when git cannot name the index's
130/// tree, the answer is yes, so no local token is written on a guess.
131pub fn proved_on_index(id: &str) -> bool {
132    proved_anywhere(id) && tree_of(Judged::Index).map_or(true, |tree| proved(id, &tree))
133}
134
135/// The ids of the manifest's `platform=any` gates. A `Runnable` exists only
136/// for a trusted manifest, so these are the trusted declarations.
137pub(crate) fn platform_any_ids(manifest: &crate::manifest::Manifest) -> Vec<String> {
138    manifest
139        .externals
140        .iter()
141        .filter(|e| is_platform_any(e))
142        .map(|e| e.id.clone())
143        .collect()
144}
145
146fn mark_proved(id: &str, tree: &str) {
147    PROVED
148        .lock()
149        .unwrap_or_else(|p| p.into_inner())
150        .insert((id.to_string(), tree.to_string()));
151}
152
153/// One cluster run, as an interrupt sees it.
154#[derive(Clone)]
155struct LiveRun {
156    run: u64,
157    kubeconfig: PathBuf,
158    namespace: String,
159    scratch: PathBuf,
160    /// The `amont.run` label of every Job this run creates: how a Job whose
161    /// `create` is still in flight, or whose answer was lost, is found.
162    run_label: String,
163    /// Where this run's Job stands, as a cancel must know it.
164    created: Created,
165    gate_ref: Option<String>,
166}
167
168/// A run's Job, as far as an interrupt can tell.
169#[derive(Clone, Debug, PartialEq, Eq)]
170enum Created {
171    /// No `create` sent, or the Job already deleted: nothing on the cluster
172    /// is this run's.
173    NotSent,
174    /// A `create` was sent; its Job, if any, is found by the run's label.
175    Sent,
176    /// The Job this run holds, by name.
177    Named(String),
178}
179
180fn live_update(run: u64, update: impl FnOnce(&mut LiveRun)) {
181    let mut live = LIVE.lock().unwrap_or_else(|p| p.into_inner());
182    if let Some(entry) = live.iter_mut().find(|l| l.run == run) {
183        update(entry);
184    }
185}
186
187/// The signal watcher's hook, after the index is restored: say so, ask the
188/// apiserver to drop every live Job without waiting for it, all under one
189/// shared budget, and remove the temporary files and refs. A second signal
190/// meanwhile ends amont at once and leaves the Job to its own deadline.
191pub fn cancel_live() {
192    for file in std::mem::take(&mut *TEMP_FILES.lock().unwrap_or_else(|p| p.into_inner())) {
193        let removed = std::fs::remove_file(&file); // amont is dying: nothing to tell
194        drop(removed);
195    }
196    let live: Vec<LiveRun> = std::mem::take(&mut *LIVE.lock().unwrap_or_else(|p| p.into_inner()));
197    if live.is_empty() {
198        return;
199    }
200    let _leaving = crate::staged_only::leave_on_second_signal();
201    let deadline = Instant::now() + Duration::from_secs(CANCEL_SECS);
202    for run in live {
203        if let Some(gate_ref) = &run.gate_ref {
204            let _ = crate::git::succeeds(&["update-ref", "-d", gate_ref]); // best-effort: amont is dying
205        }
206        let _ = std::fs::remove_dir_all(&run.scratch); // best-effort: amont is dying
207        let kube = Kube {
208            kubeconfig: run.kubeconfig.clone(),
209            namespace: run.namespace.clone(),
210        };
211        let left = secs_left(deadline, CANCEL_SECS);
212        match &run.created {
213            Created::NotSent => {}
214            Created::Named(job) => {
215                eprintln!("cancelling cluster Job {job}; Ctrl-C again to leave it");
216                if let Err(why) = kube.bounded(&["delete", "job", job, "--wait=false"], left) {
217                    eprintln!(
218                        "could not cancel cluster Job {job}: {}",
219                        crate::ui::sanitize(&why)
220                    );
221                }
222            }
223            // Not named yet: `create` may be in flight or its answer lost. The
224            // label finds the Job if it exists, and deletes nothing otherwise.
225            Created::Sent => {
226                let selector = run_selector(&run.run_label);
227                eprintln!("cancelling cluster Jobs of this run; Ctrl-C again to leave them");
228                if let Err(why) =
229                    kube.bounded(&["delete", "job", "-l", &selector, "--wait=false"], left)
230                {
231                    eprintln!(
232                        "could not cancel the cluster Jobs of this run: {}",
233                        crate::ui::sanitize(&why)
234                    );
235                }
236            }
237        }
238    }
239}
240
241/// Whole seconds until `deadline`, at most `cap`, at least 1.
242fn secs_left(deadline: Instant, cap: u64) -> u64 {
243    deadline
244        .saturating_duration_since(Instant::now())
245        .as_secs()
246        .clamp(1, cap.max(1))
247}
248
249/// Why the cluster did not prove a gate. Every one runs the gate here.
250#[derive(Debug, Clone, PartialEq, Eq)]
251enum Fallback {
252    /// A required machine key is unset: this machine has no cluster. Silent
253    /// on the terminal, so a repository that says `set executor cluster`
254    /// does not warn on every hook of a machine without one.
255    Unconfigured(&'static str),
256    /// A machine key is set but cannot be used. Said once per run, with the
257    /// fix.
258    Misconfigured {
259        why: String,
260        fix: String,
261    },
262    /// The apiserver did not answer, or kubectl could not run.
263    Unreachable(String),
264    /// The apiserver did not answer an earlier gate of this run.
265    UnreachableEarlier,
266    SlotsTaken,
267    QuotaFull,
268    BundleTooBig {
269        mib: u64,
270        cap: u64,
271    },
272    /// The gate itself exited non-zero in the pod.
273    GateFailed(String),
274    /// Anything else the recorded facts do not prove.
275    NotProved(String),
276}
277
278impl std::fmt::Display for Fallback {
279    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
280        match self {
281            Fallback::Unconfigured(why) => write!(f, "{why}"),
282            Fallback::Misconfigured { why, .. } => write!(f, "{why}"),
283            Fallback::Unreachable(why) => write!(f, "the cluster did not answer: {why}"),
284            Fallback::UnreachableEarlier => {
285                write!(f, "the cluster did not answer earlier in this run")
286            }
287            Fallback::SlotsTaken => write!(f, "all slots taken"),
288            Fallback::QuotaFull => write!(f, "the quota refused every slot"),
289            Fallback::BundleTooBig { mib, cap } => {
290                write!(f, "bundle-too-big: {mib} MiB, over the {cap} MiB cap")
291            }
292            Fallback::GateFailed(detail) => write!(f, "failed on the cluster ({detail})"),
293            Fallback::NotProved(why) => write!(f, "{why}"),
294        }
295    }
296}
297
298/// What the cluster needs from this machine and this repository.
299#[derive(Debug, Clone, PartialEq, Eq)]
300struct ClusterConfig {
301    kubeconfig: PathBuf,
302    namespace: String,
303    slots: u32,
304    image: String,
305    digest: String,
306    max_bundle_mib: u64,
307    start_wait: Duration,
308    timeout_secs: u64,
309    prepare: Option<String>,
310}
311
312/// The machine's `amont.cluster.*` keys, lowercased as git prints them.
313/// `--type=path` expands a leading `~`, which is how the kubeconfig is set.
314fn machine_keys() -> Vec<(String, String)> {
315    crate::git::stdout(&[
316        "config",
317        "--type=path",
318        "--get-regexp",
319        r"^amont\.cluster\.",
320    ])
321    .unwrap_or_default()
322    .lines()
323    .map(|l| {
324        let (k, v) = l.split_once(' ').unwrap_or((l, ""));
325        (k.to_ascii_lowercase(), v.trim().to_string())
326    })
327    .collect()
328}
329
330fn key<'a>(keys: &'a [(String, String)], name: &str) -> Option<&'a str> {
331    keys.iter()
332        .rev()
333        .find(|(k, _)| k == name)
334        .map(|(_, v)| v.as_str())
335        .filter(|v| !v.is_empty())
336}
337
338fn number(keys: &[(String, String)], name: &str, default: u64, max: u64) -> u64 {
339    key(keys, name)
340        .and_then(|v| v.parse::<u64>().ok())
341        .filter(|n| *n >= 1)
342        .map_or(default, |n| n.min(max))
343}
344
345/// The digest of a pinned image reference, `sha256:<hex>`, or `None` for a
346/// reference that is not pinned by digest.
347fn digest_of(image: &str) -> Option<&str> {
348    let (_, digest) = image.split_once('@')?;
349    let hex = digest.strip_prefix("sha256:")?;
350    (hex.len() == 64 && hex.chars().all(|c| c.is_ascii_hexdigit())).then_some(digest)
351}
352
353/// A DNS-1123 label: what a namespace may be called.
354fn is_label(s: &str) -> bool {
355    !s.is_empty()
356        && s.len() <= 63
357        && s.chars()
358            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
359        && !s.starts_with('-')
360        && !s.ends_with('-')
361}
362
363/// The trusted `set clusterPrepare` command, if any. Policy only: a local
364/// git config cannot hand the pod a command the manifest did not declare.
365fn prepare(settings: &crate::config::Settings) -> Option<String> {
366    settings
367        .policy()
368        .settings
369        .get("amont.clusterPrepare")
370        .cloned()
371}
372
373/// Whether this repository's TRUSTED policy says `set executor cluster`, and
374/// no local `git config amont.executor local` turned it off. Reading the
375/// policy map spawns nothing, so a repository that says nothing pays nothing.
376fn executor_is_cluster(settings: &crate::config::Settings) -> bool {
377    settings
378        .policy()
379        .settings
380        .get("amont.executor")
381        .is_some_and(|v| v == "cluster")
382        && crate::config::enumerated_or(settings, "amont.executor", &["cluster", "local"], "local")
383            == "cluster"
384}
385
386fn misconfigured(why: String, key_fix: &str) -> Fallback {
387    Fallback::Misconfigured {
388        why,
389        fix: format!("{key_fix}, or `git config amont.executor local`"),
390    }
391}
392
393/// The full configuration, or why the gate runs here instead.
394fn cluster_config(settings: &crate::config::Settings) -> Result<ClusterConfig, Fallback> {
395    let keys = machine_keys();
396    let kubeconfig = key(&keys, "amont.cluster.kubeconfig").ok_or(Fallback::Unconfigured(
397        "amont.cluster.kubeconfig is not set: `git config --global amont.cluster.kubeconfig ~/.config/amont/kube/homelab.yaml`",
398    ))?;
399    let kubeconfig = PathBuf::from(kubeconfig);
400    if !kubeconfig.is_file() {
401        return Err(misconfigured(
402            format!("kubeconfig {} does not exist", kubeconfig.display()),
403            "`git config --global amont.cluster.kubeconfig <path>`",
404        ));
405    }
406    let image = key(&keys, "amont.cluster.image")
407        .ok_or(Fallback::Unconfigured(
408        "amont.cluster.image is not set: `git config --global amont.cluster.image 'name:tag@sha256:<digest>'`",
409    ))?;
410    let digest = digest_of(image)
411        .ok_or_else(|| {
412            misconfigured(
413                format!("amont.cluster.image {image:?} is not pinned by @sha256: digest"),
414                "`git config --global amont.cluster.image <name>:<tag>@sha256:<digest>`",
415            )
416        })?
417        .to_string();
418    let namespace = key(&keys, "amont.cluster.namespace").unwrap_or("amont-gates");
419    if !is_label(namespace) {
420        return Err(misconfigured(
421            format!("amont.cluster.namespace {namespace:?} is not a namespace name"),
422            "`git config --global amont.cluster.namespace <name>`",
423        ));
424    }
425    let timeout_secs = crate::hooks::common::check_timeout(settings);
426    if timeout_secs == 0 {
427        return Err(misconfigured(
428            "amont.timeout is 0 (unbounded), and a Job needs a deadline".into(),
429            "`git config amont.timeout <seconds>`",
430        ));
431    }
432    Ok(ClusterConfig {
433        kubeconfig,
434        namespace: namespace.to_string(),
435        slots: u32::try_from(number(&keys, "amont.cluster.slots", 2, 2)).unwrap_or(2),
436        image: image.to_string(),
437        digest,
438        max_bundle_mib: number(&keys, "amont.cluster.maxbundlemib", 50, 4096),
439        start_wait: Duration::from_secs(number(&keys, "amont.cluster.startwait", 30, 600)),
440        timeout_secs,
441        prepare: prepare(settings),
442    })
443}
444
445fn is_platform_any(ext: &External) -> bool {
446    matches!(
447        ext.kind,
448        Kind::Runnable {
449            runs_on: crate::manifest::RunsOn::AnyPlatform,
450            ..
451        }
452    )
453}
454
455/// The cluster token for `ext` as configured now — the image digest and the
456/// prepare command included — or `None` where no cluster token can apply: a
457/// gate that is not `platform=any`, or no pinned image on this machine.
458/// Never inspects the laptop's executable.
459fn token(settings: &crate::config::Settings, ext: &External) -> Option<String> {
460    token_from(&machine_keys(), settings, ext, &ext.id)
461}
462
463/// [`token`] from machine keys already read, for `ext`'s program, arguments
464/// and file scope under the name `name`: a caller that needs several tokens
465/// reads the keys (one `git config`) once.
466fn token_from(
467    keys: &[(String, String)],
468    settings: &crate::config::Settings,
469    ext: &External,
470    name: &str,
471) -> Option<String> {
472    if !is_platform_any(ext) {
473        return None;
474    }
475    let digest = digest_of(key(keys, "amont.cluster.image")?)?;
476    crate::gate_identity::cluster_token(ext, name, prepare(settings).as_deref(), digest)
477}
478
479/// What the cluster is asked to judge.
480#[derive(Debug, Clone, Copy)]
481pub enum Judged<'a> {
482    /// The index: the tree `git commit` is about to seal.
483    Index,
484    /// A commit's tree: a pushed tip.
485    Commit(&'a str),
486}
487
488/// The tree object `judged` names, or `None` when git cannot say, or when
489/// the file set is not the index and the working tree differs from it (an
490/// `amont run` over a dirty tree judges content no tree holds).
491fn tree_of(judged: Judged) -> Option<String> {
492    match judged {
493        Judged::Index => {
494            if crate::hooks::common::not_the_index() {
495                let dirty = crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"])?;
496                if !dirty.trim().is_empty() {
497                    return None;
498                }
499            }
500            write_tree()
501        }
502        Judged::Commit(c) => crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]),
503    }
504}
505
506/// `git write-tree` of the index, one at a time: concurrent gates of one
507/// stage each ask, and git refuses a second writer while the first holds
508/// `index.lock` (it refreshes the cache-tree), so a refusal is retried.
509fn write_tree() -> Option<String> {
510    static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());
511    let _held = ONE_AT_A_TIME.lock().unwrap_or_else(|p| p.into_inner());
512    for _ in 0..20 {
513        if let Some(tree) = crate::git::stdout(&["write-tree"]) {
514            return Some(tree);
515        }
516        std::thread::sleep(Duration::from_millis(50));
517    }
518    None
519}
520
521/// pre-commit (and `run --stamp`): is the tree about to be committed already
522/// proved on the cluster for this gate, as it is declared and configured
523/// now? A hit counts as a cluster pass ([`proved`]).
524pub fn vouched(settings: &crate::config::Settings, ext: &External, judged: Judged) -> bool {
525    let Some(token) = token(settings, ext) else {
526        return false;
527    };
528    let Some(tree) = tree_of(judged) else {
529        return false;
530    };
531    let hit = crate::gate_stamp::cluster_tokens(&tree).contains(&token);
532    if hit {
533        mark_proved(&ext.id, &tree);
534    }
535    hit
536}
537
538/// pre-push: does every tip carry this gate's cluster token on its tree?
539pub fn vouched_on_every(
540    settings: &crate::config::Settings,
541    ext: &External,
542    tips: &[String],
543) -> bool {
544    if tips.is_empty() {
545        return false;
546    }
547    let Some(token) = token(settings, ext) else {
548        return false;
549    };
550    vouched_trees(ext, tips, &token).is_some()
551}
552
553/// The trees of `tips`, when every one carries `token`, `ext`'s cluster token;
554/// each is marked proved under `ext`'s id.
555fn vouched_trees(ext: &External, tips: &[String], token: &str) -> Option<Vec<String>> {
556    let stamps = crate::gate_stamp::cluster_stamps_for(tips);
557    let hit = tips.iter().all(|t| {
558        stamps
559            .get(t)
560            .is_some_and(|(_, tokens)| tokens.iter().any(|held| held == token))
561    });
562    if !hit {
563        return None;
564    }
565    let trees: Vec<String> = stamps.values().map(|(tree, _)| tree.clone()).collect();
566    for tree in &trees {
567        mark_proved(&ext.id, tree);
568    }
569    Some(trees)
570}
571
572/// pre-push, a `platform=any` gate `push` whose commit-time twin `twin` is
573/// also `platform=any` and declares the same suite (the same cluster identity
574/// under one name: program, arguments, file scope, prepare and image): when
575/// `twin`'s cluster token sits on every tip's tree, claim that pass for `push`
576/// too. An action, not a lookup: it marks `push`'s id proved on those trees,
577/// which is what puts it in the linux block. A twin that runs anything else
578/// claims nothing, so the push gate runs.
579pub(crate) fn claim_twin_cluster_pass(
580    settings: &crate::config::Settings,
581    push: &External,
582    twin: &External,
583    tips: &[String],
584) -> bool {
585    if tips.is_empty() || !is_platform_any(push) || !is_platform_any(twin) {
586        return false;
587    }
588    let keys = machine_keys();
589    let Some(twin_token) = token_from(&keys, settings, twin, &twin.id) else {
590        return false;
591    };
592    // `push` as it would read under the twin's name: equal tokens mean the
593    // same cluster identity.
594    if token_from(&keys, settings, push, &twin.id).as_deref() != Some(twin_token.as_str()) {
595        return false;
596    }
597    let Some(trees) = vouched_trees(twin, tips, &twin_token) else {
598        return false;
599    };
600    for tree in &trees {
601        mark_proved(&push.id, tree);
602    }
603    true
604}
605
606/// `amont stamps`: does `tree` carry a cluster token for any of `ids`, each
607/// a trusted `platform=any` declaration?
608pub fn stamped_on_tree(
609    settings: &crate::config::Settings,
610    externals: &[External],
611    ids: &[String],
612    tree: &str,
613) -> bool {
614    let tokens: Vec<String> = externals
615        .iter()
616        .filter(|e| ids.contains(&e.id))
617        .filter_map(|e| token(settings, e))
618        .collect();
619    if tokens.is_empty() {
620        return false;
621    }
622    let on_tree = crate::gate_stamp::cluster_tokens(tree);
623    tokens.iter().any(|t| on_tree.contains(t))
624}
625
626/// post-commit: the blocking commit-time scripts whose cluster token is on
627/// HEAD's tree. The bypass ledger reads them as stamped: their pass is
628/// recorded, only not as a local token. Spawns nothing in a repository with
629/// no `platform=any` gate.
630pub fn covered_at_head(
631    settings: &crate::config::Settings,
632    manifest: &crate::manifest::Manifest,
633) -> Vec<String> {
634    if !manifest.externals.iter().any(is_platform_any) {
635        return Vec::new();
636    }
637    let Some(tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
638        return Vec::new();
639    };
640    let on_tree = crate::gate_stamp::cluster_tokens(&tree);
641    crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
642        .into_iter()
643        .filter(|d| {
644            manifest
645                .externals
646                .iter()
647                .find(|e| e.id == d.id)
648                .and_then(|e| token(settings, e))
649                .is_some_and(|t| on_tree.contains(&t))
650        })
651        .map(|d| d.script)
652        .collect()
653}
654
655/// Run `ext` on the cluster if it is the cluster's to run. `true`: it passed
656/// there and the pass is recorded; the caller reports `Passed`. `false`: the
657/// caller runs it here, as it always has — either it was never the
658/// cluster's (no line logged), or the cluster did not prove it (the reason is
659/// logged).
660pub fn try_run(
661    settings: &crate::config::Settings,
662    ext: &External,
663    program: &str,
664    args: &[String],
665    judged: Judged,
666) -> bool {
667    if !is_platform_any(ext) || !executor_is_cluster(settings) {
668        return false;
669    }
670    let outcome = cluster_config(settings).and_then(|config| {
671        // Not announced once the apiserver has not answered: `run` refuses
672        // it at once and the gate runs here.
673        if !UNREACHABLE.load(Ordering::SeqCst) {
674            crate::say!(
675                "{}: running on the cluster",
676                crate::ui::highlight(&ext.short_name)
677            );
678        }
679        run(&config, ext, program, args, judged)
680    });
681    match outcome {
682        Ok(tree) => {
683            mark_proved(&ext.id, &tree);
684            true
685        }
686        Err(fallback) => {
687            // A signal killed the kubectl children: amont is dying, so no
688            // local re-run may start behind the signal cleanup.
689            crate::tree_run::park_if_dying();
690            if matches!(fallback, Fallback::Unreachable(_)) {
691                UNREACHABLE.store(true, Ordering::SeqCst);
692            }
693            say_fallback(&ext.short_name, &fallback);
694            log_line(&ext.id, &fallback.to_string());
695            false
696        }
697    }
698}
699
700/// The one terminal line a fallback earns, if any.
701fn say_fallback(short_name: &str, fallback: &Fallback) {
702    let name = crate::ui::highlight(short_name);
703    match fallback {
704        Fallback::Unconfigured(_) => {}
705        Fallback::Misconfigured { why, fix } => {
706            if !WARNED.swap(true, Ordering::SeqCst) {
707                crate::hooks::common::warn(&format!(
708                    "{name} runs here: {} — fix with {fix}",
709                    crate::ui::sanitize(why)
710                ));
711            }
712        }
713        Fallback::GateFailed(detail) => crate::hooks::common::warn(&format!(
714            "{name} failed on the cluster ({}); running it here for the verdict",
715            crate::ui::sanitize(detail)
716        )),
717        Fallback::Unreachable(why) => {
718            if !UNREACHABLE_SAID.swap(true, Ordering::SeqCst) {
719                crate::hooks::common::warn(&format!(
720                    "{name} and this hook's other cluster gates run here: the cluster did not answer ({})",
721                    crate::ui::sanitize(why)
722                ));
723            }
724        }
725        Fallback::UnreachableEarlier => {
726            if !UNREACHABLE_SAID.swap(true, Ordering::SeqCst) {
727                crate::hooks::common::warn(&format!(
728                    "the cluster did not answer earlier in this hook: {name} runs here"
729                ));
730            }
731        }
732        Fallback::BundleTooBig { mib, cap } => crate::hooks::common::warn(&format!(
733            "{name} runs here: its bundle is {mib} MiB, over the {cap} MiB cap — raise it with `git config amont.cluster.maxBundleMiB <MiB>`"
734        )),
735        Fallback::SlotsTaken | Fallback::QuotaFull | Fallback::NotProved(_) => {
736            warn_unavailable(&name, fallback)
737        }
738    }
739}
740
741fn warn_unavailable(name: &str, fallback: &Fallback) {
742    crate::hooks::common::warn(&format!(
743        "{name} runs here: the cluster is unavailable ({})",
744        crate::ui::sanitize(&fallback.to_string())
745    ));
746}
747
748/// Append `<epoch> <gate> <reason>` to `amont/cluster.log` in the common git
749/// directory. Best-effort: the log is evidence, never a verdict.
750fn log_line(gate: &str, reason: &str) {
751    let reason: String = reason
752        .chars()
753        .map(|c| if c.is_control() { ' ' } else { c })
754        .collect();
755    let Some(dir) =
756        crate::git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])
757    else {
758        return;
759    };
760    let dir = Path::new(&dir).join("amont");
761    let line = format!("{} {gate} {reason}\n", crate::gate_evidence::now());
762    let written = std::fs::create_dir_all(&dir).and_then(|()| {
763        let mut f = std::fs::OpenOptions::new()
764            .create(true)
765            .append(true)
766            .open(dir.join("cluster.log"))?;
767        std::io::Write::write_all(&mut f, line.as_bytes())
768    });
769    if let Err(e) = written {
770        crate::hooks::common::warn(&format!("could not append to amont/cluster.log: {e}"));
771    }
772}
773
774/// What a pass carries into its record.
775struct Proof {
776    image_id: String,
777    uid: String,
778    job: String,
779    bundle_bytes: u64,
780}
781
782/// Run on the cluster and record the pass. The judged tree on a pass.
783fn run(
784    config: &ClusterConfig,
785    ext: &External,
786    program: &str,
787    args: &[String],
788    judged: Judged,
789) -> Result<String, Fallback> {
790    // A signal that killed a kubectl child must not reach a local run.
791    crate::tree_run::park_if_dying();
792    if UNREACHABLE.load(Ordering::SeqCst) {
793        return Err(Fallback::UnreachableEarlier);
794    }
795    let tree = tree_of(judged)
796        .ok_or_else(|| Fallback::NotProved("git would not name the tree to judge".into()))?;
797    let commit = parentless_commit(&tree)
798        .ok_or_else(|| Fallback::NotProved("git commit-tree failed".into()))?;
799    let deadline = Instant::now() + Duration::from_secs(config.timeout_secs + 60);
800    let kube = Kube::new(config);
801    let scratch = Scratch::new(&ext.id, &kube)?;
802    let mut argv = vec![program.to_string()];
803    argv.extend(args.iter().cloned());
804    let spec = Spec {
805        config,
806        gate: &ext.id,
807        tree: &tree,
808        repo_dir: &repo_dir(),
809        argv: &argv,
810        run_label: &scratch.run_label(),
811    };
812    // The gate runs on the cluster and takes no host slot (ADR-0016): a slot
813    // parked for the next local gate would sit idle for the whole run.
814    crate::host_slots::release_parked();
815    let job = claim_slot(&kube, &spec, &scratch, deadline)?;
816    let outcome = run_in(&kube, config, &job, &scratch, &commit, &tree, deadline);
817    job.delete(&kube, &ext.id, deadline);
818    let proof = outcome?;
819    record(ext, config, &tree, &proof)?;
820    Ok(tree)
821}
822
823/// Write the cluster token, with its provenance. A pass with no record is no
824/// pass: the caller runs the gate here.
825fn record(
826    ext: &External,
827    config: &ClusterConfig,
828    tree: &str,
829    proof: &Proof,
830) -> Result<(), Fallback> {
831    let token = crate::gate_identity::cluster_token(
832        ext,
833        &ext.id,
834        config.prepare.as_deref(),
835        &config.digest,
836    )
837    .ok_or_else(|| Fallback::NotProved("git would not hash the cluster identity".into()))?;
838    let provenance = format!(
839        "platform={PLATFORM} image={} job={} name={} bundle={}",
840        proof.image_id, proof.uid, proof.job, proof.bundle_bytes
841    );
842    record_token(tree, &token, &provenance)
843}
844
845/// Write `token`, as given, on `tree`'s cluster note with its provenance. The
846/// detached lane passes the token it froze at submission, never one worked out
847/// from today's configuration.
848fn record_token(tree: &str, token: &str, provenance: &str) -> Result<(), Fallback> {
849    let _held = STAMP_LOCK.lock().unwrap_or_else(|p| p.into_inner());
850    if crate::gate_stamp::stamp_cluster(tree, token, provenance) {
851        Ok(())
852    } else {
853        Err(Fallback::NotProved(
854            "git refused to write the cluster stamp".into(),
855        ))
856    }
857}
858
859/// Everything after the Job exists: the bundle in, the logs out, the verdict.
860fn run_in(
861    kube: &Kube,
862    config: &ClusterConfig,
863    job: &Job,
864    scratch: &Scratch,
865    commit: &str,
866    tree: &str,
867    deadline: Instant,
868) -> Result<Proof, Fallback> {
869    let bundle = Bundle::create(scratch, job.slot, commit)?;
870    let cap = config.max_bundle_mib;
871    if bundle.bytes > cap * MIB {
872        return Err(Fallback::BundleTooBig {
873            mib: bundle.bytes.div_ceil(MIB),
874            cap,
875        });
876    }
877    let fetch_until = deadline.min(Instant::now() + config.start_wait);
878    let pod = wait_for_fetch(kube, &job.uid, fetch_until, config.start_wait)?;
879    kube.send_bundle(&pod, &bundle, deadline)?;
880    wait_for_gate(kube, &job.uid, deadline)?;
881    kube.stream_logs(&pod, deadline);
882    let end = wait_for_job(kube, job, deadline)?;
883    let pod = pod_facts(kube, &job.uid, deadline)?
884        .ok_or_else(|| Fallback::NotProved("the pod is gone".into()))?;
885    let image_id = judge(&end, &pod, tree, config.prepare.as_deref())?;
886    Ok(Proof {
887        image_id,
888        uid: job.uid.clone(),
889        job: job.name.clone(),
890        bundle_bytes: bundle.bytes,
891    })
892}
893
894/// A commit with no parent holding `tree`, fixed identity and date, so the
895/// same tree is the same commit. Nothing refers to it once the bundle is
896/// written.
897fn parentless_commit(tree: &str) -> Option<String> {
898    let out = Command::new("git")
899        .args(["commit-tree", tree, "-m", "amont cluster gate"])
900        .env("GIT_AUTHOR_NAME", "amont")
901        .env("GIT_AUTHOR_EMAIL", "amont@localhost")
902        .env("GIT_COMMITTER_NAME", "amont")
903        .env("GIT_COMMITTER_EMAIL", "amont@localhost")
904        .env("GIT_AUTHOR_DATE", "@0 +0000")
905        .env("GIT_COMMITTER_DATE", "@0 +0000")
906        .stdin(Stdio::null())
907        .output()
908        .ok()?;
909    let oid = String::from_utf8_lossy(&out.stdout).trim().to_string();
910    (out.status.success() && !oid.is_empty()).then_some(oid)
911}
912
913/// The repository's name as a plain `[A-Za-z0-9._-]` word with no leading
914/// dot: the cache subPath, so one repository's code cannot plant a cache
915/// another's gate reads. From the COMMON git directory, so every worktree of
916/// one repository shares it.
917fn repo_dir() -> String {
918    let common = crate::git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])
919        .map(PathBuf::from)
920        .unwrap_or_default();
921    let name = if common.file_name().is_some_and(|n| n == ".git") {
922        common.parent().and_then(Path::file_name)
923    } else {
924        common.file_name()
925    };
926    sanitize_repo_dir(
927        &name
928            .map(|n| n.to_string_lossy().into_owned())
929            .unwrap_or_default(),
930    )
931}
932
933/// See [`repo_dir`]. Pure.
934fn sanitize_repo_dir(raw: &str) -> String {
935    let raw = raw.strip_suffix(".git").unwrap_or(raw);
936    let clean: String = raw
937        .chars()
938        .map(|c| {
939            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
940                c
941            } else {
942                '-'
943            }
944        })
945        .collect();
946    let clean = clean.trim_start_matches('.');
947    if clean.is_empty() {
948        "repo".to_string()
949    } else {
950        clean.to_string()
951    }
952}
953
954struct Kube {
955    kubeconfig: PathBuf,
956    namespace: String,
957}
958
959/// How a kubectl call ended.
960enum Call {
961    Ok(String),
962    /// Exit non-zero, with its stderr.
963    Refused(String),
964    /// Could not start: nothing reached the apiserver.
965    NotStarted(String),
966    /// Outlived its deadline, or its wait failed: the request may have
967    /// reached the apiserver all the same.
968    TimedOut(String),
969}
970
971impl Kube {
972    fn new(config: &ClusterConfig) -> Kube {
973        Kube {
974            kubeconfig: config.kubeconfig.clone(),
975            namespace: config.namespace.clone(),
976        }
977    }
978
979    /// `kubectl --kubeconfig <path> <request timeout> -n <ns> <args>`, stdin
980    /// null, git's environment removed.
981    fn command(&self, request_timeout: &str, args: &[&str]) -> Command {
982        let mut cmd = Command::new(crate::hooks::common::program("kubectl"));
983        cmd.arg("--kubeconfig")
984            .arg(&self.kubeconfig)
985            .arg(request_timeout)
986            .args(["-n", &self.namespace])
987            .args(args)
988            .stdin(Stdio::null());
989        crate::hooks::common::strip_git_env(&mut cmd);
990        cmd
991    }
992
993    /// One request, under kubectl's own 10 s request timeout.
994    fn short_call(&self, args: &[&str]) -> Command {
995        self.command("--request-timeout=10s", args)
996    }
997
998    /// `exec` and `logs -f`, whose stream kubectl's request timeout would
999    /// cut: the ceiling is ours.
1000    fn stream_call(&self, args: &[&str]) -> Command {
1001        self.command("--request-timeout=0", args)
1002    }
1003
1004    fn capture(&self, args: &[&str], secs: u64) -> Call {
1005        capture(&mut self.short_call(args), secs)
1006    }
1007
1008    /// A call whose output does not matter, only that it worked.
1009    fn bounded(&self, args: &[&str], secs: u64) -> Result<(), String> {
1010        match self.capture(args, secs) {
1011            Call::Ok(_) => Ok(()),
1012            Call::Refused(e) | Call::NotStarted(e) | Call::TimedOut(e) => Err(last_line(&e)),
1013        }
1014    }
1015
1016    /// The bundle, on the one stdin that is not null; its stderr is the
1017    /// reason when it fails.
1018    fn send_bundle(&self, pod: &str, bundle: &Bundle, deadline: Instant) -> Result<(), Fallback> {
1019        let file = std::fs::File::open(&bundle.path)
1020            .map_err(|e| Fallback::NotProved(format!("bundle: {e}")))?;
1021        let bytes = format!("EXPECTED_BYTES={}", bundle.bytes);
1022        let mut cmd = self.stream_call(&[
1023            "exec",
1024            "-i",
1025            "-c",
1026            "fetch",
1027            pod,
1028            "--",
1029            "env",
1030            &bytes,
1031            "fetch-receive",
1032        ]);
1033        cmd.stdin(file);
1034        let secs = secs_left(deadline, u64::MAX);
1035        match capture(&mut cmd, secs) {
1036            Call::Ok(_) => Ok(()),
1037            Call::Refused(e) => Err(Fallback::NotProved(format!(
1038                "fetch-receive failed: {}",
1039                last_line(&e)
1040            ))),
1041            Call::NotStarted(e) | Call::TimedOut(e) => Err(Fallback::Unreachable(e)),
1042        }
1043    }
1044
1045    /// The gate's output, as it runs, under the ceiling clock only: the
1046    /// silence budget does not apply to a pod. What the logs say decides
1047    /// nothing, so a log stream that fails is not a reason to fall back.
1048    fn stream_logs(&self, pod: &str, deadline: Instant) {
1049        let mut cmd = self.stream_call(&["logs", "-f", pod, "-c", "gate"]);
1050        let secs = secs_left(deadline, u64::MAX);
1051        match crate::live::current_sink() {
1052            Some((stage, idx)) => {
1053                cmd.stdout(Stdio::piped()).stderr(Stdio::null());
1054                let Ok(mut child) = cmd.spawn() else {
1055                    return;
1056                };
1057                if let Some(mut out) = child.stdout.take() {
1058                    // Detached: it ends with the pipe, and the pipe with kubectl.
1059                    std::thread::spawn(move || {
1060                        let mut buf = [0u8; 8192];
1061                        while let Ok(n) = std::io::Read::read(&mut out, &mut buf) {
1062                            if n == 0 {
1063                                break;
1064                            }
1065                            stage.append_raw(idx, &buf[..n]);
1066                        }
1067                    });
1068                }
1069                let waited = crate::hooks::common::wait_within(
1070                    &mut child,
1071                    crate::hooks::common::Clocks::ceiling_only(secs),
1072                    None,
1073                );
1074                drop(waited); // the logs decide nothing; see above
1075            }
1076            None => {
1077                let shown = crate::hooks::common::status_within_secs(&mut cmd, secs);
1078                drop(shown); // the logs decide nothing; see above
1079            }
1080        }
1081    }
1082}
1083
1084/// Run `cmd` with stdout and stderr captured apart, under a ceiling of
1085/// `secs`, through the hooks' bounded wait. Takes no host slot.
1086fn capture(cmd: &mut Command, secs: u64) -> Call {
1087    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
1088    let mut child = match cmd.spawn() {
1089        Ok(c) => c,
1090        Err(e) => return Call::NotStarted(format!("kubectl: {e}")),
1091    };
1092    let out = drain(child.stdout.take());
1093    let err = drain(child.stderr.take());
1094    let ran = crate::hooks::common::wait_within(
1095        &mut child,
1096        crate::hooks::common::Clocks::ceiling_only(secs),
1097        None,
1098    );
1099    let collect = |rx: std::sync::mpsc::Receiver<Vec<u8>>| {
1100        rx.recv_timeout(Duration::from_secs(2))
1101            .map(|b| String::from_utf8_lossy(&b).into_owned())
1102            .unwrap_or_default()
1103    };
1104    match ran {
1105        Ok(crate::hooks::common::Ran::Status(s)) if s.success() => Call::Ok(collect(out)),
1106        Ok(crate::hooks::common::Ran::Status(_)) => Call::Refused(collect(err)),
1107        Ok(crate::hooks::common::Ran::TimedOut(_)) => Call::TimedOut("kubectl timed out".into()),
1108        Err(e) => Call::TimedOut(format!("kubectl: {e}")),
1109    }
1110}
1111
1112/// Read a pipe to its end on a thread, handing the bytes over once.
1113fn drain(pipe: Option<impl std::io::Read + Send + 'static>) -> std::sync::mpsc::Receiver<Vec<u8>> {
1114    let (tx, rx) = std::sync::mpsc::channel();
1115    if let Some(mut pipe) = pipe {
1116        std::thread::spawn(move || {
1117            let mut buf = Vec::new();
1118            // A read error ends the pipe early; what was read still counts.
1119            let read = pipe.read_to_end(&mut buf);
1120            drop(read);
1121            // The receiver gave up after its own timeout: nobody to tell.
1122            let sent = tx.send(buf);
1123            drop(sent);
1124        });
1125    }
1126    rx
1127}
1128
1129/// What a refused `kubectl create` means for the slot.
1130#[derive(Debug, PartialEq, Eq)]
1131enum Refusal {
1132    /// The Job name is taken: the next slot.
1133    Taken,
1134    /// The quota is full: the next slot, then local.
1135    Quota,
1136    /// Anything else: the apiserver failing.
1137    Other,
1138}
1139
1140fn refusal(stderr: &str) -> Refusal {
1141    if stderr.contains("exceeded quota") {
1142        Refusal::Quota
1143    } else if stderr.contains("AlreadyExists") || stderr.contains("already exists") {
1144        Refusal::Taken
1145    } else {
1146        Refusal::Other
1147    }
1148}
1149
1150/// A Job amont created.
1151struct Job {
1152    run: u64,
1153    slot: u32,
1154    name: String,
1155    uid: String,
1156    gate: String,
1157}
1158
1159impl Job {
1160    /// Foreground and waited for, so no old pod still holds the slot's PVC
1161    /// when the next Job takes it — within the time left; past the deadline
1162    /// it is only asked to go. A delete that fails is said and logged: the
1163    /// slot stays taken until its TTL.
1164    fn delete(&self, kube: &Kube, gate: &str, deadline: Instant) {
1165        let left = deadline.saturating_duration_since(Instant::now()).as_secs();
1166        let timeout = format!("--timeout={}s", left.max(1));
1167        let deleted = if left >= 5 {
1168            let args = [
1169                "delete",
1170                "job",
1171                &self.name,
1172                "--cascade=foreground",
1173                "--wait",
1174                &timeout,
1175            ];
1176            kube.bounded(&args, left)
1177        } else {
1178            kube.bounded(&["delete", "job", &self.name, "--wait=false"], 5)
1179        };
1180        if let Err(why) = deleted {
1181            let reason = format!("could not delete Job {}: {why}", self.name);
1182            crate::hooks::common::warn(&reason);
1183            log_line(gate, &reason);
1184        }
1185        live_update(self.run, |l| l.created = Created::NotSent);
1186    }
1187}
1188
1189/// What the Job spec is built from.
1190struct Spec<'a> {
1191    config: &'a ClusterConfig,
1192    gate: &'a str,
1193    tree: &'a str,
1194    repo_dir: &'a str,
1195    argv: &'a [String],
1196    /// The value of the Job's `amont.run` label.
1197    run_label: &'a str,
1198}
1199
1200/// Create `amont-gate-slot-<k>` for the first free `k`.
1201fn claim_slot(
1202    kube: &Kube,
1203    spec: &Spec,
1204    scratch: &Scratch,
1205    deadline: Instant,
1206) -> Result<Job, Fallback> {
1207    crate::staged_only::install_signal_handler();
1208    let mut refusals = Vec::new();
1209    for slot in 0..spec.config.slots {
1210        let path = scratch.write(
1211            &format!("job-{slot}.json"),
1212            job_manifest(spec, slot).as_bytes(),
1213        )?;
1214        let path = path.to_string_lossy().into_owned();
1215        let name = format!("{JOB_PREFIX}{slot}");
1216        let args = ["create", "-f", &path, "-o", "jsonpath={.metadata.uid}"];
1217        live_update(scratch.run, |l| l.created = Created::Sent);
1218        let created = kube.capture(&args, secs_left(deadline, CALL_SECS));
1219        if crate::tree_run::is_dying() {
1220            // The signal watcher may have cleaned up before this `create`
1221            // landed: whatever it made is ours to drop, then park.
1222            delete_by_label(kube, &scratch.run_label(), spec.gate);
1223            crate::tree_run::park_if_dying();
1224        }
1225        match created {
1226            Call::Ok(uid) if !uid.trim().is_empty() => {
1227                live_update(scratch.run, |l| l.created = Created::Named(name.clone()));
1228                return Ok(Job {
1229                    run: scratch.run,
1230                    slot,
1231                    name,
1232                    uid: uid.trim().to_string(),
1233                    gate: spec.gate.to_string(),
1234                });
1235            }
1236            Call::Ok(_) => {
1237                // The Job exists, only unnamed by its UID: take it down by
1238                // name rather than hold the slot until its deadline.
1239                live_update(scratch.run, |l| l.created = Created::Named(name.clone()));
1240                delete_by_name(kube, &name, spec.gate);
1241                live_update(scratch.run, |l| l.created = Created::NotSent);
1242                return Err(Fallback::NotProved(
1243                    "kubectl create printed no Job UID".into(),
1244                ));
1245            }
1246            Call::Refused(err) => match refusal(&err) {
1247                Refusal::Taken | Refusal::Quota => refusals.push(refusal(&err)),
1248                Refusal::Other => return Err(Fallback::Unreachable(last_line(&err))),
1249            },
1250            Call::NotStarted(err) => return Err(Fallback::Unreachable(err)),
1251            // The request may have landed: drop whatever it made, briefly and
1252            // quietly; the Job's deadline bounds what a failed delete leaves.
1253            Call::TimedOut(err) => {
1254                delete_by_label(kube, &scratch.run_label(), spec.gate);
1255                return Err(Fallback::Unreachable(err));
1256            }
1257        }
1258    }
1259    if refusals.iter().all(|r| *r == Refusal::Quota) {
1260        Err(Fallback::QuotaFull)
1261    } else {
1262        Err(Fallback::SlotsTaken)
1263    }
1264}
1265
1266/// Ask the apiserver to drop the Job `name`, without waiting for it, for a Job
1267/// whose UID is unknown. A delete that fails is said and logged.
1268fn delete_by_name(kube: &Kube, name: &str, gate: &str) {
1269    if let Err(why) = kube.bounded(&["delete", "job", name, "--wait=false"], CALL_SECS) {
1270        say_delete_failed(&format!("Job {name}"), &why, gate);
1271    }
1272}
1273
1274/// Ask the apiserver to drop every Job carrying this run's label, without
1275/// waiting: for a `create` whose answer was lost. Bounded short and logged
1276/// only: the person was already told the cluster did not answer, and a Job
1277/// left behind ends at its own deadline.
1278fn delete_by_label(kube: &Kube, label: &str, gate: &str) {
1279    let selector = run_selector(label);
1280    let args = ["delete", "job", "-l", &selector, "--wait=false"];
1281    if let Err(why) = kube.bounded(&args, LABEL_DELETE_SECS) {
1282        log_line(
1283            gate,
1284            &format!(
1285                "could not delete the Jobs of this run: {}",
1286                crate::ui::sanitize(&why)
1287            ),
1288        );
1289    }
1290}
1291
1292/// The label selector of one run's Jobs.
1293fn run_selector(label: &str) -> String {
1294    format!("{RUN_LABEL_KEY}={label}")
1295}
1296
1297fn say_delete_failed(what: &str, why: &str, gate: &str) {
1298    let reason = format!("could not delete {what}: {}", crate::ui::sanitize(why));
1299    crate::hooks::common::warn(&reason);
1300    log_line(gate, &reason);
1301}
1302
1303fn last_line(s: &str) -> String {
1304    s.lines()
1305        .rev()
1306        .map(str::trim)
1307        .find(|l| !l.is_empty())
1308        .unwrap_or("no output")
1309        .to_string()
1310}
1311
1312fn json_string(v: &str) -> String {
1313    format!("\"{}\"", crate::json::escape(v))
1314}
1315
1316fn env_var(name: &str, value: &str) -> String {
1317    format!(
1318        "{{\"name\":{},\"value\":{}}}",
1319        json_string(name),
1320        json_string(value)
1321    )
1322}
1323
1324fn mount(name: &str, path: &str) -> String {
1325    format!(
1326        "{{\"name\":{},\"mountPath\":{}}}",
1327        json_string(name),
1328        json_string(path)
1329    )
1330}
1331
1332fn mount_sub(name: &str, path: &str, sub: &str) -> String {
1333    format!(
1334        "{{\"name\":{},\"mountPath\":{},\"subPath\":{}}}",
1335        json_string(name),
1336        json_string(path),
1337        json_string(sub)
1338    )
1339}
1340
1341fn args_json(argv: &[String]) -> String {
1342    format!(
1343        "[{}]",
1344        argv.iter()
1345            .map(|a| json_string(a))
1346            .collect::<Vec<_>>()
1347            .join(",")
1348    )
1349}
1350
1351const SECURITY: &str = "{\"allowPrivilegeEscalation\":false,\"capabilities\":{\"drop\":[\"ALL\"]}}";
1352
1353fn container(name: &str, image: &str, argv: &[String], extra: &str) -> String {
1354    format!(
1355        "{{\"name\":{},\"image\":{},\"args\":{},\"securityContext\":{SECURITY},{extra}}}",
1356        json_string(name),
1357        json_string(image),
1358        args_json(argv)
1359    )
1360}
1361
1362fn resources(memory: &str, cpu: &str) -> String {
1363    format!(
1364        "\"resources\":{{\"requests\":{{\"memory\":{m},\"cpu\":\"500m\"}},\
1365         \"limits\":{{\"memory\":{m},\"cpu\":{c}}}}}",
1366        m = json_string(memory),
1367        c = json_string(cpu)
1368    )
1369}
1370
1371/// The Job, as JSON `kubectl create -f` reads. `args`, never `command`: the
1372/// image's ENTRYPOINT is tini.
1373fn job_manifest(spec: &Spec, slot: u32) -> String {
1374    let config = spec.config;
1375    let gate_ref = format!("{TEMP_REF_PREFIX}{slot}");
1376    let fetch = container(
1377        "fetch",
1378        &config.image,
1379        &["/usr/local/bin/fetch".to_string()],
1380        &format!(
1381            "\"env\":[{},{},{}],\"volumeMounts\":[{},{},{}],{}",
1382            env_var("EXPECTED_TREE", spec.tree),
1383            env_var("GATE_REF", &gate_ref),
1384            env_var("REPO_DIR", spec.repo_dir),
1385            mount("cache", "/cache"),
1386            mount("work", "/work"),
1387            mount("checkout", "/checkout"),
1388            resources("512Mi", "1"),
1389        ),
1390    );
1391    let work_mounts = format!(
1392        "\"workingDir\":\"/checkout\",\"volumeMounts\":[{},{}],{}",
1393        mount_sub("cache", "/cache", spec.repo_dir),
1394        mount("checkout", "/checkout"),
1395        resources(MEMORY, CPU_LIMIT),
1396    );
1397    let mut init = vec![fetch];
1398    if let Some(prepare) = &config.prepare {
1399        let argv = ["sh".to_string(), "-c".to_string(), prepare.clone()];
1400        init.push(container("prepare", &config.image, &argv, &work_mounts));
1401    }
1402    let gate = container("gate", &config.image, spec.argv, &work_mounts);
1403    format!(
1404        "{{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\
1405         \"metadata\":{{\"name\":{name},\"labels\":{{\"app.kubernetes.io/managed-by\":\"amont\",{run_label_key}:{run_label}}},\
1406         \"annotations\":{{\"amont.dev/gate\":{gate_id},\"amont.dev/tree\":{tree}}}}},\
1407         \"spec\":{{\"backoffLimit\":0,\"activeDeadlineSeconds\":{deadline},\
1408         \"ttlSecondsAfterFinished\":300,\"template\":{{\"spec\":{{\
1409         \"restartPolicy\":\"Never\",\"priorityClassName\":{prio},\
1410         \"nodeSelector\":{{\"kubernetes.io/hostname\":{node}}},\
1411         \"imagePullSecrets\":[{{\"name\":{pull}}}],\
1412         \"automountServiceAccountToken\":false,\
1413         \"securityContext\":{{\"runAsNonRoot\":true,\"runAsUser\":1000,\"runAsGroup\":1000,\
1414         \"fsGroup\":1000,\"seccompProfile\":{{\"type\":\"RuntimeDefault\"}}}},\
1415         \"volumes\":[{{\"name\":\"cache\",\"persistentVolumeClaim\":{{\"claimName\":{pvc}}}}},\
1416         {{\"name\":\"work\",\"emptyDir\":{{}}}},{{\"name\":\"checkout\",\"emptyDir\":{{}}}}],\
1417         \"initContainers\":[{init}],\"containers\":[{gate}]}}}}}}}}",
1418        name = json_string(&format!("{JOB_PREFIX}{slot}")),
1419        run_label_key = json_string(RUN_LABEL_KEY),
1420        run_label = json_string(spec.run_label),
1421        gate_id = json_string(spec.gate),
1422        tree = json_string(spec.tree),
1423        deadline = config.timeout_secs + 60,
1424        prio = json_string(PRIORITY_CLASS),
1425        node = json_string(NODE),
1426        pull = json_string(PULL_SECRET),
1427        pvc = json_string(&format!("{CACHE_PREFIX}{slot}")),
1428        init = init.join(","),
1429    )
1430}
1431
1432/// Unique to this process and run, across every host sharing the namespace
1433/// (pids repeat from host to host, and in containers): the pid, a random
1434/// per-process nonce and the run. 45 characters at most (a 7-digit pid, 16
1435/// hex digits, a 20-digit run), inside a label value's 63, alphanumeric at
1436/// both ends.
1437fn run_label(run: u64) -> String {
1438    format!("{}-{:016x}-{run}", std::process::id(), process_nonce())
1439}
1440
1441/// 64 random bits, drawn once per process from the standard library's
1442/// randomly seeded hasher: no dependency, no file to read.
1443fn process_nonce() -> u64 {
1444    use std::hash::{BuildHasher, Hasher};
1445    static NONCE: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1446    *NONCE.get_or_init(|| {
1447        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
1448        hasher.write_u128(
1449            std::time::SystemTime::now()
1450                .duration_since(std::time::UNIX_EPOCH)
1451                .map_or(0, |d| d.as_nanos()),
1452        );
1453        hasher.finish()
1454    })
1455}
1456
1457/// A private scratch directory for one cluster run — the Job manifests and
1458/// the bundle — created fresh (mode 0700 on unix), so no other user can guess,
1459/// pre-create or redirect a path in it. Removed on drop, with its entry in
1460/// the interrupt list.
1461struct Scratch {
1462    run: u64,
1463    dir: PathBuf,
1464}
1465
1466impl Scratch {
1467    fn new(gate: &str, kube: &Kube) -> Result<Scratch, Fallback> {
1468        let run = SEQ.fetch_add(1, Ordering::SeqCst);
1469        let gate: String = gate
1470            .chars()
1471            .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
1472            .collect();
1473        let dir =
1474            std::env::temp_dir().join(format!("amont-cluster-{}-{run}-{gate}", std::process::id()));
1475        #[cfg(unix)]
1476        let builder = {
1477            let mut builder = std::fs::DirBuilder::new();
1478            std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
1479            builder
1480        };
1481        #[cfg(not(unix))]
1482        let builder = std::fs::DirBuilder::new();
1483        builder
1484            .create(&dir)
1485            .map_err(|e| Fallback::NotProved(format!("scratch directory: {e}")))?;
1486        LIVE.lock()
1487            .unwrap_or_else(|p| p.into_inner())
1488            .push(LiveRun {
1489                run,
1490                kubeconfig: kube.kubeconfig.clone(),
1491                namespace: kube.namespace.clone(),
1492                scratch: dir.clone(),
1493                run_label: run_label(run),
1494                created: Created::NotSent,
1495                gate_ref: None,
1496            });
1497        Ok(Scratch { run, dir })
1498    }
1499
1500    /// The `amont.run` label value of this run's Jobs.
1501    fn run_label(&self) -> String {
1502        run_label(self.run)
1503    }
1504
1505    /// A new file in the scratch directory; refused if it exists.
1506    fn write(&self, name: &str, bytes: &[u8]) -> Result<PathBuf, Fallback> {
1507        let path = self.dir.join(name);
1508        let mut options = std::fs::OpenOptions::new();
1509        options.write(true).create_new(true);
1510        #[cfg(unix)]
1511        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
1512        options
1513            .open(&path)
1514            .and_then(|mut f| std::io::Write::write_all(&mut f, bytes))
1515            .map_err(|e| Fallback::NotProved(format!("scratch file: {e}")))?;
1516        Ok(path)
1517    }
1518}
1519
1520impl Drop for Scratch {
1521    fn drop(&mut self) {
1522        if let Err(e) = std::fs::remove_dir_all(&self.dir) {
1523            crate::hooks::common::warn(&format!("could not remove {}: {e}", self.dir.display()));
1524        }
1525        LIVE.lock()
1526            .unwrap_or_else(|p| p.into_inner())
1527            .retain(|l| l.run != self.run);
1528    }
1529}
1530
1531/// The judged commit as a git bundle of one temporary ref.
1532struct Bundle {
1533    path: PathBuf,
1534    bytes: u64,
1535}
1536
1537impl Bundle {
1538    fn create(scratch: &Scratch, slot: u32, commit: &str) -> Result<Bundle, Fallback> {
1539        let gate_ref = format!("{TEMP_REF_PREFIX}{slot}");
1540        if !crate::git::succeeds(&["update-ref", &gate_ref, commit]) {
1541            return Err(Fallback::NotProved(format!(
1542                "git update-ref {gate_ref} failed"
1543            )));
1544        }
1545        live_update(scratch.run, |l| l.gate_ref = Some(gate_ref.clone()));
1546        let path = scratch.dir.join(format!("{slot}.bundle"));
1547        let path_text = path.to_string_lossy().into_owned();
1548        let made = crate::git::succeeds(&["bundle", "create", "-q", &path_text, &gate_ref]);
1549        let dropped = crate::git::succeeds(&["update-ref", "-d", &gate_ref]);
1550        live_update(scratch.run, |l| l.gate_ref = None);
1551        if !dropped {
1552            crate::hooks::common::warn(&format!("could not delete the temporary ref {gate_ref}"));
1553        }
1554        if !made {
1555            return Err(Fallback::NotProved("git bundle create failed".into()));
1556        }
1557        let bytes = std::fs::metadata(&path)
1558            .map_err(|e| Fallback::NotProved(format!("bundle: {e}")))?
1559            .len();
1560        Ok(Bundle { path, bytes })
1561    }
1562}
1563
1564/// One container's state.
1565#[derive(Debug, Clone, PartialEq, Eq)]
1566enum State {
1567    Absent,
1568    Waiting,
1569    Running,
1570    Terminated {
1571        exit: Option<i64>,
1572        reason: String,
1573        message: String,
1574    },
1575}
1576
1577impl State {
1578    fn of(status: Option<&Value>) -> State {
1579        let Some(state) = status.and_then(|s| s.get("state")) else {
1580            return State::Absent;
1581        };
1582        if let Some(t) = state.get("terminated") {
1583            let text = |k: &str| t.get(k).and_then(Value::as_str).unwrap_or("").to_string();
1584            let exit = match t.get("exitCode") {
1585                Some(Value::Num(n)) => n.parse().ok(),
1586                _ => None,
1587            };
1588            return State::Terminated {
1589                exit,
1590                reason: text("reason"),
1591                message: text("message"),
1592            };
1593        }
1594        if state.get("running").is_some() {
1595            return State::Running;
1596        }
1597        State::Waiting
1598    }
1599
1600    fn started(&self) -> bool {
1601        match self {
1602            State::Running | State::Terminated { .. } => true,
1603            State::Absent | State::Waiting => false,
1604        }
1605    }
1606
1607    fn passed(&self) -> bool {
1608        matches!(self, State::Terminated { exit: Some(0), .. })
1609    }
1610
1611    /// `exit N` or `exit N, <reason>` for a container that ended badly.
1612    fn failed(&self) -> Option<String> {
1613        let State::Terminated { exit, reason, .. } = self else {
1614            return None;
1615        };
1616        if *exit == Some(0) {
1617            return None;
1618        }
1619        let code = exit.map_or("an unknown code".to_string(), |c| c.to_string());
1620        Some(match reason.as_str() {
1621            "" | "Error" | "Completed" => format!("exit {code}"),
1622            r => format!("exit {code}, {r}"),
1623        })
1624    }
1625}
1626
1627/// The pod's phase.
1628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1629enum Phase {
1630    Pending,
1631    Running,
1632    Succeeded,
1633    Failed,
1634    Unknown,
1635}
1636
1637impl Phase {
1638    fn parse(s: &str) -> Phase {
1639        match s {
1640            "Pending" => Phase::Pending,
1641            "Running" => Phase::Running,
1642            "Succeeded" => Phase::Succeeded,
1643            "Failed" => Phase::Failed,
1644            _ => Phase::Unknown,
1645        }
1646    }
1647
1648    fn ended(self) -> bool {
1649        match self {
1650            Phase::Succeeded | Phase::Failed => true,
1651            Phase::Pending | Phase::Running | Phase::Unknown => false,
1652        }
1653    }
1654}
1655
1656/// The pod's recorded facts.
1657#[derive(Debug, Clone, PartialEq, Eq)]
1658struct PodFacts {
1659    name: String,
1660    phase: Phase,
1661    disrupted: bool,
1662    fetch: State,
1663    prepare: State,
1664    gate: State,
1665    image_id: Option<String>,
1666}
1667
1668fn named<'a>(list: Option<&'a Value>, name: &str) -> Option<&'a Value> {
1669    list?
1670        .items()
1671        .iter()
1672        .find(|c| c.get("name").and_then(Value::as_str) == Some(name))
1673}
1674
1675fn str_at<'a>(v: Option<&'a Value>, key: &str) -> Option<&'a str> {
1676    v?.get(key).and_then(Value::as_str)
1677}
1678
1679/// The first pod of `kubectl get pods -o json`, as facts. Pure. The gate's
1680/// container is `gate`: a Job's.
1681fn parse_pod(json: &str) -> Option<PodFacts> {
1682    let doc = crate::json_read::parse(json)?;
1683    parse_pod_object(doc.get("items")?.items().first()?, "gate")
1684}
1685
1686/// One Pod object, as facts, the gate being the container `gate_container`:
1687/// `gate` in a Job's pod, `main` in an Argo Workflow's (Argo names the main
1688/// container itself). Pure.
1689fn parse_pod_object(pod: &Value, gate_container: &str) -> Option<PodFacts> {
1690    let status = pod.get("status");
1691    let inits = status.and_then(|s| s.get("initContainerStatuses"));
1692    let mains = status.and_then(|s| s.get("containerStatuses"));
1693    let gate = named(mains, gate_container);
1694    let disrupted = status.and_then(|s| s.get("conditions")).is_some_and(|c| {
1695        c.items().iter().any(|c| {
1696            str_at(Some(c), "type") == Some("DisruptionTarget")
1697                && str_at(Some(c), "status") == Some("True")
1698        })
1699    });
1700    Some(PodFacts {
1701        name: str_at(pod.get("metadata"), "name")?.to_string(),
1702        phase: Phase::parse(str_at(status, "phase").unwrap_or("")),
1703        disrupted,
1704        fetch: State::of(named(inits, "fetch")),
1705        prepare: State::of(named(inits, "prepare")),
1706        gate: State::of(gate),
1707        image_id: str_at(gate, "imageID")
1708            .filter(|s| !s.is_empty())
1709            .map(str::to_string),
1710    })
1711}
1712
1713/// The Job's terminal condition, if it has one.
1714#[derive(Debug, Clone, PartialEq, Eq)]
1715enum JobEnd {
1716    Running,
1717    Complete,
1718    Failed(String),
1719}
1720
1721/// `kubectl get job -o json`: its UID, its gate annotation, its end. Pure.
1722#[derive(Debug, Clone, PartialEq, Eq)]
1723struct JobFacts {
1724    uid: Option<String>,
1725    gate: Option<String>,
1726    end: JobEnd,
1727}
1728
1729fn parse_job(json: &str) -> Option<JobFacts> {
1730    let doc = crate::json_read::parse(json)?;
1731    let metadata = doc.get("metadata");
1732    let conditions = doc.get("status").and_then(|s| s.get("conditions"));
1733    let truthy = |c: &&Value| str_at(Some(c), "status") == Some("True");
1734    let mut end = JobEnd::Running;
1735    for c in conditions
1736        .map(Value::items)
1737        .unwrap_or(&[])
1738        .iter()
1739        .filter(truthy)
1740    {
1741        match str_at(Some(c), "type") {
1742            Some("Failed") => {
1743                let reason = str_at(Some(c), "reason").unwrap_or("Failed");
1744                end = JobEnd::Failed(reason.to_string());
1745                break;
1746            }
1747            Some("Complete") => end = JobEnd::Complete,
1748            _ => {}
1749        }
1750    }
1751    Some(JobFacts {
1752        uid: str_at(metadata, "uid").map(str::to_string),
1753        gate: str_at(
1754            metadata.and_then(|m| m.get("annotations")),
1755            "amont.dev/gate",
1756        )
1757        .map(str::to_string),
1758        end,
1759    })
1760}
1761
1762/// The verdict, from recorded facts only: the observed imageID on a pass,
1763/// else why not. Pure.
1764fn judge(
1765    end: &JobEnd,
1766    pod: &PodFacts,
1767    expected_tree: &str,
1768    prepare: Option<&str>,
1769) -> Result<String, Fallback> {
1770    let not = |why: String| Err(Fallback::NotProved(why));
1771    if pod.disrupted {
1772        return not("the pod was disrupted (DisruptionTarget)".into());
1773    }
1774    match end {
1775        JobEnd::Complete => {}
1776        JobEnd::Failed(reason) => {
1777            return match pod.gate.failed() {
1778                Some(detail) => Err(Fallback::GateFailed(detail)),
1779                None => not(format!("the Job failed ({reason})")),
1780            }
1781        }
1782        JobEnd::Running => return not("the Job has no terminal condition".into()),
1783    }
1784    let want = format!("tree {expected_tree}");
1785    match &pod.fetch {
1786        State::Terminated {
1787            exit: Some(0),
1788            message,
1789            ..
1790        } if message.trim() == want => {}
1791        State::Terminated { message, .. } => {
1792            return not(format!("fetch reported {:?}, not {want:?}", message.trim()))
1793        }
1794        State::Absent | State::Waiting | State::Running => {
1795            return not("fetch did not terminate".into())
1796        }
1797    }
1798    if prepare.is_some() && !pod.prepare.passed() {
1799        return not("prepare did not exit 0".into());
1800    }
1801    if !pod.gate.passed() {
1802        return match pod.gate.failed() {
1803            Some(detail) => Err(Fallback::GateFailed(detail)),
1804            None => not("the gate did not finish".into()),
1805        };
1806    }
1807    match &pod.image_id {
1808        Some(id) => Ok(id.clone()),
1809        None => not("the pod recorded no imageID".into()),
1810    }
1811}
1812
1813/// The pod of the Job `uid`, by its controller label only — never by name,
1814/// which an older Job's pod could share.
1815fn pod_facts(kube: &Kube, uid: &str, deadline: Instant) -> Result<Option<PodFacts>, Fallback> {
1816    let selector = format!("controller-uid={uid}");
1817    let args = ["get", "pods", "-l", &selector, "-o", "json"];
1818    match kube.capture(&args, secs_left(deadline, CALL_SECS)) {
1819        Call::Ok(json) => Ok(parse_pod(&json)),
1820        Call::Refused(e) => Err(Fallback::NotProved(format!(
1821            "kubectl get pods: {}",
1822            last_line(&e)
1823        ))),
1824        Call::NotStarted(e) | Call::TimedOut(e) => Err(Fallback::Unreachable(e)),
1825    }
1826}
1827
1828/// Poll until `done` answers, or `until` passes.
1829fn poll<T>(
1830    until: Instant,
1831    mut done: impl FnMut() -> Result<Option<T>, Fallback>,
1832) -> Result<Option<T>, Fallback> {
1833    loop {
1834        if let Some(v) = done()? {
1835            return Ok(Some(v));
1836        }
1837        if Instant::now() >= until {
1838            return Ok(None);
1839        }
1840        std::thread::sleep(POLL);
1841    }
1842}
1843
1844/// Wait, bounded, for `fetch` — trusted image code, before any repository
1845/// code — to be Running. The pod's name, or why not.
1846fn wait_for_fetch(
1847    kube: &Kube,
1848    uid: &str,
1849    until: Instant,
1850    wait: Duration,
1851) -> Result<String, Fallback> {
1852    let found = poll(until, || {
1853        let Some(p) = pod_facts(kube, uid, until)? else {
1854            return Ok(None);
1855        };
1856        Ok(match p.fetch {
1857            State::Running => Some(Ok(p.name)),
1858            State::Terminated { .. } => Some(Err(Fallback::NotProved(
1859                "fetch ended before the bundle arrived".into(),
1860            ))),
1861            State::Absent | State::Waiting => None,
1862        })
1863    })?;
1864    found.unwrap_or_else(|| {
1865        Err(Fallback::NotProved(format!(
1866            "the pod was not Running within {} s",
1867            wait.as_secs()
1868        )))
1869    })
1870}
1871
1872/// Wait until the gate container has started, or an init container failed.
1873fn wait_for_gate(kube: &Kube, uid: &str, deadline: Instant) -> Result<(), Fallback> {
1874    let found = poll(deadline, || {
1875        let Some(p) = pod_facts(kube, uid, deadline)? else {
1876            return Ok(None);
1877        };
1878        // An init container that failed is infrastructure, never the gate's
1879        // verdict: said first, whatever the pod's phase.
1880        if let Some(w) = p.fetch.failed() {
1881            return Ok(Some(Err(Fallback::NotProved(format!("fetch {w}")))));
1882        }
1883        if let Some(w) = p.prepare.failed() {
1884            return Ok(Some(Err(Fallback::NotProved(format!("prepare {w}")))));
1885        }
1886        Ok((p.gate.started() || p.phase.ended()).then_some(Ok(())))
1887    })?;
1888    found.unwrap_or_else(|| {
1889        Err(Fallback::NotProved(
1890            "the gate did not start before the deadline".into(),
1891        ))
1892    })
1893}
1894
1895/// Wait for the Job's terminal condition — shortly after the logs end, or at
1896/// the deadline — on the Job amont created: its UID and gate annotation must
1897/// be this run's, or nothing it reports is judged.
1898fn wait_for_job(kube: &Kube, job: &Job, deadline: Instant) -> Result<JobEnd, Fallback> {
1899    let until = deadline.min(Instant::now() + Duration::from_secs(60));
1900    let found = poll(until, || {
1901        let args = ["get", "job", &job.name, "-o", "json"];
1902        let json = match kube.capture(&args, secs_left(deadline, CALL_SECS)) {
1903            Call::Ok(json) => json,
1904            Call::Refused(e) => {
1905                return Err(Fallback::NotProved(format!(
1906                    "kubectl get job: {}",
1907                    last_line(&e)
1908                )))
1909            }
1910            Call::NotStarted(e) | Call::TimedOut(e) => return Err(Fallback::Unreachable(e)),
1911        };
1912        let Some(facts) = parse_job(&json) else {
1913            return Ok(None);
1914        };
1915        if facts.uid.as_deref() != Some(job.uid.as_str())
1916            || facts.gate.as_deref() != Some(job.gate.as_str())
1917        {
1918            return Err(Fallback::NotProved(format!(
1919                "{} is not the Job this run created",
1920                job.name
1921            )));
1922        }
1923        Ok((facts.end != JobEnd::Running).then_some(facts.end))
1924    })?;
1925    found.ok_or_else(|| Fallback::NotProved("the Job reached no terminal condition".into()))
1926}
1927
1928#[cfg(test)]
1929mod tests {
1930    use super::*;
1931    /// A run label is the pid, a 16-hex-digit nonce and the run: valid as a
1932    /// label value, distinct per run, and the same nonce within one process.
1933    #[test]
1934    fn a_run_label_is_pid_nonce_and_run() {
1935        let first = run_label(1);
1936        let parts: Vec<&str> = first.split('-').collect();
1937        assert_eq!(parts.len(), 3, "{first}");
1938        assert_eq!(parts[0], std::process::id().to_string());
1939        assert_eq!(parts[1].len(), 16, "{first}");
1940        assert!(parts[1].chars().all(|c| c.is_ascii_hexdigit()), "{first}");
1941        assert_eq!(parts[2], "1");
1942        assert!(first.len() <= 63);
1943        let second = run_label(2);
1944        assert_ne!(first, second);
1945        assert_eq!(second.split('-').nth(1), Some(parts[1]));
1946    }
1947
1948    fn cluster_config(prepare: Option<&str>) -> ClusterConfig {
1949        ClusterConfig {
1950            kubeconfig: PathBuf::from("/k"),
1951            namespace: "amont-gates".into(),
1952            slots: 2,
1953            image: format!("reg/gate:1@sha256:{}", "a".repeat(64)),
1954            digest: format!("sha256:{}", "a".repeat(64)),
1955            max_bundle_mib: 1,
1956            start_wait: Duration::from_secs(30),
1957            timeout_secs: 3600,
1958            prepare: prepare.map(str::to_string),
1959        }
1960    }
1961
1962    #[test]
1963    fn a_digest_is_sha256_and_64_hex() {
1964        let hex = "b".repeat(64);
1965        assert_eq!(
1966            digest_of(&format!("r/x:1@sha256:{hex}")),
1967            Some(format!("sha256:{hex}").as_str())
1968        );
1969        assert_eq!(digest_of("r/x:1"), None);
1970        assert_eq!(digest_of("r/x@sha256:short"), None);
1971    }
1972
1973    #[test]
1974    fn a_repo_dir_is_a_plain_name() {
1975        assert_eq!(sanitize_repo_dir("amont"), "amont");
1976        assert_eq!(sanitize_repo_dir("my repo!"), "my-repo-");
1977        assert_eq!(sanitize_repo_dir("..hidden"), "hidden");
1978        assert_eq!(sanitize_repo_dir("x.git"), "x");
1979        assert_eq!(sanitize_repo_dir(""), "repo");
1980    }
1981
1982    /// Every later wait is capped at the time the one deadline leaves.
1983    #[test]
1984    fn a_wait_never_outlives_the_deadline() {
1985        let soon = Instant::now() + Duration::from_secs(3);
1986        assert!(secs_left(soon, CALL_SECS) <= 3);
1987        let later = Instant::now() + Duration::from_secs(600);
1988        assert_eq!(secs_left(later, CALL_SECS), CALL_SECS);
1989        let past = Instant::now() - Duration::from_secs(1);
1990        assert_eq!(secs_left(past, CALL_SECS), 1, "a floor of one second");
1991    }
1992
1993    #[test]
1994    fn the_job_carries_the_contract() {
1995        let config = cluster_config(Some("make deps"));
1996        let argv = vec!["scripts/lint.sh".to_string(), "--strict".to_string()];
1997        let spec = Spec {
1998            config: &config,
1999            gate: "pre-commit-lint",
2000            tree: "abc",
2001            repo_dir: "amont",
2002            argv: &argv,
2003            run_label: "42-7",
2004        };
2005        let json = job_manifest(&spec, 1);
2006        let doc = crate::json_read::parse(&json).expect("valid JSON");
2007        let job_spec = doc.get("spec").unwrap();
2008        assert_eq!(job_spec.get("backoffLimit"), Some(&Value::Num("0".into())));
2009        assert_eq!(
2010            job_spec.get("activeDeadlineSeconds"),
2011            Some(&Value::Num("3660".into()))
2012        );
2013        assert!(!json.contains("\"command\""));
2014        for needle in [
2015            "\"name\":\"amont-gate-slot-1\"",
2016            "\"claimName\":\"gate-cache-1\"",
2017            "\"subPath\":\"amont\"",
2018            "\"restartPolicy\":\"Never\"",
2019            "\"priorityClassName\":\"gate-batch\"",
2020            "\"kubernetes.io/hostname\":\"talos-wk-3-gpu\"",
2021            "\"automountServiceAccountToken\":false",
2022            "\"args\":[\"sh\",\"-c\",\"make deps\"]",
2023            "\"args\":[\"scripts/lint.sh\",\"--strict\"]",
2024            "\"value\":\"refs/amont/cluster/1\"",
2025            "\"amont.dev/gate\":\"pre-commit-lint\"",
2026        ] {
2027            assert!(json.contains(needle), "{needle} missing from {json}");
2028        }
2029    }
2030
2031    fn pod(fetch: State, gate: State) -> PodFacts {
2032        PodFacts {
2033            name: "p".into(),
2034            phase: Phase::Succeeded,
2035            disrupted: false,
2036            fetch,
2037            prepare: State::Absent,
2038            gate,
2039            image_id: Some("img@sha256:x".into()),
2040        }
2041    }
2042
2043    fn done(exit: i64, reason: &str, message: &str) -> State {
2044        State::Terminated {
2045            exit: Some(exit),
2046            reason: reason.into(),
2047            message: message.into(),
2048        }
2049    }
2050
2051    #[test]
2052    fn only_recorded_facts_make_a_pass() {
2053        let ok = pod(done(0, "", "tree t1\n"), done(0, "", ""));
2054        assert_eq!(
2055            judge(&JobEnd::Complete, &ok, "t1", None),
2056            Ok("img@sha256:x".into())
2057        );
2058        let failed = || JobEnd::Failed("BackoffLimitExceeded".into());
2059        let cases: Vec<(&str, JobEnd, PodFacts, Option<&str>)> = vec![
2060            (
2061                "fetch reported",
2062                JobEnd::Complete,
2063                pod(done(0, "", "tree t2"), done(0, "", "")),
2064                None,
2065            ),
2066            (
2067                "failed on the cluster (exit 2)",
2068                failed(),
2069                pod(done(0, "", "tree t1"), done(2, "Error", "")),
2070                None,
2071            ),
2072            (
2073                "exit 137, OOMKilled",
2074                failed(),
2075                pod(done(0, "", "tree t1"), done(137, "OOMKilled", "")),
2076                None,
2077            ),
2078            (
2079                "DeadlineExceeded",
2080                JobEnd::Failed("DeadlineExceeded".into()),
2081                pod(done(0, "", "tree t1"), State::Running),
2082                None,
2083            ),
2084            (
2085                "prepare did not exit 0",
2086                JobEnd::Complete,
2087                ok.clone(),
2088                Some("make"),
2089            ),
2090            ("no terminal condition", JobEnd::Running, ok.clone(), None),
2091            (
2092                "no imageID",
2093                JobEnd::Complete,
2094                PodFacts {
2095                    image_id: None,
2096                    ..ok.clone()
2097                },
2098                None,
2099            ),
2100            (
2101                "DisruptionTarget",
2102                JobEnd::Complete,
2103                PodFacts {
2104                    disrupted: true,
2105                    ..ok.clone()
2106                },
2107                None,
2108            ),
2109        ];
2110        for (why, end, p, prepare) in cases {
2111            let reason = judge(&end, &p, "t1", prepare).expect_err(why).to_string();
2112            assert!(reason.contains(why), "{why}: {reason}");
2113        }
2114    }
2115
2116    #[test]
2117    fn facts_parse_from_kubectl_json() {
2118        let json = r#"{"items":[{"metadata":{"name":"amont-gate-slot-0-x"},
2119          "status":{"phase":"Failed","conditions":[{"type":"DisruptionTarget","status":"True"}],
2120          "initContainerStatuses":[{"name":"fetch","state":{"terminated":{"exitCode":0,"message":"tree t"}}}],
2121          "containerStatuses":[{"name":"gate","imageID":"i@sha256:1","state":{"terminated":{"exitCode":137,"reason":"OOMKilled"}}}]}}]}"#;
2122        let p = parse_pod(json).expect("parses");
2123        assert!(p.disrupted);
2124        assert_eq!(p.phase, Phase::Failed);
2125        assert_eq!(p.image_id.as_deref(), Some("i@sha256:1"));
2126        assert_eq!(p.gate, done(137, "OOMKilled", ""));
2127        assert_eq!(p.prepare, State::Absent);
2128        let job = r#"{"metadata":{"uid":"u1","annotations":{"amont.dev/gate":"pre-commit-x"}},
2129          "status":{"conditions":[{"type":"Failed","status":"True","reason":"DeadlineExceeded"}]}}"#;
2130        assert_eq!(
2131            parse_job(job),
2132            Some(JobFacts {
2133                uid: Some("u1".into()),
2134                gate: Some("pre-commit-x".into()),
2135                end: JobEnd::Failed("DeadlineExceeded".into()),
2136            })
2137        );
2138        let complete = r#"{"status":{"conditions":[{"type":"Complete","status":"True"}]}}"#;
2139        assert_eq!(parse_job(complete).map(|j| j.end), Some(JobEnd::Complete));
2140        assert_eq!(
2141            parse_job(r#"{"status":{}}"#).map(|j| j.end),
2142            Some(JobEnd::Running)
2143        );
2144    }
2145
2146    #[test]
2147    fn a_refusal_is_a_name_clash_the_quota_or_trouble() {
2148        assert_eq!(
2149            refusal("Error from server (AlreadyExists): jobs.batch \"amont-gate-slot-0\" already exists"),
2150            Refusal::Taken
2151        );
2152        assert_eq!(
2153            refusal("Error from server (Forbidden): ... exceeded quota: gates, requested: limits.memory=4Gi"),
2154            Refusal::Quota
2155        );
2156        assert_eq!(
2157            refusal("Unable to connect to the server: dial tcp: i/o timeout"),
2158            Refusal::Other
2159        );
2160    }
2161
2162    #[test]
2163    fn a_bundle_over_the_cap_says_its_size_in_mib() {
2164        let f = Fallback::BundleTooBig { mib: 63, cap: 50 };
2165        assert_eq!(f.to_string(), "bundle-too-big: 63 MiB, over the 50 MiB cap");
2166    }
2167}