Skip to main content

greengate_runtime/
rehearsal.rs

1//! Rehearse the push gate in the background, on a snapshot of `HEAD`.
2//!
3//! `amont run pre-push` (v1.27) moved the suite off the wire: run it first,
4//! stamp the tree, and the push that follows holds the remote for seconds.
5//! It is still a four-minute foreground wait that somebody has to remember
6//! to start. This module starts it for them, at the moment the content
7//! exists — `post-commit` — and gets out of the way.
8//!
9//! ## The shape
10//!
11//! - `post-commit` (opted in with `git config greengate.rehearseOnCommit true`)
12//!   spawns a detached WORKER: its own process group, stdio on a log file,
13//!   no terminal. git never waits for it.
14//! - The worker checks out `HEAD` into a throwaway worktree — the same
15//!   [`crate::pushed_tree`] machinery `greengate.testPushedTree` uses — and
16//!   drives the ordinary pre-push dispatcher there, with the branch and its
17//!   upstream as the ref line. The snapshot is what makes this safe to run
18//!   while you keep editing: the suite reads a tree nobody is touching, and
19//!   the stamp it earns is for exactly that tree.
20//! - The stamp is the whole hand-off. A pre-push that finds it skips the
21//!   suite; there is no second record to keep in step.
22//! - Latest wins. A worker that finds another one running on a DIFFERENT
23//!   tree kills it (the whole process group, suite included) and removes its
24//!   snapshot; one running on the same tree is left alone. A rebase replaying
25//!   ten commits does not queue ten suites.
26//! - A push that arrives while the rehearsal of its tree is still running
27//!   WAITS for it rather than starting the suite over: less remaining work
28//!   than a fresh run, and no extra CPU. The connection stays open either
29//!   way; waiting is the shorter of the two.
30//!
31//! ## What is written where
32//!
33//! `$GIT_DIR/greengate-rehearsal` — the worktree-PRIVATE git dir, like the gate
34//! marker: the commit that started this happened in this worktree, and the
35//! push that will ask about it comes from here too. One small text file:
36//! pid, commit, tree, start time, snapshot path, phase. Its log sits beside
37//! it as `greengate-rehearsal.log`. Nothing here is a second source of truth
38//! about whether a gate passed — that is the stamp's job; this file only
39//! says whether someone is still working on it, so a push can decide
40//! between waiting and running.
41//!
42//! ## Failure direction
43//!
44//! Every path that goes wrong — a worker that died, a state file that will
45//! not parse, a snapshot that could not be prepared — ends in the gate
46//! running at push time exactly as it would have without this module. The
47//! background run can only ever REMOVE work from the push; it never lets
48//! the push skip work nobody did.
49
50use crate::names::BIN;
51use std::ffi::OsString;
52use std::io::Write;
53use std::path::{Path, PathBuf};
54use std::process::{Command, Stdio};
55use std::time::{Duration, SystemTime, UNIX_EPOCH};
56
57use crate::hooks::common::{human_secs, warn};
58use crate::ui::{highlight, valid_sign, warning_sign};
59
60/// The opt-in: rehearse after every commit.
61const ON_COMMIT: &str = "greengate.rehearseOnCommit";
62
63/// How long a PUSH may wait for a running rehearsal before giving up and
64/// running the gate itself. `0` means no limit.
65///
66/// [`await_for`] runs inside `pre-push`, which is to say after git has opened
67/// its connection to the remote and while that connection sits idle — the
68/// exact window this whole feature exists to shorten. Waiting was bounded
69/// only by the worker's own deadline, which is `greengate.timeout`: an hour by
70/// default, and unbounded where somebody has set it to `0`. So the mechanism
71/// built to stop a four-minute suite killing a push could hold the same
72/// connection open for far longer than the suite would have.
73///
74/// Five minutes because that is under every idle timeout we have measured —
75/// Forgejo's git timeout is six — so a wait that expires still leaves the
76/// connection alive for the gate that follows it. `amont rehearse --wait`
77/// has no budget: nothing is connected there, and a person who typed it is
78/// asking to be told when the suite ends.
79const WAIT_BUDGET: &str = "greengate.rehearsalWait";
80
81pub fn wait_budget(settings: &crate::config::Settings) -> Option<Duration> {
82    match crate::config::integer_or(settings, WAIT_BUDGET, 300, 0..=86_400) {
83        0 => None,
84        secs => Some(Duration::from_secs(secs as u64)),
85    }
86}
87
88/// The state file, inside `$GIT_DIR`.
89const STATE: &str = crate::names::REHEARSAL_STATE;
90/// The detached worker's stdout and stderr, beside it.
91const LOG: &str = crate::names::REHEARSAL_LOG;
92/// First line of the state file — bump when the layout changes, and an
93/// older binary reads the file as "no rehearsal", which re-runs the gate.
94const FORMAT: &str = crate::names::REHEARSAL_FORMAT;
95
96/// Set in the environment of the pre-push run a worker drives inside the
97/// snapshot. The dispatcher reads it to run the content gates only — the
98/// push-shaped checks (branch-protect, secrets, the auto-rebase) ask about a
99/// push that is not happening — and to skip the wait below, which would
100/// otherwise be a process waiting for itself.
101pub const ENV: &str = "GREENGATE_REHEARSAL";
102
103/// Does this repository rehearse after every commit?
104pub fn on_commit_enabled(settings: &crate::config::Settings) -> bool {
105    crate::config::boolean_or(settings, ON_COMMIT, false)
106}
107
108/// What a push does about a gate-paired check when a pushed commit carries
109/// no record of it — rewritten by a rebase or amend, committed with
110/// `--no-verify`, made where amont is not installed:
111///
112/// - `run` (the default): run the suite in the push, as always;
113/// - `refuse`: block the push and say how to get the stamp instead
114///   (`amont rehearse --wait`). The suite then never runs while git holds
115///   its connection to the remote open — the one place a slow suite can
116///   kill a push whose checks all passed. A rehearsal still RUNNING for the
117///   tip is waited for first (`greengate.rehearsalWait`), and its stamp is
118///   honoured; a rehearsal snapshot itself always runs, since that is where
119///   the stamp is earned.
120const UNSTAMPED_PUSH: &str = "greengate.unstampedPush";
121
122/// Does this repository refuse a push the gate did not vouch for?
123pub fn refuse_unstamped(settings: &crate::config::Settings) -> bool {
124    crate::config::enumerated_or(settings, UNSTAMPED_PUSH, &["run", "refuse"], "run") == "refuse"
125}
126
127/// Is this process the pre-push run inside a rehearsal snapshot?
128///
129/// Read ONCE, and the variable is removed from the environment as it is
130/// read: everything this process spawns — the test suite above all — must
131/// not inherit it. amont's own suite pushes through a real pre-push in
132/// fixture repositories, and with the variable inherited that pre-push
133/// believed itself a rehearsal and skipped branch-protect, which is how the
134/// first rehearsal of this very feature failed its own gate.
135///
136/// **`main` primes this before anything else runs, and must keep doing so.**
137/// `remove_var` is not thread-safe — that is why Rust 2024 made it `unsafe`
138/// — and this is reachable from `pushed_tree::where_to_run`, i.e. from
139/// inside a check, and `dispatch` runs checks concurrently. Settling the
140/// `OnceLock` on the main thread means the racy call has already happened by
141/// the time any thread exists. Do not remove that call, and do not let a
142/// caller reach here first.
143pub fn in_snapshot() -> bool {
144    snapshot_env().is_some()
145}
146
147/// The prefix of the variable's value that names the gates the rehearsal gave
148/// to the cluster (ADR-0017): `detached=<id>,<id>`. A bare `1` names none.
149const DETACHED_PREFIX: &str = "detached=";
150
151/// What the variable said, parsed where it is settled: the gates the
152/// rehearsal that made this snapshot handed to the cluster.
153struct SnapshotEnv {
154    detached: Vec<String>,
155    /// The rehearsal was started by land's pre-stage: someone is waiting on
156    /// it, so a warn gate's slot wait has a ceiling (ADR-0013).
157    prestage: bool,
158}
159
160/// The leading marker of the variable's value for land's pre-stage:
161/// `prestage;1` or `prestage;detached=a,b`. An older amont reads the whole
162/// value as no detached gates.
163const PRESTAGE_PREFIX: &str = "prestage;";
164
165/// What the variable's value says: whether land's pre-stage made the
166/// snapshot, and the gates it handed to the cluster.
167fn parse_snapshot_env(raw: &str) -> SnapshotEnv {
168    let (prestage, rest) = match raw.strip_prefix(PRESTAGE_PREFIX) {
169        Some(rest) => (true, rest),
170        None => (false, raw),
171    };
172    let detached = rest
173        .strip_prefix(DETACHED_PREFIX)
174        .map(|ids| ids.split(',').map(str::to_string).collect())
175        .unwrap_or_default();
176    SnapshotEnv { detached, prestage }
177}
178
179/// The variable, settled and parsed once for the same reason [`in_snapshot`]
180/// is.
181fn snapshot_env() -> &'static Option<SnapshotEnv> {
182    static IN: std::sync::OnceLock<Option<SnapshotEnv>> = std::sync::OnceLock::new();
183    IN.get_or_init(|| {
184        let raw = std::env::var_os(ENV).map(|v| v.to_string_lossy().into_owned())?;
185        std::env::remove_var(ENV);
186        Some(parse_snapshot_env(&raw))
187    })
188}
189
190/// Is this snapshot the one land's pre-stage made? Settled with
191/// [`in_snapshot`], never read from the variable.
192pub fn in_prestage() -> bool {
193    snapshot_env().as_ref().is_some_and(|env| env.prestage)
194}
195
196/// The gates the rehearsal that started this snapshot handed to the cluster:
197/// this run does not repeat them, their passes come back as cluster tokens at
198/// the next commit or push. Empty outside a snapshot. Read by `main`, which
199/// carries it on `Ctx` to the pre-push loop.
200pub fn handed_to_cluster() -> &'static [String] {
201    snapshot_env()
202        .as_ref()
203        .map_or(&[], |env| env.detached.as_slice())
204}
205
206/// The variable `amont land` sets on its own `git push` (ADR-0018):
207/// `<sha> <remote tip>`, what its pre-stage ran the push gates against. Read
208/// once and removed, for the reason [`in_snapshot`] gives: a gate's own
209/// fixture pushes must not inherit it. `main` primes it on the main thread.
210pub const LAND_ENV: &str = "GREENGATE_LAND";
211
212/// What land's pre-stage saw: the sha it ran the gates on, and the remote tip
213/// it ran them against (all zeros for a ref the remote lacks).
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct LandLine {
216    pub sha: String,
217    pub remote_tip: String,
218}
219
220/// [`LAND_ENV`], parsed where it is read.
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub enum LandEnv {
223    /// Not land's push.
224    Absent,
225    Valid(LandLine),
226    /// Set, but not two object names: the hook refuses rather than guess.
227    Malformed(String),
228}
229
230/// A full object name: 40 (sha-1) or 64 (sha-256) hex digits.
231fn is_oid(s: &str) -> bool {
232    matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
233}
234
235impl LandEnv {
236    pub fn parse(raw: &str) -> LandEnv {
237        let fields: Vec<&str> = raw.split_whitespace().collect();
238        match fields.as_slice() {
239            [sha, remote_tip] if is_oid(sha) && is_oid(remote_tip) => LandEnv::Valid(LandLine {
240                sha: sha.to_string(),
241                remote_tip: remote_tip.to_string(),
242            }),
243            _ => LandEnv::Malformed(raw.to_string()),
244        }
245    }
246}
247
248/// The land pre-stage's line, when this process is the hook of the push
249/// `amont land` makes. `main` reads it and carries it on `Ctx`.
250pub fn land_env() -> &'static LandEnv {
251    static IN: std::sync::OnceLock<LandEnv> = std::sync::OnceLock::new();
252    IN.get_or_init(|| match std::env::var_os(LAND_ENV) {
253        None => LandEnv::Absent,
254        Some(raw) => {
255            std::env::remove_var(LAND_ENV);
256            LandEnv::parse(&raw.to_string_lossy())
257        }
258    })
259}
260
261/// Set by `amont land` on the `amont rehearse --wait` it runs as its
262/// pre-stage (ADR-0018): the real ref line of the push it is about to make,
263/// `<local ref> <sha> <remote ref> <remote tip>`, so the rehearsal selects
264/// exactly the gates that push will owe — not the ones a possibly stale
265/// tracking ref suggests. Also means "never cancel another tree's rehearsal:
266/// wait for it". Read once and removed, like [`ENV`].
267pub const PRESTAGE_ENV: &str = "GREENGATE_LAND_PRESTAGE";
268
269/// [`PRESTAGE_ENV`], parsed where it is read.
270#[derive(Debug, Clone, PartialEq, Eq)]
271pub enum Prestage {
272    /// A plain rehearsal of HEAD.
273    Absent,
274    /// Land's pre-stage, of this push line.
275    Of(crate::pushrefs::PushRef),
276    /// Set, but not a push line: `rehearse` refuses rather than fall back to
277    /// an ordinary rehearsal that might cancel somebody else's.
278    Malformed(String),
279}
280
281impl Prestage {
282    pub fn parse(raw: &str) -> Prestage {
283        let fields: Vec<&str> = raw.split_whitespace().collect();
284        match fields.as_slice() {
285            [local_ref, local_oid, remote_ref, remote_oid]
286                if is_oid(local_oid) && is_oid(remote_oid) =>
287            {
288                Prestage::Of(crate::pushrefs::PushRef {
289                    local_ref: local_ref.to_string(),
290                    local_oid: local_oid.to_string(),
291                    remote_ref: remote_ref.to_string(),
292                    remote_oid: remote_oid.to_string(),
293                })
294            }
295            _ => Prestage::Malformed(raw.to_string()),
296        }
297    }
298
299    fn line(&self) -> Option<&crate::pushrefs::PushRef> {
300        match self {
301            Prestage::Of(line) => Some(line),
302            Prestage::Absent | Prestage::Malformed(_) => None,
303        }
304    }
305}
306
307/// The working tree this rehearsal snapshot was taken from, when this process
308/// is the snapshot's pre-push (`GREENGATE_SOURCE_WORKTREE`). Read once and removed
309/// like [`ENV`]; `main` primes it and carries it on `Ctx`.
310pub fn source_worktree() -> Option<&'static std::path::Path> {
311    static IN: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
312    IN.get_or_init(|| {
313        let raw = std::env::var_os(crate::pushed_tree::SOURCE_WORKTREE_ENV)?;
314        std::env::remove_var(crate::pushed_tree::SOURCE_WORKTREE_ENV);
315        Some(std::path::PathBuf::from(raw))
316    })
317    .as_deref()
318}
319
320/// This process's pre-stage, settled once. Primed by `main`; read by
321/// `rehearse`, which passes it down.
322pub fn prestage() -> &'static Prestage {
323    static IN: std::sync::OnceLock<Prestage> = std::sync::OnceLock::new();
324    IN.get_or_init(|| match std::env::var_os(PRESTAGE_ENV) {
325        None => Prestage::Absent,
326        Some(raw) => {
327            std::env::remove_var(PRESTAGE_ENV);
328            Prestage::parse(&raw.to_string_lossy())
329        }
330    })
331}
332
333/// What a push does about a heavy gate (a scoped one its range touches) with
334/// no stamp or vouch for the pushed tree (ADR-0018):
335///
336/// - `refuse` (the default): refuse at once, before anything runs on the
337///   connection git already opened, naming `amont land`;
338/// - `inline`: run it in the push, as amont did before 2.0.
339const PUSH_GATES: &str = "greengate.pushGates";
340
341/// Does a push refuse an unstamped heavy gate instead of running it?
342pub fn refuse_push_gates(settings: &crate::config::Settings) -> bool {
343    crate::config::enumerated_or(settings, PUSH_GATES, &["refuse", "inline"], "refuse") == "refuse"
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
347pub enum Phase {
348    Running,
349    Passed,
350    Failed,
351}
352
353impl Phase {
354    fn as_str(self) -> &'static str {
355        match self {
356            Phase::Running => "running",
357            Phase::Passed => "passed",
358            Phase::Failed => "failed",
359        }
360    }
361
362    fn parse(s: &str) -> Option<Phase> {
363        match s {
364            "running" => Some(Phase::Running),
365            "passed" => Some(Phase::Passed),
366            "failed" => Some(Phase::Failed),
367            _ => None,
368        }
369    }
370}
371
372/// One rehearsal, as the state file records it.
373#[derive(Debug, Clone, PartialEq, Eq)]
374pub struct State {
375    pub pid: u32,
376    pub commit: String,
377    pub tree: String,
378    pub started: u64,
379    pub snapshot: PathBuf,
380    pub phase: Phase,
381    /// What a running worker is doing — `preparing` the snapshot or
382    /// `testing` it. A key rather than a phase value: an older amont reading
383    /// this file ignores a key it does not know, where an unknown phase would
384    /// read as no rehearsal at all.
385    pub step: Option<String>,
386    /// Why a rehearsal failed without the gate ever running.
387    pub reason: Option<String>,
388    /// Land's pre-stage (ADR-0018): a rehearsal that meets it waits for it
389    /// instead of cancelling it, since land is about to push what it proves.
390    pub prestage: bool,
391    /// The signal that stopped its push gate, when one did: no verdict, so a
392    /// follower reports it interrupted, not failed.
393    pub signal: Option<i32>,
394}
395
396impl State {
397    fn render(&self) -> String {
398        format!(
399            "{FORMAT}\npid={}\ncommit={}\ntree={}\nstarted={}\nsnapshot={}\nphase={}\n",
400            self.pid,
401            self.commit,
402            self.tree,
403            self.started,
404            self.snapshot.display(),
405            self.phase.as_str(),
406        ) + &[("step", &self.step), ("reason", &self.reason)]
407            .iter()
408            .filter_map(|(k, v)| v.as_ref().map(|v| format!("{k}={}\n", one_line(v))))
409            .collect::<String>()
410            + if self.prestage { "kind=prestage\n" } else { "" }
411            + &self
412                .signal
413                .map(|n| format!("signal={n}\n"))
414                .unwrap_or_default()
415    }
416
417    /// `None` for anything this version did not write — including a file
418    /// from a future layout — which the callers all treat as "no rehearsal".
419    pub fn parse(body: &str) -> Option<State> {
420        let mut lines = body.lines();
421        if lines.next()? != FORMAT {
422            return None;
423        }
424        let (mut pid, mut commit, mut tree, mut started, mut snapshot, mut phase) =
425            (None, None, None, None, None, None);
426        let (mut step, mut reason, mut prestage, mut signal) = (None, None, false, None);
427        for line in lines {
428            let (k, v) = line.split_once('=')?;
429            match k {
430                "pid" => pid = v.parse().ok(),
431                "commit" => commit = Some(v.to_string()),
432                "tree" => tree = Some(v.to_string()),
433                "started" => started = v.parse().ok(),
434                "snapshot" => snapshot = Some(PathBuf::from(v)),
435                "phase" => phase = Phase::parse(v),
436                "step" => step = Some(v.to_string()),
437                "reason" => reason = Some(v.to_string()),
438                "kind" => prestage = v == "prestage",
439                "signal" => signal = v.parse().ok(),
440                _ => {}
441            }
442        }
443        Some(State {
444            pid: pid?,
445            commit: commit?,
446            tree: tree?,
447            started: started?,
448            snapshot: snapshot?,
449            phase: phase?,
450            step,
451            reason,
452            prestage,
453            signal,
454        })
455    }
456
457    /// Still running, and the process is really there. A `running` record
458    /// whose pid is gone is a worker that was killed or crashed before it
459    /// could write its verdict.
460    pub fn alive(&self) -> bool {
461        self.phase == Phase::Running && process_alive(self.pid)
462    }
463
464    pub fn age_secs(&self) -> u64 {
465        now().saturating_sub(self.started)
466    }
467
468    fn short(&self) -> &str {
469        self.commit.get(..8).unwrap_or(&self.commit)
470    }
471}
472
473/// A value the one-line-per-key state file can hold.
474fn one_line(v: &str) -> String {
475    v.replace(['\n', '\r'], " ")
476}
477
478fn now() -> u64 {
479    SystemTime::now()
480        .duration_since(UNIX_EPOCH)
481        .unwrap_or_default()
482        .as_secs()
483}
484
485/// `$GIT_DIR`, absolute — the worktree-private one, deliberately (see the
486/// module doc).
487fn git_dir() -> Option<PathBuf> {
488    crate::git::stdout(&["rev-parse", "--absolute-git-dir"]).map(PathBuf::from)
489}
490
491fn state_path() -> Option<PathBuf> {
492    git_dir().map(|d| d.join(STATE))
493}
494
495/// Where a detached worker writes. Reported to the user whenever the
496/// outcome might send them looking.
497pub fn log_path() -> Option<PathBuf> {
498    git_dir().map(|d| d.join(LOG))
499}
500
501/// The recorded rehearsal for this worktree, if any.
502pub fn read() -> Option<State> {
503    let body = std::fs::read_to_string(state_path()?).ok()?;
504    State::parse(&body)
505}
506
507fn write(state: &State) {
508    if let Some(path) = state_path() {
509        // Best-effort: a state file that could not be written costs, at
510        // most, a push that runs the gate instead of waiting — the safe
511        // direction.
512        let _ = std::fs::write(path, state.render());
513    }
514}
515
516fn clear() {
517    if let Some(path) = state_path() {
518        let _ = std::fs::remove_file(path);
519    }
520}
521
522/// Is a process with this pid running? A wrong answer in the "no" direction
523/// re-runs a gate; a wrong "yes" would make a push wait on nothing, so the
524/// poll loops below also give up when the state stops changing.
525pub fn process_alive(pid: u32) -> bool {
526    #[cfg(unix)]
527    {
528        Command::new("kill")
529            .args(["-0", &pid.to_string()])
530            .stdin(Stdio::null())
531            .stdout(Stdio::null())
532            .stderr(Stdio::null())
533            .status()
534            .map(|s| s.success())
535            .unwrap_or(false)
536    }
537    #[cfg(not(unix))]
538    {
539        Command::new("tasklist")
540            .args(["/FI", &format!("PID eq {pid}"), "/NH"])
541            .stdin(Stdio::null())
542            .stderr(Stdio::null())
543            .output()
544            .map(|o| String::from_utf8_lossy(&o.stdout).contains(&pid.to_string()))
545            .unwrap_or(false)
546    }
547}
548
549/// End a worker and everything it started: the suite runs in the worker's
550/// process group, which is what makes "cancel" mean the tests too rather
551/// than an orphaned vitest carrying on against a worktree about to vanish.
552fn kill_group(pid: u32) {
553    #[cfg(unix)]
554    {
555        let _ = Command::new("kill")
556            .args(["-TERM", "--", &format!("-{pid}")])
557            .stdin(Stdio::null())
558            .stdout(Stdio::null())
559            .stderr(Stdio::null())
560            .status();
561    }
562    #[cfg(not(unix))]
563    {
564        let _ = Command::new("taskkill")
565            .args(["/PID", &pid.to_string(), "/T", "/F"])
566            .stdin(Stdio::null())
567            .stdout(Stdio::null())
568            .stderr(Stdio::null())
569            .status();
570    }
571}
572
573/// Stop the recorded worker, if it is running, and take its snapshot with
574/// it. A killed worker never reaches its own cleanup (`Drop` does not run
575/// on a signal), so whoever kills it owns the leftovers.
576fn cancel(state: &State, repo: &Path) {
577    if state.alive() {
578        kill_group(state.pid);
579        // Give the group a moment to go, so the worktree below is not
580        // removed under a test still writing into it.
581        for _ in 0..20 {
582            if !process_alive(state.pid) {
583                break;
584            }
585            std::thread::sleep(Duration::from_millis(100));
586        }
587    }
588    remove_snapshot(repo, &state.snapshot);
589}
590
591fn remove_snapshot(repo: &Path, path: &Path) {
592    if path.as_os_str().is_empty() || !path.exists() {
593        let _ = crate::git::succeeds_in(repo, &["worktree", "prune"]);
594        return;
595    }
596    let _ = crate::git::succeeds_in(
597        repo,
598        &[
599            "worktree",
600            "remove",
601            "--force",
602            path.to_str().unwrap_or_default(),
603        ],
604    );
605    let _ = std::fs::remove_dir_all(path);
606    let _ = crate::git::succeeds_in(repo, &["worktree", "prune"]);
607}
608
609/// The environment git hands a hook — `GIT_DIR`, `GIT_INDEX_FILE` and the
610/// rest — pins every git command to the hook's own repository and, for
611/// `commit -a`, to a temporary index that is gone by the time a worker
612/// reads it. The worker runs git in the primary tree and in a snapshot; it
613/// must see neither. `GIT_CONFIG_*` stays: it says where config lives, not
614/// which repository this is, and the test harness relies on it.
615fn strip_repo_env(cmd: &mut Command) {
616    for key in [
617        "GIT_DIR",
618        "GIT_WORK_TREE",
619        "GIT_INDEX_FILE",
620        "GIT_COMMON_DIR",
621        "GIT_PREFIX",
622        "GIT_OBJECT_DIRECTORY",
623        "GIT_ALTERNATE_OBJECT_DIRECTORIES",
624        "GIT_NAMESPACE",
625        "GIT_REFLOG_ACTION",
626        "GIT_EXEC_PATH",
627        // the index hints of a commit this process may be inside (see
628        // `hooks::common::strip_git_env`)
629        crate::hooks::common::INDEX_ENV,
630        crate::hooks::common::INDEX_GIT_DIR_ENV,
631    ] {
632        cmd.env_remove(key);
633    }
634}
635
636/// Start a worker for `HEAD` in the background and return at once.
637///
638/// Its own process group (so it can be cancelled as a unit), stdin closed,
639/// stdout and stderr on the log. The worker does all the deciding —
640/// whether there is anything to rehearse, whether the tree is already
641/// stamped, whether another worker has it — so the caller (a post-commit
642/// hook, or `amont rehearse`) pays one `spawn` and nothing else.
643///
644/// Unix only. On Windows a child inherits every inheritable handle of its
645/// parent — Rust's `Command` cannot restrict that today — so a worker
646/// started from a hook whose output is piped (an agent driving `git commit`)
647/// would hold the pipe until the suite ended, and the "background" run
648/// would block the very command it was meant to free. Said plainly instead
649/// of spawned: `amont rehearse --wait` runs the same thing in the foreground.
650#[cfg(not(unix))]
651pub fn spawn_detached() -> Result<u32, String> {
652    Err(format!(
653        "background rehearsal is not available on Windows yet — \
654         `{BIN} rehearse --wait` runs it in the foreground"
655    ))
656}
657
658#[cfg(unix)]
659pub fn spawn_detached() -> Result<u32, String> {
660    let log = log_path().ok_or("not inside a git repository")?;
661    spawn_amont(&["rehearse", "--worker"], &log, None)
662}
663
664/// Start `amont <args…>` in the background: its own process group, stdin
665/// closed, stdout and stderr on `log` (truncated). Every detached worker —
666/// the rehearsal, the tree-gate warm-up — goes through here, each with its
667/// OWN log, so one never truncates another's. `inherit` is a descriptor the
668/// child keeps open across `exec` (its `FD_CLOEXEC` is cleared in the child
669/// alone, so no other spawn of this process inherits it).
670#[cfg(unix)]
671pub fn spawn_amont(
672    args: &[&str],
673    log: &std::path::Path,
674    inherit: Option<i32>,
675) -> Result<u32, String> {
676    use std::os::unix::process::CommandExt;
677    let exe = std::env::current_exe().map_err(|e| format!("cannot locate {BIN}: {e}"))?;
678    let file =
679        std::fs::File::create(log).map_err(|e| format!("cannot open {}: {e}", log.display()))?;
680    let err = file
681        .try_clone()
682        .map_err(|e| format!("cannot open {}: {e}", log.display()))?;
683    let mut cmd = Command::new(exe);
684    cmd.args(args)
685        .stdin(Stdio::null())
686        .stdout(Stdio::from(file))
687        .stderr(Stdio::from(err));
688    strip_repo_env(&mut cmd);
689    cmd.process_group(0);
690    if let Some(fd) = inherit {
691        // SAFETY: the closure runs between fork and exec and calls only
692        // fcntl, which is async-signal-safe.
693        unsafe {
694            cmd.pre_exec(move || {
695                if crate::fdlock::clear_cloexec(fd) {
696                    Ok(())
697                } else {
698                    Err(std::io::Error::last_os_error())
699                }
700            });
701        }
702    }
703    let child = cmd
704        .spawn()
705        .map_err(|e| format!("cannot start {BIN} {}: {e}", args.join(" ")))?;
706    Ok(child.id())
707}
708
709/// What a worker found, or did.
710#[derive(Debug, Clone, PartialEq, Eq)]
711pub enum Outcome {
712    /// No scoped gate has work to do for what `HEAD` would push.
713    NothingToDo,
714    /// Every gate that would run is already stamped on this tree.
715    AlreadyStamped,
716    /// Another worker is on this exact tree; it was left alone.
717    AlreadyRunning(u32),
718    /// Every gate left to run went to the cluster (ADR-0017); the next commit
719    /// or push collects the result.
720    Detached,
721    Passed,
722    Failed,
723    /// The snapshot's push gate was stopped by this signal: no verdict.
724    Interrupted(i32),
725}
726
727/// The signal that ended a child, if one did.
728pub(crate) fn signal_of(status: &std::process::ExitStatus) -> Option<i32> {
729    #[cfg(unix)]
730    {
731        std::os::unix::process::ExitStatusExt::signal(status)
732    }
733    #[cfg(not(unix))]
734    {
735        let _ = status;
736        None
737    }
738}
739
740/// Is the rehearsal `state` recorded still the one running now?
741fn still_running(state: &State) -> bool {
742    read().is_some_and(|now| now.alive() && now.pid == state.pid && now.started == state.started)
743}
744
745/// How long a rehearsal waits behind land's pre-stage, or land's pre-stage
746/// behind another rehearsal, before giving up (ADR-0018). Nothing holds a
747/// connection open meanwhile; the bound is for a worker that hangs.
748const PRESTAGE_WAIT: Duration = Duration::from_secs(3 * 60 * 60);
749
750/// What a rehearsal of `HEAD` has to decide with.
751struct Plan {
752    root: String,
753    head: String,
754    tree: String,
755    push_ref: crate::pushrefs::PushRef,
756    manifest: crate::manifest::Manifest,
757    settings: crate::config::Settings,
758    /// The scoped push gates with work to do.
759    gates: Vec<String>,
760    /// Tree gates this tree has not proven yet (ADR-0024).
761    tree_todo: Vec<crate::manifest::TreeGate>,
762    /// The audit reads this plan made, asked again by `vouched`.
763    audits: crate::hooks::audit::Ledger,
764}
765
766fn plan(prestage: Option<&crate::pushrefs::PushRef>) -> Result<Plan, String> {
767    let root = crate::hooks::common::repo_root_checked()?;
768    let repo = Path::new(&root);
769    // Land's pre-stage names the commit it will push (a tag's, for
770    // `land --tag`); a plain rehearsal tests HEAD.
771    let head = match prestage {
772        Some(line) => crate::git::stdout(&["rev-parse", &format!("{}^{{commit}}", line.local_oid)])
773            .ok_or("could not resolve the commit to pre-stage")?,
774        None => crate::git::stdout(&["rev-parse", "HEAD"]).ok_or("could not resolve HEAD")?,
775    };
776    let tree = crate::git::stdout(&["rev-parse", &format!("{head}^{{tree}}")])
777        .ok_or("could not resolve the tree to rehearse")?;
778    // The branch and its upstream, read HERE in the primary worktree: the
779    // snapshot is a detached HEAD and could not answer.
780    let push_ref = match prestage {
781        Some(line) => line.clone(),
782        None => crate::pushrefs::synthetic_from_upstream()?,
783    };
784    let (manifest, settings) = crate::manifest::load_resolved(repo);
785    let changed = crate::pushrefs::changed_files(std::slice::from_ref(&push_ref));
786    let mut gates = crate::dispatch::scoped_push_gates(&settings, &manifest, &changed);
787    // Audits are owed whatever the range touches, until a fresh record
788    // answers for them (ADR-0018).
789    let audits = crate::hooks::audit::Ledger::default();
790    for audit in crate::dispatch::owed_audits(
791        &settings,
792        &manifest,
793        &audits,
794        std::slice::from_ref(&push_ref),
795    ) {
796        if !gates.contains(&audit) {
797            gates.push(audit);
798        }
799    }
800    // Tree gates this tree has not proven yet (ADR-0024). Resolved BEFORE
801    // the nothing-to-do exit: a push whose only gates are lint must still be
802    // rehearsed, or a rebased branch could never be attested.
803    let proven_here = crate::gate_stamp::tree_tokens(&tree);
804    let tree_todo: Vec<crate::manifest::TreeGate> = if crate::tree_lint::enabled(&settings) {
805        manifest
806            .tree
807            .iter()
808            .filter(|g| !proven_here.contains(&g.stamp_key()))
809            .cloned()
810            .collect()
811    } else {
812        Vec::new()
813    };
814    Ok(Plan {
815        root,
816        head,
817        tree,
818        push_ref,
819        manifest,
820        settings,
821        gates,
822        tree_todo,
823        audits,
824    })
825}
826
827impl Plan {
828    /// Is `gate` already vouched for on HEAD: by a local token, or by a
829    /// cluster token (ADR-0016, ADR-0017)?
830    fn vouched(&self, gate: &str) -> bool {
831        if crate::hooks::audit::is_audit(gate) {
832            return !crate::hooks::audit::owed(
833                &self.settings,
834                &self.audits,
835                gate,
836                std::slice::from_ref(&self.push_ref),
837            );
838        }
839        vouched_by(&self.settings, &self.manifest, &self.head, gate)
840    }
841
842    /// Hand the gates that are not vouched yet to the cluster, as far as it
843    /// may take them. The gates now on the cluster.
844    fn detach(&self, ask: crate::cluster::Ask) -> Vec<String> {
845        let unstamped: Vec<String> = self
846            .gates
847            .iter()
848            .filter(|gate| !self.vouched(gate))
849            .cloned()
850            .collect();
851        crate::cluster::detach(&self.settings, &self.manifest, &unstamped, ask).gates
852    }
853}
854
855/// Who asked for a rehearsal.
856#[derive(Debug, Clone, Copy, PartialEq, Eq)]
857enum Origin {
858    /// A push's own pre-push.
859    Push,
860    /// Land's pre-stage.
861    Prestage,
862}
863
864impl Origin {
865    /// Land's pre-stage hands the rehearsal its push line; any other
866    /// rehearsal has none.
867    fn of(prestage: Option<&crate::pushrefs::PushRef>) -> Origin {
868        match prestage {
869            Some(_) => Origin::Prestage,
870            None => Origin::Push,
871        }
872    }
873}
874
875/// The value of [`ENV`] for a run that gave `on_cluster` to the cluster.
876/// Land's pre-stage marks it with a leading `prestage;`.
877fn snapshot_env_value(on_cluster: &[String], origin: Origin) -> String {
878    let marker = match origin {
879        Origin::Push => "",
880        Origin::Prestage => PRESTAGE_PREFIX,
881    };
882    if on_cluster.is_empty() {
883        format!("{marker}1")
884    } else {
885        format!("{marker}{DETACHED_PREFIX}{}", on_cluster.join(","))
886    }
887}
888
889/// [`Plan::vouched`] for a plan taken apart.
890fn vouched_by(
891    settings: &crate::config::Settings,
892    manifest: &crate::manifest::Manifest,
893    head: &str,
894    gate: &str,
895) -> bool {
896    let tips = [head.to_string()];
897    // A stamp or a cluster proof is by tree and the push no longer honours
898    // one for a `warn` gate (f129); only an hour-long completion vouches.
899    if let Some(check) = crate::registry::one_named(gate, manifest) {
900        let severity = crate::registry::severity_of(settings, check);
901        if severity == crate::check::Severity::Warn {
902            return crate::gate_identity::token(&manifest.externals, gate)
903                .is_some_and(|t| crate::gate_stamp::done_on_every(&tips, &t, severity));
904        }
905    }
906    let stamped = crate::gate_stamp::stamps_for(&tips);
907    let local = crate::gate_identity::token(&manifest.externals, gate)
908        .is_some_and(|t| stamped.get(head).is_some_and(|s| s.contains(&t)));
909    local
910        || manifest
911            .externals
912            .iter()
913            .find(|e| e.id == gate)
914            .is_some_and(|e| crate::cluster::vouched_on_every(settings, e, &tips))
915}
916
917/// Why a snapshot prepare failed. A wait that ended in line refused the
918/// install, so its cause is the reason, not the install's own error; only the
919/// ceiling means a busy host. `busy` is the guard's `deferred_end`.
920fn prepare_failure(busy: Option<(greenharness_slots::WaitEnd, String)>, why: String) -> String {
921    match busy {
922        Some((greenharness_slots::WaitEnd::Ceiling, cause)) => format!(
923            "the host stayed busy: {cause}; raise greengate.timeout or rehearse \
924             again when the host is quieter"
925        ),
926        Some((_, cause)) => cause,
927        None => why,
928    }
929}
930
931/// THE worker. Runs in the foreground of whoever called it — the detached
932/// process `spawn_detached` started, or `amont rehearse --wait` when nothing
933/// was running — and returns only when the verdict is in.
934pub fn worker(
935    ask: crate::cluster::Ask,
936    prestage: Option<&crate::pushrefs::PushRef>,
937) -> Result<Outcome, String> {
938    let planned = plan(prestage)?;
939    let repo = Path::new(&planned.root);
940    let (head, tree) = (planned.head.clone(), planned.tree.clone());
941    let short = head.get(..8).unwrap_or(&head);
942    if planned.gates.is_empty() && planned.tree_todo.is_empty() {
943        println!("nothing to rehearse: no test gate has work to do for what {short} would push");
944        return Ok(Outcome::NothingToDo);
945    }
946    if planned.gates.iter().all(|gate| planned.vouched(gate)) && planned.tree_todo.is_empty() {
947        println!(
948            "{} {} already stamped on this tree — nothing to rehearse",
949            valid_sign(),
950            highlight(&planned.gates.join(" "))
951        );
952        return Ok(Outcome::AlreadyStamped);
953    }
954    // Another tree's rehearsal is cancelled — the newer tree is what matters —
955    // except where land is involved: land's pre-stage never cancels anyone,
956    // and is never cancelled; whoever meets it waits for it, within a bound
957    // (ADR-0018). Then the state is read again, since another worker may
958    // have registered meanwhile.
959    let mut settled = false;
960    for _ in 0..3 {
961        let Some(prev) = read() else {
962            settled = true;
963            break;
964        };
965        if !prev.alive() {
966            if prev.phase == Phase::Running {
967                // Died without a verdict. Its snapshot is nobody's now.
968                remove_snapshot(repo, &prev.snapshot);
969            }
970            settled = true;
971            break;
972        }
973        if prev.tree == tree {
974            println!(
975                "a rehearsal of this tree is already running (pid {}, started {} ago)",
976                prev.pid,
977                human_secs(prev.age_secs())
978            );
979            return Ok(Outcome::AlreadyRunning(prev.pid));
980        }
981        if prestage.is_some() || prev.prestage {
982            eprintln!(
983                "waiting for the rehearsal of {} (pid {}) before rehearsing {short}",
984                prev.short(),
985                prev.pid,
986            );
987            if follow(&prev, Some(PRESTAGE_WAIT)).is_none() && still_running(&prev) {
988                return Err(format!(
989                    "the rehearsal of {} (pid {}) is still running after {}; \
990                     not starting another beside it",
991                    prev.short(),
992                    prev.pid,
993                    human_secs(PRESTAGE_WAIT.as_secs())
994                ));
995            }
996            continue;
997        }
998        eprintln!(
999            "cancelling the rehearsal of {} (pid {}) — {} is the tree that matters now",
1000            prev.short(),
1001            prev.pid,
1002            short
1003        );
1004        cancel(&prev, repo);
1005        settled = true;
1006        break;
1007    }
1008    if !settled {
1009        return Err("other rehearsals kept starting in this worktree; try again".to_string());
1010    }
1011    // Gates the cluster may take go there (ADR-0017); the snapshot below runs
1012    // the rest, and its pre-push is told which gates not to repeat. Never from
1013    // land's pre-stage (f35): its push follows at once and judges the evidence
1014    // then, and a Workflow's pass only counts once a later hook collects it.
1015    // So the pre-stage neither submits nor rides a Workflow already running:
1016    // its snapshot runs every gate, a cluster gate on the Job lane (ADR-0016),
1017    // which waits for the pass.
1018    let on_cluster = match Origin::of(prestage) {
1019        Origin::Prestage => Vec::new(),
1020        Origin::Push => planned.detach(ask),
1021    };
1022    let Plan {
1023        push_ref,
1024        manifest,
1025        settings,
1026        gates,
1027        tree_todo,
1028        ..
1029    } = planned;
1030    let local_work = gates
1031        .iter()
1032        .any(|gate| !on_cluster.contains(gate) && !vouched_by(&settings, &manifest, &head, gate));
1033    if !local_work && tree_todo.is_empty() {
1034        eprintln!(
1035            "{} every gate left to rehearse went to the cluster ({}) — the next commit or push collects the result",
1036            valid_sign(),
1037            highlight(&on_cluster.join(" "))
1038        );
1039        return Ok(Outcome::Detached);
1040    }
1041    let snapshot = crate::pushed_tree::PushedTree::checkout(repo, &head)
1042        .ok_or("could not check out HEAD into a snapshot worktree")?;
1043    // Registered BEFORE preparing: an install can take minutes, and in that
1044    // time `--status`, a push looking for this tree, and a newer commit that
1045    // must cancel it all need to know it exists.
1046    let mut me = State {
1047        pid: std::process::id(),
1048        commit: head.clone(),
1049        tree,
1050        started: now(),
1051        snapshot: snapshot.path().to_path_buf(),
1052        phase: Phase::Running,
1053        step: Some("preparing (may queue for a host slot)".to_string()),
1054        reason: None,
1055        prestage: prestage.is_some(),
1056        signal: None,
1057    };
1058    // Checking out took time: a worker that registered since is not
1059    // overwritten when land is on either side (ADR-0018).
1060    if let Some(other) = read().filter(|s| s.alive() && s.pid != me.pid) {
1061        if prestage.is_some() || other.prestage {
1062            drop(snapshot);
1063            return Err(format!(
1064                "the rehearsal of {} (pid {}) started meanwhile; try again",
1065                other.short(),
1066                other.pid
1067            ));
1068        }
1069        cancel(&other, repo);
1070    }
1071    write(&me);
1072    // The install takes one heavy host slot (t30, ADR-0014), here and not in
1073    // `PushedTree::prepare`: its other caller runs under a check's own guard,
1074    // and a second one would clear that check's lease. The guard lives for
1075    // the prepare alone, so the slot is back before tree lint and the gates,
1076    // which queue for their own.
1077    let (prepared, queued, busy) = {
1078        let guard =
1079            crate::host_slots::enter_check("snapshot-prepare", crate::host_slots::Weight::Heavy);
1080        let place = if prestage.is_some() {
1081            greenharness_slots::WaitPlace::Prestage
1082        } else {
1083            greenharness_slots::WaitPlace::Rehearsal
1084        };
1085        crate::host_slots::rehearsal_place(place);
1086        let prepared = snapshot.prepare(&settings);
1087        (prepared, guard.queued(), guard.deferred_end())
1088    };
1089    // Said whenever the prepare ran after its wait, failed or not; a wait
1090    // that ended in line never ran it.
1091    if busy.is_none() && queued >= Duration::from_secs(1) {
1092        eprintln!(
1093            "waited {} for a host slot before preparing the snapshot",
1094            human_secs(queued.as_secs())
1095        );
1096    }
1097    if let Err(why) = prepared {
1098        let why = prepare_failure(busy, why);
1099        write(&State {
1100            phase: Phase::Failed,
1101            step: None,
1102            reason: Some(format!("could not prepare the snapshot: {why}")),
1103            ..me
1104        });
1105        drop(snapshot);
1106        return Err(format!("could not prepare the snapshot: {why}"));
1107    }
1108    if !tree_todo.is_empty() {
1109        me.step = Some("tree lint".to_string());
1110        write(&me);
1111        crate::tree_lint::rehearse(&settings, snapshot.path(), &me.tree, &tree_todo);
1112    }
1113    if gates.is_empty() {
1114        // Lint was all there was: the push gate has nothing to run here.
1115        write(&State {
1116            phase: Phase::Passed,
1117            step: None,
1118            ..me
1119        });
1120        drop(snapshot);
1121        println!(
1122            "{} rehearsal of {short} done (tree lint only)",
1123            valid_sign()
1124        );
1125        return Ok(Outcome::Passed);
1126    }
1127    me.step = Some("testing".to_string());
1128    write(&me);
1129    println!(
1130        "rehearsing {} for {} in {}",
1131        highlight(&gates.join(" ")),
1132        short,
1133        snapshot.path().display()
1134    );
1135    let hooks_dir = crate::git::stdout(&["rev-parse", "--git-path", "hooks"])
1136        .map(PathBuf::from)
1137        .map(|p| if p.is_absolute() { p } else { repo.join(p) })
1138        .ok_or("could not locate the hooks directory")?;
1139    let exe = std::env::current_exe().map_err(|e| format!("cannot locate {BIN}: {e}"))?;
1140    let mut cmd = Command::new(exe);
1141    cmd.arg("--hooks-dir")
1142        .arg(&hooks_dir)
1143        .arg("pre-push")
1144        .current_dir(snapshot.path())
1145        .env(ENV, snapshot_env_value(&on_cluster, Origin::of(prestage)))
1146        // A rehearsal is how a gate runs with no push waiting on it, so it
1147        // waits for a slot rather than defer: a rehearsal whose gates all
1148        // deferred would report "passed" having run nothing (ADR-0013).
1149        .env(crate::host_slots::ON_BUSY_ENV, "wait")
1150        // where the source's installed environment lives (a virtualenv the
1151        // Python audit reads; ADR-0018)
1152        .env(crate::pushed_tree::SOURCE_WORKTREE_ENV, repo)
1153        .stdin(Stdio::piped());
1154    strip_repo_env(&mut cmd);
1155    let line = format!(
1156        "{} {} {} {}\n",
1157        push_ref.local_ref, push_ref.local_oid, push_ref.remote_ref, push_ref.remote_oid
1158    );
1159    let status = (|| -> std::io::Result<std::process::ExitStatus> {
1160        let mut child = cmd.spawn()?;
1161        if let Some(mut stdin) = child.stdin.take() {
1162            stdin.write_all(line.as_bytes())?;
1163        }
1164        child.wait()
1165    })()
1166    .map_err(|e| format!("could not run the push gate in the snapshot: {e}"))?;
1167    let passed = status.success();
1168    let done = State {
1169        phase: if passed { Phase::Passed } else { Phase::Failed },
1170        step: None,
1171        reason: signal_of(&status).map(|n| format!("the push gate was stopped by signal {n}")),
1172        signal: signal_of(&status),
1173        ..me
1174    };
1175    write(&done);
1176    drop(snapshot);
1177    if let Some(n) = signal_of(&status) {
1178        eprintln!(
1179            "{} rehearsal of {short} stopped by signal {n}",
1180            warning_sign()
1181        );
1182        return Ok(Outcome::Interrupted(n));
1183    }
1184    if passed {
1185        println!("{} rehearsal of {short} passed", valid_sign());
1186        Ok(Outcome::Passed)
1187    } else {
1188        println!("{} rehearsal of {short} FAILED", warning_sign());
1189        Ok(Outcome::Failed)
1190    }
1191}
1192
1193/// Where the live pre-push meets the background: if a worker is on the tree
1194/// of one of these tips right now, wait for it. Returns the phase it ended
1195/// in, or `None` when there was nothing to wait for — in which case the
1196/// caller runs the gate as usual.
1197///
1198/// A rehearsal that already FAILED is reported, not honoured: the gate runs
1199/// again here, which is what shows the developer the failure in the
1200/// terminal they are looking at.
1201pub fn await_for(settings: &crate::config::Settings, tips: &[String]) -> Option<Phase> {
1202    if in_snapshot() {
1203        return None;
1204    }
1205    let state = read()?;
1206    let on_a_tip = tips.iter().any(|t| {
1207        let spec = format!("{t}^{{tree}}");
1208        crate::git::stdout(&["rev-parse", &spec]).as_deref() == Some(state.tree.as_str())
1209    });
1210    if !on_a_tip {
1211        return None;
1212    }
1213    let log = log_path()
1214        .map(|p| format!(" (log: {})", p.display()))
1215        .unwrap_or_default();
1216    // what happens next is the push's call, and under `refuse` it is not a
1217    // run here — say so rather than promise one
1218    let then = if refuse_unstamped(settings) {
1219        format!("fix it and rehearse again (`{BIN} rehearse --wait`)")
1220    } else {
1221        "running the gate here".to_string()
1222    };
1223    match state.phase {
1224        Phase::Passed => None, // the stamps say it all
1225        Phase::Failed => {
1226            crate::say!(
1227                "{} the background rehearsal of this tree failed {} ago{}{log} — {then}",
1228                warning_sign(),
1229                human_secs(state.age_secs()),
1230                state
1231                    .reason
1232                    .as_deref()
1233                    .map(|r| format!(" ({r})"))
1234                    .unwrap_or_default(),
1235            );
1236            None
1237        }
1238        Phase::Running if !process_alive(state.pid) => {
1239            crate::say!(
1240                "{} a background rehearsal of this tree died without a verdict{log} — {then}",
1241                warning_sign(),
1242            );
1243            None
1244        }
1245        Phase::Running => {
1246            let budget = wait_budget(settings);
1247            crate::say!(
1248                "{} a background rehearsal of this tree started {} ago is still running — \
1249                 waiting{} for it rather than starting the suite over{log}",
1250                warning_sign(),
1251                human_secs(state.age_secs()),
1252                match budget {
1253                    Some(b) => format!(" up to {}", human_secs(b.as_secs())),
1254                    None => String::new(),
1255                },
1256            );
1257            let followed = follow(&state, budget).map(|(phase, _)| phase);
1258            if followed.is_none() && still_running(&state) {
1259                // Left RUNNING on purpose: it may still finish and stamp the
1260                // tree for the next push. We simply stop holding an open
1261                // connection open for it.
1262                warn(&format!(
1263                    "the rehearsal is still running after {} — running the gate here \
1264                     rather than holding the push open (`git config \
1265                     greengate.rehearsalWait <secs>`, or 0 to wait indefinitely)",
1266                    human_secs(state.age_secs())
1267                ));
1268            }
1269            followed
1270        }
1271    }
1272}
1273
1274/// Poll a running rehearsal to its end. `None` when it vanished — a new
1275/// worker took over for a different tree, the process died, or `budget`
1276/// expired.
1277///
1278/// `budget` is `None` for a caller with nothing on the wire; see
1279/// [`WAIT_BUDGET`] for why the push path always passes one.
1280fn follow(state: &State, budget: Option<Duration>) -> Option<(Phase, State)> {
1281    let mut last_word = std::time::Instant::now();
1282    let deadline = budget.map(|b| std::time::Instant::now() + b);
1283    loop {
1284        std::thread::sleep(Duration::from_secs(1));
1285        let now_state = read()?;
1286        if now_state.tree != state.tree || now_state.started != state.started {
1287            return None;
1288        }
1289        match now_state.phase {
1290            Phase::Running => {
1291                if !process_alive(now_state.pid) {
1292                    warn("the rehearsal died without a verdict");
1293                    return None;
1294                }
1295                if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
1296                    // The caller says what stopping the wait means for it.
1297                    return None;
1298                }
1299                if last_word.elapsed() >= Duration::from_secs(60) {
1300                    eprintln!(
1301                        "  still rehearsing ({} so far)",
1302                        human_secs(now_state.age_secs())
1303                    );
1304                    last_word = std::time::Instant::now();
1305                }
1306            }
1307            phase => {
1308                let verb = if phase == Phase::Passed {
1309                    format!("{} rehearsal passed", valid_sign())
1310                } else {
1311                    format!(
1312                        "{} rehearsal failed{}",
1313                        warning_sign(),
1314                        now_state
1315                            .reason
1316                            .as_deref()
1317                            .map(|r| format!(" ({r})"))
1318                            .unwrap_or_default()
1319                    )
1320                };
1321                crate::say!("{verb} after {}", human_secs(now_state.age_secs()));
1322                return Some((phase, now_state));
1323            }
1324        }
1325    }
1326}
1327
1328/// `amont rehearse [--wait|--status|--stop|--worker] [--cluster]`.
1329pub fn command(args: &[OsString], prestage: &Prestage) -> i32 {
1330    let flag = |f: &str| args.iter().any(|a| a == f);
1331    let ask = if flag("--cluster") {
1332        crate::cluster::Ask::Flag
1333    } else {
1334        crate::cluster::Ask::Setting
1335    };
1336    let prestage = match prestage {
1337        Prestage::Malformed(raw) => {
1338            eprintln!("{BIN}: {PRESTAGE_ENV} is not a push line ({raw:?}); nothing was rehearsed");
1339            return 2;
1340        }
1341        line => line.line(),
1342    };
1343    if flag("--worker") {
1344        return match worker(ask, prestage) {
1345            Ok(Outcome::Failed) => 1,
1346            Ok(Outcome::Interrupted(n)) => 128 + n,
1347            Ok(_) => 0,
1348            Err(e) => {
1349                eprintln!("{BIN}: {e}");
1350                2
1351            }
1352        };
1353    }
1354    let root = match crate::hooks::common::repo_root_checked() {
1355        Ok(r) => r,
1356        Err(e) => {
1357            eprintln!("{BIN}: {e}");
1358            return 2;
1359        }
1360    };
1361    if flag("--status") {
1362        return status();
1363    }
1364    if flag("--stop") {
1365        // The Workflows go first: they are what outlives this process.
1366        let terminated = crate::cluster::stop_pending();
1367        for line in terminated.done.iter().chain(&terminated.failed) {
1368            eprintln!("{line}");
1369        }
1370        match read() {
1371            Some(s) if s.alive() => {
1372                cancel(&s, Path::new(&root));
1373                clear();
1374                println!("stopped the rehearsal of {} (pid {})", s.short(), s.pid);
1375            }
1376            _ if terminated.done.is_empty() && terminated.failed.is_empty() => {
1377                println!("no rehearsal is running in this worktree");
1378            }
1379            _ => {}
1380        }
1381        // A Workflow that is still running after `--stop` is a failure of it.
1382        return i32::from(!terminated.failed.is_empty());
1383    }
1384    if flag("--cluster") && !flag("--wait") {
1385        // Submit in the foreground — one line per Workflow, back in seconds —
1386        // then let a worker run what is left here.
1387        match plan(prestage) {
1388            Ok(planned) => {
1389                let on_cluster = planned.detach(crate::cluster::Ask::Flag);
1390                let left = planned
1391                    .gates
1392                    .iter()
1393                    .any(|gate| !on_cluster.contains(gate) && !planned.vouched(gate));
1394                if !left && planned.tree_todo.is_empty() && !on_cluster.is_empty() {
1395                    return 0;
1396                }
1397            }
1398            Err(e) => {
1399                // It ran and failed (no upstream, no HEAD): not a usage error.
1400                eprintln!("{BIN}: {e}");
1401                return 1;
1402            }
1403        }
1404    }
1405    let head = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
1406    let running_here = read().filter(|s| s.alive() && Some(s.tree.as_str()) == head.as_deref());
1407    if flag("--wait") {
1408        // A LOOP, not recursion. `worker()` answering `AlreadyRunning` means
1409        // somebody else claimed the tree between our own look and its own,
1410        // and the answer is to follow theirs — but re-entering `command`
1411        // from inside itself made that a stack frame per lost race with no
1412        // ceiling on it. Two passes is all the race can honestly need: one
1413        // to lose it, one to find the worker that won. A third would mean
1414        // the state file is churning, and running the gate ourselves is a
1415        // better answer than spinning on it.
1416        //
1417        // No budget here: nothing is connected, and somebody typed this
1418        // command to be told when the suite ends. See `WAIT_BUDGET`.
1419        // The tree to follow is the one being rehearsed: HEAD's, or the
1420        // commit land's pre-stage names (a tag's may be older than HEAD).
1421        let target = match prestage {
1422            Some(line) => format!("{}^{{tree}}", line.local_oid),
1423            None => "HEAD^{tree}".to_string(),
1424        };
1425        for _ in 0..3 {
1426            let running = read().filter(|s| {
1427                s.alive()
1428                    && Some(s.tree.as_str())
1429                        == crate::git::stdout(&["rev-parse", &target]).as_deref()
1430            });
1431            let Some(state) = running else {
1432                // Nothing running: do it here, in the foreground, and say so.
1433                match worker(ask, prestage) {
1434                    Ok(Outcome::Failed) => return 1,
1435                    Ok(Outcome::Interrupted(n)) => return 128 + n,
1436                    Ok(Outcome::AlreadyRunning(_)) => continue,
1437                    Ok(_) => return 0,
1438                    Err(e) => {
1439                        eprintln!("{BIN}: {e}");
1440                        return 2;
1441                    }
1442                }
1443            };
1444            eprintln!(
1445                "following the rehearsal of {} (pid {}, started {} ago)",
1446                state.short(),
1447                state.pid,
1448                human_secs(state.age_secs())
1449            );
1450            match follow(&state, None) {
1451                // Its stamps say what IT selected. Plan again: another base
1452                // can owe another set, and the worker answers at once when
1453                // the followed run covered everything (ADR-0018).
1454                Some((Phase::Passed, _)) => continue,
1455                // Stopped by a signal: no verdict, so not a failure either.
1456                Some((
1457                    _,
1458                    State {
1459                        signal: Some(n), ..
1460                    },
1461                )) => return 128 + n,
1462                Some(_) => {
1463                    show_log_tail();
1464                    return 1;
1465                }
1466                None => {
1467                    eprintln!("{BIN}: the rehearsal ended without a verdict");
1468                    return 2;
1469                }
1470            }
1471        }
1472        eprintln!("{BIN}: another rehearsal keeps claiming this tree — run the gate yourself");
1473        return 2;
1474    }
1475    if let Some(state) = running_here {
1476        println!(
1477            "a rehearsal of this tree is already running (pid {}, started {} ago) — \
1478             `{BIN} rehearse --wait` follows it",
1479            state.pid,
1480            human_secs(state.age_secs())
1481        );
1482        return 0;
1483    }
1484    match spawn_detached() {
1485        Ok(pid) => {
1486            println!(
1487                "rehearsing the push gate for HEAD in the background (pid {pid}) — \
1488                 `{BIN} rehearse --wait` follows it, `--status` reports{}",
1489                log_path()
1490                    .map(|p| format!("; log: {}", p.display()))
1491                    .unwrap_or_default()
1492            );
1493            0
1494        }
1495        Err(e) => {
1496            eprintln!("{BIN}: {e}");
1497            2
1498        }
1499    }
1500}
1501
1502fn status() -> i32 {
1503    // What the cluster finished since the last hook is collected first, so the
1504    // lines below are today's. Asked for, so stdout: this is the answer.
1505    let collected = crate::cluster::collect();
1506    let mut detached = crate::cluster::settled_lines(&collected.settled);
1507    detached.extend(crate::cluster::status_lines());
1508    for line in &detached {
1509        println!("{line}");
1510    }
1511    if let Some(trouble) = &collected.trouble {
1512        eprintln!("cluster runs not refreshed — {trouble}");
1513    }
1514    let Some(state) = read() else {
1515        if detached.is_empty() {
1516            println!("no rehearsal recorded in this worktree");
1517        }
1518        return 0;
1519    };
1520    let head = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
1521    let which = if head.as_deref() == Some(state.tree.as_str()) {
1522        "HEAD's tree".to_string()
1523    } else {
1524        format!("{} (not HEAD's tree)", state.short())
1525    };
1526    let age = human_secs(state.age_secs());
1527    let line = match state.phase {
1528        Phase::Running if state.alive() => {
1529            format!(
1530                "rehearsal of {which}: running for {age} (pid {}{})",
1531                state.pid,
1532                state
1533                    .step
1534                    .as_deref()
1535                    .map(|s| format!(", {s}"))
1536                    .unwrap_or_default()
1537            )
1538        }
1539        Phase::Running => {
1540            format!("rehearsal of {which}: died without a verdict, started {age} ago")
1541        }
1542        Phase::Passed => format!("rehearsal of {which}: passed, started {age} ago"),
1543        Phase::Failed => format!(
1544            "rehearsal of {which}: FAILED, started {age} ago{}",
1545            state
1546                .reason
1547                .as_deref()
1548                .map(|r| format!(" — {r}"))
1549                .unwrap_or_default()
1550        ),
1551    };
1552    println!("{line}");
1553    if let Some(log) = log_path().filter(|p| p.exists()) {
1554        println!("log: {}", log.display());
1555    }
1556    0
1557}
1558
1559/// The last lines of the detached log — the failure a `--wait` just
1560/// reported happened in another process, and this is where it went.
1561fn show_log_tail() {
1562    let Some(log) = log_path() else { return };
1563    let Ok(body) = std::fs::read_to_string(&log) else {
1564        return;
1565    };
1566    let lines: Vec<&str> = body.lines().collect();
1567    let start = lines.len().saturating_sub(40);
1568    eprintln!(
1569        "--- {} (last {} lines) ---",
1570        log.display(),
1571        lines.len() - start
1572    );
1573    for l in &lines[start..] {
1574        eprintln!("{l}");
1575    }
1576}
1577
1578#[cfg(test)]
1579mod tests {
1580    use super::prepare_failure;
1581    use greenharness_slots::WaitEnd;
1582
1583    /// A busy host is named only for a ceiling; a failed queue keeps its own
1584    /// cause; a prepare that did not defer keeps the install's error. None
1585    /// carries the hook path's "deferred to CI".
1586    #[test]
1587    fn a_failed_prepare_names_its_cause() {
1588        let ceiling = prepare_failure(
1589            Some((
1590                WaitEnd::Ceiling,
1591                "no host slot within 2s (greengate.timeout)".to_string(),
1592            )),
1593            "npm ci failed in root".to_string(),
1594        );
1595        assert!(
1596            ceiling.starts_with("the host stayed busy: no host slot within 2s"),
1597            "{ceiling}"
1598        );
1599        assert!(ceiling.contains("raise greengate.timeout"), "{ceiling}");
1600        let failed = prepare_failure(
1601            Some((
1602                WaitEnd::IoError,
1603                "the host slot files failed: busy disk".to_string(),
1604            )),
1605            "npm ci failed in root".to_string(),
1606        );
1607        assert_eq!(failed, "the host slot files failed: busy disk");
1608        let broke = prepare_failure(None, "npm ci failed in root".to_string());
1609        assert_eq!(broke, "npm ci failed in root");
1610        for text in [ceiling, failed, broke] {
1611            assert!(!text.contains("deferred to CI"), "{text}");
1612        }
1613    }
1614
1615    use super::*;
1616
1617    fn sample() -> State {
1618        State {
1619            pid: 4242,
1620            commit: "a".repeat(40),
1621            tree: "b".repeat(40),
1622            started: 1_700_000_000,
1623            snapshot: PathBuf::from("/tmp/greengate-push-1-2"),
1624            phase: Phase::Running,
1625            step: Some("preparing".to_string()),
1626            reason: None,
1627            prestage: false,
1628            signal: None,
1629        }
1630    }
1631
1632    #[test]
1633    fn the_prestage_marker_leaves_the_detached_gates_intact() {
1634        let marked = parse_snapshot_env("prestage;detached=a,b");
1635        assert!(marked.prestage);
1636        assert_eq!(marked.detached, ["a", "b"]);
1637        let plain = parse_snapshot_env("detached=a,b");
1638        assert!(!plain.prestage);
1639        assert_eq!(plain.detached, ["a", "b"]);
1640        let bare = parse_snapshot_env("1");
1641        assert!(!bare.prestage);
1642        assert!(bare.detached.is_empty());
1643        let marked_bare = parse_snapshot_env("prestage;1");
1644        assert!(marked_bare.prestage);
1645        assert!(marked_bare.detached.is_empty());
1646    }
1647
1648    /// A pre-stage is recorded as one, so a rehearsal that meets it waits
1649    /// instead of cancelling it (ADR-0018); an older file reads as not one.
1650    #[test]
1651    fn a_prestage_survives_the_state_file() {
1652        let staged = State {
1653            prestage: true,
1654            signal: Some(9),
1655            ..sample()
1656        };
1657        assert_eq!(State::parse(&staged.render()), Some(staged));
1658        assert_eq!(State::parse(&sample().render()), Some(sample()));
1659    }
1660
1661    /// The land variables are parsed where they are read: a malformed value
1662    /// is never mistaken for a remote that moved, or for a plain rehearsal.
1663    #[test]
1664    fn the_land_variables_take_object_names_only() {
1665        let (a, b) = ("a".repeat(40), "0".repeat(40));
1666        assert_eq!(
1667            LandEnv::parse(&format!("{a} {b}")),
1668            LandEnv::Valid(LandLine {
1669                sha: a.clone(),
1670                remote_tip: b.clone()
1671            })
1672        );
1673        for bad in [
1674            "",
1675            "abc",
1676            a.as_str(),
1677            &format!("{a} {b} extra"),
1678            &format!("{a} xyz"),
1679        ] {
1680            assert!(
1681                matches!(LandEnv::parse(bad), LandEnv::Malformed(_)),
1682                "{bad:?}"
1683            );
1684        }
1685        assert!(matches!(
1686            Prestage::parse(&format!("refs/heads/x {a} refs/heads/x {b}")),
1687            Prestage::Of(_)
1688        ));
1689        for bad in [
1690            format!("refs/heads/x {a} refs/heads/x"),
1691            "x y z w".to_string(),
1692        ] {
1693            assert!(
1694                matches!(Prestage::parse(&bad), Prestage::Malformed(_)),
1695                "{bad:?}"
1696            );
1697        }
1698    }
1699
1700    #[test]
1701    fn a_state_survives_the_round_trip() {
1702        let s = sample();
1703        assert_eq!(State::parse(&s.render()), Some(s));
1704        let done = State {
1705            phase: Phase::Failed,
1706            step: None,
1707            reason: Some("could not prepare the snapshot: npm ci failed\nin web/".to_string()),
1708            ..sample()
1709        };
1710        let back = State::parse(&done.render()).expect("parses");
1711        assert_eq!(
1712            back.reason.as_deref(),
1713            Some("could not prepare the snapshot: npm ci failed in web/"),
1714            "a reason is kept on one line"
1715        );
1716        assert_eq!(back.phase, Phase::Failed);
1717    }
1718
1719    /// The failure direction: anything this version did not write reads as
1720    /// "no rehearsal", which runs the gate.
1721    #[test]
1722    fn a_foreign_or_partial_file_is_no_rehearsal() {
1723        assert_eq!(State::parse(""), None);
1724        assert_eq!(State::parse("greengate-rehearsal-v2\npid=1\n"), None);
1725        assert_eq!(State::parse("greengate-rehearsal-v1\npid=1\n"), None);
1726        assert_eq!(
1727            State::parse("greengate-rehearsal-v1\npid=x\ncommit=a\ntree=b\nstarted=1\nsnapshot=/s\nphase=running\n"),
1728            None
1729        );
1730    }
1731
1732    /// A pid this box never had is not alive — and a record naming it is a
1733    /// dead worker, not a running one.
1734    #[test]
1735    fn a_dead_pid_is_not_alive() {
1736        let s = State {
1737            pid: u32::MAX - 7,
1738            ..sample()
1739        };
1740        assert!(!s.alive());
1741        let done = State {
1742            phase: Phase::Passed,
1743            pid: std::process::id(),
1744            ..sample()
1745        };
1746        assert!(
1747            !done.alive(),
1748            "a finished rehearsal is not running whoever's pid it names"
1749        );
1750    }
1751}