Skip to main content

greengate_runtime/cluster/detached/
collect.rs

1//! Collect: turn the passes of detached Workflows into cluster tokens
2//! (ADR-0017), cheaply, at the start of a hook.
3//!
4//! With nothing pending it costs one `stat` and spawns no `kubectl`. With
5//! something pending it takes the pending file's lock without waiting (busy
6//! means somebody else is collecting: return), and asks the cluster ONE
7//! question per hook process: `kubectl get workflows,pods -l 'greengate.run in
8//! (…)' -o json`, under a 1 s request timeout and a wall deadline. A failed
9//! read keeps every record for the next hook.
10//!
11//! What a pod proves is read from its `containerStatuses` and
12//! `initContainerStatuses` alone, as ADR-0016's Job does. The Workflow's and
13//! its nodes' phases say only that the pod FINISHED: gate code can write what
14//! Argo's executor reads, so a phase is never a pass. The pod must also be
15//! the one submitted (its owner is the saved Workflow UID; its images, tree
16//! and command are the frozen ones), and the token written is the one frozen
17//! at submission.
18
19use std::sync::atomic::{AtomicBool, Ordering};
20
21use crate::attest::{BlockRefusal, SignerBlock};
22use crate::json_read::Value;
23
24use super::super::{
25    capture, in_cluster_signer, judge, last_line, log_line, parse_pod_object, record_token, Call,
26    Fallback, JobEnd, Kube, PodFacts, State, PLATFORM, RUN_LABEL_KEY,
27};
28use super::pending::{GateState, Pending, PendingError, RecordPhase, Store};
29use super::sign::{SIGNER_LABEL, SIGNER_LABEL_VALUE};
30use super::workflow::{check_pod, check_workflow, node_name, template_name, TTL_SECS};
31
32/// The wall deadline for the one batched call. `kubectl`'s own request timeout
33/// is 1 s; this bounds the process around it.
34const COLLECT_SECS: u64 = 5;
35/// Bound on each `patch` of `--stop`, and on all of them together.
36const PATCH_SECS: u64 = 10;
37const STOP_SECS: u64 = 30;
38/// An intent no Workflow appeared for in this long was never created.
39// holds-until: an apiserver slower than this to show a created Workflow — a
40// create that lands after the grace is not adopted, and its gates run at the
41// push instead
42const INTENT_GRACE_SECS: u64 = 600;
43/// A record outlives its Workflow's TTL by this long, then goes whatever the
44/// cluster says.
45const EXPIRY_SLACK_SECS: u64 = 3600;
46
47/// Once per hook process, however many callers ask. Process-scoped on
48/// purpose: a hook runs as one process and asks the cluster one question, so
49/// `stamps` inside a hook, or `--status` after a collect, do not repeat it;
50/// the next hook is a new process and asks again.
51static COLLECTED: AtomicBool = AtomicBool::new(false);
52
53/// Why a collect learned nothing, or could not keep what it learned.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub(crate) enum Trouble {
56    /// Another collect, or a submission, holds the pending file.
57    Busy,
58    /// The cluster did not answer.
59    NotReached(String),
60    /// The pending file could not be read or written.
61    StoreFailed(PendingError),
62}
63
64impl std::fmt::Display for Trouble {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        match self {
67            Trouble::Busy => write!(f, "another collect is running"),
68            Trouble::NotReached(why) => write!(f, "cluster not reached: {why}"),
69            Trouble::StoreFailed(why) => write!(f, "pending store failed: {why}"),
70        }
71    }
72}
73
74/// A Workflow that left the pending file in this collect, for `--status`.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub(crate) struct Settled {
77    pub name: String,
78    /// The Workflow's last phase in plain words.
79    pub phase: RecordPhase,
80    pub passed: Vec<String>,
81    pub failed: Vec<String>,
82}
83
84/// What a collect did.
85#[derive(Debug, Clone, PartialEq, Eq, Default)]
86pub(crate) struct Collected {
87    /// Passes written as cluster tokens.
88    pub passes: usize,
89    /// Workflows still pending afterwards.
90    pub pending: usize,
91    /// The Workflows this collect finished with.
92    pub settled: Vec<Settled>,
93    pub trouble: Option<Trouble>,
94}
95
96impl Collected {
97    fn troubled(trouble: Trouble) -> Collected {
98        Collected {
99            trouble: Some(trouble),
100            ..Collected::default()
101        }
102    }
103}
104
105/// A gate judged a pass: the token to write, frozen at submission.
106#[derive(Debug, Clone, PartialEq, Eq)]
107struct Pass {
108    gate: String,
109    tree: String,
110    token: String,
111    provenance: String,
112}
113
114/// What one record became.
115#[derive(Debug)]
116struct Resolution {
117    /// The record as it stands now.
118    record: Pending,
119    /// Whether it leaves the pending file: its Workflow is finished and judged,
120    /// or gone. A pass whose token is not written keeps it there all the same.
121    leaves: bool,
122    passes: Vec<Pass>,
123    /// One `cluster.log` line per gate that is not a pass: `(gate, why)`.
124    notes: Vec<(String, String)>,
125}
126
127/// What the in-cluster signer's ConfigMap came to for one record
128/// (`greengate.cluster.signer in-cluster`).
129#[derive(Debug, Clone, PartialEq, Eq)]
130enum Signed {
131    /// Checked and filed in the local attestation notes: the principal it
132    /// verified as. The next push publishes it.
133    Filed(String),
134    /// No ConfigMap yet, or none could be read or filed: the record waits.
135    NotReady,
136    /// A block that does not check: the laptop signs at the push.
137    /// `namespace` is the signer's, where the ConfigMap can be read.
138    Refused {
139        refusal: BlockRefusal,
140        namespace: String,
141    },
142    /// The signer judged no gate a pass: the laptop signs at the push.
143    Skipped(String),
144}
145
146/// Asks what the signer wrote for a record; `None` in the laptop mode.
147type SignerLookup<'a> = Option<&'a mut dyn FnMut(&Pending) -> Signed>;
148
149/// Collect, once per hook process. Called at the start of pre-commit and
150/// pre-push, by `amont stamps`, `amont cluster collect` and `rehearse
151/// --status`.
152pub(crate) fn collect() -> Collected {
153    if COLLECTED.swap(true, Ordering::SeqCst) {
154        return Collected::default();
155    }
156    Store::here().map_or_else(Collected::default, |store| collect_from(&store))
157}
158
159fn collect_from(store: &Store) -> Collected {
160    if !store.exists() {
161        return Collected::default();
162    }
163    // Busy: another hook is collecting, or a submission is writing.
164    let Some(held) = store.try_lock() else {
165        return Collected::troubled(Trouble::Busy);
166    };
167    let records = match store.read() {
168        Ok(records) => records,
169        Err(why) => {
170            log_line("collect", &why.to_string());
171            return Collected::troubled(Trouble::StoreFailed(why));
172        }
173    };
174    if records.is_empty() {
175        return Collected::default();
176    }
177    let now = crate::gate_evidence::now();
178    let mut kept: Vec<Pending> = Vec::new();
179    let mut settled: Vec<Settled> = Vec::new();
180    let mut passes = 0;
181    let mut unreached: Vec<String> = Vec::new();
182    // Read only with something pending: one git call.
183    let signer_namespace = in_cluster_signer();
184    for group in by_cluster(records) {
185        let kube = Kube {
186            kubeconfig: group[0].kubeconfig.clone(),
187            namespace: group[0].namespace.clone(),
188        };
189        match fetch(&kube, &group) {
190            Ok(list) => {
191                // The signer's ConfigMaps: asked at most once per group, and
192                // only once a record needs them.
193                let labels: Vec<String> = group.iter().map(|r| r.label.clone()).collect();
194                let mut configmaps: Option<Result<Value, String>> = None;
195                let mut lookup = |record: &Pending| -> Signed {
196                    let Some(namespace) = &signer_namespace else {
197                        return Signed::NotReady;
198                    };
199                    let answer = configmaps.get_or_insert_with(|| {
200                        let signer = Kube {
201                            kubeconfig: kube.kubeconfig.clone(),
202                            namespace: namespace.clone(),
203                        };
204                        let read = fetch_blocks(&signer, &labels);
205                        if let Err(why) = &read {
206                            log_line(
207                                "collect",
208                                &format!("the signer's blocks could not be read: {why}"),
209                            );
210                        }
211                        read
212                    });
213                    match answer {
214                        Ok(list) => match_block(record, list, namespace),
215                        Err(_) => Signed::NotReady,
216                    }
217                };
218                for mut record in group {
219                    let done = if signer_namespace.is_none() {
220                        // Nothing awaits a signer the machine no longer uses.
221                        record.awaiting_signer = false;
222                        settle(resolve(record, &list, now), None)
223                    } else if record.awaiting_signer {
224                        settle_awaiting(record, now, &mut lookup)
225                    } else {
226                        settle(resolve(record, &list, now), Some(&mut lookup))
227                    };
228                    passes += done.written;
229                    settled.extend(done.settled);
230                    kept.extend(done.record);
231                }
232            }
233            Err(why) => {
234                log_line("collect", &format!("the cluster could not be read: {why}"));
235                // The rollback says an unreadable record expires: it does,
236                // even when the cluster cannot be asked.
237                let (old, young): (Vec<Pending>, Vec<Pending>) =
238                    group.into_iter().partition(|r| is_expired(r, now));
239                for record in &old {
240                    if record.awaiting_signer && signer_namespace.is_some() {
241                        unsigned_at_ttl(record);
242                        continue;
243                    }
244                    log_line(
245                        record.gates.first().map_or("collect", |g| g.id.as_str()),
246                        &format!(
247                            "detached {}: older than the Workflow TTL; dropped",
248                            record.name
249                        ),
250                    );
251                }
252                kept.extend(young);
253                unreached.push(format!(
254                    "{why} (namespace {}, kubeconfig {})",
255                    kube.namespace,
256                    kube.kubeconfig.display()
257                ));
258            }
259        }
260    }
261    let trouble = match (store.write(&held, &kept), unreached) {
262        (Err(why), _) => {
263            log_line(
264                "collect",
265                &format!("cluster-pending was not updated: {why}"),
266            );
267            Some(Trouble::StoreFailed(why))
268        }
269        // Any group left unasked is named, even when another answered.
270        (Ok(()), why) if !why.is_empty() => Some(Trouble::NotReached(why.join("; "))),
271        (Ok(()), _) => None,
272    };
273    Collected {
274        passes,
275        pending: kept.len(),
276        settled,
277        trouble,
278    }
279}
280
281fn is_expired(record: &Pending, now: u64) -> bool {
282    now > record.submitted + TTL_SECS + EXPIRY_SLACK_SECS
283}
284
285/// Whether the pending file at `path` still lists a run that has not
286/// outlived its Workflow by [`EXPIRY_SLACK_SECS`]: what `collect` would keep.
287/// `Ok(false)` for no file; `Err` for a file this version cannot read.
288pub(crate) fn lists_live(path: &std::path::Path, now: u64) -> Result<bool, String> {
289    let text = match std::fs::read_to_string(path) {
290        Ok(text) => text,
291        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
292        Err(e) => return Err(e.to_string()),
293    };
294    Ok(super::pending::parse_file(&text)?
295        .iter()
296        .any(|record| !is_expired(record, now)))
297}
298
299/// The records grouped by the cluster they live on: one call each.
300fn by_cluster(records: Vec<Pending>) -> Vec<Vec<Pending>> {
301    let mut groups: Vec<Vec<Pending>> = Vec::new();
302    for record in records {
303        match groups
304            .iter_mut()
305            .find(|g| g[0].kubeconfig == record.kubeconfig && g[0].namespace == record.namespace)
306        {
307            Some(group) => group.push(record),
308            None => groups.push(vec![record]),
309        }
310    }
311    groups
312}
313
314/// The one batched call: every Workflow and pod carrying one of the records'
315/// run labels.
316fn fetch(kube: &Kube, records: &[Pending]) -> Result<Value, String> {
317    let labels: Vec<&str> = records.iter().map(|r| r.label.as_str()).collect();
318    let selector = format!("{RUN_LABEL_KEY} in ({})", labels.join(","));
319    get_json(kube, "workflows,pods", &selector)
320}
321
322/// The one batched call of `in-cluster` signing, in the signer namespace:
323/// every signer ConfigMap carrying one of the records' run labels, under the
324/// same request timeout and deadline as [`fetch`].
325fn fetch_blocks(signer: &Kube, labels: &[String]) -> Result<Value, String> {
326    let selector = format!(
327        "{SIGNER_LABEL}={SIGNER_LABEL_VALUE},{RUN_LABEL_KEY} in ({})",
328        labels.join(",")
329    );
330    get_json(signer, "configmaps", &selector)
331}
332
333fn get_json(kube: &Kube, what: &str, selector: &str) -> Result<Value, String> {
334    let mut cmd = kube.command(
335        "--request-timeout=1s",
336        &["get", what, "-l", selector, "-o", "json"],
337    );
338    match capture(&mut cmd, COLLECT_SECS) {
339        Call::Ok(json) => crate::json_read::parse(&json)
340            .ok_or_else(|| "kubectl printed something that is not JSON".to_string()),
341        Call::Refused(e) | Call::NotStarted(e) | Call::TimedOut(e) => Err(last_line(&e)),
342    }
343}
344
345/// What settling a resolution left.
346struct Settlement {
347    /// The record if it stays in the file.
348    record: Option<Pending>,
349    /// Tokens written.
350    written: usize,
351    /// The record's end, when it left the file.
352    settled: Option<Settled>,
353}
354
355/// [`settle_with`], writing tokens to the cluster note.
356fn settle(resolution: Resolution, signer: SignerLookup) -> Settlement {
357    settle_with(
358        resolution,
359        |pass| record_token(&pass.tree, &pass.token, &pass.provenance),
360        signer,
361    )
362}
363
364/// Write the passes of a resolution through `write` and log its notes. A pass
365/// whose token was not written returns its gate to waiting and keeps the
366/// record in the file, finished Workflow or not, so that the next collect
367/// tries again.
368///
369/// With a `signer` (`in-cluster`), a record that leaves with a pass asks it
370/// for the block first, and each gate's `collected` line waits for the
371/// answer, so that it is said once: with the principal when the block was
372/// filed, plainly beside the reason when the laptop signs. A block not there
373/// yet keeps the record, awaiting it, its tokens written.
374fn settle_with(
375    resolution: Resolution,
376    mut write: impl FnMut(&Pass) -> Result<(), Fallback>,
377    signer: SignerLookup,
378) -> Settlement {
379    let Resolution {
380        mut record,
381        leaves,
382        passes,
383        notes,
384    } = resolution;
385    for (gate, why) in &notes {
386        log_line(gate, why);
387    }
388    let mut written = 0;
389    let mut unwritten = 0;
390    for pass in &passes {
391        match write(pass) {
392            Ok(()) => {
393                written += 1;
394                if signer.is_none() {
395                    say_collected(&pass.gate, &pass.tree);
396                }
397            }
398            Err(why) => {
399                log_line(
400                    &pass.gate,
401                    &format!("detached: the pass was not recorded: {why}"),
402                );
403                unwritten += 1;
404                for gate in record.gates.iter_mut().filter(|g| g.id == pass.gate) {
405                    gate.state = GateState::Waiting;
406                }
407            }
408        }
409    }
410    if !leaves || unwritten > 0 {
411        return Settlement {
412            record: Some(record),
413            written,
414            settled: None,
415        };
416    }
417    if let Some(lookup) = signer {
418        if record.gates.iter().any(|g| g.state == GateState::Passed) {
419            let signed = lookup(&record);
420            if signed == Signed::NotReady {
421                say_signed(&record, &signed);
422                record.awaiting_signer = true;
423                return Settlement {
424                    record: Some(record),
425                    written,
426                    settled: None,
427                };
428            }
429            say_signed(&record, &signed);
430        }
431    }
432    Settlement {
433        written,
434        ..ended(record)
435    }
436}
437
438/// A record whose passes are written and which awaits the signer's block:
439/// filed, refused or skipped, it leaves; past the Workflow's TTL and its
440/// slack it leaves unsigned; otherwise it stays. No token is written again.
441fn settle_awaiting(
442    record: Pending,
443    now: u64,
444    lookup: &mut dyn FnMut(&Pending) -> Signed,
445) -> Settlement {
446    if is_expired(&record, now) {
447        unsigned_at_ttl(&record);
448        return ended(record);
449    }
450    let signed = lookup(&record);
451    say_signed(&record, &signed);
452    if signed == Signed::NotReady {
453        return Settlement {
454            record: Some(record),
455            written: 0,
456            settled: None,
457        };
458    }
459    ended(record)
460}
461
462/// The record leaves the file: its end, for `--status`.
463fn ended(record: Pending) -> Settlement {
464    let ids = |state: GateState| -> Vec<String> {
465        record
466            .gates
467            .iter()
468            .filter(|g| g.state == state)
469            .map(|g| g.id.clone())
470            .collect()
471    };
472    let settled = Settled {
473        name: record.name.clone(),
474        phase: record.phase,
475        passed: ids(GateState::Passed),
476        failed: ids(GateState::Failed),
477    };
478    Settlement {
479        record: None,
480        written: 0,
481        settled: Some(settled),
482    }
483}
484
485/// The gates of `record` that passed.
486fn passed(record: &Pending) -> impl Iterator<Item = &str> {
487    record
488        .gates
489        .iter()
490        .filter(|g| g.state == GateState::Passed)
491        .map(|g| g.id.as_str())
492}
493
494/// The line a collected pass is announced with when the laptop signs it as
495/// today (no in-cluster signer). stderr: `greengate stamps --json` collects
496/// first, and its stdout is the JSON object alone.
497fn say_collected(gate: &str, tree: &str) {
498    eprintln!(
499        "collected the cluster pass of {} for tree {}",
500        crate::ui::sanitize(gate),
501        short(tree)
502    );
503}
504
505/// A collected gate in the in-cluster signer mode: `collected <gate> for
506/// tree <short>; <rest>`, one line, whether the signer's block was filed
507/// (`signed by <principal>`) or the laptop signs it (why, and what to do).
508fn say_collected_unsigned(gate: &str, tree: &str, rest: &str) {
509    eprintln!(
510        "collected {} for tree {}; {}",
511        crate::ui::sanitize(gate),
512        short(tree),
513        crate::ui::sanitize(rest)
514    );
515}
516
517/// What a person checks after a refusal, by its cause.
518fn next_step(record: &Pending, refusal: &BlockRefusal, namespace: &str) -> String {
519    match refusal {
520        BlockRefusal::Signer(_) => {
521            format!("check {} lists cluster-signer@{PLATFORM}", signers_shown())
522        }
523        BlockRefusal::Content(_) => {
524            format!(
525                "see kubectl --kubeconfig {} -n {namespace} get configmap {}",
526                record.kubeconfig.display(),
527                record.name
528            )
529        }
530    }
531}
532
533/// What the signer's answer means for each passed gate of `record`, said.
534fn say_signed(record: &Pending, signed: &Signed) {
535    for gate in passed(record) {
536        match signed {
537            Signed::Filed(principal) => {
538                say_collected_unsigned(gate, &record.tree, &format!("signed by {principal}"))
539            }
540            Signed::NotReady => {
541                eprintln!(
542                    "signer block for {} not ready; next collect retries",
543                    crate::ui::sanitize(gate)
544                );
545            }
546            Signed::Refused { refusal, namespace } => {
547                log_line(
548                    gate,
549                    &format!(
550                        "detached {}: signer block refused: {}",
551                        record.name,
552                        refusal.reason()
553                    ),
554                );
555                say_collected_unsigned(
556                    gate,
557                    &record.tree,
558                    &format!(
559                        "signer block refused: {}; the laptop signs it; {}",
560                        refusal.reason(),
561                        next_step(record, refusal, namespace)
562                    ),
563                );
564            }
565            Signed::Skipped(why) => say_collected_unsigned(
566                gate,
567                &record.tree,
568                &format!("signer skipped: {why}; the laptop signs it"),
569            ),
570        }
571    }
572}
573
574/// An awaiting record past the Workflow's TTL: logged and said, per gate.
575fn unsigned_at_ttl(record: &Pending) {
576    for gate in passed(record) {
577        log_line(
578            gate,
579            &format!("detached {}: unsigned: no signer block", record.name),
580        );
581        say_collected_unsigned(
582            gate,
583            &record.tree,
584            "signer block did not arrive before the Workflow TTL; the laptop signs it",
585        );
586    }
587}
588
589/// The signers file a refusal points at: the repository's, or where it
590/// belongs when there is none.
591fn signers_shown() -> String {
592    crate::attest::default_signers()
593        .or_else(|| {
594            crate::git::stdout(&["rev-parse", "--show-toplevel"])
595                .map(|top| std::path::Path::new(&top).join(".github/allowed_signers"))
596        })
597        .map_or_else(
598            || ".github/allowed_signers".to_string(),
599            |p| shown_from_top(&p),
600        )
601}
602
603/// `path` relative to the repository's top level when it is inside it (a
604/// refusal line stays short), else as it is.
605fn shown_from_top(path: &std::path::Path) -> String {
606    crate::git::stdout(&["rev-parse", "--show-toplevel"])
607        .and_then(|top| {
608            path.strip_prefix(&top)
609                .ok()
610                .map(|rel| rel.display().to_string())
611        })
612        .unwrap_or_else(|| path.display().to_string())
613}
614
615/// The signer's ConfigMap for `record` in `configmaps`: named after its
616/// Workflow, labelled with its run and as a signer block.
617fn signer_configmap<'a>(record: &Pending, configmaps: &'a Value) -> Option<&'a Value> {
618    configmaps
619        .get("items")
620        .map(Value::items)
621        .unwrap_or(&[])
622        .iter()
623        .find(|cm| {
624            let metadata = cm.get("metadata");
625            let labels = metadata.and_then(|m| m.get("labels"));
626            text(metadata, "name") == Some(record.name.as_str())
627                && text(labels, RUN_LABEL_KEY) == Some(record.label.as_str())
628                && text(labels, SIGNER_LABEL) == Some(SIGNER_LABEL_VALUE)
629        })
630}
631
632/// What the signer wrote for `record` in `configmaps` (in `namespace`):
633/// nothing yet, a skip, or a block [`judge_block`] judges, then files under
634/// the tree, and under the snapshot commit when this repository has it.
635fn match_block(record: &Pending, configmaps: &Value, namespace: &str) -> Signed {
636    let Some(cm) = signer_configmap(record, configmaps) else {
637        return Signed::NotReady;
638    };
639    let fields = cm.get("data");
640    let block = text(fields, "block").unwrap_or("");
641    if block.is_empty() {
642        return Signed::Skipped(
643            text(fields, "skipped")
644                .filter(|why| !why.is_empty())
645                .unwrap_or("no reason given")
646                .to_string(),
647        );
648    }
649    let signers = crate::attest::default_signers();
650    let checked = match judge_block(record, block, signers.as_deref()) {
651        Ok(checked) => checked,
652        Err(refusal) => {
653            return Signed::Refused {
654                refusal,
655                namespace: namespace.to_string(),
656            }
657        }
658    };
659    let commit = &record.source.oid;
660    let mut keys = vec![record.tree.as_str()];
661    if !commit.is_empty()
662        && crate::git::succeeds(&["cat-file", "-e", &format!("{commit}^{{commit}}")])
663    {
664        keys.push(commit);
665    }
666    match crate::attest::file_signer_block(&checked.body, &keys) {
667        Ok(()) => Signed::Filed(checked.principal),
668        Err(why) => {
669            log_line(
670                passed(record).next().unwrap_or("collect"),
671                &format!(
672                    "detached {}: the signer block could not be filed ({why}); the next collect retries",
673                    record.name
674                ),
675            );
676            Signed::NotReady
677        }
678    }
679}
680
681/// `block` judged for `record`: checked by attest's reader and verifier
682/// against `signers`, the repository's `allowed_signers` (the file a
683/// push-time verification reads), for the record's tree, naming every gate
684/// that passed in it. Writes nothing; the verification runs `ssh-keygen`.
685fn judge_block(
686    record: &Pending,
687    block: &str,
688    signers: Option<&std::path::Path>,
689) -> Result<SignerBlock, BlockRefusal> {
690    let Some(signers) = signers else {
691        return Err(BlockRefusal::Signer(
692            "the repository has no allowed_signers".into(),
693        ));
694    };
695    let checked = crate::attest::signer_block(block, &record.tree, signers)?;
696    let missing: Vec<&str> = passed(record)
697        .filter(|g| !checked.gates.iter().any(|named| named == g))
698        .collect();
699    if !missing.is_empty() {
700        return Err(BlockRefusal::Content(format!(
701            "it does not name {}",
702            missing.join(" ")
703        )));
704    }
705    Ok(checked)
706}
707
708fn short(oid: &str) -> &str {
709    oid.get(..8).unwrap_or(oid)
710}
711
712fn text<'a>(v: Option<&'a Value>, key: &str) -> Option<&'a str> {
713    v?.get(key).and_then(Value::as_str)
714}
715
716pub(super) fn kind_of<'a>(list: &'a Value, kind: &'a str) -> impl Iterator<Item = &'a Value> {
717    list.get("items")
718        .map(Value::items)
719        .unwrap_or(&[])
720        .iter()
721        .filter(move |i| text(Some(i), "kind") == Some(kind))
722}
723
724/// The pod of the Workflow `uid` that ran `node`: named so by Argo's
725/// annotation, owned by that Workflow, and a Pod node of the Workflow's own
726/// status of the template the gate was submitted under.
727pub(super) fn pod_of<'a>(
728    list: &'a Value,
729    wf: &Value,
730    name: &str,
731    uid: &str,
732    task: &str,
733) -> Option<&'a Value> {
734    let node = node_name(name, task);
735    let recorded = wf
736        .get("status")
737        .and_then(|s| s.get("nodes"))
738        .map(Value::members)
739        .unwrap_or(&[])
740        .iter()
741        .map(|(_, n)| n)
742        .find(|n| {
743            text(Some(n), "name") == Some(node.as_str())
744                && text(Some(n), "type") == Some("Pod")
745                && text(Some(n), "templateName") == Some(template_name(task).as_str())
746        })?;
747    kind_of(list, "Pod").find(|pod| {
748        let metadata = pod.get("metadata");
749        let annotations = metadata.and_then(|m| m.get("annotations"));
750        let owned = metadata
751            .and_then(|m| m.get("ownerReferences"))
752            .map(Value::items)
753            .unwrap_or(&[])
754            .iter()
755            .any(|o| {
756                text(Some(o), "kind") == Some("Workflow")
757                    && text(Some(o), "uid") == Some(uid)
758                    && text(Some(o), "name") == Some(name)
759                    && o.get("controller").is_some_and(Value::is_true)
760            });
761        // The node id is required, not optional: a pod that does not name its
762        // node cannot be bound to the Workflow's record of it.
763        let node_id = text(annotations, "workflows.argoproj.io/node-id");
764        owned
765            && text(annotations, "workflows.argoproj.io/node-name") == Some(node.as_str())
766            && node_id.is_some()
767            && node_id == text(Some(recorded), "id")
768    })
769}
770
771/// The Job-shaped end of a Workflow pod, from `main`'s termination status
772/// alone: exit 0 is `Complete`, any other exit is `Failed`, and a container
773/// that has not terminated is `Running`. Workflow and node phases are never
774/// read here: gate code can write what Argo's executor reports from.
775pub(super) fn end_from_main(main: &State) -> JobEnd {
776    match main {
777        State::Terminated { exit: Some(0), .. } => JobEnd::Complete,
778        State::Terminated { reason, .. } => JobEnd::Failed(if reason.is_empty() {
779            "Error".to_string()
780        } else {
781            reason.clone()
782        }),
783        State::Absent | State::Waiting | State::Running => JobEnd::Running,
784    }
785}
786
787/// Why a pod that never ended `main` is no pass, as the pod says it.
788fn unfinished(facts: &PodFacts) -> String {
789    if let Some(w) = facts.fetch.failed() {
790        format!("fetch {w}")
791    } else if let Some(w) = facts.prepare.failed() {
792        format!("prepare {w}")
793    } else {
794        "the pod ended without a verdict from main".to_string()
795    }
796}
797
798/// Decide what the cluster's answer means for one record. Pure.
799fn resolve(record: Pending, list: &Value, now: u64) -> Resolution {
800    let mut notes: Vec<(String, String)> = Vec::new();
801    let wf = kind_of(list, "Workflow").find(|w| {
802        text(w.get("metadata"), "name") == Some(record.name.as_str())
803            && text(
804                w.get("metadata").and_then(|m| m.get("labels")),
805                RUN_LABEL_KEY,
806            ) == Some(record.label.as_str())
807    });
808    // The record ends here, its waiting gates failed, one note each.
809    let drop_all = |mut record: Pending, why: &str| {
810        let notes = record
811            .waiting()
812            .map(|g| (g.id.clone(), format!("detached {}: {why}", record.name)))
813            .collect();
814        for gate in record
815            .gates
816            .iter_mut()
817            .filter(|g| g.state == GateState::Waiting)
818        {
819            gate.state = GateState::Failed;
820        }
821        record.phase = RecordPhase::Gone;
822        Resolution {
823            record,
824            leaves: true,
825            passes: Vec::new(),
826            notes,
827        }
828    };
829    let Some(wf) = wf else {
830        return if record.uid.is_some() {
831            drop_all(
832                record,
833                "the Workflow is gone (its TTL passed, or it was deleted)",
834            )
835        } else if is_expired(&record, now) || now > record.submitted + INTENT_GRACE_SECS {
836            drop_all(record, "the Workflow never appeared")
837        } else {
838            // A create that may still land: the intent stays.
839            Resolution {
840                record,
841                leaves: false,
842                passes: Vec::new(),
843                notes,
844            }
845        };
846    };
847    if is_expired(&record, now) {
848        return drop_all(record, "older than the Workflow TTL");
849    }
850    let found_uid = text(wf.get("metadata"), "uid").map(str::to_string);
851    let uid = match (&record.uid, &found_uid) {
852        (Some(saved), Some(found)) if saved == found => saved.clone(),
853        (Some(_), _) => {
854            return drop_all(
855                record,
856                "another Workflow than the one submitted holds the name",
857            )
858        }
859        (None, Some(found)) => match check_workflow(wf, &record) {
860            Ok(()) => found.clone(),
861            Err(why) => {
862                return drop_all(record, &format!("not the Workflow submitted: {why}"));
863            }
864        },
865        (None, None) => return drop_all(record, "the Workflow has no UID"),
866    };
867    let phase = RecordPhase::parse(text(wf.get("status"), "phase").unwrap_or(""));
868    let mut passes: Vec<Pass> = Vec::new();
869    let mut gates = record.gates.clone();
870    for gate in gates.iter_mut().filter(|g| g.state == GateState::Waiting) {
871        let Some(pod) = pod_of(list, wf, &record.name, &uid, &gate.task) else {
872            if phase.finished() {
873                gate.state = GateState::Failed;
874                notes.push((
875                    gate.id.clone(),
876                    format!(
877                        "detached {}: no pod of {} was found ({})",
878                        record.name,
879                        gate.task,
880                        phase.as_str()
881                    ),
882                ));
883            }
884            continue;
885        };
886        if let Err(why) = check_pod(pod, gate, &record) {
887            gate.state = GateState::Failed;
888            notes.push((
889                gate.id.clone(),
890                format!(
891                    "detached {}: the pod is not the one submitted: {why}",
892                    record.name
893                ),
894            ));
895            continue;
896        }
897        let Some(facts) = parse_pod_object(pod, "main") else {
898            if phase.finished() {
899                gate.state = GateState::Failed;
900                notes.push((
901                    gate.id.clone(),
902                    format!("detached {}: the pod's status cannot be read", record.name),
903                ));
904            }
905            continue;
906        };
907        let end = end_from_main(&facts.gate);
908        if end == JobEnd::Running {
909            if phase.finished() {
910                gate.state = GateState::Failed;
911                notes.push((
912                    gate.id.clone(),
913                    format!("detached {}: {}", record.name, unfinished(&facts)),
914                ));
915            }
916            continue;
917        }
918        match judge(&end, &facts, &record.tree, gate.prepare.as_deref()) {
919            Ok(image_id) => {
920                gate.state = GateState::Passed;
921                passes.push(Pass {
922                    gate: gate.id.clone(),
923                    tree: record.tree.clone(),
924                    token: gate.token.clone(),
925                    provenance: format!(
926                        "platform={PLATFORM} image={image_id} job={uid} name={} bundle=0",
927                        node_name(&record.name, &gate.task)
928                    ),
929                });
930            }
931            Err(fallback) => {
932                gate.state = GateState::Failed;
933                notes.push((
934                    gate.id.clone(),
935                    format!("detached {}: {}", record.name, fallback),
936                ));
937            }
938        }
939    }
940    let settled = gates.iter().all(|g| g.state != GateState::Waiting);
941    Resolution {
942        leaves: settled || phase.finished(),
943        record: Pending {
944            uid: Some(uid),
945            phase,
946            gates,
947            ..record
948        },
949        passes,
950        notes,
951    }
952}
953
954/// `amont cluster collect`: exit 0 when it asked the cluster (or had nothing
955/// to ask, or another collect is at it), 1 when it learned nothing or could
956/// not keep what it learned, 2 on usage.
957pub fn collect_command(args: &[std::ffi::OsString]) -> i32 {
958    if args.iter().any(|a| a == "--help" || a == "-h") {
959        println!("usage: {} cluster collect", crate::names::BIN);
960        return 0;
961    }
962    match args.first().and_then(|a| a.to_str()) {
963        Some("collect") if args.len() == 1 => {
964            let done = collect();
965            match &done.trouble {
966                Some(Trouble::Busy) => {
967                    eprintln!("{}; nothing was asked of the cluster", Trouble::Busy);
968                    0
969                }
970                Some(trouble) => {
971                    eprintln!("{trouble}");
972                    1
973                }
974                None => {
975                    eprintln!(
976                        "collected {} cluster pass{}; {} Workflow{} still pending",
977                        done.passes,
978                        if done.passes == 1 { "" } else { "es" },
979                        done.pending,
980                        if done.pending == 1 { "" } else { "s" },
981                    );
982                    0
983                }
984            }
985        }
986        _ => {
987            eprintln!("usage: {} cluster collect", crate::names::BIN);
988            2
989        }
990    }
991}
992
993/// `rehearse --status`: one line per pending Workflow, its phase as the last
994/// collect saw it and the gates collected so far.
995pub(crate) fn status_lines() -> Vec<String> {
996    let Some(store) = Store::here() else {
997        return Vec::new();
998    };
999    match store.read() {
1000        Ok(records) => records.iter().map(describe).collect(),
1001        Err(why) => {
1002            eprintln!("cluster run records cannot be read: {why}");
1003            Vec::new()
1004        }
1005    }
1006}
1007
1008/// The Workflows a collect finished with, for the person who asked.
1009pub(crate) fn settled_lines(settled: &[Settled]) -> Vec<String> {
1010    settled
1011        .iter()
1012        .map(|run| {
1013            let mut parts: Vec<String> = Vec::new();
1014            if !run.passed.is_empty() {
1015                parts.push(format!("collected: {}", run.passed.join(" ")));
1016            }
1017            if !run.failed.is_empty() {
1018                parts.push(format!(
1019                    "did not pass: {} — see cluster.log; the gate runs at the push",
1020                    run.failed.join(" ")
1021                ));
1022            }
1023            format!(
1024                "cluster run {} {}: {}",
1025                run.name,
1026                run.phase.plain(),
1027                parts.join("; ")
1028            )
1029        })
1030        .collect()
1031}
1032
1033fn describe(record: &Pending) -> String {
1034    let named = |label: &str, state: GateState| -> Option<String> {
1035        let ids: Vec<&str> = record
1036            .gates
1037            .iter()
1038            .filter(|g| g.state == state)
1039            .map(|g| g.id.as_str())
1040            .collect();
1041        (!ids.is_empty()).then(|| format!("{label}: {}", ids.join(" ")))
1042    };
1043    let fields: Vec<String> = [
1044        named("collected", GateState::Passed),
1045        named("did not pass", GateState::Failed),
1046        named("waiting", GateState::Waiting),
1047    ]
1048    .into_iter()
1049    .flatten()
1050    .collect();
1051    let follow = if record.phase.finished() {
1052        String::new()
1053    } else {
1054        format!(
1055            " (follow: kubectl -n {} get wf {})",
1056            record.namespace, record.name
1057        )
1058    };
1059    format!(
1060        "cluster run {}: {}{}{follow}",
1061        record.name,
1062        record.phase.plain(),
1063        if fields.is_empty() {
1064            String::new()
1065        } else {
1066            format!(" — {}", fields.join("; "))
1067        }
1068    )
1069}
1070
1071/// The command that does by hand what `--stop` does for one Workflow.
1072fn terminate_command(record: &Pending) -> String {
1073    format!(
1074        "kubectl --kubeconfig {} -n {} patch workflow {} --type merge -p '{{\"spec\":{{\"shutdown\":\"Terminate\"}}}}'",
1075        shell_quote(&record.kubeconfig.to_string_lossy()),
1076        record.namespace,
1077        record.name
1078    )
1079}
1080
1081/// `text` as one word for a POSIX shell.
1082fn shell_quote(text: &str) -> String {
1083    format!("'{}'", text.replace('\'', "'\\''"))
1084}
1085
1086/// What `rehearse --stop` did to the pending Workflows.
1087#[derive(Debug, Clone, PartialEq, Eq, Default)]
1088pub(crate) struct Stopped {
1089    /// One line per Workflow asked to terminate.
1090    pub done: Vec<String>,
1091    /// One line per Workflow that was not, with the command to do it by hand.
1092    pub failed: Vec<String>,
1093}
1094
1095/// `rehearse --stop`: ask the cluster to terminate every pending Workflow,
1096/// each call and all of them bounded. Once the overall deadline is gone the
1097/// rest are reported as not attempted.
1098pub(crate) fn stop_pending() -> Stopped {
1099    let mut report = Stopped::default();
1100    let Some(store) = Store::here() else {
1101        return report;
1102    };
1103    let records = match store.read() {
1104        Ok(records) => records,
1105        Err(why) => {
1106            report
1107                .failed
1108                .push(format!("cluster run records cannot be read: {why}"));
1109            return report;
1110        }
1111    };
1112    let until = std::time::Instant::now() + std::time::Duration::from_secs(STOP_SECS);
1113    for record in &records {
1114        let left = until.saturating_duration_since(std::time::Instant::now());
1115        if left.is_zero() {
1116            report.failed.push(format!(
1117                "cluster run {} was not attempted: the stop deadline passed — {}",
1118                record.name,
1119                terminate_command(record)
1120            ));
1121            continue;
1122        }
1123        let kube = Kube {
1124            kubeconfig: record.kubeconfig.clone(),
1125            namespace: record.namespace.clone(),
1126        };
1127        let patched = kube.bounded(
1128            &[
1129                "patch",
1130                "workflow",
1131                &record.name,
1132                "--type",
1133                "merge",
1134                "-p",
1135                "{\"spec\":{\"shutdown\":\"Terminate\"}}",
1136            ],
1137            left.as_secs().clamp(1, PATCH_SECS),
1138        );
1139        match patched {
1140            Ok(()) => report
1141                .done
1142                .push(format!("terminating cluster run {}", record.name)),
1143            Err(why) => report.failed.push(format!(
1144                "could not terminate cluster run {}: {why} — {}",
1145                record.name,
1146                terminate_command(record)
1147            )),
1148        }
1149    }
1150    report
1151}
1152
1153#[cfg(test)]
1154pub(in crate::cluster::detached) mod tests {
1155    use super::super::pending::tests::sample;
1156    use super::*;
1157
1158    #[test]
1159    fn lists_live_skips_a_run_past_its_ttl_and_reads_the_owner_format() {
1160        let dir = std::env::temp_dir().join(format!("greengate-lists-live-{}", std::process::id()));
1161        let _ = std::fs::remove_dir_all(&dir); // best-effort: a scratch path; absent or left behind is harmless
1162        std::fs::create_dir_all(&dir).unwrap();
1163        let file = dir.join(super::super::PENDING_FILE);
1164        let now = 1_800_000_000;
1165        assert_eq!(lists_live(&file, now), Ok(false), "no file, no run");
1166        let mut live = super::super::pending::tests::sample("wf-live");
1167        live.submitted = now;
1168        let mut gone = super::super::pending::tests::sample("wf-gone");
1169        gone.submitted = now - TTL_SECS - EXPIRY_SLACK_SECS - 1;
1170        std::fs::write(&file, super::super::pending::render_file(&[gone.clone()])).unwrap();
1171        assert_eq!(
1172            lists_live(&file, now),
1173            Ok(false),
1174            "a run past its TTL is not live"
1175        );
1176        std::fs::write(&file, super::super::pending::render_file(&[gone, live])).unwrap();
1177        assert_eq!(lists_live(&file, now), Ok(true));
1178        std::fs::write(&file, "not json").unwrap();
1179        assert!(lists_live(&file, now).is_err());
1180    }
1181
1182    pub(in crate::cluster::detached) fn fixture(name: &str) -> String {
1183        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1184            .join("../greengate/tests/it/fixtures/argo");
1185        std::fs::read_to_string(dir.join(name)).expect("fixture")
1186    }
1187
1188    /// `text` without the whitespace outside strings, so a replacement does
1189    /// not depend on how the fixture was indented.
1190    pub(in crate::cluster::detached) fn compact(text: &str) -> String {
1191        let (mut out, mut in_string, mut escaped) = (String::new(), false, false);
1192        for c in text.chars() {
1193            if in_string {
1194                out.push(c);
1195                match (escaped, c) {
1196                    (true, _) => escaped = false,
1197                    (false, '\\') => escaped = true,
1198                    (false, '"') => in_string = false,
1199                    (false, _) => {}
1200                }
1201            } else if c == '"' {
1202                in_string = true;
1203                out.push(c);
1204            } else if !c.is_whitespace() {
1205                out.push(c);
1206            }
1207        }
1208        out
1209    }
1210
1211    /// What the cluster answers for `record`: the first live run's pod, made
1212    /// the pod of task `g0` of the Workflow, and a Workflow in `phase` whose
1213    /// node for it is in `node_phase`. `tweak` edits the pod's compact text.
1214    fn list_for(
1215        record: &Pending,
1216        phase: &str,
1217        node_phase: &str,
1218        tweak: impl Fn(String) -> String,
1219    ) -> Value {
1220        let node = node_name(&record.name, "g0");
1221        let pod = compact(&fixture("pod-succeeded.json"))
1222            .replace(
1223                "\"workflows.argoproj.io/node-name\":\"greengate-handrun-pqtbl\"",
1224                &format!("\"workflows.argoproj.io/node-name\":\"{node}\""),
1225            )
1226            .replace(
1227                "\"workflows.argoproj.io/node-id\":\"greengate-handrun-pqtbl\"",
1228                "\"workflows.argoproj.io/node-id\":\"node-g0\"",
1229            )
1230            .replace("greengate-handrun-pqtbl", &record.name)
1231            .replace("b8eb52b7-8ede-4c1f-bd94-9ada529eec97", "uid-1")
1232            .replace("handrun-2", &record.label);
1233        let wf = format!(
1234            "{{\"kind\":\"Workflow\",\"metadata\":{{\"name\":\"{}\",\"uid\":\"uid-1\",\
1235             \"labels\":{{\"greengate.run\":\"{}\"}}}},\"status\":{{\"phase\":\"{phase}\",\
1236             \"nodes\":{{\"node-g0\":{{\"id\":\"node-g0\",\"name\":\"{node}\",\"type\":\"Pod\",\
1237             \"templateName\":\"gate-g0\",\"phase\":\"{node_phase}\"}}}}}}}}",
1238            record.name, record.label
1239        );
1240        let list = format!("{{\"kind\":\"List\",\"items\":[{wf},{}]}}", tweak(pod));
1241        crate::json_read::parse(&list).expect("list json")
1242    }
1243
1244    #[test]
1245    fn a_workflow_phase_is_only_ever_finished_or_not() {
1246        for (phase, finished) in [
1247            ("Succeeded", true),
1248            ("Failed", true),
1249            ("Error", true),
1250            ("Running", false),
1251            ("Pending", false),
1252            ("", false),
1253        ] {
1254            assert_eq!(RecordPhase::parse(phase).finished(), finished, "{phase}");
1255        }
1256    }
1257
1258    /// `main` alone decides: exit 0 is the only pass, whatever else the pod
1259    /// or the Workflow says.
1260    #[test]
1261    fn the_end_of_a_pod_comes_from_main_alone() {
1262        let ended = |exit, reason: &str| State::Terminated {
1263            exit: Some(exit),
1264            reason: reason.into(),
1265            message: String::new(),
1266        };
1267        assert_eq!(end_from_main(&ended(0, "Completed")), JobEnd::Complete);
1268        assert_eq!(
1269            end_from_main(&ended(1, "Error")),
1270            JobEnd::Failed("Error".into())
1271        );
1272        assert_eq!(
1273            end_from_main(&ended(137, "OOMKilled")),
1274            JobEnd::Failed("OOMKilled".into())
1275        );
1276        assert_eq!(end_from_main(&State::Running), JobEnd::Running);
1277        assert_eq!(end_from_main(&State::Waiting), JobEnd::Running);
1278        assert_eq!(end_from_main(&State::Absent), JobEnd::Running);
1279    }
1280
1281    fn record_of_the_fixture() -> Pending {
1282        let mut record = sample("greengate-rh-test");
1283        record.uid = Some("uid-1".into());
1284        record.label = "label-1".into();
1285        record.tree = "13b5ee2d54389399fa2738f084a1b653b5844028".into();
1286        record.source.oid = "7e04624939f8c93f774d570276af8643c61f0320".into();
1287        record.gates[0].argv = vec!["python3".into(), "scripts/check-module-cycles.py".into()];
1288        record.gates[0].prepare = None;
1289        record.gates[0].digest =
1290            "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c".into();
1291        record
1292    }
1293
1294    fn collected(record: Pending, list: &Value) -> Resolution {
1295        resolve(record, list, 1_700_000_100)
1296    }
1297
1298    /// The first live run, collected: a pass written under the FROZEN token,
1299    /// and the finished Workflow leaves the file.
1300    #[test]
1301    fn the_live_fixture_is_a_pass() {
1302        let record = record_of_the_fixture();
1303        let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
1304        let done = collected(record, &list);
1305        assert!(done.notes.is_empty(), "{:?}", done.notes);
1306        assert_eq!(done.passes.len(), 1, "{done:?}");
1307        assert_eq!(
1308            done.passes[0].token, "pre-push-lint@abc",
1309            "the frozen token"
1310        );
1311        assert!(done.passes[0].provenance.contains("platform=x86_64-linux"));
1312        assert!(done.leaves, "a finished Workflow leaves the file");
1313    }
1314
1315    /// The node and the Workflow say Succeeded; `main` exited 1. Phases only
1316    /// say the pod finished.
1317    #[test]
1318    fn a_succeeded_node_with_a_failed_main_is_no_pass() {
1319        let record = record_of_the_fixture();
1320        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1321            p.replacen(
1322                "\"exitCode\":0,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
1323                "\"exitCode\":1,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
1324                1,
1325            )
1326        });
1327        let done = collected(record, &list);
1328        assert!(done.passes.is_empty(), "{done:?}");
1329        assert_eq!(done.notes.len(), 1, "{done:?}");
1330        assert!(done.notes[0].1.contains("exit 1"), "{:?}", done.notes);
1331    }
1332
1333    #[test]
1334    fn a_pod_of_another_workflow_uid_is_not_this_ones() {
1335        let record = record_of_the_fixture();
1336        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1337            p.replace("\"uid\":\"uid-1\"", "\"uid\":\"uid-other\"")
1338        });
1339        let done = collected(record, &list);
1340        assert!(done.passes.is_empty(), "{done:?}");
1341    }
1342
1343    #[test]
1344    fn a_pod_with_another_image_or_command_is_not_the_submission() {
1345        for tweak in [
1346            |p: String| {
1347                p.replace(
1348                    "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c",
1349                    &format!("sha256:{}", "0".repeat(64)),
1350                )
1351            },
1352            |p: String| p.replace("scripts/check-module-cycles.py", "scripts/other.py"),
1353            |p: String| {
1354                p.replace(
1355                    "tree 13b5ee2d54389399fa2738f084a1b653b5844028",
1356                    "tree 0000000000000000000000000000000000000000",
1357                )
1358            },
1359        ] {
1360            let record = record_of_the_fixture();
1361            let list = list_for(&record, "Succeeded", "Succeeded", tweak);
1362            let done = collected(record, &list);
1363            assert!(done.passes.is_empty(), "{done:?}");
1364            assert_eq!(done.notes.len(), 1, "{done:?}");
1365        }
1366    }
1367
1368    #[test]
1369    fn a_running_workflow_keeps_its_waiting_gates() {
1370        let record = record_of_the_fixture();
1371        let list = list_for(&record, "Running", "Running", |p| {
1372            // `main` has not terminated: the same state, reopened as running
1373            p.replace(
1374                "\"terminated\":{\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
1375                "\"running\":{\"startedAt\":\"t\",\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
1376            )
1377        });
1378        let done = collected(record, &list);
1379        assert!(done.passes.is_empty(), "{done:?}");
1380        assert!(!done.leaves);
1381        assert_eq!(done.record.gates[0].state, GateState::Waiting);
1382        assert_eq!(done.record.phase, RecordPhase::Running);
1383    }
1384
1385    #[test]
1386    fn a_workflow_gone_after_its_ttl_drops_the_record_with_one_note() {
1387        let record = record_of_the_fixture();
1388        let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
1389        let done = collected(record, &empty);
1390        assert!(done.leaves);
1391        assert_eq!(done.record.phase, RecordPhase::Gone);
1392        assert_eq!(done.record.phase.plain(), "gone (TTL passed or deleted)");
1393        assert_eq!(done.notes.len(), 1, "{done:?}");
1394    }
1395
1396    /// A create whose answer was lost: no Workflow yet, so the intent stays
1397    /// for a while, and goes once the grace has passed.
1398    #[test]
1399    fn an_intent_with_no_workflow_waits_then_goes() {
1400        let mut record = record_of_the_fixture();
1401        record.uid = None;
1402        let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
1403        let young = resolve(record.clone(), &empty, record.submitted + 60);
1404        assert!(!young.leaves);
1405        let old = resolve(
1406            record.clone(),
1407            &empty,
1408            record.submitted + INTENT_GRACE_SECS + 1,
1409        );
1410        assert!(old.leaves);
1411        assert_eq!(old.notes.len(), 1);
1412    }
1413
1414    /// The Workflow finished and passed, but the token cannot be written: the
1415    /// record stays, its gate waiting, and the next collect writes the token.
1416    #[test]
1417    fn a_pass_whose_token_cannot_be_written_keeps_the_record() {
1418        let record = record_of_the_fixture();
1419        let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
1420        let refuse = |_: &Pass| Err(Fallback::NotProved("git refused".into()));
1421        let first = settle_with(resolve(record.clone(), &list, 1_700_000_100), refuse, None);
1422        assert_eq!(first.written, 0);
1423        assert!(
1424            first.settled.is_none(),
1425            "the run has not ended for the person"
1426        );
1427        let kept = first.record.expect("the record survives");
1428        assert_eq!(kept.gates[0].state, GateState::Waiting);
1429
1430        let mut tokens = Vec::new();
1431        let second = settle_with(
1432            resolve(kept, &list, 1_700_000_200),
1433            |pass| {
1434                tokens.push(pass.token.clone());
1435                Ok(())
1436            },
1437            None,
1438        );
1439        assert_eq!(second.written, 1);
1440        assert_eq!(tokens, ["pre-push-lint@abc"]);
1441        assert!(second.record.is_none());
1442        let ended = second.settled.expect("now it ends");
1443        assert_eq!(ended.passed, ["pre-push-lint"]);
1444    }
1445
1446    /// A finished Workflow whose pod status cannot be read fails the gate.
1447    #[test]
1448    fn an_unreadable_pod_status_on_a_finished_workflow_fails_the_gate() {
1449        let record = record_of_the_fixture();
1450        let list = list_for(&record, "Failed", "Failed", |p| {
1451            p.replace(
1452                "\"name\":\"greengate-rh-test\",\"namespace\"",
1453                "\"namex\":\"greengate-rh-test\",\"namespace\"",
1454            )
1455        });
1456        let done = collected(record, &list);
1457        assert!(done.passes.is_empty());
1458        assert_eq!(done.notes.len(), 1, "{done:?}");
1459        assert!(
1460            done.notes[0].1.contains("status cannot be read"),
1461            "{done:?}"
1462        );
1463    }
1464
1465    /// A pod that does not name its node cannot be bound to the Workflow's.
1466    #[test]
1467    fn a_pod_without_a_node_id_is_not_bound() {
1468        let record = record_of_the_fixture();
1469        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1470            p.replace(
1471                "workflows.argoproj.io/node-id",
1472                "workflows.argoproj.io/node-idx",
1473            )
1474        });
1475        let done = collected(record, &list);
1476        assert!(done.passes.is_empty(), "{done:?}");
1477    }
1478
1479    #[test]
1480    fn a_record_older_than_the_ttl_expires_whatever_the_cluster_says() {
1481        let record = record_of_the_fixture();
1482        assert!(!is_expired(&record, record.submitted + TTL_SECS));
1483        assert!(is_expired(
1484            &record,
1485            record.submitted + TTL_SECS + EXPIRY_SLACK_SECS + 1
1486        ));
1487    }
1488}