Skip to main content

runner_manager_agent/
lifecycle.rs

1// owner: e3-jit-lifecycle-recovery
2
3//! One ephemeral runner, from an allocation decision to a scrubbed runtime.
4//!
5//! The ordering in this module is intentional.  An attempt is written before
6//! the package or GitHub is touched, the JIT value exists only in a restrictive
7//! handoff, and a registration-timeout termination is journalled before the
8//! process is signalled.  Recovery uses the same code as ordinary supervision;
9//! startup merely supplies the first observation.
10
11#[cfg(test)]
12use std::collections::VecDeque;
13use std::collections::{BTreeMap, BTreeSet};
14use std::ffi::OsStr;
15use std::fmt;
16use std::fs;
17use std::io::Write;
18use std::num::NonZeroU16;
19use std::path::{Path, PathBuf};
20use std::sync::{Arc, Mutex};
21use std::time::Duration;
22
23use async_trait::async_trait;
24use runner_manager_domain::attempt::{
25    AttemptOutcome, AttemptState, FailureReason, GithubRunnerObservation, RecoveryDecision,
26    RecoveryObservation, RecoveryTimeouts, RunnerAttempt, authorize, recovery_decision,
27};
28use runner_manager_domain::model::{AttemptId, Clock, HostId, PolicyId, ScaleTarget};
29use runner_manager_domain::path::LocalAbsolutePath;
30use runner_manager_domain::policy::ScalePolicy;
31use runner_manager_domain::store::{Store, StoreError};
32use runner_manager_domain::workspace::{AttemptWorkspace, WorkspacePolicy};
33use runner_manager_github::jit::{
34    DEFAULT_WORK_FOLDER, EncodedJitConfig, JitError, JitGateway, JitRegistration, JitRunnerRequest,
35};
36use runner_manager_github::rest::{CancelToken, InventoryGateway};
37use runner_manager_platform::process::{
38    Adoption, ChildProcess, ProcessIdentity, RestrictiveHandoff, SpawnSpec, Termination,
39};
40use runner_manager_platform::runner_root::{
41    self, RootOwner, RootPreflight, RunnerRootError, default_runner_root,
42};
43use secrecy::SecretString;
44
45use crate::package::{PackageCache, PackageError, RunnerVersion};
46use crate::reconcile::{
47    AllocationGuard, EventSink, LaunchFailure, LaunchRequest, LifecycleEvent, OutcomeKind,
48    ReplacementIntent, RunnerLauncher,
49};
50
51const IDENTITY_FILE: &str = ".runner-process.json";
52const FALLBACK_IDENTITY_FILE: &str = ".runner-process.recovery.json";
53const UNRESOLVED_PROCESS_FILE: &str = ".runner-process.unresolved";
54const RUNNER_ID_FILE: &str = ".github-runner-id";
55const TERMINATE_INTENT_FILE: &str = ".terminate-registration-timeout";
56const MAX_POST_SPAWN_STOP_ATTEMPTS: usize = 3;
57
58/// Slot-root names a cleaned persistent attempt must not have left behind.
59///
60/// This is not the rule — the rule is that *nothing* but a real `_work`
61/// survives, and [`verify_slot_scrubbed`] enforces that by counting. This list
62/// is the second, independent question asked of the same directory: each name
63/// is stat-ed directly, so a scrub that skipped one is caught even if the
64/// enumeration that was supposed to find it under-reported. Every entry is one
65/// of the things `04-security-recovery.md` requires to be proven absent before a
66/// slot is released; the encoded JIT handoff is the one exception, matched by
67/// its published prefix in [`verify_slot_scrubbed`] because the rest of its name
68/// is a UUID. Being compile-time constants, these are also the only entry names
69/// a refusal message is allowed to print.
70const SENSITIVE_SLOT_ENTRIES: &[&str] = &[
71    // Runner binaries and the launchers beside them.
72    "bin",
73    "externals",
74    "run.sh",
75    "run.cmd",
76    "config.sh",
77    "config.cmd",
78    // The registration identity GitHub's runner writes for itself, and the
79    // per-run environment it reads back.
80    ".runner",
81    ".credentials",
82    ".credentials_rsaparams",
83    ".env",
84    ".path",
85    "_diag",
86    // This agent's own process-identity and lifecycle sidecars.
87    IDENTITY_FILE,
88    FALLBACK_IDENTITY_FILE,
89    UNRESOLVED_PROCESS_FILE,
90    RUNNER_ID_FILE,
91    TERMINATE_INTENT_FILE,
92];
93#[cfg(test)]
94const TEST_LISTENER_READY: &str = ".test-listener-ready";
95
96/// GitHub Runner v2.336.0 accepts JIT configuration for `run` through its
97/// secret `ACTIONS_RUNNER_INPUT_JITCONFIG` input. The platform spawn boundary
98/// supplies that input from the restrictive handoff; the listener command line
99/// must contain only the supported `run` command.
100fn runner_listener_spec(program: PathBuf, runtime: &Path) -> SpawnSpec {
101    let tmp = runtime.join("tmp");
102    let _ = std::fs::create_dir_all(&tmp);
103    SpawnSpec::new(program)
104        .arg("run")
105        .working_dir(runtime)
106        .env("TMPDIR", &tmp)
107        .env("TEMP", &tmp)
108        .env("TMP", &tmp)
109}
110
111/// Retry bounds for failures that can resolve without operator action.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub struct RetryPolicy {
114    pub max_attempts: u32,
115    pub initial: Duration,
116    pub maximum: Duration,
117}
118
119impl RetryPolicy {
120    #[must_use]
121    pub const fn bounded(max_attempts: u32, initial: Duration, maximum: Duration) -> Self {
122        Self {
123            max_attempts,
124            initial,
125            maximum,
126        }
127    }
128
129    fn delay(self, failure_index: u32) -> Duration {
130        let shift = failure_index.saturating_sub(1).min(31);
131        self.initial
132            .saturating_mul(1_u32 << shift)
133            .min(self.maximum)
134    }
135}
136
137/// Non-secret lifecycle evidence.  Payloads are identifiers and closed enums;
138/// neither the encoded configuration nor child output can enter this type.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub enum AttemptEvent {
141    State {
142        attempt: AttemptId,
143        state: AttemptState,
144    },
145    Retry {
146        attempt: AttemptId,
147        operation: &'static str,
148        delay: Duration,
149    },
150    Adopted {
151        attempt: AttemptId,
152    },
153    RemoteIdentityRecovered {
154        attempt: AttemptId,
155        runner_id: u64,
156    },
157    TerminateIntent {
158        attempt: AttemptId,
159    },
160    Terminated {
161        attempt: AttemptId,
162    },
163    /// The attempt's GitHub registration was removed by this agent. Carries the
164    /// runner id because that is the identifier an operator sees in the
165    /// target's runner settings, and the attempt id is not shown there.
166    Deregistered {
167        attempt: AttemptId,
168        runner_id: u64,
169    },
170    Concluded {
171        attempt: AttemptId,
172        outcome: OutcomeKind,
173    },
174    Cleaned {
175        attempt: AttemptId,
176        outcome: OutcomeKind,
177    },
178}
179
180pub trait AttemptEventSink: fmt::Debug + Send + Sync {
181    fn emit(&self, event: AttemptEvent);
182}
183
184#[derive(Debug, Default)]
185pub struct AttemptEventLog(Mutex<Vec<AttemptEvent>>);
186
187impl AttemptEventLog {
188    #[must_use]
189    pub fn events(&self) -> Vec<AttemptEvent> {
190        self.0
191            .lock()
192            .map(|events| events.clone())
193            .unwrap_or_default()
194    }
195}
196
197impl AttemptEventSink for AttemptEventLog {
198    fn emit(&self, event: AttemptEvent) {
199        if let Ok(mut events) = self.0.lock() {
200            events.push(event);
201        }
202    }
203}
204
205#[derive(Debug, Clone, Copy, Default)]
206pub struct NoAttemptEvents;
207
208impl AttemptEventSink for NoAttemptEvents {
209    fn emit(&self, _event: AttemptEvent) {}
210}
211
212/// Whether the demand that justified a retry still exists.
213#[async_trait]
214pub trait DemandPersistence: fmt::Debug + Send + Sync {
215    async fn persists(&self, policy: PolicyId) -> bool;
216}
217
218#[derive(Debug, Clone, Copy, Default)]
219pub struct PersistentDemand;
220
221#[async_trait]
222impl DemandPersistence for PersistentDemand {
223    async fn persists(&self, _policy: PolicyId) -> bool {
224        true
225    }
226}
227
228#[async_trait]
229pub trait RetryDelay: fmt::Debug + Send + Sync {
230    async fn wait(&self, duration: Duration);
231}
232
233#[derive(Debug, Clone, Copy, Default)]
234pub struct TokioRetryDelay;
235
236#[async_trait]
237impl RetryDelay for TokioRetryDelay {
238    async fn wait(&self, duration: Duration) {
239        tokio::time::sleep(duration).await;
240    }
241}
242
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct JitRequestFailure {
245    pub terminal: bool,
246    pub reason: FailureReason,
247    pub retry_after: Option<Duration>,
248}
249
250/// GitHub's authoritative runner state plus the identity returned by inventory.
251/// The id is carried independently of the local sidecar so recovery can close
252/// the crash boundary immediately after a successful remote registration.
253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254pub struct LifecycleGithubObservation {
255    pub status: GithubRunnerObservation,
256    pub runner_id: Option<u64>,
257}
258
259impl LifecycleGithubObservation {
260    #[must_use]
261    pub const fn unreachable() -> Self {
262        Self {
263            status: GithubRunnerObservation::Unreachable,
264            runner_id: None,
265        }
266    }
267
268    #[must_use]
269    pub const fn not_registered() -> Self {
270        Self {
271            status: GithubRunnerObservation::NotRegistered,
272            runner_id: None,
273        }
274    }
275
276    #[must_use]
277    pub const fn registered(runner_id: u64, busy: bool) -> Self {
278        Self {
279            status: GithubRunnerObservation::Registered { busy },
280            runner_id: Some(runner_id),
281        }
282    }
283}
284
285/// The two GitHub views the lifecycle needs, combined so one fake can drive
286/// registration and authoritative runner telemetry.
287#[async_trait]
288pub trait LifecycleGithub: fmt::Debug + Send + Sync {
289    async fn register(
290        &self,
291        target: &ScaleTarget,
292        request: &JitRunnerRequest,
293        cancel: &CancelToken,
294    ) -> Result<JitRegistration, JitRequestFailure>;
295
296    async fn observe(
297        &self,
298        target: &ScaleTarget,
299        attempt: AttemptId,
300        cancel: &CancelToken,
301    ) -> LifecycleGithubObservation;
302
303    /// Remove one runner registration this agent created.
304    ///
305    /// Answers whether the registration is gone, and is deliberately not
306    /// fallible in the `Result` sense: no caller may abandon a conclusion
307    /// because GitHub was unreachable. See
308    /// [`LifecycleLauncher::deregister_runner`].
309    async fn deregister(&self, target: &ScaleTarget, runner_id: u64, cancel: &CancelToken) -> bool;
310}
311
312#[async_trait]
313impl<T> LifecycleGithub for T
314where
315    T: JitGateway + InventoryGateway + fmt::Debug + Send + Sync,
316{
317    async fn register(
318        &self,
319        target: &ScaleTarget,
320        request: &JitRunnerRequest,
321        cancel: &CancelToken,
322    ) -> Result<JitRegistration, JitRequestFailure> {
323        self.generate_jit_config(target, request, cancel)
324            .await
325            .map_err(|error| {
326                let reason = if matches!(&error, JitError::Forbidden { .. }) {
327                    FailureReason::Other(
328                        "GitHub refused JIT registration with 403; check the App's runner permission and runner-group access"
329                            .into(),
330                    )
331                } else {
332                    FailureReason::JitRequestFailed
333                };
334                JitRequestFailure {
335                    terminal: error.is_terminal(),
336                    reason,
337                    retry_after: error
338                        .rate_limited()
339                        .map(|limit| limit.delay_from(self.now())),
340                }
341            })
342    }
343
344    async fn observe(
345        &self,
346        target: &ScaleTarget,
347        attempt: AttemptId,
348        cancel: &CancelToken,
349    ) -> LifecycleGithubObservation {
350        let expected_name = runner_name(attempt);
351        match self.list_runners(target, cancel).await {
352            Ok(inventory) => inventory
353                .runners()
354                .iter()
355                .find(|runner| runner.name == expected_name)
356                .map_or(LifecycleGithubObservation::not_registered(), |runner| {
357                    LifecycleGithubObservation::registered(runner.id, runner.busy)
358                }),
359            Err(_) => LifecycleGithubObservation::unreachable(),
360        }
361    }
362
363    async fn deregister(&self, target: &ScaleTarget, runner_id: u64, cancel: &CancelToken) -> bool {
364        self.remove_runner(target, runner_id, cancel).await.is_ok()
365    }
366}
367
368/// Package/cache operations used by one attempt.
369#[async_trait]
370pub trait RuntimePackages: fmt::Debug + Send + Sync {
371    async fn materialize(&self, attempt: &RunnerAttempt) -> Result<RunnerVersion, FailureReason>;
372    fn release(&self, attempt: AttemptId) -> Result<(), FailureReason>;
373    fn prune_obsolete_guarded(
374        &self,
375        authority: PruneAuthority<'_>,
376        current: &RunnerVersion,
377        attempts: &[RunnerAttempt],
378    ) -> Result<(), FailureReason>;
379}
380
381/// Unforgeable evidence that pruning was reached through e1's launch request.
382/// The type is public only because it appears in the public adapter trait; its
383/// private field and constructor prevent callers from substituting a guard
384/// acquired from an unrelated lock.
385pub struct PruneAuthority<'a> {
386    _guard: &'a AllocationGuard,
387}
388
389impl fmt::Debug for PruneAuthority<'_> {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        f.write_str("PruneAuthority")
392    }
393}
394
395impl<'a> PruneAuthority<'a> {
396    fn from_launch_request(guard: &'a AllocationGuard) -> Self {
397        Self { _guard: guard }
398    }
399}
400
401/// Production package adapter.  It takes an e2 lease before returning, so a
402/// cache entry can never look unused while its runtime is starting.
403#[derive(Debug)]
404pub struct CachedRuntimePackages {
405    cache: Arc<PackageCache>,
406}
407
408impl CachedRuntimePackages {
409    #[must_use]
410    pub fn new(cache: Arc<PackageCache>) -> Self {
411        Self { cache }
412    }
413}
414
415#[async_trait]
416impl RuntimePackages for CachedRuntimePackages {
417    async fn materialize(&self, attempt: &RunnerAttempt) -> Result<RunnerVersion, FailureReason> {
418        let installed = self
419            .cache
420            .ensure_installed()
421            .await
422            .map_err(package_failure)?;
423        copy_package_tree(installed.root(), attempt.runtime_path())
424            .map_err(|_| FailureReason::ProcessStartFailed)?;
425        if let Err(error) = self.cache.lease(attempt, installed.version()) {
426            // Undoing the copy must not undo the *job* workspace: a persistent
427            // slot's `_work` is retained across attempts, and this rollback
428            // runs before the attempt that would have owned it ever started.
429            let _ = remove_materialized_package(attempt);
430            return Err(package_failure(error));
431        }
432        Ok(installed.version().clone())
433    }
434
435    fn release(&self, attempt: AttemptId) -> Result<(), FailureReason> {
436        self.cache.release(attempt).map_err(package_failure)
437    }
438
439    fn prune_obsolete_guarded(
440        &self,
441        _authority: PruneAuthority<'_>,
442        current: &RunnerVersion,
443        attempts: &[RunnerAttempt],
444    ) -> Result<(), FailureReason> {
445        for installed in self.cache.installed().map_err(package_failure)? {
446            if installed.version() != current {
447                match self.cache.prune(installed.version(), attempts) {
448                    Ok(()) | Err(PackageError::VersionInUse { .. }) => {}
449                    Err(error) => return Err(package_failure(error)),
450                }
451            }
452        }
453        Ok(())
454    }
455}
456
457fn package_failure(error: PackageError) -> FailureReason {
458    error.failure_reason().unwrap_or(FailureReason::Other(
459        "runner package cache operation failed".into(),
460    ))
461}
462
463fn package_failure_is_terminal(reason: &FailureReason) -> bool {
464    matches!(
465        reason,
466        FailureReason::RunnerPackageUnverified | FailureReason::RunnerVersionRejected
467    )
468}
469
470/// How many hex characters of the attempt id name its workspace.
471///
472/// # Why this is not the whole identifier, and why the policy is not in the path
473///
474/// Windows refuses a path over `MAX_PATH`, and the runner writes deep inside
475/// this directory: `_work/<repo>/<repo>/.git/objects/pack/pack-<40 hex>.keep`
476/// is 100 characters on its own before the repository is named twice. The
477/// layout used to add two full identifiers -- the policy's and the attempt's,
478/// 74 characters between them -- and that was enough to put a real checkout
479/// over the line. Measured, not guessed: this repository's own CI failed here
480/// three times in a row at 264 characters against a limit of 260, with
481/// `fatal: cannot write keep file ...: Filename too long`. A repository whose
482/// name is ten characters longer would have missed by fourteen.
483///
484/// The policy identifier is simply redundant -- an attempt identifier is
485/// unique on its own, and nothing reads the directory tree to find a policy's
486/// attempts, because [`crate::lifecycle::LifecycleLauncher`] asks the journal.
487/// Twelve hex characters of the attempt is 48 bits, which for the handful of
488/// directories one host holds at once is not a collision anybody will see, and
489/// the journal keeps the full identifier either way.
490///
491/// Together that is 61 characters returned to the repository name.
492const WORKSPACE_NAME_LEN: usize = 12;
493
494/// The directory name for one attempt's workspace.
495fn workspace_name(id: AttemptId) -> String {
496    let full = id.to_string();
497    full.chars()
498        .filter(|c| *c != '-')
499        .take(WORKSPACE_NAME_LEN)
500        .collect()
501}
502
503/// Where one attempt's files go, and which cleanup algorithm they are owed.
504///
505/// The pair travels together because journalling them apart is exactly the bug
506/// `AttemptWorkspace` exists to prevent: a `runtime_path` under a persistent
507/// root recorded as ephemeral would be removed whole, taking the retained job
508/// workspace with it.
509#[derive(Debug, Clone)]
510struct Placement {
511    runtime: PathBuf,
512    workspace: AttemptWorkspace,
513}
514
515/// A runner-root refusal, rendered for the operator who has to fix it.
516///
517/// `RunnerRootError`'s `Display` already names the path, the relation and the
518/// remediation command, and none of its variants can carry a credential — they
519/// are paths, and `03-migration-rollout.md` requires the remediation command to
520/// reach the operator verbatim.
521fn root_failure(error: RunnerRootError) -> LifecycleError {
522    // Logged here because here is the last place this is known at all. A launch
523    // refused by the runner root fails *before* `record_allocation`, so no
524    // attempt row is ever written: `b2` has nothing to carry the failure on and
525    // `g2` has nothing to show it from. The lifecycle event keeps only
526    // `reason=other`, by `failure_reason_kind`'s rule that no free text may
527    // reach an event -- which left the whole refusal reading
528    // `runner_start_failed reason=other`, once per poll, naming nothing.
529    //
530    // What travels is the *kind* and not the sentence, and that is forced rather
531    // than chosen: `crate::logging` redacts every field it does not allow-list
532    // and then scrubs anything path-shaped out of the ones it does, so a
533    // rendered `RunnerRootError` -- which is mostly paths -- reaches the log as
534    // `[redacted]`. `error_kind` is allow-listed and `RunnerRootError::kind` is
535    // a closed vocabulary that survives the scrub, so this names which of a
536    // dozen causes the operator has. The paths and the remediation reach them
537    // through the command line, which is not redacted.
538    tracing::warn!(
539        error_kind = error.kind(),
540        "the runner root refused this launch, so no attempt was created; the host will \
541         retry every poll until the cause is resolved. Re-running `host set-runtime-root` \
542         with the same path re-runs this check and prints the directory and the \
543         remediation in full"
544    );
545    LifecycleError::Failed(FailureReason::Other(error.to_string()))
546}
547
548/// The lowest positive slot inside `ceiling` that no uncleaned attempt holds.
549///
550/// `leases` is the journal's answer to "which slots are leased"
551/// (`Store::slot_leases_for_policy`), which deliberately includes a terminal
552/// attempt whose cleanup has not finished: that attempt still owns its
553/// directory, so its slot is not free even though it no longer counts against
554/// host capacity. `None` means the ceiling is reached, which is a refusal and
555/// not a reason to allocate `s(ceiling + 1)`.
556fn lowest_free_slot(leases: &[RunnerAttempt], ceiling: NonZeroU16) -> Option<NonZeroU16> {
557    let held: BTreeSet<u16> = leases
558        .iter()
559        .filter_map(|attempt| attempt.workspace().slot_number())
560        .collect();
561    (1..=ceiling.get())
562        .find(|slot| !held.contains(slot))
563        .and_then(NonZeroU16::new)
564}
565
566/// Create `<root>/sN`, or prove that what is already there is a real directory.
567///
568/// A symlink, junction or reparse point standing where the slot should be is
569/// refused rather than followed: it is the one thing that could put an attempt's
570/// files outside the root the operator configured, and
571/// `04-security-recovery.md` requires that case to fail closed rather than to
572/// be repaired here.
573fn create_or_validate_slot(slot: &Path) -> Result<(), LifecycleError> {
574    match fs::symlink_metadata(slot) {
575        // [`is_link_like`] and not `is_symlink`, so that this is the same
576        // question cleanup asks in [`slot_is_present`]: a reparse tag the
577        // standard library has no name for is refused here rather than
578        // allocated into and then quarantined forever by a cleanup that will
579        // not scrub it.
580        Ok(metadata) if is_link_like(&metadata) => Err(slot_refusal(
581            slot,
582            "is a symbolic link, junction or other reparse point, which could place runner \
583             files outside the configured root",
584        )),
585        Ok(metadata) if !metadata.is_dir() => Err(slot_refusal(slot, "is not a directory")),
586        Ok(_) => Ok(()),
587        Err(error) if error.kind() == std::io::ErrorKind::NotFound => fs::create_dir(slot)
588            .map_err(|source| slot_refusal(slot, format!("could not be created: {source}"))),
589        Err(source) => Err(slot_refusal(
590            slot,
591            format!("could not be inspected: {source}"),
592        )),
593    }
594}
595
596/// Accept a slot for reuse only when it is empty or holds one real `_work`.
597///
598/// `02-target-architecture.md`: "Before materialization, a reusable slot must
599/// contain only a valid real `_work` directory or be empty." Everything else —
600/// a leftover `bin/`, a link-shaped `_work`, a stray file — is refused here
601/// rather than cleaned, because deciding whether those bytes are safe is
602/// cleanup's and recovery's job (`c3`), and quietly reusing them would hand one
603/// repository's retained state to the next attempt without anybody choosing to.
604///
605/// The inspection is one level deep and uses `symlink_metadata`, so nothing is
606/// followed while it is being judged.
607fn accept_reusable_slot(slot: &Path) -> Result<(), LifecycleError> {
608    let unreadable =
609        |source: std::io::Error| slot_refusal(slot, format!("could not be read: {source}"));
610    let entries = fs::read_dir(slot).map_err(unreadable)?;
611    let mut refused: Vec<String> = Vec::new();
612    for entry in entries {
613        let entry = entry.map_err(unreadable)?;
614        let name = entry.file_name();
615        let metadata = fs::symlink_metadata(entry.path()).map_err(|source| {
616            slot_refusal(
617                slot,
618                format!("entry {name:?} could not be inspected: {source}"),
619            )
620        })?;
621        // The same predicate cleanup retains by, so a `_work` this accepts is
622        // one [`scrub_slot_entries`] will keep rather than refuse: a link, a
623        // junction or any other reparse point is not a job workspace to either
624        // of them.
625        if is_retainable_work_folder(&name, &metadata) {
626            continue;
627        }
628        refused.push(name.to_string_lossy().into_owned());
629    }
630    if refused.is_empty() {
631        return Ok(());
632    }
633    refused.sort();
634    Err(slot_refusal(
635        slot,
636        format!(
637            "holds {} that this attempt may not reuse: [{}]. A reusable slot is empty or holds \
638             one real `{DEFAULT_WORK_FOLDER}` directory and nothing else; remove or move the \
639             entries listed, or let cleanup and recovery resolve them",
640            if refused.len() == 1 {
641                "an entry"
642            } else {
643                "entries"
644            },
645            refused.join(", ")
646        ),
647    ))
648}
649
650fn slot_refusal(slot: &Path, detail: impl fmt::Display) -> LifecycleError {
651    LifecycleError::Failed(FailureReason::Other(format!(
652        "the persistent slot {} {detail}",
653        slot.display()
654    )))
655}
656
657/// Whether a directory entry names the retained job workspace.
658///
659/// The comparison folds case on Windows because the filesystem does: there
660/// `_Work` and `_work` are one directory, so a case-sensitive test would let
661/// [`scrub_slot_entries`] delete the very directory it exists to keep, let
662/// [`accept_reusable_slot`] refuse a slot that holds nothing but a valid job
663/// workspace, and let a package's top-level `_Work` merge itself into the
664/// previous attempt's `_work`. Elsewhere the two names really are two
665/// directories and only the exact one is the job workspace.
666fn is_work_folder(name: &OsStr) -> bool {
667    if cfg!(windows) {
668        name.eq_ignore_ascii_case(DEFAULT_WORK_FOLDER)
669    } else {
670        name == OsStr::new(DEFAULT_WORK_FOLDER)
671    }
672}
673
674/// Whether the operating system would follow this entry somewhere else.
675///
676/// `FileType::is_symlink` is the whole answer on Unix. On Windows it is not:
677/// the standard library reports only the symlink and mount-point reparse tags,
678/// and the substitution this has to refuse is *any* reparse point standing
679/// where a real directory should be. So the attribute bit is the test there,
680/// and a tag the standard library has no name for fails closed with the two it
681/// does.
682fn is_link_like(metadata: &fs::Metadata) -> bool {
683    if metadata.file_type().is_symlink() {
684        return true;
685    }
686    #[cfg(windows)]
687    {
688        use std::os::windows::fs::MetadataExt;
689
690        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
691        metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
692    }
693    #[cfg(not(windows))]
694    false
695}
696
697/// Whether an entry is the retained job workspace and is safe to retain.
698///
699/// The two halves are one question. A `_work` that is a file, a symlink, a
700/// junction or any other reparse point is not a job workspace, and it is also
701/// the exact substitution a hostile workflow makes to send cleanup somewhere
702/// else (`04-security-recovery.md`, "A workflow replaces `_work` with a
703/// junction or symlink to escape cleanup").
704fn is_retainable_work_folder(name: &OsStr, metadata: &fs::Metadata) -> bool {
705    is_work_folder(name) && metadata.is_dir() && !is_link_like(metadata)
706}
707
708/// Undo one package materialization, dispatching on the journalled workspace.
709///
710/// The ephemeral half is what this always did: the directory is the attempt's
711/// alone, so it goes whole. The persistent half removes the copy and nothing
712/// else, because the slot's `_work` predates this attempt and outlives it
713/// (`02-target-architecture.md`, "Persistent repository").
714fn remove_materialized_package(attempt: &RunnerAttempt) -> std::io::Result<()> {
715    match attempt.workspace() {
716        AttemptWorkspace::Ephemeral => fs::remove_dir_all(attempt.runtime_path()),
717        AttemptWorkspace::PersistentSlot { .. } => scrub_slot_entries(attempt.runtime_path())
718            .map_err(|quarantine| std::io::Error::other(quarantine.to_string())),
719    }
720}
721
722// ---------------------------------------------------------------------------
723// Persistent cleanup (`04-security-recovery.md`, "Safe path handling")
724// ---------------------------------------------------------------------------
725
726/// Why a persistent slot could not be proven safe to scrub.
727///
728/// A closed set rather than a formatted string, for two reasons that point the
729/// same way. [`LifecycleEvent::AttemptCleanFailed`] takes a `&'static str` for
730/// exactly the reason [`crate::reconcile::failure_reason_kind`] documents —
731/// free text is the one shape that can carry a credential past a field
732/// allow-list. And the entries under a slot root are *workflow-controlled*: a
733/// job that writes a file named after a secret would publish it through any
734/// message that echoed a directory listing, which is why nothing here ever
735/// renders an entry name that did not come from this module's own constants.
736#[derive(Debug, Clone, Copy, PartialEq, Eq)]
737enum SlotRefusal {
738    /// The journalled runtime path is not `<root>/sN` for the journalled slot.
739    NotTheJournalledSlot,
740    /// A policy that still exists names a different root than the journal does.
741    PolicyRootDisagrees,
742    /// The slot is not strictly inside its root once components resolve.
743    Containment,
744    /// The slot itself is a file, a link, or could not be inspected.
745    SlotNotADirectory,
746    /// The slot's direct entries could not be listed.
747    Enumeration,
748    /// `_work` is a file, a symlink, a junction or another reparse point.
749    WorkNotADirectory,
750    /// An entry that had to go could not be removed.
751    Deletion,
752    /// Something other than the job workspace survived removal.
753    Residue,
754}
755
756impl SlotRefusal {
757    /// The event field: a fixed vocabulary, never operator or workflow text.
758    const fn class(self) -> &'static str {
759        match self {
760            Self::NotTheJournalledSlot => "slot_path_is_not_the_journalled_slot",
761            Self::PolicyRootDisagrees => "slot_root_disagrees_with_policy",
762            Self::Containment => "slot_escapes_its_root",
763            Self::SlotNotADirectory => "slot_is_not_a_directory",
764            Self::Enumeration => "slot_could_not_be_enumerated",
765            Self::WorkNotADirectory => "retained_work_is_not_a_directory",
766            Self::Deletion => "slot_entry_could_not_be_removed",
767            Self::Residue => "slot_still_holds_runner_state",
768        }
769    }
770
771    /// What the operator has to do, in one sentence and with no path in it.
772    const fn remediation(self) -> &'static str {
773        match self {
774            Self::NotTheJournalledSlot | Self::PolicyRootDisagrees | Self::Containment => {
775                "the attempt keeps its slot lease and nothing was removed; correct the \
776                 repository's persistent workspace path, or remove the slot directory by hand \
777                 once you have confirmed what is in it"
778            }
779            Self::SlotNotADirectory | Self::WorkNotADirectory => {
780                "the attempt keeps its slot lease and nothing was removed; a job replaced the \
781                 slot or its `_work` with a link, so inspect it before deleting anything and \
782                 treat the retained workspace as untrusted"
783            }
784            Self::Enumeration | Self::Deletion | Self::Residue => {
785                "the attempt keeps its slot lease and will be cleaned again on the next pass; \
786                 release whatever is holding the files open, or remove the slot's contents by \
787                 hand leaving only `_work`"
788            }
789        }
790    }
791}
792
793/// A refusal that leaves one persistent slot quarantined.
794///
795/// `detail` is redacted by construction: it may hold paths this product
796/// configured, `std::io::ErrorKind` values, counts, and names drawn from
797/// [`SENSITIVE_SLOT_ENTRIES`] — and nothing that came out of a directory
798/// listing.
799#[derive(Debug, Clone, PartialEq, Eq)]
800struct SlotQuarantine {
801    refusal: SlotRefusal,
802    detail: String,
803}
804
805impl SlotQuarantine {
806    fn new(refusal: SlotRefusal, detail: impl Into<String>) -> Self {
807        Self {
808            refusal,
809            detail: detail.into(),
810        }
811    }
812}
813
814impl fmt::Display for SlotQuarantine {
815    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
816        write!(f, "{}; {}", self.detail, self.refusal.remediation())
817    }
818}
819
820/// Steps 1 to 3: the journalled root, the journalled slot, and containment.
821///
822/// Everything comes from the two immutable allocation facts — the exact runtime
823/// path and the slot number. Not from the filesystem: scanning a root to decide
824/// which directories are "mine" is what invariant 6 forbids, and it is also
825/// impossible for an attempt whose policy has since been deleted. `configured`
826/// is therefore a *cross-check* and not a source. A policy that survives has to
827/// agree; a policy that does not survive removes a check rather than the
828/// ability to clean the directory the journal already names.
829///
830/// The name test comes before the parent is used, so `<root>/s1` for a journal
831/// row that says `s2` — and anything at all that is not one `sN` component —
832/// is refused before a root is derived from it.
833fn verify_journalled_slot(
834    runtime: &Path,
835    slot: NonZeroU16,
836    configured: Option<&LocalAbsolutePath>,
837) -> Result<(), SlotQuarantine> {
838    let mislaid = || {
839        SlotQuarantine::new(
840            SlotRefusal::NotTheJournalledSlot,
841            format!(
842                "the journalled runtime {} is not the slot s{slot} this attempt was allocated as",
843                runtime.display()
844            ),
845        )
846    };
847    let local = |path: &Path| {
848        path.to_str()
849            .and_then(|raw| LocalAbsolutePath::new(raw).ok())
850            .ok_or_else(mislaid)
851    };
852
853    let runtime_path = local(runtime)?;
854    let root = local(runtime.parent().ok_or_else(mislaid)?)?;
855    // Containment's lexical half, by construction: `derive_child` accepts one
856    // component, so the equality below can only hold when the journalled path
857    // really is this root's `sN` and nothing else.
858    // The directory name comes from the domain that allocation named it with,
859    // never from a second `s{n}` spelled out here: a convention with two
860    // spellings would let cleanup refuse every slot the allocator created.
861    let name = AttemptWorkspace::persistent_slot(slot)
862        .slot_directory_name()
863        .expect("a persistent workspace names its slot directory");
864    let derived = runner_root::derive_child(&root, &name).map_err(|_| mislaid())?;
865    if derived != runtime_path {
866        return Err(mislaid());
867    }
868    if let Some(configured) = configured
869        && configured != &root
870    {
871        return Err(SlotQuarantine::new(
872            SlotRefusal::PolicyRootDisagrees,
873            format!(
874                "the journalled slot {} is not under the repository's configured persistent root \
875                 {}",
876                runtime.display(),
877                configured.as_str()
878            ),
879        ));
880    }
881    // And containment's canonical half, which is what a junction planted inside
882    // the root between allocation and cleanup has to get past.
883    runner_root::verify_containment(&root, &derived).map_err(|source| {
884        SlotQuarantine::new(
885            SlotRefusal::Containment,
886            format!("the journalled slot is not inside the root it was allocated from: {source}"),
887        )
888    })
889}
890
891/// Whether the slot is there to be scrubbed at all, before its entries are.
892///
893/// `Ok(false)` — the directory is gone — is not a refusal. There is nothing to
894/// remove and nothing to prove absent, which is the same tolerance the
895/// disposable arm has always had for a runtime that vanished under it.
896///
897/// A slot that is a file, a link, a junction or any other reparse point *is* a
898/// refusal, and it is checked here rather than inside the enumeration so that
899/// the reason an operator reads names the shape rather than reporting that a
900/// directory could not be listed.
901fn slot_is_present(slot: &Path) -> Result<bool, SlotQuarantine> {
902    match fs::symlink_metadata(slot) {
903        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
904        Err(source) => Err(SlotQuarantine::new(
905            SlotRefusal::SlotNotADirectory,
906            format!(
907                "the slot {} could not be inspected: {:?}",
908                slot.display(),
909                source.kind()
910            ),
911        )),
912        Ok(metadata) if !metadata.is_dir() || is_link_like(&metadata) => Err(SlotQuarantine::new(
913            SlotRefusal::SlotNotADirectory,
914            format!(
915                "the slot {} is a link or a file rather than a real directory",
916                slot.display()
917            ),
918        )),
919        Ok(_) => Ok(true),
920    }
921}
922
923/// Steps 4 to 6: list the slot's direct entries, keep one real `_work`, remove
924/// every other one.
925///
926/// Every call is a literal filesystem API against a path built from the slot
927/// root and one entry name — no glob, no shell string, no repository-controlled
928/// fragment. Nothing is followed: `symlink_metadata` says what each entry *is*,
929/// and a link-shaped entry is unlinked rather than descended into, so a junction
930/// planted where `bin` used to be cannot take the deletion outside the slot.
931///
932/// A `_work` that is not a real directory is the one entry this refuses to act
933/// on at all. Removing it could destroy an operator's data if the link were
934/// theirs; keeping it would hand the next attempt a workspace pointing
935/// anywhere. `04-security-recovery.md` requires that case to quarantine the
936/// slot, so the whole scrub stops there with nothing removed after it.
937fn scrub_slot_entries(slot: &Path) -> Result<(), SlotQuarantine> {
938    let unreadable = |source: std::io::Error| {
939        SlotQuarantine::new(
940            SlotRefusal::Enumeration,
941            format!(
942                "the entries of {} could not be listed: {:?}",
943                slot.display(),
944                source.kind()
945            ),
946        )
947    };
948    for entry in fs::read_dir(slot).map_err(unreadable)? {
949        let name = entry.map_err(unreadable)?.file_name();
950        let path = slot.join(&name);
951        // Nothing is assumed from an entry that vanished: `verify_slot_scrubbed`
952        // asks the filesystem again afterwards and refuses if it is still there.
953        let Some(metadata) = listed_entry_metadata(&path).map_err(unreadable)? else {
954            continue;
955        };
956        if is_work_folder(&name) {
957            if is_retainable_work_folder(&name, &metadata) {
958                continue;
959            }
960            return Err(SlotQuarantine::new(
961                SlotRefusal::WorkNotADirectory,
962                format!(
963                    "the retained `{DEFAULT_WORK_FOLDER}` in {} is a link or a file rather than a \
964                     real directory",
965                    slot.display()
966                ),
967            ));
968        }
969        remove_slot_entry(&path, &metadata).map_err(|source| {
970            SlotQuarantine::new(
971                SlotRefusal::Deletion,
972                format!(
973                    "an entry of {} could not be removed: {:?}",
974                    slot.display(),
975                    source.kind()
976                ),
977            )
978        })?;
979    }
980    Ok(())
981}
982
983/// What a listed entry *is*, or `None` when it is no longer there.
984///
985/// An entry named by a listing and gone by the time it is stat-ed is absent,
986/// which is a fact both passes over a slot want rather than an enumeration that
987/// failed. Nothing is followed: `symlink_metadata` reports a link as a link.
988fn listed_entry_metadata(path: &Path) -> std::io::Result<Option<fs::Metadata>> {
989    match fs::symlink_metadata(path) {
990        Ok(metadata) => Ok(Some(metadata)),
991        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
992        Err(source) => Err(source),
993    }
994}
995
996/// Remove one slot entry without following it.
997///
998/// An entry that is already gone is removed: the post-condition this serves is
999/// "not there", and racing with whatever removed it first is not a refusal.
1000fn remove_slot_entry(path: &Path, metadata: &fs::Metadata) -> std::io::Result<()> {
1001    let removed = if is_link_like(metadata) {
1002        // A file symlink unlinks with `remove_file`; a directory symlink or a
1003        // Windows junction needs `remove_dir`. Neither follows the link.
1004        fs::remove_file(path).or_else(|_| fs::remove_dir(path))
1005    } else if metadata.is_dir() {
1006        fs::remove_dir_all(path)
1007    } else {
1008        fs::remove_file(path)
1009    };
1010    match removed {
1011        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1012        other => other,
1013    }
1014}
1015
1016/// Step 7: prove that nothing but the retained job workspace is left.
1017///
1018/// Two passes, deliberately independent, because the interesting failure is an
1019/// enumeration that under-reports. The first asks the directory what remains
1020/// and counts everything that is not a real `_work`. The second ignores the
1021/// listing entirely and stats the names an attempt is known to write — the
1022/// runner's binaries, the registration identity it stores beside them, the
1023/// process-identity sidecars and this agent's lifecycle marks — so a scrub that
1024/// silently skipped one is caught by a question that never consulted the
1025/// listing that skipped it.
1026///
1027/// Only the second pass names anything, and the encoded JIT handoff is reported
1028/// by its published prefix rather than by the UUID that follows it. A slot root
1029/// is workflow-writable, so a job that named a file after a secret would publish
1030/// it through any message that echoed the listing; the first pass therefore
1031/// reports a count.
1032fn verify_slot_scrubbed(slot: &Path) -> Result<(), SlotQuarantine> {
1033    let unreadable = |source: std::io::Error| {
1034        SlotQuarantine::new(
1035            SlotRefusal::Enumeration,
1036            format!(
1037                "the entries of {} could not be listed to verify the scrub: {:?}",
1038                slot.display(),
1039                source.kind()
1040            ),
1041        )
1042    };
1043    let mut residue = 0_usize;
1044    let mut named: Vec<String> = Vec::new();
1045    for entry in fs::read_dir(slot).map_err(unreadable)? {
1046        let name = entry.map_err(unreadable)?.file_name();
1047        // Absent is what this pass is here to establish. The named half below
1048        // stats every sensitive entry again, so an entry that only *looks*
1049        // absent to this listing is still caught.
1050        let Some(metadata) = listed_entry_metadata(&slot.join(&name)).map_err(unreadable)? else {
1051            continue;
1052        };
1053        if is_retainable_work_folder(&name, &metadata) {
1054            continue;
1055        }
1056        residue = residue.saturating_add(1);
1057        if name
1058            .to_string_lossy()
1059            .starts_with(RestrictiveHandoff::NAME_PREFIX)
1060        {
1061            named.push("an encoded JIT handoff".to_owned());
1062        }
1063    }
1064    named.extend(
1065        SENSITIVE_SLOT_ENTRIES
1066            .iter()
1067            .filter(|entry| fs::symlink_metadata(slot.join(entry)).is_ok())
1068            .map(|entry| format!("`{entry}`")),
1069    );
1070    if residue == 0 && named.is_empty() {
1071        return Ok(());
1072    }
1073    named.sort_unstable();
1074    named.dedup();
1075    Err(SlotQuarantine::new(
1076        SlotRefusal::Residue,
1077        residue_detail(slot, residue, &named),
1078    ))
1079}
1080
1081/// Word a [`SlotRefusal::Residue`] refusal from the two facts that produced it.
1082///
1083/// Separate from [`verify_slot_scrubbed`] because the disagreement it has to
1084/// report — a listing that counted nothing and a filesystem that answered
1085/// otherwise — is a race no test can stage, and a message that contradicts
1086/// itself is exactly what an operator reads at three in the morning.
1087///
1088/// `named` is the sanitized half: entries this crate published the names of.
1089/// A name a workflow chose is only ever counted, never echoed.
1090fn residue_detail(slot: &Path, residue: usize, named: &[String]) -> String {
1091    if residue == 0 {
1092        // The whole reason the second pass ignores the listing: the listing
1093        // reported a clean slot and the filesystem disagrees. Saying "0
1094        // entries survived" here would report the under-count as the fact.
1095        format!(
1096            "the listing of {} reported nothing but `{DEFAULT_WORK_FOLDER}`, yet {} survived \
1097                 cleanup",
1098            slot.display(),
1099            named.join(", ")
1100        )
1101    } else {
1102        format!(
1103            "{residue} entr{} other than `{DEFAULT_WORK_FOLDER}` survived cleanup of {}{}",
1104            if residue == 1 { "y" } else { "ies" },
1105            slot.display(),
1106            if named.is_empty() {
1107                String::new()
1108            } else {
1109                format!(", including {}", named.join(", "))
1110            }
1111        )
1112    }
1113}
1114
1115fn replacement_operation(outcome: &AttemptOutcome) -> Option<&'static str> {
1116    match outcome {
1117        AttemptOutcome::Failed {
1118            reason: FailureReason::JitExpired,
1119        } => Some("jit_expired_replacement"),
1120        AttemptOutcome::Failed {
1121            reason: FailureReason::ProcessExitedUnexpectedly,
1122        } => Some("exit_before_acceptance_replacement"),
1123        _ => None,
1124    }
1125}
1126
1127/// Lay the verified runner package out *around* whatever the slot retains.
1128///
1129/// `02-target-architecture.md`: "The verified runner package is copied into the
1130/// slot for the attempt", beside a `_work` that survives every attempt. Two
1131/// properties make that safe, and both are structural rather than documented:
1132///
1133/// * the walk is of the **source** tree, so a retained `_work` in the
1134///   destination is never opened, never descended into, and cannot be followed
1135///   wherever it might point;
1136/// * a top-level source entry named `_work` is refused rather than copied, so a
1137///   package that ever grew one could not merge itself into, or replace, the
1138///   job workspace of the attempt before it. The refusal is top-level only,
1139///   because the retained directory is a direct child of the slot; a `_work`
1140///   nested inside the package's own tree is an ordinary name.
1141fn copy_package_tree(source: &Path, destination: &Path) -> std::io::Result<()> {
1142    if source.join(DEFAULT_WORK_FOLDER).exists() {
1143        return Err(std::io::Error::new(
1144            std::io::ErrorKind::InvalidData,
1145            "a cached runner package contains a _work folder, which means it was used \
1146             to run a job before it was archived; the cache must only contain clean \
1147             extracts to prevent data leakage",
1148        ));
1149    }
1150
1151    #[cfg(unix)]
1152    {
1153        let status = std::process::Command::new("cp")
1154            .arg("-a")
1155            .arg(format!("{}/.", source.display()))
1156            .arg(destination)
1157            .status()?;
1158        if status.success() {
1159            Ok(())
1160        } else {
1161            Err(std::io::Error::other("cp failed"))
1162        }
1163    }
1164    #[cfg(not(unix))]
1165    copy_package_entries(source, destination, true)
1166}
1167
1168#[cfg(not(unix))]
1169fn copy_package_entries(source: &Path, destination: &Path, top_level: bool) -> std::io::Result<()> {
1170    fs::create_dir_all(destination)?;
1171    for entry in fs::read_dir(source)? {
1172        let entry = entry?;
1173        if top_level && is_work_folder(&entry.file_name()) {
1174            return Err(std::io::Error::new(
1175                std::io::ErrorKind::InvalidData,
1176                format!(
1177                    "the runner package holds a top-level `{DEFAULT_WORK_FOLDER}`; copying \
1178                     it would overwrite the job workspace a persistent slot retains"
1179                ),
1180            ));
1181        }
1182        let target = destination.join(entry.file_name());
1183        if entry.file_type()?.is_dir() {
1184            copy_package_entries(&entry.path(), &target, false)?;
1185        } else {
1186            fs::copy(entry.path(), target)?;
1187        }
1188    }
1189    Ok(())
1190}
1191
1192/// Process operations are attempt-addressed so a recovered process and a child
1193/// started in this invocation are supervised through one port.
1194#[derive(Debug, Clone, PartialEq, Eq)]
1195pub struct ProcessStartFailure {
1196    pub reason: FailureReason,
1197    /// False once a child existed: the one-shot JIT value may have been
1198    /// consumed, so retrying it could start a duplicate.
1199    pub retryable: bool,
1200    /// Set only when cleanup could not prove the spawned process dead.  The
1201    /// caller must journal `starting` and retain capacity/supervision.
1202    pub live_pid: Option<u32>,
1203}
1204
1205impl ProcessStartFailure {
1206    fn before_spawn(reason: FailureReason) -> Self {
1207        Self {
1208            reason,
1209            retryable: true,
1210            live_pid: None,
1211        }
1212    }
1213
1214    fn after_spawn_stopped() -> Self {
1215        Self {
1216            reason: FailureReason::ProcessStartFailed,
1217            retryable: false,
1218            live_pid: None,
1219        }
1220    }
1221
1222    fn after_spawn_live(pid: u32) -> Self {
1223        Self::after_spawn_live_with_reason(pid, FailureReason::ProcessStartFailed)
1224    }
1225
1226    fn after_spawn_live_with_reason(pid: u32, reason: FailureReason) -> Self {
1227        Self {
1228            reason,
1229            retryable: false,
1230            live_pid: Some(pid),
1231        }
1232    }
1233}
1234
1235pub trait ProcessSupervisor: fmt::Debug + Send + Sync {
1236    fn spawn(
1237        &self,
1238        attempt: &RunnerAttempt,
1239        config: &EncodedJitConfig,
1240    ) -> Result<u32, ProcessStartFailure>;
1241    fn is_alive(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason>;
1242    /// Durable identity observed for a process that spawned before the
1243    /// `starting` journal write survived.
1244    fn recovered_pid(&self, attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason>;
1245    /// True only for a child this invocation owned and reaped with a successful
1246    /// exit status.  A recovered process that is merely gone answers false.
1247    fn completed_successfully(&self, attempt: &RunnerAttempt) -> bool;
1248    fn record_terminate_intent(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason>;
1249    fn has_terminate_intent(&self, attempt: &RunnerAttempt) -> bool;
1250    fn terminate(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason>;
1251}
1252
1253/// Native process supervision.  The start token is stored beside the runtime;
1254/// recovery never trusts a recycled PID merely because SQLite contains it.
1255#[derive(Debug, Default)]
1256pub struct NativeProcesses {
1257    children: Mutex<BTreeMap<AttemptId, ChildProcess>>,
1258    successful_exits: Mutex<BTreeMap<AttemptId, bool>>,
1259    #[cfg(test)]
1260    post_spawn_faults: Mutex<VecDeque<PostSpawnBoundary>>,
1261    #[cfg(test)]
1262    post_spawn_reaps: std::sync::atomic::AtomicUsize,
1263    #[cfg(test)]
1264    post_spawn_stop_failures: std::sync::atomic::AtomicUsize,
1265    #[cfg(test)]
1266    use_long_lived_test_listener: std::sync::atomic::AtomicBool,
1267}
1268
1269#[cfg(test)]
1270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1271enum PostSpawnBoundary {
1272    HandoffDelete,
1273    IdentitySerialize,
1274    IdentityWrite,
1275    ChildMapInsert,
1276}
1277
1278impl NativeProcesses {
1279    #[must_use]
1280    pub fn new() -> Self {
1281        Self::default()
1282    }
1283
1284    #[cfg(test)]
1285    fn fail_post_spawn_at(&self, boundary: PostSpawnBoundary) {
1286        self.post_spawn_faults.lock().unwrap().push_back(boundary);
1287    }
1288
1289    #[cfg(test)]
1290    fn faults_at(&self, boundary: PostSpawnBoundary) -> bool {
1291        let mut faults = self.post_spawn_faults.lock().unwrap();
1292        if faults.front() == Some(&boundary) {
1293            faults.pop_front();
1294            true
1295        } else {
1296            false
1297        }
1298    }
1299
1300    #[cfg(test)]
1301    fn fail_post_spawn_stops(&self, count: usize) {
1302        self.post_spawn_stop_failures
1303            .fetch_add(count, std::sync::atomic::Ordering::SeqCst);
1304    }
1305
1306    #[cfg(test)]
1307    fn fail_next_post_spawn_stop(&self) {
1308        self.fail_post_spawn_stops(1);
1309    }
1310
1311    #[cfg(test)]
1312    fn use_long_lived_test_listener(&self) {
1313        self.use_long_lived_test_listener
1314            .store(true, std::sync::atomic::Ordering::SeqCst);
1315    }
1316
1317    fn stop_spawned_child(&self, child: &mut ChildProcess) -> Result<(), FailureReason> {
1318        #[cfg(test)]
1319        if self
1320            .post_spawn_stop_failures
1321            .fetch_update(
1322                std::sync::atomic::Ordering::SeqCst,
1323                std::sync::atomic::Ordering::SeqCst,
1324                |left| if left > 0 { Some(left - 1) } else { None },
1325            )
1326            .is_ok()
1327        {
1328            return Err(FailureReason::Other("injected runner stop failure".into()));
1329        }
1330        child
1331            .stop(Duration::from_secs(1))
1332            .map(|_| ())
1333            .map_err(|_| FailureReason::Other("spawned runner process could not be stopped".into()))
1334    }
1335
1336    fn abort_spawned_child(
1337        &self,
1338        mut child: ChildProcess,
1339        attempt: &RunnerAttempt,
1340        remove_identity: bool,
1341    ) -> ProcessStartFailure {
1342        let mut reaped = self.stop_spawned_child(&mut child).is_ok();
1343        if reaped {
1344            if remove_identity {
1345                Self::remove_identity_files(attempt);
1346            }
1347        } else {
1348            // A failed stop is not a failed attempt yet.  Persist enough truth
1349            // for crash recovery, and retain the owned child when possible.
1350            let identity_durable =
1351                serde_json::to_vec(child.identity())
1352                    .ok()
1353                    .is_some_and(|identity| {
1354                        self.persist_identity(attempt, &identity).is_ok()
1355                            || self.persist_fallback_identity(attempt, &identity).is_ok()
1356                    });
1357            if !identity_durable {
1358                // Returning a live PID as though recovery were complete would
1359                // make the next boot trust a recyclable PID. Reaping is bounded;
1360                // if it cannot finish, the durable `starting` journal entry is
1361                // deliberately unresolved on restart and blocks new launches.
1362                for _ in 1..MAX_POST_SPAWN_STOP_ATTEMPTS {
1363                    if self.stop_spawned_child(&mut child).is_ok() {
1364                        reaped = true;
1365                        break;
1366                    }
1367                }
1368                if !reaped {
1369                    // The attempt journal will durably record `starting` and
1370                    // its PID. Recovery treats a missing full identity as
1371                    // unresolved and starts nothing, so bounded stop failure
1372                    // cannot turn into either a hang or a duplicate runner.
1373                    let pid = child.pid();
1374                    let marker = write_durable_file(
1375                        &Self::unresolved_process_path(attempt),
1376                        pid.to_string().as_bytes(),
1377                    );
1378                    self.children
1379                        .lock()
1380                        .unwrap_or_else(std::sync::PoisonError::into_inner)
1381                        .insert(attempt.id, child);
1382                    let reason = if marker.is_ok() {
1383                        FailureReason::Other(
1384                            "spawn cleanup exhausted its bounded stop attempts; the live process remains under durable unresolved supervision"
1385                                .into(),
1386                        )
1387                    } else {
1388                        FailureReason::Other(
1389                            "spawn cleanup exhausted its bounded stop attempts and the unresolved-process marker could not be journalled"
1390                                .into(),
1391                        )
1392                    };
1393                    return ProcessStartFailure::after_spawn_live_with_reason(pid, reason);
1394                }
1395            } else {
1396                let pid = child.pid();
1397                self.children
1398                    .lock()
1399                    .unwrap_or_else(std::sync::PoisonError::into_inner)
1400                    .insert(attempt.id, child);
1401                return ProcessStartFailure::after_spawn_live(pid);
1402            }
1403        }
1404        #[cfg(test)]
1405        if reaped {
1406            self.post_spawn_reaps
1407                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1408        }
1409        #[cfg(not(test))]
1410        let _ = reaped;
1411        ProcessStartFailure::after_spawn_stopped()
1412    }
1413
1414    fn identity_path(attempt: &RunnerAttempt) -> PathBuf {
1415        attempt.runtime_path().join(IDENTITY_FILE)
1416    }
1417
1418    fn fallback_identity_path(attempt: &RunnerAttempt) -> PathBuf {
1419        attempt.runtime_path().join(FALLBACK_IDENTITY_FILE)
1420    }
1421
1422    fn unresolved_process_path(attempt: &RunnerAttempt) -> PathBuf {
1423        attempt.runtime_path().join(UNRESOLVED_PROCESS_FILE)
1424    }
1425
1426    fn remove_identity_files(attempt: &RunnerAttempt) {
1427        let _ = fs::remove_file(Self::identity_path(attempt));
1428        let _ = fs::remove_file(Self::fallback_identity_path(attempt));
1429        let _ = fs::remove_file(Self::unresolved_process_path(attempt));
1430    }
1431
1432    fn persist_identity(&self, attempt: &RunnerAttempt, bytes: &[u8]) -> std::io::Result<()> {
1433        self.persist_identity_at(&Self::identity_path(attempt), bytes)
1434    }
1435
1436    fn persist_fallback_identity(
1437        &self,
1438        attempt: &RunnerAttempt,
1439        bytes: &[u8],
1440    ) -> std::io::Result<()> {
1441        self.persist_identity_at(&Self::fallback_identity_path(attempt), bytes)
1442    }
1443
1444    fn persist_identity_at(&self, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
1445        #[cfg(test)]
1446        if self.faults_at(PostSpawnBoundary::IdentityWrite) {
1447            return Err(std::io::Error::other("injected identity write failure"));
1448        }
1449        write_durable_file(path, bytes)
1450    }
1451
1452    fn intent_path(attempt: &RunnerAttempt) -> PathBuf {
1453        attempt.runtime_path().join(TERMINATE_INTENT_FILE)
1454    }
1455
1456    fn read_identity(attempt: &RunnerAttempt) -> Result<Option<ProcessIdentity>, FailureReason> {
1457        match Self::read_identity_at(&Self::identity_path(attempt))? {
1458            Some(identity) => Ok(Some(identity)),
1459            None => Self::read_identity_at(&Self::fallback_identity_path(attempt)),
1460        }
1461    }
1462
1463    fn read_identity_at(path: &Path) -> Result<Option<ProcessIdentity>, FailureReason> {
1464        match fs::read(path) {
1465            Ok(bytes) => serde_json::from_slice(&bytes)
1466                .map(Some)
1467                .map_err(|_| FailureReason::Other("process identity journal is unreadable".into())),
1468            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
1469            Err(_) => Err(FailureReason::Other(
1470                "process identity journal could not be read".into(),
1471            )),
1472        }
1473    }
1474}
1475
1476impl ProcessSupervisor for NativeProcesses {
1477    fn spawn(
1478        &self,
1479        attempt: &RunnerAttempt,
1480        config: &EncodedJitConfig,
1481    ) -> Result<u32, ProcessStartFailure> {
1482        let handoff = RestrictiveHandoff::create(
1483            attempt.runtime_path(),
1484            SecretString::from(config.expose().to_owned()),
1485        )
1486        .map_err(|_| ProcessStartFailure::before_spawn(FailureReason::ProcessStartFailed))?;
1487        #[cfg(windows)]
1488        let program = attempt
1489            .runtime_path()
1490            .join("bin")
1491            .join("Runner.Listener.exe");
1492        #[cfg(not(windows))]
1493        let program = attempt.runtime_path().join("bin").join("Runner.Listener");
1494        // Checked after the handoff exists on purpose: the error path below is
1495        // a real post-handoff launch failure, and unwinding must delete it.
1496        if !program.is_file() {
1497            return Err(ProcessStartFailure::before_spawn(
1498                FailureReason::ProcessStartFailed,
1499            ));
1500        }
1501        #[cfg(test)]
1502        let spec = if self
1503            .use_long_lived_test_listener
1504            .load(std::sync::atomic::Ordering::SeqCst)
1505        {
1506            SpawnSpec::new(program)
1507                .args([
1508                    "--ignored",
1509                    "--exact",
1510                    "lifecycle::tests::long_lived_native_listener_helper",
1511                    "--nocapture",
1512                ])
1513                .env(
1514                    "RUNNER_MANAGER_TEST_LISTENER_READY",
1515                    attempt.runtime_path().join(TEST_LISTENER_READY),
1516                )
1517                .working_dir(attempt.runtime_path())
1518        } else {
1519            runner_listener_spec(program, attempt.runtime_path())
1520        };
1521        #[cfg(not(test))]
1522        let spec = runner_listener_spec(program, attempt.runtime_path());
1523        let child = spec
1524            .spawn_runner_with_handoff(&handoff)
1525            .map_err(|_| ProcessStartFailure::before_spawn(FailureReason::ProcessStartFailed))?;
1526        // The payload is gone before any state saying "starting" is persisted.
1527        #[cfg(test)]
1528        if self.faults_at(PostSpawnBoundary::HandoffDelete) {
1529            drop(handoff);
1530            return Err(self.abort_spawned_child(child, attempt, false));
1531        }
1532        if handoff.delete().is_err() {
1533            return Err(self.abort_spawned_child(child, attempt, false));
1534        }
1535        #[cfg(test)]
1536        if self.faults_at(PostSpawnBoundary::IdentitySerialize) {
1537            return Err(self.abort_spawned_child(child, attempt, false));
1538        }
1539        let identity = match serde_json::to_vec(child.identity()) {
1540            Ok(identity) => identity,
1541            Err(_) => {
1542                return Err(self.abort_spawned_child(child, attempt, false));
1543            }
1544        };
1545        if self.persist_identity(attempt, &identity).is_err() {
1546            return Err(self.abort_spawned_child(child, attempt, true));
1547        }
1548        let pid = child.pid();
1549        #[cfg(test)]
1550        if self.faults_at(PostSpawnBoundary::ChildMapInsert) {
1551            return Err(self.abort_spawned_child(child, attempt, true));
1552        }
1553        let mut children = self
1554            .children
1555            .lock()
1556            .unwrap_or_else(std::sync::PoisonError::into_inner);
1557        children.insert(attempt.id, child);
1558        Ok(pid)
1559    }
1560
1561    fn is_alive(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
1562        let mut children = self
1563            .children
1564            .lock()
1565            .unwrap_or_else(std::sync::PoisonError::into_inner);
1566        if let Some(child) = children.get_mut(&attempt.id) {
1567            return match child
1568                .try_exit_status()
1569                .map_err(|_| FailureReason::Other("runner process could not be observed".into()))?
1570            {
1571                None => Ok(true),
1572                Some(status) => {
1573                    if let Ok(mut exits) = self.successful_exits.lock() {
1574                        exits.insert(attempt.id, status.success());
1575                    }
1576                    Ok(false)
1577                }
1578            };
1579        }
1580        let Some(identity) = Self::read_identity(attempt)? else {
1581            if attempt.process_id().is_some() || Self::unresolved_process_path(attempt).is_file() {
1582                return Err(FailureReason::Other(
1583                    "runner process identity is missing; refusing recovery until the process is resolved"
1584                        .into(),
1585                ));
1586            }
1587            return Ok(false);
1588        };
1589        match identity.recheck() {
1590            Ok(Adoption::Live) => Ok(true),
1591            Ok(Adoption::Gone | Adoption::PidRecycled { .. }) => Ok(false),
1592            Err(_) => Ok(false),
1593        }
1594    }
1595
1596    fn recovered_pid(&self, attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
1597        Ok(Self::read_identity(attempt)?.map(|identity| identity.pid()))
1598    }
1599
1600    fn completed_successfully(&self, attempt: &RunnerAttempt) -> bool {
1601        self.successful_exits
1602            .lock()
1603            .ok()
1604            .and_then(|exits| exits.get(&attempt.id).copied())
1605            .unwrap_or(false)
1606    }
1607
1608    fn record_terminate_intent(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
1609        let path = Self::intent_path(attempt);
1610        write_durable_file(&path, b"registration-timeout\n")
1611            .map_err(|_| FailureReason::Other("terminate intent could not be journalled".into()))
1612    }
1613
1614    fn has_terminate_intent(&self, attempt: &RunnerAttempt) -> bool {
1615        Self::intent_path(attempt).is_file()
1616    }
1617
1618    fn terminate(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
1619        let mut children = self
1620            .children
1621            .lock()
1622            .unwrap_or_else(std::sync::PoisonError::into_inner);
1623        if let Some(child) = children.get_mut(&attempt.id) {
1624            child
1625                .stop(Duration::from_secs(10))
1626                .map_err(|_| FailureReason::Other("runner process could not be stopped".into()))?;
1627            return Ok(());
1628        }
1629        let Some(identity) = Self::read_identity(attempt)? else {
1630            return Ok(());
1631        };
1632        match identity
1633            .terminate(Duration::from_secs(10))
1634            .map_err(|_| FailureReason::Other("runner process could not be stopped".into()))?
1635        {
1636            Termination::Terminated | Termination::AlreadyGone => Ok(()),
1637            Termination::RefusedPidRecycled { .. } => Err(FailureReason::Other(
1638                "runner PID was recycled; refusing to signal it".into(),
1639            )),
1640        }
1641    }
1642}
1643
1644pub struct LifecyclePorts {
1645    pub store: Arc<dyn Store>,
1646    pub github: Arc<dyn LifecycleGithub>,
1647    pub packages: Arc<dyn RuntimePackages>,
1648    pub processes: Arc<dyn ProcessSupervisor>,
1649    pub clock: Arc<dyn Clock>,
1650    pub demand: Arc<dyn DemandPersistence>,
1651    pub delay: Arc<dyn RetryDelay>,
1652    pub events: Arc<dyn AttemptEventSink>,
1653    pub reconcile_events: Arc<dyn EventSink>,
1654}
1655
1656impl fmt::Debug for LifecyclePorts {
1657    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1658        f.debug_struct("LifecyclePorts")
1659            .field("store", &self.store)
1660            .field("github", &self.github)
1661            .field("packages", &self.packages)
1662            .field("processes", &self.processes)
1663            .finish_non_exhaustive()
1664    }
1665}
1666
1667#[derive(Debug, thiserror::Error)]
1668pub enum LifecycleError {
1669    #[error("attempt journal operation failed")]
1670    Journal,
1671    #[error("attempt {0} is not in the journal")]
1672    Missing(AttemptId),
1673    #[error("attempt lifecycle transition was refused")]
1674    Transition,
1675    #[error("startup recovery has not completed")]
1676    RecoveryIncomplete,
1677    /// A persistent slot could not be proven safe to scrub, so the attempt keeps
1678    /// its uncleaned state and, with it, its slot lease.
1679    ///
1680    /// Separate from [`Self::Failed`] because the two demand opposite handling
1681    /// from the same call sites. A failure aborts the pass; a quarantine must
1682    /// not, or one stuck slot would stop the host launching anything at all —
1683    /// which is precisely what `04-security-recovery.md` rules out when it says
1684    /// such an attempt "does not count as active host capacity" and "recovery
1685    /// retries the same cleanup".
1686    #[error("the persistent slot was not cleaned: {detail}")]
1687    SlotQuarantined {
1688        /// The closed-vocabulary event field; never operator or workflow text.
1689        class: &'static str,
1690        detail: String,
1691    },
1692    #[error("runner lifecycle failed: {0}")]
1693    Failed(FailureReason),
1694}
1695
1696impl LifecycleError {
1697    fn reason(&self) -> FailureReason {
1698        match self {
1699            Self::Failed(reason) => reason.clone(),
1700            Self::RecoveryIncomplete => FailureReason::Other("startup recovery incomplete".into()),
1701            Self::Journal => FailureReason::Other("attempt journal operation failed".into()),
1702            Self::Missing(_) => FailureReason::Other("attempt disappeared from the journal".into()),
1703            Self::Transition => FailureReason::Other("attempt transition was refused".into()),
1704            // Rendered through `Display` rather than a second copy of the same
1705            // sentence, so the two cannot drift apart.
1706            Self::SlotQuarantined { .. } => FailureReason::Other(self.to_string()),
1707        }
1708    }
1709}
1710
1711/// Production implementation of e1's launcher port.
1712#[derive(Debug)]
1713pub struct LifecycleLauncher {
1714    host_id: HostId,
1715    app_paths: runner_manager_platform::paths::AppPaths,
1716    diagnostics_root: PathBuf,
1717    runner_group_id: u64,
1718    timeouts: RecoveryTimeouts,
1719    retry: RetryPolicy,
1720    cancel: CancelToken,
1721    ports: LifecyclePorts,
1722    recovery_complete: Mutex<bool>,
1723    versions: Mutex<BTreeMap<AttemptId, RunnerVersion>>,
1724    pending_replacements: Mutex<BTreeMap<AttemptId, ReplacementIntent>>,
1725}
1726
1727#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1728enum ReconcileProgress {
1729    Reconciled,
1730    Deferred,
1731    Replacement {
1732        attempt: AttemptId,
1733        operation: &'static str,
1734    },
1735}
1736
1737impl LifecycleLauncher {
1738    #[must_use]
1739    pub fn new(
1740        host_id: HostId,
1741        app_paths: runner_manager_platform::paths::AppPaths,
1742        diagnostics_root: impl Into<PathBuf>,
1743        runner_group_id: u64,
1744        timeouts: RecoveryTimeouts,
1745        retry: RetryPolicy,
1746        ports: LifecyclePorts,
1747    ) -> Self {
1748        Self {
1749            host_id,
1750            app_paths,
1751            diagnostics_root: diagnostics_root.into(),
1752            runner_group_id,
1753            timeouts,
1754            retry,
1755            cancel: CancelToken::new(),
1756            ports,
1757            recovery_complete: Mutex::new(false),
1758            versions: Mutex::new(BTreeMap::new()),
1759            pending_replacements: Mutex::new(BTreeMap::new()),
1760        }
1761    }
1762
1763    /// Reconcile the entire journal before allowing a launch.  Unknown-policy
1764    /// attempts are left untouched rather than being acted on without an
1765    /// ownership proof.
1766    pub async fn recover_startup(
1767        &self,
1768        policies: &[ScalePolicy],
1769    ) -> Result<Vec<ReplacementIntent>, LifecycleError> {
1770        let by_id: BTreeMap<_, _> = policies.iter().map(|policy| (policy.id, policy)).collect();
1771        let attempts = self
1772            .ports
1773            .store
1774            .attempts()
1775            .map_err(|_| LifecycleError::Journal)?;
1776        let mut unresolved = false;
1777        for attempt in attempts {
1778            let Some(policy) = by_id.get(&attempt.policy_id) else {
1779                if !attempt.is_terminal() && attempt.state() != AttemptState::Cleaned {
1780                    unresolved = true;
1781                }
1782                continue;
1783            };
1784            authorize(self.host_id, policy, &attempt).map_err(|_| LifecycleError::Journal)?;
1785            match self.reconcile_one(policy, attempt).await? {
1786                ReconcileProgress::Deferred => unresolved = true,
1787                ReconcileProgress::Replacement { attempt, operation } => {
1788                    self.pending_replacements
1789                        .lock()
1790                        .map_err(|_| LifecycleError::Journal)?
1791                        .insert(
1792                            attempt,
1793                            ReplacementIntent {
1794                                policy: policy.id,
1795                                previous_attempt: attempt,
1796                                operation,
1797                            },
1798                        );
1799                }
1800                ReconcileProgress::Reconciled => {}
1801            }
1802        }
1803        if unresolved {
1804            return Err(LifecycleError::RecoveryIncomplete);
1805        }
1806        *self
1807            .recovery_complete
1808            .lock()
1809            .map_err(|_| LifecycleError::Journal)? = true;
1810        Ok(self
1811            .pending_replacements
1812            .lock()
1813            .map_err(|_| LifecycleError::Journal)?
1814            .values()
1815            .copied()
1816            .collect())
1817    }
1818
1819    /// Supervise all attempts of one policy during an ordinary poll.
1820    pub async fn supervise(
1821        &self,
1822        policy: &ScalePolicy,
1823    ) -> Result<Vec<ReplacementIntent>, LifecycleError> {
1824        let mut replacements = Vec::new();
1825        self.pending_replacements
1826            .lock()
1827            .map_err(|_| LifecycleError::Journal)?
1828            .retain(|_, intent| {
1829                if intent.policy == policy.id {
1830                    replacements.push(*intent);
1831                    false
1832                } else {
1833                    true
1834                }
1835            });
1836        let attempts = self
1837            .ports
1838            .store
1839            .attempts_for_policy(policy.id)
1840            .map_err(|_| LifecycleError::Journal)?;
1841        for attempt in attempts {
1842            authorize(self.host_id, policy, &attempt).map_err(|_| LifecycleError::Journal)?;
1843            if let ReconcileProgress::Replacement { attempt, operation } =
1844                self.reconcile_one(policy, attempt).await?
1845            {
1846                replacements.push(ReplacementIntent {
1847                    policy: policy.id,
1848                    previous_attempt: attempt,
1849                    operation,
1850                });
1851            }
1852        }
1853        Ok(replacements)
1854    }
1855
1856    async fn reconcile_one(
1857        &self,
1858        policy: &ScalePolicy,
1859        mut attempt: RunnerAttempt,
1860    ) -> Result<ReconcileProgress, LifecycleError> {
1861        if attempt.state() == AttemptState::Cleaned {
1862            return Ok(ReconcileProgress::Reconciled);
1863        }
1864        if attempt.is_terminal() {
1865            self.clean_or_quarantine(&mut attempt)?;
1866            return Ok(ReconcileProgress::Reconciled);
1867        }
1868        let process_alive = self
1869            .ports
1870            .processes
1871            .is_alive(&attempt)
1872            .map_err(LifecycleError::Failed)?;
1873        let github = self
1874            .ports
1875            .github
1876            .observe(&policy.target, attempt.id, &self.cancel)
1877            .await;
1878
1879        // If the agent died after GitHub accepted the registration but before
1880        // the non-secret runner-id sidecar landed, inventory closes the gap.
1881        // Persist it before making any state decision so a second crash moves
1882        // the boundary forward rather than repeating it.
1883        if let Some(runner_id) = github.runner_id
1884            && read_runner_id(attempt.runtime_path()).is_none()
1885        {
1886            write_runner_id(attempt.runtime_path(), runner_id)?;
1887            self.ports
1888                .events
1889                .emit(AttemptEvent::RemoteIdentityRecovered {
1890                    attempt: attempt.id,
1891                    runner_id,
1892                });
1893        }
1894
1895        // The child identity is synced before `spawn` returns.  If the agent
1896        // crashed before the following `starting` journal write, recover that
1897        // exact PID and take the legal `jit_received -> starting` edge before
1898        // applying GitHub's authoritative idle/busy observation below.
1899        if attempt.state() == AttemptState::JitReceived
1900            && process_alive
1901            && let Some(pid) = self
1902                .ports
1903                .processes
1904                .recovered_pid(&attempt)
1905                .map_err(LifecycleError::Failed)?
1906        {
1907            attempt
1908                .started(pid, self.ports.clock.now())
1909                .map_err(|_| LifecycleError::Transition)?;
1910            self.record(&attempt)?;
1911        }
1912
1913        // A one-shot child owned by this invocation exited successfully after
1914        // GitHub had already reported it busy, and its ephemeral registration
1915        // is now gone.  This concludes the *runner attempt*, never the workflow
1916        // outcome; GitHub remains authoritative for that outcome.
1917        if attempt.state() == AttemptState::Busy
1918            && !process_alive
1919            && github.status == GithubRunnerObservation::NotRegistered
1920            && self.ports.processes.completed_successfully(&attempt)
1921        {
1922            self.conclude(&mut attempt, AttemptOutcome::CompletedJob)?;
1923            self.clean_or_quarantine(&mut attempt)?;
1924            return Ok(ReconcileProgress::Reconciled);
1925        }
1926
1927        // This durable mark is more authoritative than a later observation
1928        // which cannot distinguish an agent kill from a crash.
1929        if self.ports.processes.has_terminate_intent(&attempt) && !process_alive {
1930            self.deregister_runner(policy, &attempt).await;
1931            self.conclude(
1932                &mut attempt,
1933                AttemptOutcome::failed(FailureReason::TerminatedAfterRegistrationTimeout),
1934            )?;
1935            self.clean_or_quarantine(&mut attempt)?;
1936            return Ok(ReconcileProgress::Replacement {
1937                attempt: attempt.id,
1938                operation: "registration_timeout_replacement",
1939            });
1940        }
1941
1942        // A remote registration with no surviving process has lost its
1943        // one-shot JIT secret.  Walking it to `starting` would require inventing
1944        // a PID; retrying the same registration would require inventing the
1945        // secret.  Record the configuration as expired and let the bounded
1946        // replacement path request a fresh one only if demand remains.
1947        if matches!(
1948            attempt.state(),
1949            AttemptState::Allocated | AttemptState::JitReceived
1950        ) && !process_alive
1951            && matches!(github.status, GithubRunnerObservation::Registered { .. })
1952        {
1953            if attempt.state() == AttemptState::Allocated {
1954                attempt
1955                    .jit_received(self.ports.clock.now())
1956                    .map_err(|_| LifecycleError::Transition)?;
1957                self.record(&attempt)?;
1958            }
1959            self.deregister_runner(policy, &attempt).await;
1960            self.conclude(
1961                &mut attempt,
1962                AttemptOutcome::failed(FailureReason::JitExpired),
1963            )?;
1964            self.clean_or_quarantine(&mut attempt)?;
1965            return Ok(ReconcileProgress::Replacement {
1966                attempt: attempt.id,
1967                operation: "jit_expired_replacement",
1968            });
1969        }
1970
1971        match recovery_decision(
1972            &attempt,
1973            RecoveryObservation {
1974                process_alive,
1975                github: github.status,
1976            },
1977            self.timeouts,
1978            self.ports.clock.as_ref(),
1979        ) {
1980            RecoveryDecision::Nothing | RecoveryDecision::Wait => Ok(ReconcileProgress::Reconciled),
1981            RecoveryDecision::Defer => Ok(ReconcileProgress::Deferred),
1982            RecoveryDecision::Adopt => {
1983                self.ports.events.emit(AttemptEvent::Adopted {
1984                    attempt: attempt.id,
1985                });
1986                Ok(ReconcileProgress::Reconciled)
1987            }
1988            RecoveryDecision::Clean => {
1989                self.clean_or_quarantine(&mut attempt)?;
1990                Ok(ReconcileProgress::Reconciled)
1991            }
1992            RecoveryDecision::Observe(state) => {
1993                let runner_id = attempt
1994                    .github_runner_id()
1995                    .or(github.runner_id)
1996                    .or_else(|| read_runner_id(attempt.runtime_path()))
1997                    .ok_or(LifecycleError::Transition)?;
1998                match state {
1999                    AttemptState::JitReceived => attempt
2000                        .jit_received(self.ports.clock.now())
2001                        .map_err(|_| LifecycleError::Transition)?,
2002                    AttemptState::Starting => {
2003                        let pid = attempt.process_id().ok_or(LifecycleError::Transition)?;
2004                        attempt
2005                            .started(pid, self.ports.clock.now())
2006                            .map_err(|_| LifecycleError::Transition)?;
2007                    }
2008                    AttemptState::Idle => attempt
2009                        .registered_idle(runner_id, self.ports.clock.now())
2010                        .map_err(|_| LifecycleError::Transition)?,
2011                    AttemptState::Busy => attempt
2012                        .assigned_job(runner_id, self.ports.clock.now())
2013                        .map_err(|_| LifecycleError::Transition)?,
2014                    _ => return Err(LifecycleError::Transition),
2015                }
2016                self.record(&attempt)?;
2017                Ok(ReconcileProgress::Reconciled)
2018            }
2019            RecoveryDecision::Conclude(outcome) => {
2020                let replacement = replacement_operation(&outcome);
2021                // Only when GitHub still holds one. Every other conclusion here
2022                // was reached *because* the observation was `NotRegistered`, and
2023                // spending a DELETE to be told so again would put a request per
2024                // concluded attempt on a budget `rest.rs` prices to the request.
2025                if matches!(github.status, GithubRunnerObservation::Registered { .. }) {
2026                    self.deregister_runner(policy, &attempt).await;
2027                }
2028                self.conclude(&mut attempt, outcome)?;
2029                self.clean_or_quarantine(&mut attempt)?;
2030                Ok(
2031                    replacement.map_or(ReconcileProgress::Reconciled, |operation| {
2032                        ReconcileProgress::Replacement {
2033                            attempt: attempt.id,
2034                            operation,
2035                        }
2036                    }),
2037                )
2038            }
2039            RecoveryDecision::Terminate(payload) => {
2040                // The mark is synced first, and what proves the process died is
2041                // the `is_alive` re-read below -- not the outcome recorded after
2042                // it. Which outcome that is depends on why the termination was
2043                // ordered, and only the payload knows: a `starting` runner that
2044                // never registered is a failure this agent then stopped, while
2045                // an `idle` one past its timeout is flow 2.7's surplus exit and
2046                // no failure at all. Hardcoding the first reason here labelled
2047                // the second as a registration timeout and asked the allocator
2048                // for a replacement to boot.
2049                let idle_exit = payload.is_idle_exit();
2050                self.ports
2051                    .processes
2052                    .record_terminate_intent(&attempt)
2053                    .map_err(LifecycleError::Failed)?;
2054                self.ports.events.emit(AttemptEvent::TerminateIntent {
2055                    attempt: attempt.id,
2056                });
2057                self.ports
2058                    .processes
2059                    .terminate(&attempt)
2060                    .map_err(LifecycleError::Failed)?;
2061                if self
2062                    .ports
2063                    .processes
2064                    .is_alive(&attempt)
2065                    .map_err(LifecycleError::Failed)?
2066                {
2067                    return Ok(ReconcileProgress::Deferred);
2068                }
2069                self.ports.events.emit(AttemptEvent::Terminated {
2070                    attempt: attempt.id,
2071                });
2072                // The registration-timeout path keeps deriving its own reason
2073                // rather than applying the payload: on the pass that reads the
2074                // journalled mark back the process is dead, and
2075                // `TerminatedAfterRegistrationTimeout` is the reason that stays
2076                // true of a dead process. See `RecoveryDecision::Terminate`.
2077                let outcome = if idle_exit {
2078                    AttemptOutcome::ExitedIdleWithoutWork
2079                } else {
2080                    AttemptOutcome::failed(FailureReason::TerminatedAfterRegistrationTimeout)
2081                };
2082                self.deregister_runner(policy, &attempt).await;
2083                self.conclude(&mut attempt, outcome)?;
2084                self.clean_or_quarantine(&mut attempt)?;
2085                // A surplus runner is not replaced. It was stopped precisely
2086                // because the work it was started for went elsewhere; asking the
2087                // allocator for another one rebuilds it every idle timeout.
2088                if idle_exit {
2089                    Ok(ReconcileProgress::Reconciled)
2090                } else {
2091                    Ok(ReconcileProgress::Replacement {
2092                        attempt: attempt.id,
2093                        operation: "registration_timeout_replacement",
2094                    })
2095                }
2096            }
2097        }
2098    }
2099
2100    fn record(&self, attempt: &RunnerAttempt) -> Result<(), LifecycleError> {
2101        self.ports
2102            .store
2103            .record_attempt(attempt)
2104            .map_err(|_| LifecycleError::Journal)?;
2105        self.ports.events.emit(AttemptEvent::State {
2106            attempt: attempt.id,
2107            state: attempt.state(),
2108        });
2109        Ok(())
2110    }
2111
2112    /// Remove the GitHub registration an attempt is about to leave behind.
2113    ///
2114    /// # Why this is not fallible, and does not block the conclusion
2115    ///
2116    /// GitHub retires an ephemeral runner itself once that runner *completes a
2117    /// job*, and for the ordinary path that is the whole story. The paths that
2118    /// reach here are the ones where it does not: a runner stopped before it
2119    /// was ever assigned work, a registration whose process died still holding
2120    /// it, a JIT configuration that expired. Nothing else deletes those, and
2121    /// before this existed nothing did — they accumulated in the target's
2122    /// runner settings, one row per attempt, for the life of the repository.
2123    ///
2124    /// It returns `()` rather than a `Result` because the alternative is worse
2125    /// in both directions. The attempt is over: its process is gone and its
2126    /// slot has to come back, so a failed delete may not abort the conclusion
2127    /// or the host leaks capacity every time GitHub is unreachable. And a
2128    /// registration that outlives this call is not lost — it is exactly the
2129    /// `Registered` + dead-process observation that
2130    /// [`AttemptOutcome::Orphaned`] already names, which a later pass can still
2131    /// see. So a failure is logged and stepped over, deliberately.
2132    async fn deregister_runner(&self, policy: &ScalePolicy, attempt: &RunnerAttempt) {
2133        let Some(runner_id) = attempt
2134            .github_runner_id()
2135            .or_else(|| read_runner_id(attempt.runtime_path()))
2136        else {
2137            return;
2138        };
2139        if self
2140            .ports
2141            .github
2142            .deregister(&policy.target, runner_id, &self.cancel)
2143            .await
2144        {
2145            self.ports.events.emit(AttemptEvent::Deregistered {
2146                attempt: attempt.id,
2147                runner_id,
2148            });
2149        } else {
2150            tracing::warn!(
2151                attempt = %attempt.id,
2152                runner_id,
2153                "the runner registration could not be removed from GitHub; it will show in the \
2154                 target's runner settings until GitHub retires it or a later pass removes it"
2155            );
2156        }
2157    }
2158
2159    fn conclude(
2160        &self,
2161        attempt: &mut RunnerAttempt,
2162        outcome: AttemptOutcome,
2163    ) -> Result<(), LifecycleError> {
2164        attempt
2165            .conclude(outcome.clone(), self.ports.clock.now())
2166            .map_err(|_| LifecycleError::Transition)?;
2167        self.record(attempt)?;
2168        self.ports.events.emit(AttemptEvent::Concluded {
2169            attempt: attempt.id,
2170            outcome: OutcomeKind::of(&outcome),
2171        });
2172        Ok(())
2173    }
2174
2175    /// Clean a concluded attempt, tolerating a quarantined persistent slot.
2176    ///
2177    /// The quarantine is reported and stepped over rather than raised, because
2178    /// raising it aborts the whole pass: on the startup path that leaves
2179    /// `recovery_complete` false and stops the host launching anything, which is
2180    /// the opposite of `04-security-recovery.md`'s "it does not count as active
2181    /// host capacity" and "recovery retries the same cleanup". The attempt keeps
2182    /// its state, so it keeps its slot lease and its directory, and the next
2183    /// pass — [`crate::reconcile::Reconciler`]'s terminal sweep on every poll,
2184    /// or the next startup — attempts exactly the same cleanup again.
2185    ///
2186    /// Only a *quarantine* is tolerated. A journal failure or a package lease
2187    /// that cannot be released still propagates: those are not one slot's
2188    /// problem.
2189    fn clean_or_quarantine(&self, attempt: &mut RunnerAttempt) -> Result<(), LifecycleError> {
2190        match self.clean_attempt(attempt) {
2191            Err(LifecycleError::SlotQuarantined { class, .. }) => {
2192                self.ports
2193                    .reconcile_events
2194                    .emit(LifecycleEvent::AttemptCleanFailed {
2195                        policy: attempt.policy_id,
2196                        attempt: attempt.id,
2197                        reason: class,
2198                    });
2199                Ok(())
2200            }
2201            other => other,
2202        }
2203    }
2204
2205    fn clean_attempt(&self, attempt: &mut RunnerAttempt) -> Result<(), LifecycleError> {
2206        let outcome = attempt
2207            .outcome()
2208            .cloned()
2209            .ok_or(LifecycleError::Transition)?;
2210        self.preserve_diagnostics(attempt, &outcome)?;
2211        self.scrub_workspace(attempt)?;
2212        self.ports
2213            .packages
2214            .release(attempt.id)
2215            .map_err(LifecycleError::Failed)?;
2216        attempt
2217            .clean(self.ports.clock.now())
2218            .map_err(|_| LifecycleError::Transition)?;
2219        self.record(attempt)?;
2220        let kind = OutcomeKind::of(&outcome);
2221        self.ports.events.emit(AttemptEvent::Cleaned {
2222            attempt: attempt.id,
2223            outcome: kind,
2224        });
2225        self.ports
2226            .reconcile_events
2227            .emit(LifecycleEvent::AttemptCleaned {
2228                policy: attempt.policy_id,
2229                attempt: attempt.id,
2230                outcome: kind,
2231            });
2232        Ok(())
2233    }
2234
2235    /// Undo an attempt's placement by the algorithm its journalled workspace
2236    /// kind makes legal (`02-target-architecture.md`, "Cleanup and recovery").
2237    ///
2238    /// The dispatch is on the *journal*, never on what the directory looks like
2239    /// now. A slot whose `_work` was replaced by a junction is still scrubbed as
2240    /// a slot rather than removed whole, and a disposable directory that happens
2241    /// to contain a `_work` still goes whole rather than being spared: the
2242    /// workspace kind is immutable precisely so that the shape of a directory a
2243    /// workflow can write to cannot choose the algorithm applied to it.
2244    fn scrub_workspace(&self, attempt: &RunnerAttempt) -> Result<(), LifecycleError> {
2245        #[cfg(test)]
2246        {
2247            // The two contamination mutants `f1` drives the security gates with.
2248            // They sit in front of the dispatch rather than inside one arm so
2249            // that a skipped cleanup is equally observable in both modes.
2250            if matches!(
2251                std::env::var("RUNNER_MANAGER_TEST_MUTANT").as_deref(),
2252                Ok("skip_workspace_cleanup" | "reuse_job_workspace")
2253            ) {
2254                return Ok(());
2255            }
2256        }
2257        match attempt.workspace() {
2258            AttemptWorkspace::Ephemeral => match fs::remove_dir_all(attempt.runtime_path()) {
2259                Ok(()) => Ok(()),
2260                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
2261                Err(_) => Err(LifecycleError::Failed(FailureReason::Other(
2262                    "attempt workspace could not be removed".into(),
2263                ))),
2264            },
2265            AttemptWorkspace::PersistentSlot { slot } => self.scrub_persistent_slot(attempt, slot),
2266        }
2267    }
2268
2269    /// Retain exactly `_work` and prove everything else is gone.
2270    ///
2271    /// The seven ordered checks of `04-security-recovery.md`, "Safe path
2272    /// handling": the journalled root and slot, a surviving policy's agreement,
2273    /// lexical and canonical containment, a literal enumeration, the one-entry
2274    /// allowlist, and a verification pass before the caller releases the package
2275    /// lease and marks the attempt cleaned. Any of them may refuse, and a
2276    /// refusal removes nothing after it.
2277    ///
2278    /// A slot directory that is already gone is not a refusal. There is nothing
2279    /// to scrub and nothing to prove absent, which is the same tolerance the
2280    /// disposable arm has always had for a runtime that vanished under it.
2281    fn scrub_persistent_slot(
2282        &self,
2283        attempt: &RunnerAttempt,
2284        slot: NonZeroU16,
2285    ) -> Result<(), LifecycleError> {
2286        // The policy is read from the journal, never inferred from the
2287        // directory tree, and its absence is legal: `Reconciler` cleans every
2288        // concluded attempt whether or not its policy still exists, and this
2289        // one's root is already journalled on the attempt itself.
2290        let configured = self
2291            .ports
2292            .store
2293            .policy(attempt.policy_id)
2294            .map_err(|_| LifecycleError::Journal)?
2295            .and_then(|policy| match policy.workspace_policy() {
2296                WorkspacePolicy::Persistent { root } => Some(root.clone()),
2297                WorkspacePolicy::Ephemeral => None,
2298            });
2299        let runtime = attempt.runtime_path();
2300        self.quarantine_on_refusal(
2301            attempt,
2302            verify_journalled_slot(runtime, slot, configured.as_ref())
2303                .and_then(|()| slot_is_present(runtime))
2304                .and_then(|present| {
2305                    if present {
2306                        scrub_slot_entries(runtime).and_then(|()| verify_slot_scrubbed(runtime))
2307                    } else {
2308                        Ok(())
2309                    }
2310                }),
2311        )
2312    }
2313
2314    /// Turn a slot refusal into the error that keeps the attempt uncleaned.
2315    ///
2316    /// The warning is emitted here, at the one place a quarantine is minted, so
2317    /// that both routes out of cleanup carry it: the reconciler's terminal sweep,
2318    /// which receives the error through the launcher port, and
2319    /// [`Self::clean_or_quarantine`], which swallows it to keep the pass alive.
2320    /// Everything logged is either a path this product configured or a constant
2321    /// from this module — see [`SlotQuarantine`] for why that matters.
2322    fn quarantine_on_refusal(
2323        &self,
2324        attempt: &RunnerAttempt,
2325        outcome: Result<(), SlotQuarantine>,
2326    ) -> Result<(), LifecycleError> {
2327        let Err(quarantine) = outcome else {
2328            return Ok(());
2329        };
2330        let detail = quarantine.to_string();
2331        tracing::warn!(
2332            attempt = %attempt.id,
2333            policy = %attempt.policy_id,
2334            slot = attempt.workspace().slot_number(),
2335            refusal = quarantine.refusal.class(),
2336            "{detail}"
2337        );
2338        Err(LifecycleError::SlotQuarantined {
2339            class: quarantine.refusal.class(),
2340            detail,
2341        })
2342    }
2343
2344    fn preserve_diagnostics(
2345        &self,
2346        attempt: &RunnerAttempt,
2347        outcome: &AttemptOutcome,
2348    ) -> Result<(), LifecycleError> {
2349        fs::create_dir_all(&self.diagnostics_root).map_err(|_| {
2350            LifecycleError::Failed(FailureReason::Other(
2351                "diagnostics directory could not be created".into(),
2352            ))
2353        })?;
2354        // Intentionally constructed from typed local facts, not runner output.
2355        // Raw child output can contain workflow secrets and is never copied.
2356        let diagnostic = format!(
2357            "attempt_id={}\npolicy_id={}\noutcome={}\n",
2358            attempt.id,
2359            attempt.policy_id,
2360            OutcomeKind::of(outcome).as_str()
2361        );
2362        fs::write(
2363            self.diagnostics_root.join(format!("{}.log", attempt.id)),
2364            diagnostic,
2365        )
2366        .map_err(|_| {
2367            LifecycleError::Failed(FailureReason::Other(
2368                "redacted diagnostics could not be preserved".into(),
2369            ))
2370        })
2371    }
2372
2373    async fn materialize_with_retry(
2374        &self,
2375        policy: &ScalePolicy,
2376        attempt: &RunnerAttempt,
2377    ) -> Result<RunnerVersion, FailureReason> {
2378        let mut issued = 0_u32;
2379        loop {
2380            issued = issued.saturating_add(1);
2381            match self.ports.packages.materialize(attempt).await {
2382                Ok(version) => return Ok(version),
2383                Err(reason)
2384                    if package_failure_is_terminal(&reason)
2385                        || issued >= self.retry.max_attempts.max(1) =>
2386                {
2387                    return Err(reason);
2388                }
2389                Err(reason) => {
2390                    if !self.ports.demand.persists(policy.id).await {
2391                        return Err(reason);
2392                    }
2393                    let delay = self.retry.delay(issued);
2394                    self.ports.events.emit(AttemptEvent::Retry {
2395                        attempt: attempt.id,
2396                        operation: "package_materialization",
2397                        delay,
2398                    });
2399                    self.ports.delay.wait(delay).await;
2400                    if !self.ports.demand.persists(policy.id).await {
2401                        return Err(reason);
2402                    }
2403                }
2404            }
2405        }
2406    }
2407
2408    async fn register_with_retry(
2409        &self,
2410        policy: &ScalePolicy,
2411        attempt: AttemptId,
2412        request: &JitRunnerRequest,
2413    ) -> Result<JitRegistration, LifecycleError> {
2414        let mut issued = 0_u32;
2415        loop {
2416            issued = issued.saturating_add(1);
2417            match self
2418                .ports
2419                .github
2420                .register(&policy.target, request, &self.cancel)
2421                .await
2422            {
2423                Ok(registration) => return Ok(registration),
2424                Err(error) if error.terminal => {
2425                    return Err(LifecycleError::Failed(error.reason));
2426                }
2427                Err(error) => {
2428                    if issued >= self.retry.max_attempts.max(1)
2429                        || !self.ports.demand.persists(policy.id).await
2430                    {
2431                        return Err(LifecycleError::Failed(error.reason));
2432                    }
2433                    let delay = error
2434                        .retry_after
2435                        .unwrap_or_else(|| self.retry.delay(issued));
2436                    self.ports.events.emit(AttemptEvent::Retry {
2437                        attempt,
2438                        operation: "jit_request",
2439                        delay,
2440                    });
2441                    self.ports.delay.wait(delay).await;
2442                    if !self.ports.demand.persists(policy.id).await {
2443                        return Err(LifecycleError::Failed(error.reason));
2444                    }
2445                }
2446            }
2447        }
2448    }
2449
2450    /// Where one attempt's files go, decided while the host allocation lock is
2451    /// held and before anything external happens.
2452    ///
2453    /// The branch is on the *repository's configured* workspace policy, so an
2454    /// organization policy and an ephemeral repository never reach slot
2455    /// selection at all: a persistent policy is unrepresentable for an
2456    /// organization target (D7, refused by `WorkspacePolicy::permitted_for` in
2457    /// both the constructor and the loader), and an ephemeral repository takes
2458    /// the disposable arm that existed before slots did.
2459    fn allocate_workspace(
2460        &self,
2461        policy: &ScalePolicy,
2462        id: AttemptId,
2463    ) -> Result<Placement, LifecycleError> {
2464        let placement = match policy.workspace_policy() {
2465            // Precedence (`02-target-architecture.md`): the repository's
2466            // persistent root is selected *before* the host root, which is why
2467            // this arm is first and why it never makes resolving the host
2468            // default a precondition of its own success.
2469            WorkspacePolicy::Persistent { root } => self.allocate_persistent_slot(policy, root),
2470            WorkspacePolicy::Ephemeral => self.allocate_disposable(policy, id),
2471        };
2472        // Here rather than inside the two arms, so that every path a root can
2473        // accept clears the record and none can be forgotten.
2474        if placement.is_ok() {
2475            self.root_accepted(policy.id);
2476        }
2477        placement
2478    }
2479
2480    /// `Host.runner_root_override`, read from the journal.
2481    ///
2482    /// Separated from [`Self::effective_host_root`] so that the two failures it
2483    /// folds together stay apart: an unreadable or missing host row is a journal
2484    /// problem and is always fatal, while an unresolvable *platform default* is
2485    /// only fatal to a placement that actually needs the host root.
2486    fn configured_host_root(&self) -> Result<Option<LocalAbsolutePath>, LifecycleError> {
2487        let host = self
2488            .ports
2489            .store
2490            .host(self.host_id)
2491            .map_err(|_| LifecycleError::Journal)?
2492            .ok_or_else(|| LifecycleError::Failed(FailureReason::Other("host not found".into())))?;
2493        Ok(host.runner_root_override.clone())
2494    }
2495
2496    /// `Host.runner_root_override`, or the platform default standing in for it.
2497    ///
2498    /// Takes the policy because an unresolvable default is a refusal like any
2499    /// other, and the record it leaves is that policy's.
2500    fn effective_host_root(
2501        &self,
2502        policy: &ScalePolicy,
2503    ) -> Result<LocalAbsolutePath, LifecycleError> {
2504        match self.configured_host_root()? {
2505            Some(configured) => Ok(configured),
2506            None => default_runner_root(&self.app_paths).map_err(|error| {
2507                // No root resolved, so there is no path to name but the one the
2508                // platform would have produced.
2509                self.root_refused(policy.id, "the platform default runner root", error)
2510            }),
2511        }
2512    }
2513
2514    /// Turns a runner-root refusal into a failure, and leaves the sentence
2515    /// somewhere an operator can read it.
2516    ///
2517    /// Per policy, because the policies on a host do not share a fate: one with
2518    /// its own persistent root places runners while another on a withheld
2519    /// volume places none, and a host-wide record would have the first clear
2520    /// the second's on the same pass.
2521    ///
2522    /// The recording is best-effort and its failure is deliberately swallowed:
2523    /// this runs on the path that is already failing, and a host that cannot
2524    /// write a diagnostic file must still report the refusal it came to report.
2525    /// `service status` says so itself when the file is unreadable.
2526    fn root_refused(&self, policy: PolicyId, root: &str, error: RunnerRootError) -> LifecycleError {
2527        let _ = runner_manager_platform::service::record_runner_root_refusal(
2528            &self.app_paths,
2529            &policy.to_string(),
2530            self.ports.clock.now(),
2531            error.kind(),
2532            root,
2533            &error.to_string(),
2534        );
2535        root_failure(error)
2536    }
2537
2538    /// Clears that policy's record, because its root accepted a placement.
2539    ///
2540    /// Called on every successful placement rather than only after a failure:
2541    /// the daemon that recovers is often not the process that failed -- a
2542    /// self-update restarts it -- so "clear it if we wrote it" would leave a
2543    /// stale note on `service status` for as long as the host ran.
2544    fn root_accepted(&self, policy: PolicyId) {
2545        let _ = runner_manager_platform::service::clear_runner_root_refusal(
2546            &self.app_paths,
2547            &policy.to_string(),
2548        );
2549    }
2550
2551    /// D3's disposable placement: a unique child of the effective host root,
2552    /// removed whole on cleanup. `c1`'s behaviour, moved behind the branch.
2553    fn allocate_disposable(
2554        &self,
2555        policy: &ScalePolicy,
2556        id: AttemptId,
2557    ) -> Result<Placement, LifecycleError> {
2558        let effective_root = self.effective_host_root(policy)?;
2559        RootPreflight::new(&self.app_paths)
2560            .check(&RootOwner::Host, &effective_root)
2561            .map_err(|error| self.root_refused(policy.id, effective_root.as_str(), error))?;
2562        let runtime = effective_root.as_path().join({
2563            #[cfg(test)]
2564            {
2565                if std::env::var("RUNNER_MANAGER_TEST_MUTANT").as_deref()
2566                    == Ok("reuse_job_workspace")
2567                {
2568                    "mutant-shared-workspace".to_owned()
2569                } else {
2570                    workspace_name(id)
2571                }
2572            }
2573            #[cfg(not(test))]
2574            {
2575                workspace_name(id)
2576            }
2577        });
2578        fs::create_dir_all(&runtime)
2579            .map_err(|_| LifecycleError::Failed(FailureReason::ProcessStartFailed))?;
2580        Ok(Placement {
2581            runtime,
2582            workspace: AttemptWorkspace::Ephemeral,
2583        })
2584    }
2585
2586    /// D4/D5's persistent placement: the lowest free `sN` under the repository's
2587    /// configured root.
2588    ///
2589    /// Steps 1 to 6 of `02-target-architecture.md`, "Slot allocation", in order;
2590    /// step 7 is the journal write [`Self::record_allocation`] owns. All of them
2591    /// run under the host allocation lock, because [`Self::launch_attempt`] is
2592    /// reachable only through a `LaunchRequest` and that carries the guard.
2593    ///
2594    /// **The filesystem is never consulted to decide which slots are taken**
2595    /// (invariant 6). The leases come from the journal; the directory is
2596    /// inspected only to decide whether *this* slot is safe to reuse.
2597    fn allocate_persistent_slot(
2598        &self,
2599        policy: &ScalePolicy,
2600        root: &LocalAbsolutePath,
2601    ) -> Result<Placement, LifecycleError> {
2602        // 1-4. The lowest positive slot no uncleaned attempt holds, refused
2603        // above the policy ceiling.
2604        let ceiling = policy.max_capacity().ok_or_else(|| {
2605            LifecycleError::Failed(FailureReason::Other(
2606                "a persistent workspace needs the policy's max_capacity to bound its slots"
2607                    .to_string(),
2608            ))
2609        })?;
2610        let leases = self
2611            .ports
2612            .store
2613            .slot_leases_for_policy(policy.id)
2614            .map_err(|_| LifecycleError::Journal)?;
2615        let slot = lowest_free_slot(&leases, ceiling).ok_or_else(|| {
2616            LifecycleError::Failed(FailureReason::Other(format!(
2617                "every persistent slot s1 to s{ceiling} for {} is leased by an attempt that has \
2618                 not been cleaned, so no slot is free; raise the repository's max capacity, or \
2619                 finish cleaning a concluded attempt",
2620                policy.target
2621            )))
2622        })?;
2623        let workspace = AttemptWorkspace::persistent_slot(slot);
2624        let name = workspace
2625            .slot_directory_name()
2626            .expect("a persistent allocation names its slot directory");
2627
2628        // The operational preflight, for the reasons the host root gets one: a
2629        // root that is remote, unwritable, or overlapping application data has
2630        // to fail before a directory is created rather than after. The host
2631        // root is registered only as something *not* to overlap; a host default
2632        // that cannot be resolved is a host-root problem and does not block a
2633        // repository that configured a root of its own.
2634        //
2635        // Only *that* failure is tolerated. An unreadable host row is a journal
2636        // failure and propagates, because silently continuing would drop the
2637        // overlap check entirely and accept a repository root that sits inside
2638        // the host root — the pair `RootPreflight` exists to refuse.
2639        let host_root = self
2640            .configured_host_root()?
2641            .or_else(|| default_runner_root(&self.app_paths).ok());
2642        let mut preflight = RootPreflight::new(&self.app_paths);
2643        if let Some(host_root) = host_root {
2644            preflight = preflight.against(RootOwner::Host, host_root);
2645        }
2646        let checked = preflight
2647            .check(&RootOwner::Repository(policy.target.to_string()), root)
2648            .map_err(|error| self.root_refused(policy.id, root.as_str(), error))?;
2649        if let Some(leaf) = checked.leaf_to_create() {
2650            fs::create_dir(leaf).map_err(|source| {
2651                LifecycleError::Failed(FailureReason::Other(format!(
2652                    "the persistent workspace root {} could not be created: {source}",
2653                    leaf.display()
2654                )))
2655            })?;
2656        }
2657
2658        // 5-6. `<root>/sN`, contained lexically by construction, then created or
2659        // validated, then contained canonically now that it resolves, and only
2660        // then accepted for reuse.
2661        let slot_path = runner_root::derive_child(root, &name)
2662            .map_err(|error| self.root_refused(policy.id, root.as_str(), error))?;
2663        create_or_validate_slot(slot_path.as_path())?;
2664        runner_root::verify_containment(root, &slot_path)
2665            .map_err(|error| self.root_refused(policy.id, root.as_str(), error))?;
2666        accept_reusable_slot(slot_path.as_path())?;
2667        Ok(Placement {
2668            runtime: slot_path.as_path().to_path_buf(),
2669            workspace,
2670        })
2671    }
2672
2673    /// The first journal write of an attempt, where a duplicate slot lease is
2674    /// still possible and has to be reported as itself.
2675    ///
2676    /// [`Self::record`] flattens every store failure into
2677    /// [`LifecycleError::Journal`], which is right for a state transition and
2678    /// wrong here: the partial unique index
2679    /// `one_uncleaned_persistent_attempt_per_slot` is the final race fence
2680    /// (`04-security-recovery.md`, "two attempts use one slot concurrently"),
2681    /// and an operator who reaches it needs to read that rather than "attempt
2682    /// journal operation failed". Nothing was written, so the caller returns
2683    /// without concluding an attempt that is not in the journal.
2684    fn record_allocation(&self, attempt: &RunnerAttempt) -> Result<(), LifecycleError> {
2685        match self.ports.store.record_attempt(attempt) {
2686            Ok(()) => {
2687                self.ports.events.emit(AttemptEvent::State {
2688                    attempt: attempt.id,
2689                    state: attempt.state(),
2690                });
2691                Ok(())
2692            }
2693            Err(error @ StoreError::SlotAlreadyLeased { .. }) => Err(LifecycleError::Failed(
2694                FailureReason::Other(error.to_string()),
2695            )),
2696            Err(_) => Err(LifecycleError::Journal),
2697        }
2698    }
2699
2700    async fn launch_attempt(
2701        &self,
2702        policy: &ScalePolicy,
2703        allocation_guard: &AllocationGuard,
2704    ) -> Result<RunnerAttempt, LifecycleError> {
2705        if !*self
2706            .recovery_complete
2707            .lock()
2708            .map_err(|_| LifecycleError::Journal)?
2709        {
2710            return Err(LifecycleError::RecoveryIncomplete);
2711        }
2712        let labels = policy
2713            .routing_labels()
2714            .ok_or(LifecycleError::Failed(FailureReason::JitRequestFailed))?;
2715        let id = AttemptId::new_random();
2716        let placement = self.allocate_workspace(policy, id)?;
2717        let mut attempt = RunnerAttempt::allocate_in(
2718            id,
2719            policy.id,
2720            placement.runtime,
2721            placement.workspace,
2722            self.ports.clock.now(),
2723        );
2724        // This is deliberately the first effect after directory allocation, and
2725        // for a persistent attempt it is also what makes the slot lease durable
2726        // before any package or GitHub effect
2727        // (`02-target-architecture.md`, "Slot allocation", step 7).
2728        self.record_allocation(&attempt)?;
2729
2730        let version = match self.materialize_with_retry(policy, &attempt).await {
2731            Ok(version) => version,
2732            Err(reason) => return self.fail_launch(&mut attempt, reason),
2733        };
2734        self.prune_under_allocation_lock(allocation_guard, &version)?;
2735        self.versions
2736            .lock()
2737            .map_err(|_| LifecycleError::Journal)?
2738            .insert(id, version);
2739
2740        let jit_request =
2741            JitRunnerRequest::for_policy(runner_name(id), self.runner_group_id, labels);
2742        let registration = match self.register_with_retry(policy, id, &jit_request).await {
2743            Ok(registration) => registration,
2744            Err(error) => return self.fail_launch(&mut attempt, error.reason()),
2745        };
2746        let runner_id = registration.runner().id;
2747        write_runner_id(attempt.runtime_path(), runner_id)?;
2748        attempt
2749            .jit_received(self.ports.clock.now())
2750            .map_err(|_| LifecycleError::Transition)?;
2751        self.record(&attempt)?;
2752        let config = registration.into_config();
2753        let mut issued = 0_u32;
2754        let pid = loop {
2755            issued = issued.saturating_add(1);
2756            match self.ports.processes.spawn(&attempt, &config) {
2757                Ok(pid) => break pid,
2758                Err(error) => {
2759                    if let Some(pid) = error.live_pid {
2760                        attempt
2761                            .started(pid, self.ports.clock.now())
2762                            .map_err(|_| LifecycleError::Transition)?;
2763                        self.record(&attempt)?;
2764                        return Err(LifecycleError::Failed(error.reason));
2765                    }
2766                    if !error.retryable
2767                        || issued >= self.retry.max_attempts.max(1)
2768                        || !self.ports.demand.persists(policy.id).await
2769                    {
2770                        return self.fail_launch(&mut attempt, error.reason);
2771                    }
2772                    let delay = self.retry.delay(issued);
2773                    self.ports.events.emit(AttemptEvent::Retry {
2774                        attempt: attempt.id,
2775                        operation: "process_start",
2776                        delay,
2777                    });
2778                    self.ports.delay.wait(delay).await;
2779                    if !self.ports.demand.persists(policy.id).await {
2780                        return self.fail_launch(&mut attempt, error.reason);
2781                    }
2782                }
2783            }
2784        };
2785        attempt
2786            .started(pid, self.ports.clock.now())
2787            .map_err(|_| LifecycleError::Transition)?;
2788        self.record(&attempt)?;
2789        Ok(attempt)
2790    }
2791
2792    fn fail_launch<T>(
2793        &self,
2794        attempt: &mut RunnerAttempt,
2795        reason: FailureReason,
2796    ) -> Result<T, LifecycleError> {
2797        self.conclude(attempt, AttemptOutcome::failed(reason.clone()))?;
2798        Err(LifecycleError::Failed(reason))
2799    }
2800
2801    /// e2's prune guard is invoked only with e1's allocation guard borrowed.
2802    /// The otherwise-unused argument is a compile-time witness of the ordering.
2803    fn prune_under_allocation_lock(
2804        &self,
2805        guard: &AllocationGuard,
2806        version: &RunnerVersion,
2807    ) -> Result<(), LifecycleError> {
2808        let attempts = self
2809            .ports
2810            .store
2811            .attempts()
2812            .map_err(|_| LifecycleError::Journal)?;
2813        self.ports
2814            .packages
2815            .prune_obsolete_guarded(
2816                PruneAuthority::from_launch_request(guard),
2817                version,
2818                &attempts,
2819            )
2820            .map_err(LifecycleError::Failed)
2821    }
2822}
2823
2824#[async_trait]
2825impl RunnerLauncher for LifecycleLauncher {
2826    async fn supervise(
2827        &self,
2828        policy: &ScalePolicy,
2829    ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
2830        LifecycleLauncher::supervise(self, policy)
2831            .await
2832            .map_err(|error| LaunchFailure::new(error.reason()))
2833    }
2834
2835    async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
2836        self.ports.store.attempts().map_err(|_| {
2837            LaunchFailure::new(FailureReason::Other(
2838                "attempt journal could not be read".into(),
2839            ))
2840        })
2841    }
2842
2843    async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure> {
2844        self.launch_attempt(request.policy, request.allocation_guard)
2845            .await
2846            .map_err(|error| LaunchFailure::new(error.reason()))
2847    }
2848
2849    async fn clean(&self, id: AttemptId) -> Result<(), LaunchFailure> {
2850        let mut attempt = self
2851            .ports
2852            .store
2853            .attempt(id)
2854            .map_err(|_| {
2855                LaunchFailure::new(FailureReason::Other(
2856                    "attempt journal could not be read".into(),
2857                ))
2858            })?
2859            .ok_or_else(|| {
2860                LaunchFailure::new(FailureReason::Other(
2861                    "attempt disappeared from the journal".into(),
2862                ))
2863            })?;
2864        self.clean_attempt(&mut attempt)
2865            .map_err(|error| LaunchFailure::new(error.reason()))
2866    }
2867}
2868
2869fn runner_name(attempt: AttemptId) -> String {
2870    format!("runner-manager-{attempt}")
2871}
2872
2873fn read_runner_id(runtime: &Path) -> Option<u64> {
2874    fs::read_to_string(runtime.join(RUNNER_ID_FILE))
2875        .ok()?
2876        .trim()
2877        .parse()
2878        .ok()
2879}
2880
2881fn write_runner_id(runtime: &Path, runner_id: u64) -> Result<(), LifecycleError> {
2882    let target = runtime.join(RUNNER_ID_FILE);
2883    if let Some(existing) = read_runner_id(runtime) {
2884        return (existing == runner_id)
2885            .then_some(())
2886            .ok_or(LifecycleError::Journal);
2887    }
2888    let temporary = runtime.join(format!("{RUNNER_ID_FILE}.{}.tmp", uuid::Uuid::new_v4()));
2889    write_durable_file(&temporary, runner_id.to_string().as_bytes())
2890        .map_err(|_| LifecycleError::Journal)?;
2891    match fs::rename(&temporary, &target) {
2892        Ok(()) => sync_directory(runtime).map_err(|_| LifecycleError::Journal),
2893        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
2894            let _ = fs::remove_file(&temporary);
2895            (read_runner_id(runtime) == Some(runner_id))
2896                .then_some(())
2897                .ok_or(LifecycleError::Journal)
2898        }
2899        Err(_) => {
2900            let _ = fs::remove_file(&temporary);
2901            Err(LifecycleError::Journal)
2902        }
2903    }
2904}
2905
2906fn write_durable_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
2907    let mut file = fs::OpenOptions::new()
2908        .create(true)
2909        .truncate(true)
2910        .write(true)
2911        .open(path)?;
2912    file.write_all(bytes)?;
2913    file.sync_all()?;
2914    let parent = path.parent().ok_or_else(|| {
2915        std::io::Error::new(
2916            std::io::ErrorKind::InvalidInput,
2917            "file has no parent directory",
2918        )
2919    })?;
2920    sync_directory(parent)
2921}
2922
2923#[cfg(unix)]
2924fn sync_directory(path: &Path) -> std::io::Result<()> {
2925    fs::File::open(path)?.sync_all()
2926}
2927
2928#[cfg(windows)]
2929fn sync_directory(path: &Path) -> std::io::Result<()> {
2930    use std::os::windows::fs::OpenOptionsExt;
2931
2932    const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
2933    const FILE_SHARE_ALL: u32 = 0x0000_0007;
2934    const GENERIC_WRITE: u32 = 0x4000_0000;
2935    fs::OpenOptions::new()
2936        .access_mode(GENERIC_WRITE)
2937        .share_mode(FILE_SHARE_ALL)
2938        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
2939        .open(path)?
2940        .sync_all()
2941}
2942
2943#[cfg(test)]
2944mod tests {
2945    use super::*;
2946    use std::collections::BTreeSet;
2947    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
2948
2949    use crate::reconcile::{AllocationLock, InProcessAllocationLock};
2950    use runner_manager_domain::model::{Elapsed, TargetScope};
2951    use runner_manager_domain::store::SqliteStore;
2952    use runner_manager_github::jit::JitRunner;
2953    use runner_manager_testkit::clock::FakeClock;
2954    use runner_manager_testkit::fixtures;
2955
2956    /// One event's fields, in the order they were recorded.
2957    type CapturedFields = Vec<(String, String)>;
2958
2959    /// Keeps the `(name, value)` fields of every `tracing` event emitted while
2960    /// it is installed.
2961    ///
2962    /// The names are kept and not just the rendered line, so a test can hold the
2963    /// event to `crate::logging`'s two rules -- the field allow-list and the
2964    /// value scrub -- instead of asserting that some string was passed to a
2965    /// macro.
2966    #[derive(Clone, Default)]
2967    struct CapturedEvents(std::sync::Arc<std::sync::Mutex<Vec<CapturedFields>>>);
2968
2969    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for CapturedEvents {
2970        fn on_event(
2971            &self,
2972            event: &tracing::Event<'_>,
2973            _context: tracing_subscriber::layer::Context<'_, S>,
2974        ) {
2975            struct Collect(Vec<(String, String)>);
2976            impl tracing::field::Visit for Collect {
2977                fn record_debug(
2978                    &mut self,
2979                    field: &tracing::field::Field,
2980                    value: &dyn std::fmt::Debug,
2981                ) {
2982                    // `{value:?}` on a `&str` field would keep the quotes, and
2983                    // the redaction rules are about the value, not its literal.
2984                    self.0.push((
2985                        field.name().to_owned(),
2986                        format!("{value:?}").trim_matches('"').to_owned(),
2987                    ));
2988                }
2989            }
2990            let mut collected = Collect(Vec::new());
2991            event.record(&mut collected);
2992            self.0
2993                .lock()
2994                .expect("the capture mutex is not poisoned")
2995                .push(collected.0);
2996        }
2997    }
2998
2999    /// The regression behind a three-hour outage that showed nothing an operator
3000    /// could act on.
3001    ///
3002    /// A root the daemon cannot use refuses the launch *before*
3003    /// `record_allocation`, so no attempt row is ever written: `b2` has nothing
3004    /// to carry the failure on and `g2` has nothing to show it from. The
3005    /// lifecycle event keeps only the variant -- `failure_reason_kind` allows no
3006    /// free text on an event -- so the whole failure read
3007    /// `runner_start_failed reason=other`, once per poll, for hours.
3008    ///
3009    /// The assertion is deliberately made against the **production redaction
3010    /// rules** and not merely against what was emitted. An earlier attempt at
3011    /// this fix logged the rendered error on a `detail` field and passed a test
3012    /// exactly like this one, while shipping `detail="[redacted]"`: the field
3013    /// was not allow-listed, and had it been, the value is mostly paths and
3014    /// would have been scrubbed to `[path]`. A test that does not ask
3015    /// `crate::logging` what survives is a test that proves nothing.
3016    #[test]
3017    fn a_launch_the_runner_root_refused_names_the_cause_in_the_log_that_ships() {
3018        use runner_manager_platform::logging;
3019        use tracing_subscriber::layer::SubscriberExt as _;
3020
3021        let captured = CapturedEvents::default();
3022        let error = RunnerRootError::DeniedByPrivacyPolicy {
3023            requested: PathBuf::from("/Volumes/NVME/runners"),
3024            refused: PathBuf::from("/Volumes/NVME"),
3025            remediation: RootOwner::Host.remediation(),
3026        };
3027        let kind = error.kind();
3028
3029        let failure = tracing::subscriber::with_default(
3030            tracing_subscriber::registry().with(captured.clone()),
3031            || root_failure(error),
3032        );
3033
3034        // The reason still carries the whole sentence. Nothing on *this* path
3035        // renders it -- there is no attempt row, and the event carries only the
3036        // variant -- so this is a guard against a refactor that drops the detail
3037        // before some future surface can show it, and not a claim that one does.
3038        assert!(
3039            matches!(
3040                &failure,
3041                LifecycleError::Failed(FailureReason::Other(detail))
3042                    if detail.contains("/Volumes/NVME/runners")
3043                        && detail.contains("Full Disk Access")
3044            ),
3045            "the reason must still carry the detail: {failure:?}"
3046        );
3047
3048        let events = captured
3049            .0
3050            .lock()
3051            .expect("the capture mutex is not poisoned")
3052            .clone();
3053        let event = events
3054            .iter()
3055            .find(|fields| fields.iter().any(|(_, value)| value.contains(kind)))
3056            .unwrap_or_else(|| panic!("the refusal did not name its cause: {events:?}"));
3057
3058        // Held to the rules the real sink applies, by name and by value. An
3059        // earlier fix put the rendered error on an unlisted `detail` field and
3060        // shipped `[redacted]`; asserting only that something was emitted would
3061        // have passed then too.
3062        for (name, value) in event {
3063            assert!(
3064                logging::is_field_allowed(name),
3065                "`{name}` is not allow-listed, so it ships as `{}`: {event:?}",
3066                logging::REDACTION
3067            );
3068            assert_eq!(
3069                &logging::redact(value),
3070                value,
3071                "`{name}` does not survive value-shape scrubbing: {event:?}"
3072            );
3073        }
3074    }
3075
3076    /// A slot number, for the tests that name one.
3077    fn nz(slot: u16) -> NonZeroU16 {
3078        NonZeroU16::new(slot).expect("a positive slot")
3079    }
3080
3081    const JIT: &str = "eyJzZWNyZXQiOiJnaHBfRE9fTk9UX0xFQUsifQ==";
3082
3083    #[derive(Debug, Default)]
3084    struct FakeGithubLifecycle {
3085        registration_failures: Mutex<VecDeque<bool>>,
3086        observations: Mutex<VecDeque<LifecycleGithubObservation>>,
3087        registrations: AtomicUsize,
3088        remaining_runners: AtomicUsize,
3089        /// Every runner id `deregister` was asked to remove, in order. A count
3090        /// would not do: the assertions worth making are that the *right*
3091        /// registration was deleted and that it was deleted once.
3092        deregistrations: Mutex<Vec<u64>>,
3093        /// Set to make `deregister` answer `false`, standing for a GitHub that
3094        /// could not be reached at the moment the attempt concluded.
3095        deregistration_fails: AtomicBool,
3096        /// The journal to read *during* a registration, for the ordering
3097        /// assertion `02-target-architecture.md` makes: the slot lease is
3098        /// written "before package or GitHub effects". Reading it afterwards
3099        /// would pass even if the write happened second.
3100        journal: Mutex<Option<Arc<SqliteStore>>>,
3101        /// One entry per registration, in order.
3102        registration_facts: Mutex<Vec<RegistrationFact>>,
3103    }
3104
3105    /// What one JIT registration saw of the world at the moment it was issued.
3106    ///
3107    /// `runner_name` is what ties the other two fields to *one* attempt: with
3108    /// two allocators racing, "some slot was journalled" is a much weaker claim
3109    /// than "the slot this very request belongs to was journalled", and only the
3110    /// name distinguishes them.
3111    #[derive(Debug, Clone)]
3112    struct RegistrationFact {
3113        /// The persistent slots the journal already held.
3114        leased_slots: Vec<u16>,
3115        /// The `work_folder` the request carried.
3116        work_folder: String,
3117        /// The runner name the request carried, i.e. [`runner_name`] of the
3118        /// registering attempt.
3119        runner_name: String,
3120    }
3121
3122    impl FakeGithubLifecycle {
3123        fn fail(mut self, terminal: bool) -> Self {
3124            self.registration_failures
3125                .get_mut()
3126                .expect("unpoisoned")
3127                .push_back(terminal);
3128            self
3129        }
3130
3131        fn watch_journal(&self, store: Arc<SqliteStore>) {
3132            *self.journal.lock().unwrap() = Some(store);
3133        }
3134
3135        fn registration_facts(&self) -> Vec<RegistrationFact> {
3136            self.registration_facts.lock().unwrap().clone()
3137        }
3138
3139        fn observe(&self, observation: GithubRunnerObservation) {
3140            let observation = match observation {
3141                GithubRunnerObservation::Unreachable => LifecycleGithubObservation::unreachable(),
3142                GithubRunnerObservation::NotRegistered => {
3143                    LifecycleGithubObservation::not_registered()
3144                }
3145                GithubRunnerObservation::Registered { busy } => {
3146                    LifecycleGithubObservation::registered(73, busy)
3147                }
3148            };
3149            self.observations.lock().unwrap().push_back(observation);
3150        }
3151    }
3152
3153    #[async_trait]
3154    impl LifecycleGithub for FakeGithubLifecycle {
3155        async fn register(
3156            &self,
3157            _target: &ScaleTarget,
3158            request: &JitRunnerRequest,
3159            _cancel: &CancelToken,
3160        ) -> Result<JitRegistration, JitRequestFailure> {
3161            self.registrations.fetch_add(1, Ordering::SeqCst);
3162            if let Some(store) = self.journal.lock().unwrap().as_ref() {
3163                let slots = store
3164                    .attempts()
3165                    .expect("the journal is readable")
3166                    .iter()
3167                    .filter_map(|attempt| attempt.workspace().slot_number())
3168                    .collect();
3169                self.registration_facts
3170                    .lock()
3171                    .unwrap()
3172                    .push(RegistrationFact {
3173                        leased_slots: slots,
3174                        work_folder: request.work_folder().to_string(),
3175                        runner_name: request.name().to_string(),
3176                    });
3177            }
3178            if let Some(terminal) = self.registration_failures.lock().unwrap().pop_front() {
3179                return Err(JitRequestFailure {
3180                    terminal,
3181                    reason: if terminal {
3182                        FailureReason::Other("GitHub refused JIT registration with 403".into())
3183                    } else {
3184                        FailureReason::JitRequestFailed
3185                    },
3186                    retry_after: None,
3187                });
3188            }
3189            self.remaining_runners.store(1, Ordering::SeqCst);
3190            Ok(JitRegistration::new(
3191                EncodedJitConfig::new(JIT),
3192                JitRunner {
3193                    id: 73,
3194                    name: request.name().to_string(),
3195                    os: "windows".into(),
3196                    status: "offline".into(),
3197                    busy: false,
3198                    runner_group_id: Some(1),
3199                    labels: request.labels().to_vec(),
3200                },
3201            ))
3202        }
3203
3204        async fn observe(
3205            &self,
3206            _target: &ScaleTarget,
3207            _attempt: AttemptId,
3208            _cancel: &CancelToken,
3209        ) -> LifecycleGithubObservation {
3210            let observation = self
3211                .observations
3212                .lock()
3213                .unwrap()
3214                .pop_front()
3215                .unwrap_or(LifecycleGithubObservation::not_registered());
3216            if observation.status == GithubRunnerObservation::NotRegistered {
3217                self.remaining_runners.store(0, Ordering::SeqCst);
3218            }
3219            observation
3220        }
3221
3222        async fn deregister(
3223            &self,
3224            _target: &ScaleTarget,
3225            runner_id: u64,
3226            _cancel: &CancelToken,
3227        ) -> bool {
3228            self.deregistrations.lock().unwrap().push(runner_id);
3229            if self.deregistration_fails.load(Ordering::SeqCst) {
3230                return false;
3231            }
3232            self.remaining_runners.store(0, Ordering::SeqCst);
3233            true
3234        }
3235    }
3236
3237    #[derive(Debug)]
3238    struct FakePackages {
3239        version: RunnerVersion,
3240        leases: Mutex<BTreeSet<AttemptId>>,
3241        materializations: AtomicUsize,
3242        materialization_failures: AtomicUsize,
3243        releases: AtomicUsize,
3244        prunes: AtomicUsize,
3245        prune_currents: Mutex<Vec<RunnerVersion>>,
3246    }
3247
3248    impl Default for FakePackages {
3249        fn default() -> Self {
3250            Self {
3251                version: RunnerVersion::parse("2.330.0").unwrap(),
3252                leases: Mutex::new(BTreeSet::new()),
3253                materializations: AtomicUsize::new(0),
3254                materialization_failures: AtomicUsize::new(0),
3255                releases: AtomicUsize::new(0),
3256                prunes: AtomicUsize::new(0),
3257                prune_currents: Mutex::new(Vec::new()),
3258            }
3259        }
3260    }
3261
3262    impl FakePackages {
3263        fn fail_materializations(&self, count: usize) {
3264            self.materialization_failures.store(count, Ordering::SeqCst);
3265        }
3266    }
3267
3268    #[async_trait]
3269    impl RuntimePackages for FakePackages {
3270        async fn materialize(
3271            &self,
3272            attempt: &RunnerAttempt,
3273        ) -> Result<RunnerVersion, FailureReason> {
3274            self.materializations.fetch_add(1, Ordering::SeqCst);
3275            if self
3276                .materialization_failures
3277                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
3278                    if left > 0 { Some(left - 1) } else { None }
3279                })
3280                .is_ok()
3281            {
3282                return Err(FailureReason::Other(
3283                    "runner package materialization failed transiently".into(),
3284                ));
3285            }
3286            fs::create_dir_all(attempt.runtime_path()).unwrap();
3287            fs::write(attempt.runtime_path().join("runner-package"), b"verified").unwrap();
3288            self.leases.lock().unwrap().insert(attempt.id);
3289            Ok(self.version.clone())
3290        }
3291
3292        fn release(&self, attempt: AttemptId) -> Result<(), FailureReason> {
3293            self.leases.lock().unwrap().remove(&attempt);
3294            self.releases.fetch_add(1, Ordering::SeqCst);
3295            Ok(())
3296        }
3297
3298        fn prune_obsolete_guarded(
3299            &self,
3300            _authority: PruneAuthority<'_>,
3301            current: &RunnerVersion,
3302            _attempts: &[RunnerAttempt],
3303        ) -> Result<(), FailureReason> {
3304            self.prunes.fetch_add(1, Ordering::SeqCst);
3305            self.prune_currents.lock().unwrap().push(current.clone());
3306            Ok(())
3307        }
3308    }
3309
3310    #[derive(Debug, Default)]
3311    struct FakeProcesses {
3312        alive: AtomicBool,
3313        completed_successfully: AtomicBool,
3314        spawns: AtomicUsize,
3315        spawn_failures: AtomicUsize,
3316        live_spawn_failure: AtomicBool,
3317        terminations: AtomicUsize,
3318        intent: AtomicBool,
3319        intent_failure: AtomicBool,
3320        actions: Mutex<Vec<&'static str>>,
3321        saw_secret: AtomicBool,
3322    }
3323
3324    impl FakeProcesses {
3325        fn fail_spawns(&self, count: usize) {
3326            self.spawn_failures.store(count, Ordering::SeqCst);
3327        }
3328
3329        fn fail_spawn_with_live_child(&self) {
3330            self.live_spawn_failure.store(true, Ordering::SeqCst);
3331        }
3332
3333        fn set_alive(&self, alive: bool) {
3334            self.alive.store(alive, Ordering::SeqCst);
3335        }
3336
3337        fn finish_successfully(&self) {
3338            self.completed_successfully.store(true, Ordering::SeqCst);
3339            self.alive.store(false, Ordering::SeqCst);
3340        }
3341
3342        fn fail_intent(&self) {
3343            self.intent_failure.store(true, Ordering::SeqCst);
3344        }
3345    }
3346
3347    impl ProcessSupervisor for FakeProcesses {
3348        fn spawn(
3349            &self,
3350            attempt: &RunnerAttempt,
3351            config: &EncodedJitConfig,
3352        ) -> Result<u32, ProcessStartFailure> {
3353            self.spawns.fetch_add(1, Ordering::SeqCst);
3354            // Model the production handoff on both paths: the sensitive file is
3355            // scoped to this call and absent when it returns.
3356            let handoff = RestrictiveHandoff::create(
3357                attempt.runtime_path(),
3358                SecretString::from(config.expose().to_owned()),
3359            )
3360            .unwrap();
3361            self.saw_secret
3362                .store(config.expose() == JIT, Ordering::SeqCst);
3363            let handoff_path = handoff.path().to_path_buf();
3364            let failing = self
3365                .spawn_failures
3366                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
3367                    if left > 0 { Some(left - 1) } else { None }
3368                })
3369                .is_ok();
3370            drop(handoff);
3371            assert!(!handoff_path.exists(), "handoff must be absent on return");
3372            if self.live_spawn_failure.swap(false, Ordering::SeqCst) {
3373                self.alive.store(true, Ordering::SeqCst);
3374                return Err(ProcessStartFailure::after_spawn_live(4242));
3375            }
3376            if failing {
3377                return Err(ProcessStartFailure::before_spawn(
3378                    FailureReason::ProcessStartFailed,
3379                ));
3380            }
3381            self.alive.store(true, Ordering::SeqCst);
3382            Ok(4242)
3383        }
3384
3385        fn is_alive(&self, _attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
3386            self.actions.lock().unwrap().push("observe_process");
3387            Ok(self.alive.load(Ordering::SeqCst))
3388        }
3389
3390        fn recovered_pid(&self, _attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
3391            Ok(self.alive.load(Ordering::SeqCst).then_some(4242))
3392        }
3393
3394        fn completed_successfully(&self, _attempt: &RunnerAttempt) -> bool {
3395            self.completed_successfully.load(Ordering::SeqCst)
3396        }
3397
3398        fn record_terminate_intent(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
3399            self.actions.lock().unwrap().push("terminate_intent");
3400            if self.intent_failure.load(Ordering::SeqCst) {
3401                return Err(FailureReason::Other(
3402                    "terminate intent directory sync failed".into(),
3403                ));
3404            }
3405            self.intent.store(true, Ordering::SeqCst);
3406            Ok(())
3407        }
3408
3409        fn has_terminate_intent(&self, _attempt: &RunnerAttempt) -> bool {
3410            self.intent.load(Ordering::SeqCst)
3411        }
3412
3413        fn terminate(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
3414            assert!(
3415                self.intent.load(Ordering::SeqCst),
3416                "the durable intent must exist before signalling"
3417            );
3418            self.actions.lock().unwrap().push("terminate");
3419            self.terminations.fetch_add(1, Ordering::SeqCst);
3420            self.alive.store(false, Ordering::SeqCst);
3421            Ok(())
3422        }
3423    }
3424
3425    #[derive(Debug, Default)]
3426    struct FakeDemand {
3427        answers: Mutex<VecDeque<bool>>,
3428    }
3429
3430    impl FakeDemand {
3431        fn answering(answers: impl IntoIterator<Item = bool>) -> Self {
3432            Self {
3433                answers: Mutex::new(answers.into_iter().collect()),
3434            }
3435        }
3436    }
3437
3438    #[async_trait]
3439    impl DemandPersistence for FakeDemand {
3440        async fn persists(&self, _policy: PolicyId) -> bool {
3441            self.answers.lock().unwrap().pop_front().unwrap_or(true)
3442        }
3443    }
3444
3445    #[derive(Debug, Default)]
3446    struct FakeDelay(Mutex<Vec<Duration>>);
3447
3448    #[async_trait]
3449    impl RetryDelay for FakeDelay {
3450        async fn wait(&self, duration: Duration) {
3451            self.0.lock().unwrap().push(duration);
3452        }
3453    }
3454
3455    struct Harness {
3456        _root: tempfile::TempDir,
3457        app_paths: runner_manager_platform::paths::AppPaths,
3458        launcher: LifecycleLauncher,
3459        demand: Arc<dyn DemandPersistence>,
3460        store: Arc<SqliteStore>,
3461        github: Arc<FakeGithubLifecycle>,
3462        packages: Arc<FakePackages>,
3463        processes: Arc<FakeProcesses>,
3464        clock: Arc<FakeClock>,
3465        events: Arc<AttemptEventLog>,
3466        reconcile_events: Arc<crate::reconcile::EventLog>,
3467        delay: Arc<FakeDelay>,
3468        host: runner_manager_domain::model::Host,
3469        policy: ScalePolicy,
3470        allocation_lock: InProcessAllocationLock,
3471        /// The repository persistent root, once one is configured.
3472        workspace_root: Option<LocalAbsolutePath>,
3473    }
3474
3475    impl Harness {
3476        fn new(github: FakeGithubLifecycle, demand: Arc<dyn DemandPersistence>) -> Self {
3477            let root = tempfile::tempdir().unwrap();
3478            let paths = runner_manager_platform::paths::AppPaths::rooted_at(root.path());
3479            paths.create_all().unwrap();
3480            let policy = fixtures::policy()
3481                .repository("octo/repo")
3482                .autoscale("home", 2)
3483                .active()
3484                .build();
3485            let host = fixtures::host().build();
3486            let store = Arc::new(SqliteStore::open_in_memory().unwrap());
3487            store.put_host(&host).unwrap();
3488            let github = Arc::new(github);
3489            let packages = Arc::new(FakePackages::default());
3490            let processes = Arc::new(FakeProcesses::default());
3491            let clock = Arc::new(FakeClock::default());
3492            let events = Arc::new(AttemptEventLog::default());
3493            let reconcile_events = Arc::new(crate::reconcile::EventLog::new());
3494            let delay = Arc::new(FakeDelay::default());
3495            let ports = LifecyclePorts {
3496                store: Arc::clone(&store) as Arc<dyn Store>,
3497                github: Arc::clone(&github) as Arc<dyn LifecycleGithub>,
3498                packages: Arc::clone(&packages) as Arc<dyn RuntimePackages>,
3499                processes: Arc::clone(&processes) as Arc<dyn ProcessSupervisor>,
3500                clock: Arc::clone(&clock) as Arc<dyn Clock>,
3501                demand: Arc::clone(&demand),
3502                delay: Arc::clone(&delay) as Arc<dyn RetryDelay>,
3503                events: Arc::clone(&events) as Arc<dyn AttemptEventSink>,
3504                reconcile_events: Arc::clone(&reconcile_events) as Arc<dyn EventSink>,
3505            };
3506            let launcher = Self::launcher_over(policy.host_id, &paths, ports);
3507            Self {
3508                _root: root,
3509                app_paths: paths,
3510                launcher,
3511                demand,
3512                store,
3513                github,
3514                packages,
3515                processes,
3516                clock,
3517                events,
3518                reconcile_events,
3519                delay,
3520                host,
3521                policy,
3522                allocation_lock: InProcessAllocationLock::new(),
3523                workspace_root: None,
3524            }
3525        }
3526
3527        /// Put disposable attempts under a host root of this harness's own.
3528        ///
3529        /// Without it the launcher resolves the *platform* default, which on
3530        /// Windows is `%SystemDrive%\rman` — a real directory on the machine
3531        /// running the suite. Every test added by `c2` places its files inside
3532        /// its own temporary directory instead.
3533        fn with_host_runner_root(mut self) -> Self {
3534            let host_root = self.host_root();
3535            fs::create_dir_all(&host_root).unwrap();
3536            self.host.runner_root_override = Some(
3537                LocalAbsolutePath::new(host_root.to_str().expect("a UTF-8 temporary path"))
3538                    .expect("a local absolute host root"),
3539            );
3540            self.store.put_host(&self.host).unwrap();
3541            self
3542        }
3543
3544        /// Opt this harness's repository into a persistent workspace (D4).
3545        fn with_persistent_workspace(mut self, capacity: u16) -> Self {
3546            self = self.with_host_runner_root();
3547            let root = self._root.path().join("persist");
3548            let root = LocalAbsolutePath::new(root.to_str().expect("a UTF-8 temporary path"))
3549                .expect("a local absolute workspace root");
3550            self.policy = fixtures::policy()
3551                .repository("octo/repo")
3552                .autoscale("home", capacity)
3553                .active()
3554                .build();
3555            self.policy
3556                .set_workspace_policy(
3557                    WorkspacePolicy::persistent(root.clone(), TargetScope::Repository)
3558                        .expect("a repository may be persistent"),
3559                )
3560                .expect("a repository may be persistent");
3561            self.workspace_root = Some(root);
3562            // The journal's copy, so that cleanup's cross-check against a
3563            // surviving policy is exercised rather than skipped.
3564            self.store.insert_policy(&self.policy).unwrap();
3565            self
3566        }
3567
3568        fn workspace_root(&self) -> &LocalAbsolutePath {
3569            self.workspace_root
3570                .as_ref()
3571                .expect("this harness configured a persistent workspace")
3572        }
3573
3574        fn slot_path(&self, slot: u16) -> PathBuf {
3575            self.workspace_root().as_path().join(format!("s{slot}"))
3576        }
3577
3578        fn host_root(&self) -> PathBuf {
3579            self._root.path().join("host-root")
3580        }
3581
3582        fn attempt(&self, id: AttemptId) -> RunnerAttempt {
3583            self.store
3584                .attempt(id)
3585                .unwrap()
3586                .expect("the attempt is journalled")
3587        }
3588
3589        /// Conclude an attempt and run the real cleanup over it.
3590        fn conclude(&self, id: AttemptId) -> RunnerAttempt {
3591            let mut attempt = self.attempt(id);
3592            attempt
3593                .conclude(
3594                    AttemptOutcome::failed(FailureReason::ProcessExitedUnexpectedly),
3595                    self.clock.now(),
3596                )
3597                .unwrap();
3598            self.store.record_attempt(&attempt).unwrap();
3599            attempt
3600        }
3601
3602        async fn cleanup_retaining_work(&self, id: AttemptId) {
3603            self.conclude(id);
3604            self.launcher
3605                .clean(id)
3606                .await
3607                .expect("the slot is scrubbed and the lease released");
3608        }
3609
3610        /// The launcher configuration every launcher in this harness shares, so
3611        /// that the one a restart mints cannot drift from the original.
3612        fn launcher_over(
3613            host: HostId,
3614            paths: &runner_manager_platform::paths::AppPaths,
3615            ports: LifecyclePorts,
3616        ) -> LifecycleLauncher {
3617            LifecycleLauncher::new(
3618                host,
3619                paths.clone(),
3620                paths.logs_dir(),
3621                1,
3622                RecoveryTimeouts::new(
3623                    Elapsed::seconds(10),
3624                    Elapsed::seconds(10),
3625                    Elapsed::seconds(10),
3626                ),
3627                RetryPolicy::bounded(3, Duration::from_millis(10), Duration::from_millis(25)),
3628                ports,
3629            )
3630        }
3631
3632        /// The same journal, the same directories, a launcher that remembers
3633        /// nothing — which is what a daemon restart is.
3634        fn restart(&self) -> LifecycleLauncher {
3635            Self::launcher_over(
3636                self.policy.host_id,
3637                &self.app_paths,
3638                LifecyclePorts {
3639                    store: Arc::clone(&self.store) as Arc<dyn Store>,
3640                    github: Arc::clone(&self.github) as Arc<dyn LifecycleGithub>,
3641                    packages: Arc::clone(&self.packages) as Arc<dyn RuntimePackages>,
3642                    processes: Arc::clone(&self.processes) as Arc<dyn ProcessSupervisor>,
3643                    clock: Arc::clone(&self.clock) as Arc<dyn Clock>,
3644                    demand: Arc::clone(&self.demand),
3645                    delay: Arc::clone(&self.delay) as Arc<dyn RetryDelay>,
3646                    events: Arc::clone(&self.events) as Arc<dyn AttemptEventSink>,
3647                    reconcile_events: Arc::clone(&self.reconcile_events) as Arc<dyn EventSink>,
3648                },
3649            )
3650        }
3651
3652        async fn ready(&self) {
3653            self.launcher
3654                .recover_startup(std::slice::from_ref(&self.policy))
3655                .await
3656                .unwrap();
3657        }
3658
3659        async fn launch(&self) -> RunnerAttempt {
3660            self.launch_result().await.unwrap()
3661        }
3662
3663        async fn launch_result(&self) -> Result<RunnerAttempt, LaunchFailure> {
3664            let guard = self.allocation_lock.acquire().await.unwrap();
3665            self.launcher
3666                .launch(LaunchRequest {
3667                    host: &self.host,
3668                    policy: &self.policy,
3669                    allocation_guard: &guard,
3670                })
3671                .await
3672        }
3673
3674        fn only_attempt(&self) -> RunnerAttempt {
3675            self.store.attempts().unwrap().into_iter().next().unwrap()
3676        }
3677    }
3678
3679    /// The wiring the three-hour outage needed and did not have.
3680    ///
3681    /// A root that refuses a launch does so before `record_allocation`, so no
3682    /// attempt row carries it, and the daemon's log scrubs the paths out of the
3683    /// sentence. The record this asserts is the only surface left, and
3684    /// `service status` reads it -- so if this wiring is ever dropped, the
3685    /// failure goes back to reading `runner_start_failed reason=other` once per
3686    /// poll and nothing else.
3687    #[tokio::test]
3688    async fn a_root_that_refuses_a_launch_is_recorded_and_cleared_when_one_succeeds() {
3689        use runner_manager_platform::service::{clear_runner_root_refusal, runner_root_refusals};
3690
3691        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
3692            .with_host_runner_root();
3693        harness.ready().await;
3694
3695        // A root under two directories that do not exist: refused by the
3696        // preflight, for a reason that has nothing to do with this platform, so
3697        // the assertion holds on all three.
3698        let unusable = harness
3699            ._root
3700            .path()
3701            .join("absent")
3702            .join("deeper")
3703            .join("runners");
3704        let mut host = harness.host.clone();
3705        host.runner_root_override = Some(
3706            LocalAbsolutePath::new(unusable.to_str().expect("a UTF-8 temporary path"))
3707                .expect("a local absolute host root"),
3708        );
3709        harness.store.put_host(&host).unwrap();
3710
3711        let failure = harness
3712            .launch_result()
3713            .await
3714            .expect_err("a root whose parents are missing cannot hold a runner");
3715        assert!(
3716            matches!(failure.reason, FailureReason::Other(_)),
3717            "{failure:?}"
3718        );
3719
3720        let refusals = runner_root_refusals(&harness.app_paths).expect("readable");
3721        let refusal = refusals
3722            .first()
3723            .expect("the refusal reached the one surface that can hold it");
3724        assert_eq!(refusal.policy, harness.policy.id.to_string());
3725        assert_eq!(refusal.kind, "missing_parents");
3726        assert!(
3727            refusal.root.contains("runners") && refusal.detail.contains("runners"),
3728            "the directory must be named in full: {refusal:?}"
3729        );
3730
3731        // And a root that works clears it, so a host that has been fixed stops
3732        // reporting a fault it no longer has.
3733        harness.store.put_host(&harness.host).unwrap();
3734        harness.launch().await;
3735        assert!(
3736            runner_root_refusals(&harness.app_paths)
3737                .expect("readable")
3738                .is_empty(),
3739            "a successful placement clears that policy's record"
3740        );
3741
3742        clear_runner_root_refusal(&harness.app_paths, &harness.policy.id.to_string())
3743            .expect("cleanup");
3744    }
3745
3746    #[tokio::test]
3747    async fn a_job_walks_every_state_and_cleans_every_artifact() {
3748        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
3749        harness.ready().await;
3750        let started = harness.launch().await;
3751        assert_eq!(started.state(), AttemptState::Starting);
3752        assert_eq!(read_runner_id(started.runtime_path()), Some(73));
3753
3754        harness
3755            .github
3756            .observe(GithubRunnerObservation::Registered { busy: false });
3757        harness.launcher.supervise(&harness.policy).await.unwrap();
3758        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
3759
3760        harness
3761            .github
3762            .observe(GithubRunnerObservation::Registered { busy: true });
3763        harness.launcher.supervise(&harness.policy).await.unwrap();
3764        assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
3765
3766        harness.processes.finish_successfully();
3767        harness
3768            .github
3769            .observe(GithubRunnerObservation::NotRegistered);
3770        harness.launcher.supervise(&harness.policy).await.unwrap();
3771        let cleaned = harness.only_attempt();
3772        assert_eq!(cleaned.state(), AttemptState::Cleaned);
3773        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
3774        assert!(!started.runtime_path().exists());
3775        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
3776        assert_eq!(harness.github.remaining_runners.load(Ordering::SeqCst), 0);
3777
3778        let states: Vec<_> = harness
3779            .events
3780            .events()
3781            .into_iter()
3782            .filter_map(|event| match event {
3783                AttemptEvent::State { state, .. } => Some(state),
3784                _ => None,
3785            })
3786            .collect();
3787        assert_eq!(
3788            states,
3789            vec![
3790                AttemptState::Allocated,
3791                AttemptState::JitReceived,
3792                AttemptState::Starting,
3793                AttemptState::Idle,
3794                AttemptState::Busy,
3795                AttemptState::Finished,
3796                AttemptState::Cleaned,
3797            ]
3798        );
3799    }
3800
3801    #[tokio::test]
3802    async fn an_idle_exit_is_not_a_failure_in_the_journal_or_events() {
3803        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
3804        harness.ready().await;
3805        let started = harness.launch().await;
3806        harness
3807            .github
3808            .observe(GithubRunnerObservation::Registered { busy: false });
3809        harness.launcher.supervise(&harness.policy).await.unwrap();
3810        harness.clock.advance_secs(11);
3811        harness.processes.set_alive(false);
3812        harness
3813            .github
3814            .observe(GithubRunnerObservation::NotRegistered);
3815        harness.launcher.supervise(&harness.policy).await.unwrap();
3816
3817        let cleaned = harness.only_attempt();
3818        assert!(cleaned.outcome().unwrap().is_idle_exit());
3819        assert!(!cleaned.outcome().unwrap().is_failure());
3820        assert!(!started.runtime_path().exists());
3821        assert!(
3822            harness
3823                .reconcile_events
3824                .events()
3825                .iter()
3826                .any(|event| matches!(
3827                    event,
3828                    LifecycleEvent::AttemptCleaned {
3829                        outcome: OutcomeKind::IdleExit,
3830                        ..
3831                    }
3832                ))
3833        );
3834        assert!(!harness.events.events().iter().any(|event| matches!(
3835            event,
3836            AttemptEvent::Concluded {
3837                outcome: OutcomeKind::Failed,
3838                ..
3839            }
3840        )));
3841    }
3842
3843    #[tokio::test]
3844    async fn handoff_is_absent_after_success_and_every_failed_spawn_retry() {
3845        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
3846        harness.processes.fail_spawns(2);
3847        harness.ready().await;
3848        let attempt = harness.launch().await;
3849        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 3);
3850        assert!(harness.processes.saw_secret.load(Ordering::SeqCst));
3851        let names: Vec<_> = fs::read_dir(attempt.runtime_path())
3852            .unwrap()
3853            .map(|entry| entry.unwrap().file_name())
3854            .collect();
3855        assert!(
3856            names.iter().all(|name| {
3857                !name
3858                    .to_string_lossy()
3859                    .starts_with(RestrictiveHandoff::NAME_PREFIX)
3860            }),
3861            "JIT artifact survived: {names:?}"
3862        );
3863        assert_eq!(
3864            *harness.delay.0.lock().unwrap(),
3865            vec![Duration::from_millis(10), Duration::from_millis(20)]
3866        );
3867    }
3868
3869    #[tokio::test]
3870    async fn jit_retry_stops_with_demand_and_a_terminal_403_never_retries() {
3871        let gone = Harness::new(
3872            FakeGithubLifecycle::default().fail(false),
3873            Arc::new(FakeDemand::answering([false])),
3874        );
3875        gone.ready().await;
3876        assert!(gone.launch_result().await.is_err());
3877        assert_eq!(gone.github.registrations.load(Ordering::SeqCst), 1);
3878        assert!(gone.delay.0.lock().unwrap().is_empty());
3879
3880        let forbidden = Harness::new(
3881            FakeGithubLifecycle::default().fail(true),
3882            Arc::new(PersistentDemand),
3883        );
3884        forbidden.ready().await;
3885        assert!(forbidden.launch_result().await.is_err());
3886        assert_eq!(forbidden.github.registrations.load(Ordering::SeqCst), 1);
3887        assert!(forbidden.delay.0.lock().unwrap().is_empty());
3888        assert!(matches!(
3889            forbidden.only_attempt().outcome(),
3890            Some(AttemptOutcome::Failed {
3891                reason: FailureReason::Other(action)
3892            }) if action.contains("403")
3893        ));
3894
3895        let transient = Harness::new(
3896            FakeGithubLifecycle::default().fail(false).fail(false),
3897            Arc::new(PersistentDemand),
3898        );
3899        transient.ready().await;
3900        transient.launch().await;
3901        assert_eq!(transient.github.registrations.load(Ordering::SeqCst), 3);
3902        assert_eq!(
3903            *transient.delay.0.lock().unwrap(),
3904            vec![Duration::from_millis(10), Duration::from_millis(20)]
3905        );
3906    }
3907
3908    /// The layout has to leave room for what the runner writes underneath it.
3909    ///
3910    /// Windows refuses a path over `MAX_PATH`, and this product's own CI hit
3911    /// that: 264 characters against a limit of 260, failing three checkout
3912    /// retries with `Filename too long`. The two identifiers in the old layout
3913    /// cost 74 characters between them for no benefit -- an attempt id is
3914    /// unique on its own.
3915    #[test]
3916    fn a_workspace_leaves_room_for_the_deepest_path_a_checkout_writes() {
3917        const MAX_PATH: usize = 260;
3918        // The real root on the machine this was found on.
3919        let root = r"C:\Users\IvanD\AppData\Local\IvanMurzak\runner-manager\data\runtime";
3920        // What `actions/checkout` writes at its deepest: the work directory,
3921        // the repository named twice, and a pack keep-file with a 40-character
3922        // object name.
3923        let repo = "GitHub-Runner-Scaler-UI";
3924        let deepest = format!(
3925            r"_work\{repo}\{repo}\.git\objects\pack\pack-{}.keep",
3926            "0".repeat(40)
3927        );
3928
3929        let name = workspace_name(AttemptId::new_random());
3930        assert_eq!(name.len(), WORKSPACE_NAME_LEN, "{name}");
3931        assert!(
3932            name.chars().all(|c| c.is_ascii_hexdigit()),
3933            "a directory name must not carry the identifier's dashes: {name}"
3934        );
3935
3936        let full = format!(r"{root}\{name}\{deepest}");
3937        assert!(
3938            full.len() < MAX_PATH,
3939            "the deepest path a checkout writes must fit: {} characters, limit {MAX_PATH}",
3940            full.len()
3941        );
3942
3943        // The discriminator: the layout this replaced does not fit, so a test
3944        // that passed for both would be proving nothing.
3945        let old = format!(
3946            r"{root}\{}\{}\{deepest}",
3947            PolicyId::new_random(),
3948            AttemptId::new_random()
3949        );
3950        assert!(
3951            old.len() > MAX_PATH,
3952            "the old layout is supposed to be the thing that did not fit: {} characters",
3953            old.len()
3954        );
3955    }
3956
3957    #[tokio::test]
3958    async fn two_attempts_never_share_a_workspace_even_after_failure() {
3959        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
3960        harness.ready().await;
3961        let first = harness.launch().await;
3962        fs::write(first.runtime_path().join("hostile-leftover"), b"first job").unwrap();
3963        harness
3964            .github
3965            .observe(GithubRunnerObservation::Registered { busy: false });
3966        harness.launcher.supervise(&harness.policy).await.unwrap();
3967        harness.clock.advance_secs(11);
3968        harness.processes.set_alive(false);
3969        harness
3970            .github
3971            .observe(GithubRunnerObservation::NotRegistered);
3972        harness.launcher.supervise(&harness.policy).await.unwrap();
3973        assert!(!first.runtime_path().exists());
3974
3975        let second = harness.launch().await;
3976        assert_ne!(first.runtime_path(), second.runtime_path());
3977        assert!(!second.runtime_path().join("hostile-leftover").exists());
3978
3979        fs::write(
3980            second.runtime_path().join("hostile-on-failure"),
3981            b"second job",
3982        )
3983        .unwrap();
3984        harness.processes.set_alive(false);
3985        harness
3986            .github
3987            .observe(GithubRunnerObservation::NotRegistered);
3988        harness.launcher.supervise(&harness.policy).await.unwrap();
3989        assert!(
3990            !second.runtime_path().exists(),
3991            "failed workspace was retained"
3992        );
3993    }
3994
3995    #[tokio::test]
3996    async fn a_runner_that_never_gets_a_job_is_stopped_deregistered_and_not_replaced() {
3997        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
3998        harness.ready().await;
3999        let attempt = harness.launch().await;
4000
4001        // Registered and waiting, which is where it stays: the fake keeps
4002        // answering the same observation, exactly as GitHub does for a runner
4003        // nobody assigns work to.
4004        harness
4005            .github
4006            .observe(GithubRunnerObservation::Registered { busy: false });
4007        harness.launcher.supervise(&harness.policy).await.unwrap();
4008        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
4009
4010        // One second inside the ten-second idle timeout nothing happens, which
4011        // is what keeps this from being a test that would pass on any clock.
4012        harness.clock.advance_secs(9);
4013        harness
4014            .github
4015            .observe(GithubRunnerObservation::Registered { busy: false });
4016        let none_yet = harness.launcher.supervise(&harness.policy).await.unwrap();
4017        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
4018        assert!(none_yet.is_empty());
4019        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 0);
4020
4021        // Past it, the agent ends the runner itself.
4022        harness.clock.advance_secs(1);
4023        harness
4024            .github
4025            .observe(GithubRunnerObservation::Registered { busy: false });
4026        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4027
4028        let concluded = harness.store.attempt(attempt.id).unwrap().unwrap();
4029        assert_eq!(
4030            concluded.outcome(),
4031            Some(&AttemptOutcome::ExitedIdleWithoutWork),
4032            "a surplus runner did not fail; recording one as a failure sends an operator \
4033             hunting a fault that does not exist"
4034        );
4035        assert_eq!(concluded.state(), AttemptState::Cleaned);
4036        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 1);
4037        assert!(!attempt.runtime_path().exists());
4038
4039        // The registration goes with it. Without this the runner stays listed
4040        // in the target's runner settings after the process it named is gone.
4041        assert_eq!(
4042            *harness.github.deregistrations.lock().unwrap(),
4043            vec![73],
4044            "the attempt's own runner id, deleted exactly once"
4045        );
4046
4047        // And nothing is started in its place: the work it was launched for went
4048        // elsewhere, so a replacement would rebuild it every idle timeout.
4049        assert!(
4050            replacements.is_empty(),
4051            "a surplus exit must not request a replacement"
4052        );
4053    }
4054
4055    #[tokio::test]
4056    async fn a_registration_github_will_not_delete_still_concludes_the_attempt() {
4057        // The delete is best-effort by construction: the process is gone and the
4058        // slot has to come back. Holding the conclusion until GitHub cooperates
4059        // would leak a capacity slot on every unreachable moment.
4060        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4061        harness.ready().await;
4062        let attempt = harness.launch().await;
4063        harness
4064            .github
4065            .observe(GithubRunnerObservation::Registered { busy: false });
4066        harness.launcher.supervise(&harness.policy).await.unwrap();
4067
4068        harness
4069            .github
4070            .deregistration_fails
4071            .store(true, Ordering::SeqCst);
4072        harness.clock.advance_secs(11);
4073        harness
4074            .github
4075            .observe(GithubRunnerObservation::Registered { busy: false });
4076        harness.launcher.supervise(&harness.policy).await.unwrap();
4077
4078        assert_eq!(
4079            *harness.github.deregistrations.lock().unwrap(),
4080            vec![73],
4081            "the delete was attempted"
4082        );
4083        let concluded = harness.store.attempt(attempt.id).unwrap().unwrap();
4084        assert_eq!(
4085            concluded.outcome(),
4086            Some(&AttemptOutcome::ExitedIdleWithoutWork),
4087            "the attempt concluded anyway"
4088        );
4089        assert_eq!(concluded.state(), AttemptState::Cleaned);
4090        assert!(!attempt.runtime_path().exists());
4091    }
4092
4093    #[tokio::test]
4094    async fn exit_before_acceptance_returns_replacement_intent_without_launching() {
4095        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4096        harness.ready().await;
4097        let first = harness.launch().await;
4098        harness.processes.set_alive(false);
4099        harness
4100            .github
4101            .observe(GithubRunnerObservation::NotRegistered);
4102        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4103        let failed = harness.store.attempt(first.id).unwrap().unwrap();
4104        assert!(matches!(
4105            failed.outcome(),
4106            Some(AttemptOutcome::Failed {
4107                reason: FailureReason::ProcessExitedUnexpectedly
4108            })
4109        ));
4110        assert!(!first.runtime_path().exists());
4111
4112        assert_eq!(
4113            replacements,
4114            vec![ReplacementIntent {
4115                policy: harness.policy.id,
4116                previous_attempt: first.id,
4117                operation: "exit_before_acceptance_replacement",
4118            }]
4119        );
4120        assert_eq!(harness.store.attempts().unwrap().len(), 1);
4121        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
4122        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
4123        assert!(harness.delay.0.lock().unwrap().is_empty());
4124    }
4125
4126    #[tokio::test]
4127    async fn expired_jit_is_removed_and_does_not_reregister_after_demand_disappears() {
4128        let harness = Harness::new(
4129            FakeGithubLifecycle::default(),
4130            Arc::new(FakeDemand::answering([false])),
4131        );
4132        let id = AttemptId::new_random();
4133        let runtime = harness
4134            .launcher
4135            .app_paths
4136            .runtime_dir()
4137            .join(harness.policy.id.to_string())
4138            .join(id.to_string());
4139        fs::create_dir_all(&runtime).unwrap();
4140        let mut attempt =
4141            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4142        attempt.jit_received(harness.clock.now()).unwrap();
4143        harness.store.record_attempt(&attempt).unwrap();
4144        harness.clock.advance_secs(11);
4145        let replacements = harness
4146            .launcher
4147            .recover_startup(std::slice::from_ref(&harness.policy))
4148            .await
4149            .unwrap();
4150        assert_eq!(
4151            replacements,
4152            vec![ReplacementIntent {
4153                policy: harness.policy.id,
4154                previous_attempt: id,
4155                operation: "jit_expired_replacement",
4156            }]
4157        );
4158
4159        let cleaned = harness.store.attempt(id).unwrap().unwrap();
4160        assert_eq!(cleaned.state(), AttemptState::Cleaned);
4161        assert!(matches!(
4162            cleaned.outcome(),
4163            Some(AttemptOutcome::Failed {
4164                reason: FailureReason::JitExpired
4165            })
4166        ));
4167        assert!(!runtime.exists());
4168        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
4169        assert!(harness.delay.0.lock().unwrap().is_empty());
4170    }
4171
4172    #[tokio::test]
4173    async fn expired_jit_returns_intent_but_never_launches_inside_lifecycle() {
4174        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4175        let id = AttemptId::new_random();
4176        let runtime = harness
4177            .launcher
4178            .app_paths
4179            .runtime_dir()
4180            .join("expired-with-demand");
4181        fs::create_dir_all(&runtime).unwrap();
4182        let mut attempt =
4183            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4184        attempt.jit_received(harness.clock.now()).unwrap();
4185        harness.store.record_attempt(&attempt).unwrap();
4186        harness.clock.advance_secs(11);
4187        let replacements = harness
4188            .launcher
4189            .recover_startup(std::slice::from_ref(&harness.policy))
4190            .await
4191            .unwrap();
4192
4193        let attempts = harness.store.attempts().unwrap();
4194        assert_eq!(attempts.len(), 1);
4195        assert_eq!(
4196            attempts
4197                .iter()
4198                .find(|attempt| attempt.id == id)
4199                .unwrap()
4200                .state(),
4201            AttemptState::Cleaned
4202        );
4203        assert_eq!(
4204            replacements,
4205            vec![ReplacementIntent {
4206                policy: harness.policy.id,
4207                previous_attempt: id,
4208                operation: "jit_expired_replacement",
4209            }]
4210        );
4211        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
4212        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
4213        assert!(harness.delay.0.lock().unwrap().is_empty());
4214    }
4215
4216    #[tokio::test]
4217    async fn package_materialization_retries_are_bounded_and_demand_adjacent() {
4218        let persistent = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4219        persistent.packages.fail_materializations(2);
4220        persistent.ready().await;
4221        persistent.launch().await;
4222        assert_eq!(
4223            persistent.packages.materializations.load(Ordering::SeqCst),
4224            3
4225        );
4226        assert_eq!(
4227            *persistent.delay.0.lock().unwrap(),
4228            vec![Duration::from_millis(10), Duration::from_millis(20)]
4229        );
4230
4231        let gone_before_wait = Harness::new(
4232            FakeGithubLifecycle::default(),
4233            Arc::new(FakeDemand::answering([false])),
4234        );
4235        gone_before_wait.packages.fail_materializations(3);
4236        gone_before_wait.ready().await;
4237        assert!(gone_before_wait.launch_result().await.is_err());
4238        assert_eq!(
4239            gone_before_wait
4240                .packages
4241                .materializations
4242                .load(Ordering::SeqCst),
4243            1
4244        );
4245        assert!(gone_before_wait.delay.0.lock().unwrap().is_empty());
4246
4247        let gone_during_wait = Harness::new(
4248            FakeGithubLifecycle::default(),
4249            Arc::new(FakeDemand::answering([true, false])),
4250        );
4251        gone_during_wait.packages.fail_materializations(3);
4252        gone_during_wait.ready().await;
4253        assert!(gone_during_wait.launch_result().await.is_err());
4254        assert_eq!(
4255            gone_during_wait
4256                .packages
4257                .materializations
4258                .load(Ordering::SeqCst),
4259            1
4260        );
4261        assert_eq!(
4262            *gone_during_wait.delay.0.lock().unwrap(),
4263            vec![Duration::from_millis(10)]
4264        );
4265    }
4266
4267    #[tokio::test]
4268    async fn replacement_is_intent_only_and_never_launches_inside_lifecycle() {
4269        let harness = Harness::new(
4270            FakeGithubLifecycle::default(),
4271            Arc::new(FakeDemand::answering([true, false])),
4272        );
4273        harness.ready().await;
4274        let first = harness.launch().await;
4275        harness.processes.set_alive(false);
4276        harness
4277            .github
4278            .observe(GithubRunnerObservation::NotRegistered);
4279        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4280
4281        assert_eq!(harness.store.attempts().unwrap().len(), 1);
4282        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
4283        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
4284        assert!(harness.delay.0.lock().unwrap().is_empty());
4285        assert_eq!(
4286            replacements,
4287            vec![ReplacementIntent {
4288                policy: harness.policy.id,
4289                previous_attempt: first.id,
4290                operation: "exit_before_acceptance_replacement",
4291            }]
4292        );
4293        assert_eq!(
4294            harness.store.attempt(first.id).unwrap().unwrap().state(),
4295            AttemptState::Cleaned
4296        );
4297    }
4298
4299    #[tokio::test]
4300    async fn startup_adopts_a_live_process_and_refuses_launch_before_recovery() {
4301        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4302        let before = harness.launch_result().await;
4303        assert!(before.is_err());
4304        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
4305
4306        let id = AttemptId::new_random();
4307        let runtime = harness.launcher.app_paths.runtime_dir().join("adopt");
4308        fs::create_dir_all(&runtime).unwrap();
4309        let mut attempt =
4310            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
4311        attempt.jit_received(harness.clock.now()).unwrap();
4312        attempt.started(4242, harness.clock.now()).unwrap();
4313        harness.store.record_attempt(&attempt).unwrap();
4314        harness.processes.set_alive(true);
4315        harness
4316            .github
4317            .observe(GithubRunnerObservation::NotRegistered);
4318        let replacements = harness
4319            .launcher
4320            .recover_startup(std::slice::from_ref(&harness.policy))
4321            .await
4322            .unwrap();
4323        assert!(replacements.is_empty());
4324        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
4325        assert!(
4326            harness
4327                .events
4328                .events()
4329                .contains(&AttemptEvent::Adopted { attempt: id })
4330        );
4331    }
4332
4333    #[tokio::test]
4334    async fn spawn_before_starting_crash_recovers_pid_then_completes_and_cleans() {
4335        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4336        let id = AttemptId::new_random();
4337        let runtime = harness
4338            .launcher
4339            .app_paths
4340            .runtime_dir()
4341            .join("spawn-before-starting");
4342        fs::create_dir_all(&runtime).unwrap();
4343        let mut attempt =
4344            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4345        attempt.jit_received(harness.clock.now()).unwrap();
4346        harness.store.record_attempt(&attempt).unwrap();
4347        harness.processes.set_alive(true);
4348        harness
4349            .github
4350            .observe(GithubRunnerObservation::Registered { busy: true });
4351
4352        let replacements = harness
4353            .launcher
4354            .recover_startup(std::slice::from_ref(&harness.policy))
4355            .await
4356            .unwrap();
4357        assert!(replacements.is_empty());
4358        let recovered = harness.store.attempt(id).unwrap().unwrap();
4359        assert_eq!(recovered.state(), AttemptState::Busy);
4360        assert_eq!(recovered.process_id(), Some(4242));
4361        assert_eq!(recovered.github_runner_id(), Some(73));
4362        let events = harness.events.events();
4363        let starting = events
4364            .iter()
4365            .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Starting } if *attempt == id))
4366            .unwrap();
4367        let busy = events
4368            .iter()
4369            .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Busy } if *attempt == id))
4370            .unwrap();
4371        assert!(starting < busy, "recovery skipped a legal edge: {events:?}");
4372
4373        harness.processes.finish_successfully();
4374        harness
4375            .github
4376            .observe(GithubRunnerObservation::NotRegistered);
4377        assert!(
4378            harness
4379                .launcher
4380                .supervise(&harness.policy)
4381                .await
4382                .unwrap()
4383                .is_empty()
4384        );
4385        let cleaned = harness.store.attempt(id).unwrap().unwrap();
4386        assert_eq!(cleaned.state(), AttemptState::Cleaned);
4387        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
4388        assert!(!runtime.exists());
4389    }
4390
4391    #[tokio::test]
4392    async fn failed_post_spawn_stop_keeps_capacity_until_supervision_proves_death() {
4393        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4394        harness.processes.fail_spawn_with_live_child();
4395        harness.ready().await;
4396        assert!(harness.launch_result().await.is_err());
4397
4398        let attempt = harness.only_attempt();
4399        assert_eq!(attempt.state(), AttemptState::Starting);
4400        assert_eq!(attempt.process_id(), Some(4242));
4401        assert!(attempt.outcome().is_none());
4402        assert!(attempt.state().counts_against_capacity());
4403        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
4404        assert!(harness.delay.0.lock().unwrap().is_empty());
4405
4406        harness.processes.set_alive(false);
4407        harness
4408            .github
4409            .observe(GithubRunnerObservation::NotRegistered);
4410        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4411        assert_eq!(replacements.len(), 1);
4412        assert_eq!(
4413            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
4414            AttemptState::Cleaned
4415        );
4416    }
4417
4418    #[tokio::test]
4419    async fn remote_runner_identity_closes_both_sides_of_the_registration_crash_boundary() {
4420        for sidecar_already_present in [false, true] {
4421            let harness = Harness::new(
4422                FakeGithubLifecycle::default(),
4423                Arc::new(FakeDemand::answering([false])),
4424            );
4425            let id = AttemptId::new_random();
4426            let runtime =
4427                harness
4428                    .launcher
4429                    .app_paths
4430                    .runtime_dir()
4431                    .join(if sidecar_already_present {
4432                        "after-id-sidecar"
4433                    } else {
4434                        "before-id-sidecar"
4435                    });
4436            fs::create_dir_all(&runtime).unwrap();
4437            let mut attempt =
4438                RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4439            if sidecar_already_present {
4440                write_runner_id(&runtime, 73).unwrap();
4441                attempt.jit_received(harness.clock.now()).unwrap();
4442            }
4443            harness.store.record_attempt(&attempt).unwrap();
4444            harness.processes.set_alive(true);
4445            harness
4446                .github
4447                .observe(GithubRunnerObservation::Registered { busy: false });
4448            harness
4449                .launcher
4450                .recover_startup(std::slice::from_ref(&harness.policy))
4451                .await
4452                .unwrap();
4453
4454            assert_eq!(read_runner_id(&runtime), Some(73));
4455            assert!(
4456                harness
4457                    .store
4458                    .attempt(id)
4459                    .unwrap()
4460                    .unwrap()
4461                    .outcome()
4462                    .is_none()
4463            );
4464            let events = harness.events.events();
4465            let recovered = events.iter().position(|event| {
4466                matches!(
4467                    event,
4468                    AttemptEvent::RemoteIdentityRecovered {
4469                        attempt,
4470                        runner_id: 73
4471                    } if *attempt == id
4472                )
4473            });
4474            assert_eq!(recovered.is_some(), !sidecar_already_present);
4475            if let Some(recovered) = recovered {
4476                let adopted = events
4477                    .iter()
4478                    .position(|event| matches!(event, AttemptEvent::Adopted { attempt } if *attempt == id))
4479                    .unwrap();
4480                assert!(
4481                    recovered < adopted,
4482                    "identity was not durable before adoption: {events:?}"
4483                );
4484            }
4485            assert!(runtime.exists());
4486        }
4487    }
4488
4489    #[tokio::test]
4490    async fn recovery_stays_closed_for_unknown_policy_and_unreachable_attempts() {
4491        let unknown = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4492        let unknown_attempt = RunnerAttempt::allocate(
4493            AttemptId::new_random(),
4494            PolicyId::from_u128(0xfeed),
4495            unknown
4496                .launcher
4497                .app_paths
4498                .runtime_dir()
4499                .join("unknown-policy"),
4500            unknown.clock.now(),
4501        );
4502        unknown.store.record_attempt(&unknown_attempt).unwrap();
4503        let expired_id = AttemptId::new_random();
4504        let expired_runtime = unknown
4505            .launcher
4506            .app_paths
4507            .runtime_dir()
4508            .join("expired-beside-unknown");
4509        fs::create_dir_all(&expired_runtime).unwrap();
4510        let mut expired = RunnerAttempt::allocate(
4511            expired_id,
4512            unknown.policy.id,
4513            expired_runtime,
4514            unknown.clock.now(),
4515        );
4516        expired.jit_received(unknown.clock.now()).unwrap();
4517        unknown.store.record_attempt(&expired).unwrap();
4518        unknown.clock.advance_secs(11);
4519        assert!(matches!(
4520            unknown
4521                .launcher
4522                .recover_startup(std::slice::from_ref(&unknown.policy))
4523                .await,
4524            Err(LifecycleError::RecoveryIncomplete)
4525        ));
4526        assert!(unknown.launch_result().await.is_err());
4527        assert_eq!(unknown.processes.spawns.load(Ordering::SeqCst), 0);
4528        let recovered_policy = fixtures::policy()
4529            .id(PolicyId::from_u128(0xfeed))
4530            .repository("octo/repo")
4531            .autoscale("home", 2)
4532            .active()
4533            .build();
4534        let pending = unknown
4535            .launcher
4536            .recover_startup(&[unknown.policy.clone(), recovered_policy])
4537            .await
4538            .unwrap();
4539        assert_eq!(
4540            pending,
4541            vec![ReplacementIntent {
4542                policy: unknown.policy.id,
4543                previous_attempt: expired_id,
4544                operation: "jit_expired_replacement",
4545            }]
4546        );
4547        assert_eq!(unknown.processes.spawns.load(Ordering::SeqCst), 0);
4548
4549        let unreachable = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4550        let id = AttemptId::new_random();
4551        let runtime = unreachable
4552            .launcher
4553            .app_paths
4554            .runtime_dir()
4555            .join("unreachable");
4556        fs::create_dir_all(&runtime).unwrap();
4557        unreachable
4558            .store
4559            .record_attempt(&RunnerAttempt::allocate(
4560                id,
4561                unreachable.policy.id,
4562                runtime,
4563                unreachable.clock.now(),
4564            ))
4565            .unwrap();
4566        unreachable
4567            .github
4568            .observe(GithubRunnerObservation::Unreachable);
4569        assert!(matches!(
4570            unreachable
4571                .launcher
4572                .recover_startup(std::slice::from_ref(&unreachable.policy))
4573                .await,
4574            Err(LifecycleError::RecoveryIncomplete)
4575        ));
4576        assert!(unreachable.launch_result().await.is_err());
4577        assert_eq!(unreachable.processes.spawns.load(Ordering::SeqCst), 0);
4578    }
4579
4580    #[tokio::test]
4581    async fn a_dead_busy_process_unknown_to_github_is_orphaned_and_cleaned() {
4582        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4583        let id = AttemptId::new_random();
4584        let runtime = harness.launcher.app_paths.runtime_dir().join("orphan");
4585        fs::create_dir_all(&runtime).unwrap();
4586        let mut attempt =
4587            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4588        attempt.jit_received(harness.clock.now()).unwrap();
4589        attempt.started(4242, harness.clock.now()).unwrap();
4590        attempt.assigned_job(73, harness.clock.now()).unwrap();
4591        harness.store.record_attempt(&attempt).unwrap();
4592        harness.processes.set_alive(false);
4593        harness
4594            .github
4595            .observe(GithubRunnerObservation::NotRegistered);
4596        harness
4597            .launcher
4598            .recover_startup(std::slice::from_ref(&harness.policy))
4599            .await
4600            .unwrap();
4601        let cleaned = harness.store.attempt(id).unwrap().unwrap();
4602        assert_eq!(cleaned.state(), AttemptState::Cleaned);
4603        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::Orphaned));
4604        assert!(!runtime.exists());
4605    }
4606
4607    #[tokio::test]
4608    async fn registration_timeout_journals_intent_stops_then_concludes_with_dead_reason() {
4609        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4610        harness.ready().await;
4611        let id = AttemptId::new_random();
4612        let runtime = harness.launcher.app_paths.runtime_dir().join("timeout");
4613        fs::create_dir_all(&runtime).unwrap();
4614        let mut attempt =
4615            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
4616        attempt.jit_received(harness.clock.now()).unwrap();
4617        attempt.started(4242, harness.clock.now()).unwrap();
4618        harness.store.record_attempt(&attempt).unwrap();
4619        harness.clock.advance_secs(11);
4620        harness.processes.set_alive(true);
4621        harness
4622            .github
4623            .observe(GithubRunnerObservation::NotRegistered);
4624        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4625        assert_eq!(
4626            replacements,
4627            vec![ReplacementIntent {
4628                policy: harness.policy.id,
4629                previous_attempt: id,
4630                operation: "registration_timeout_replacement",
4631            }]
4632        );
4633
4634        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 1);
4635        assert!(!harness.processes.alive.load(Ordering::SeqCst));
4636        let actions = harness.processes.actions.lock().unwrap().clone();
4637        let intent = actions
4638            .iter()
4639            .position(|action| *action == "terminate_intent")
4640            .unwrap();
4641        let signal = actions
4642            .iter()
4643            .position(|action| *action == "terminate")
4644            .unwrap();
4645        assert!(
4646            intent < signal,
4647            "intent was not durable before signal: {actions:?}"
4648        );
4649
4650        let cleaned = harness.store.attempt(id).unwrap().unwrap();
4651        assert!(matches!(
4652            cleaned.outcome(),
4653            Some(AttemptOutcome::Failed {
4654                reason: FailureReason::TerminatedAfterRegistrationTimeout
4655            })
4656        ));
4657        let events = harness.events.events();
4658        let intent = events
4659            .iter()
4660            .position(|event| matches!(event, AttemptEvent::TerminateIntent { .. }))
4661            .unwrap();
4662        let stopped = events
4663            .iter()
4664            .position(|event| matches!(event, AttemptEvent::Terminated { .. }))
4665            .unwrap();
4666        let concluded = events
4667            .iter()
4668            .position(|event| matches!(event, AttemptEvent::Concluded { .. }))
4669            .unwrap();
4670        assert!(intent < stopped && stopped < concluded, "{events:?}");
4671    }
4672
4673    #[tokio::test]
4674    async fn timeout_crash_recovery_returns_the_same_replacement_intent() {
4675        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4676        let id = AttemptId::new_random();
4677        let runtime = harness
4678            .launcher
4679            .app_paths
4680            .runtime_dir()
4681            .join("timeout-after-crash");
4682        fs::create_dir_all(&runtime).unwrap();
4683        let mut attempt =
4684            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
4685        attempt.jit_received(harness.clock.now()).unwrap();
4686        attempt.started(4242, harness.clock.now()).unwrap();
4687        harness.store.record_attempt(&attempt).unwrap();
4688        harness.processes.intent.store(true, Ordering::SeqCst);
4689        harness.processes.set_alive(false);
4690        harness
4691            .github
4692            .observe(GithubRunnerObservation::NotRegistered);
4693
4694        let replacements = harness
4695            .launcher
4696            .recover_startup(std::slice::from_ref(&harness.policy))
4697            .await
4698            .unwrap();
4699        assert_eq!(
4700            replacements,
4701            vec![ReplacementIntent {
4702                policy: harness.policy.id,
4703                previous_attempt: id,
4704                operation: "registration_timeout_replacement",
4705            }]
4706        );
4707        let consumed = RunnerLauncher::supervise(&harness.launcher, &harness.policy)
4708            .await
4709            .unwrap();
4710        assert_eq!(consumed, replacements);
4711        assert!(
4712            RunnerLauncher::supervise(&harness.launcher, &harness.policy)
4713                .await
4714                .unwrap()
4715                .is_empty(),
4716            "startup replacement evidence must be consumed exactly once by e1"
4717        );
4718        assert!(matches!(
4719            harness.store.attempt(id).unwrap().unwrap().outcome(),
4720            Some(AttemptOutcome::Failed {
4721                reason: FailureReason::TerminatedAfterRegistrationTimeout
4722            })
4723        ));
4724    }
4725
4726    #[tokio::test]
4727    async fn terminate_intent_sync_failure_prevents_signal_and_conclusion() {
4728        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4729        let id = AttemptId::new_random();
4730        let runtime = harness
4731            .launcher
4732            .app_paths
4733            .runtime_dir()
4734            .join("timeout-sync-failure");
4735        fs::create_dir_all(&runtime).unwrap();
4736        let mut attempt =
4737            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4738        attempt.jit_received(harness.clock.now()).unwrap();
4739        attempt.started(4242, harness.clock.now()).unwrap();
4740        harness.store.record_attempt(&attempt).unwrap();
4741        harness.clock.advance_secs(11);
4742        harness.processes.set_alive(true);
4743        harness.processes.fail_intent();
4744        harness
4745            .github
4746            .observe(GithubRunnerObservation::NotRegistered);
4747
4748        assert!(
4749            harness
4750                .launcher
4751                .recover_startup(std::slice::from_ref(&harness.policy))
4752                .await
4753                .is_err()
4754        );
4755        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 0);
4756        assert!(harness.processes.alive.load(Ordering::SeqCst));
4757        assert_eq!(
4758            harness.store.attempt(id).unwrap().unwrap().state(),
4759            AttemptState::Starting
4760        );
4761        assert!(!harness.events.events().iter().any(|event| matches!(
4762            event,
4763            AttemptEvent::Terminated { attempt } | AttemptEvent::Concluded { attempt, .. }
4764                if *attempt == id
4765        )));
4766    }
4767
4768    #[tokio::test]
4769    async fn diagnostics_survive_cleanup_without_the_jit_or_a_token() {
4770        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4771        harness.ready().await;
4772        let attempt = harness.launch().await;
4773        harness
4774            .github
4775            .observe(GithubRunnerObservation::Registered { busy: false });
4776        harness.launcher.supervise(&harness.policy).await.unwrap();
4777        harness.clock.advance_secs(11);
4778        harness.processes.set_alive(false);
4779        harness
4780            .github
4781            .observe(GithubRunnerObservation::NotRegistered);
4782        harness.launcher.supervise(&harness.policy).await.unwrap();
4783        let diagnostic = fs::read_to_string(
4784            harness
4785                .launcher
4786                .diagnostics_root
4787                .join(format!("{}.log", attempt.id)),
4788        )
4789        .unwrap();
4790        assert!(diagnostic.contains("exited_idle_without_work"));
4791        assert!(!diagnostic.contains(JIT));
4792        assert!(!diagnostic.contains("ghp_"));
4793        assert!(!attempt.runtime_path().exists());
4794    }
4795
4796    #[test]
4797    fn native_process_listing_never_contains_jit_and_handoffs_never_survive() {
4798        let root = tempfile::tempdir().unwrap();
4799        let policy = fixtures::policy()
4800            .repository("octo/repo")
4801            .autoscale("home", 1)
4802            .active()
4803            .build();
4804        let runtime = root.path().join("successful");
4805        fs::create_dir_all(&runtime).unwrap();
4806        let processes = NativeProcesses::new();
4807        let config = EncodedJitConfig::new(JIT);
4808        let handoff =
4809            RestrictiveHandoff::create(&runtime, SecretString::from(config.expose().to_owned()))
4810                .unwrap();
4811        let mut child = native_inspection_spec()
4812            .spawn_runner_with_handoff(&handoff)
4813            .expect("native child starts");
4814        let pid = child.pid();
4815        handoff.delete().unwrap();
4816        let command_line = native_command_line(pid);
4817        assert!(
4818            !command_line.contains(JIT),
4819            "the encoded JIT configuration appeared in the native process listing"
4820        );
4821        assert_no_jit_file(&runtime);
4822        child
4823            .stop(Duration::from_secs(1))
4824            .expect("native child stops");
4825
4826        let failed_runtime = root.path().join("failed");
4827        fs::create_dir_all(&failed_runtime).unwrap();
4828        let failed = RunnerAttempt::allocate(
4829            AttemptId::new_random(),
4830            policy.id,
4831            &failed_runtime,
4832            FakeClock::default().now(),
4833        );
4834        assert!(
4835            processes
4836                .spawn(&failed, &EncodedJitConfig::new(JIT))
4837                .is_err(),
4838            "a runtime with no runner executable must fail"
4839        );
4840        assert_no_jit_file(&failed_runtime);
4841        processes
4842            .record_terminate_intent(&failed)
4843            .expect("the intent file and its directory entry are durably synced");
4844        assert_eq!(
4845            fs::read(NativeProcesses::intent_path(&failed)).unwrap(),
4846            b"registration-timeout\n"
4847        );
4848    }
4849
4850    #[test]
4851    fn post_spawn_boundaries_are_bounded_durable_and_never_retry_jit() {
4852        let root = tempfile::tempdir().unwrap();
4853        let policy = fixtures::policy()
4854            .repository("octo/repo")
4855            .autoscale("home", 1)
4856            .active()
4857            .build();
4858        let processes = NativeProcesses::new();
4859        processes.use_long_lived_test_listener();
4860        for (index, boundary) in [
4861            PostSpawnBoundary::HandoffDelete,
4862            PostSpawnBoundary::IdentitySerialize,
4863            PostSpawnBoundary::IdentityWrite,
4864            PostSpawnBoundary::ChildMapInsert,
4865        ]
4866        .into_iter()
4867        .enumerate()
4868        {
4869            let runtime = root.path().join(format!("post-spawn-{index}"));
4870            let bin = runtime.join("bin");
4871            fs::create_dir_all(&bin).unwrap();
4872            #[cfg(windows)]
4873            let listener = bin.join("Runner.Listener.exe");
4874            #[cfg(not(windows))]
4875            let listener = bin.join("Runner.Listener");
4876            fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
4877            let attempt = RunnerAttempt::allocate(
4878                AttemptId::new_random(),
4879                policy.id,
4880                &runtime,
4881                FakeClock::default().now(),
4882            );
4883            processes.fail_post_spawn_at(boundary);
4884            let failure = processes
4885                .spawn(&attempt, &EncodedJitConfig::new(JIT))
4886                .expect_err("fault must cross the post-spawn cleanup path");
4887            assert!(!failure.retryable, "{boundary:?} allowed duplicate retry");
4888            assert!(
4889                !processes.is_alive(&attempt).unwrap(),
4890                "{boundary:?} left a child"
4891            );
4892            assert!(!NativeProcesses::identity_path(&attempt).exists());
4893            assert_no_jit_file(&runtime);
4894        }
4895        assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
4896
4897        let runtime = root.path().join("identity-and-stop-fail");
4898        let bin = runtime.join("bin");
4899        fs::create_dir_all(&bin).unwrap();
4900        #[cfg(windows)]
4901        let listener = bin.join("Runner.Listener.exe");
4902        #[cfg(not(windows))]
4903        let listener = bin.join("Runner.Listener");
4904        fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
4905        let attempt = RunnerAttempt::allocate(
4906            AttemptId::new_random(),
4907            policy.id,
4908            &runtime,
4909            FakeClock::default().now(),
4910        );
4911        // The first fault rejects the normal identity write; the second rejects
4912        // its retry after the first stop fails. The fallback sidecar must make
4913        // the live-child result durable without an unbounded reap loop.
4914        processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
4915        processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
4916        processes.fail_next_post_spawn_stop();
4917        let failure = processes
4918            .spawn(&attempt, &EncodedJitConfig::new(JIT))
4919            .expect_err("the identity boundary must fail closed");
4920        assert!(failure.live_pid.is_some());
4921        assert_long_lived_listener_ready(&processes, &attempt);
4922        assert!(processes.is_alive(&attempt).unwrap());
4923        assert!(!NativeProcesses::identity_path(&attempt).exists());
4924        assert!(NativeProcesses::fallback_identity_path(&attempt).is_file());
4925        assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
4926        processes.terminate(&attempt).unwrap();
4927
4928        let runtime = root.path().join("persistent-stop-and-identity-failures");
4929        let bin = runtime.join("bin");
4930        fs::create_dir_all(&bin).unwrap();
4931        #[cfg(windows)]
4932        let listener = bin.join("Runner.Listener.exe");
4933        #[cfg(not(windows))]
4934        let listener = bin.join("Runner.Listener");
4935        fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
4936        let mut unresolved = RunnerAttempt::allocate(
4937            AttemptId::new_random(),
4938            policy.id,
4939            &runtime,
4940            FakeClock::default().now(),
4941        );
4942        for _ in 0..3 {
4943            processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
4944        }
4945        processes.fail_post_spawn_stops(MAX_POST_SPAWN_STOP_ATTEMPTS);
4946        let failure = processes
4947            .spawn(&unresolved, &EncodedJitConfig::new(JIT))
4948            .expect_err("bounded cleanup must return even when every stop errors");
4949        let pid = failure
4950            .live_pid
4951            .expect("the owned child remains supervised in this invocation");
4952        assert!(matches!(failure.reason, FailureReason::Other(_)));
4953        assert_long_lived_listener_ready(&processes, &unresolved);
4954        unresolved.jit_received(FakeClock::default().now()).unwrap();
4955        unresolved.started(pid, FakeClock::default().now()).unwrap();
4956        let journal = SqliteStore::open_in_memory().unwrap();
4957        journal.record_attempt(&unresolved).unwrap();
4958        let recovered = journal.attempt(unresolved.id).unwrap().unwrap();
4959        assert_eq!(recovered.process_id(), Some(pid));
4960        assert_eq!(recovered.state(), AttemptState::Starting);
4961        assert!(processes.is_alive(&unresolved).unwrap());
4962        assert!(!NativeProcesses::identity_path(&unresolved).exists());
4963        assert!(!NativeProcesses::fallback_identity_path(&unresolved).exists());
4964        assert_eq!(
4965            fs::read_to_string(NativeProcesses::unresolved_process_path(&unresolved)).unwrap(),
4966            pid.to_string(),
4967            "bounded cleanup must leave durable unresolved-process evidence before returning"
4968        );
4969        assert!(
4970            NativeProcesses::new().is_alive(&recovered).is_err(),
4971            "restart must fail closed on the durable starting/PID journal rather than trust a bare PID"
4972        );
4973        processes.terminate(&unresolved).unwrap();
4974
4975        let runtime = root.path().join("post-spawn-stop-failed");
4976        let bin = runtime.join("bin");
4977        fs::create_dir_all(&bin).unwrap();
4978        #[cfg(windows)]
4979        let listener = bin.join("Runner.Listener.exe");
4980        #[cfg(not(windows))]
4981        let listener = bin.join("Runner.Listener");
4982        fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
4983        let attempt = RunnerAttempt::allocate(
4984            AttemptId::new_random(),
4985            policy.id,
4986            &runtime,
4987            FakeClock::default().now(),
4988        );
4989        processes.fail_post_spawn_at(PostSpawnBoundary::ChildMapInsert);
4990        processes.fail_next_post_spawn_stop();
4991        let failure = processes
4992            .spawn(&attempt, &EncodedJitConfig::new(JIT))
4993            .expect_err("the injected stop failure must preserve supervision");
4994        let live_pid = failure
4995            .live_pid
4996            .expect("live PID is returned to the journal");
4997        assert!(!failure.retryable);
4998        assert_long_lived_listener_ready(&processes, &attempt);
4999        assert!(NativeProcesses::identity_path(&attempt).is_file());
5000        assert_eq!(
5001            NativeProcesses::read_identity(&attempt)
5002                .unwrap()
5003                .unwrap()
5004                .pid(),
5005            live_pid
5006        );
5007        assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
5008        processes.terminate(&attempt).unwrap();
5009    }
5010
5011    #[test]
5012    #[ignore = "spawned only as the platform-stable native listener fixture"]
5013    fn long_lived_native_listener_helper() {
5014        let ready = std::env::var_os("RUNNER_MANAGER_TEST_LISTENER_READY")
5015            .map(PathBuf::from)
5016            .expect("the parent supplies the readiness path");
5017        fs::write(ready, b"ready\n").expect("the listener publishes readiness");
5018        std::thread::sleep(Duration::from_secs(30));
5019    }
5020
5021    fn assert_long_lived_listener_ready(processes: &NativeProcesses, attempt: &RunnerAttempt) {
5022        let ready = attempt.runtime_path().join(TEST_LISTENER_READY);
5023        let deadline = std::time::Instant::now() + Duration::from_secs(5);
5024        loop {
5025            if ready.is_file() {
5026                assert_eq!(fs::read(&ready).unwrap(), b"ready\n");
5027                return;
5028            }
5029            assert!(
5030                processes.is_alive(attempt).unwrap(),
5031                "the native listener exited before publishing readiness"
5032            );
5033            assert!(
5034                std::time::Instant::now() < deadline,
5035                "the native listener stayed alive but never published readiness"
5036            );
5037            std::thread::sleep(Duration::from_millis(10));
5038        }
5039    }
5040
5041    #[tokio::test]
5042    async fn every_production_launch_prunes_under_the_same_allocation_guard() {
5043        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
5044        harness.ready().await;
5045        assert_eq!(harness.packages.prunes.load(Ordering::SeqCst), 0);
5046        harness.launch().await;
5047        assert_eq!(harness.packages.prunes.load(Ordering::SeqCst), 1);
5048        assert_eq!(
5049            *harness.packages.prune_currents.lock().unwrap(),
5050            vec![harness.packages.version.clone()],
5051            "the leased current version is an exclusion, never the prune target"
5052        );
5053    }
5054
5055    fn assert_no_jit_file(runtime: &Path) {
5056        for entry in fs::read_dir(runtime).unwrap() {
5057            let path = entry.unwrap().path();
5058            if path.is_file() {
5059                let bytes = fs::read(&path).unwrap();
5060                assert!(
5061                    !bytes
5062                        .windows(JIT.len())
5063                        .any(|window| window == JIT.as_bytes()),
5064                    "a JIT payload survived in a runtime file"
5065                );
5066            }
5067        }
5068    }
5069
5070    #[test]
5071    fn production_listener_command_uses_the_supported_jit_contract() {
5072        let runtime = Path::new("runtime");
5073        let spec = runner_listener_spec(PathBuf::from("Runner.Listener"), runtime);
5074        let arguments: Vec<_> = spec
5075            .arguments()
5076            .iter()
5077            .map(|argument| argument.to_string_lossy().into_owned())
5078            .collect();
5079
5080        assert_eq!(arguments, ["run"]);
5081        assert!(
5082            !arguments
5083                .iter()
5084                .any(|argument| argument == "--jit-config-file"),
5085            "the obsolete file option would be rejected by Runner.Listener 2.336.0"
5086        );
5087    }
5088
5089    #[cfg(windows)]
5090    fn native_inspection_spec() -> SpawnSpec {
5091        SpawnSpec::new("powershell.exe").args([
5092            "-NoProfile",
5093            "-NonInteractive",
5094            "-Command",
5095            "Start-Sleep -Seconds 30",
5096        ])
5097    }
5098
5099    #[cfg(unix)]
5100    fn native_inspection_spec() -> SpawnSpec {
5101        SpawnSpec::new("/bin/sh").args(["-c", "sleep 30"])
5102    }
5103
5104    #[cfg(windows)]
5105    fn native_command_line(pid: u32) -> String {
5106        let output = std::process::Command::new("powershell.exe")
5107            .args([
5108                "-NoProfile",
5109                "-NonInteractive",
5110                "-Command",
5111                &format!("(Get-CimInstance Win32_Process -Filter 'ProcessId = {pid}').CommandLine"),
5112            ])
5113            .output()
5114            .expect("PowerShell can inspect the native child");
5115        assert!(output.status.success(), "native process inspection failed");
5116        String::from_utf8(output.stdout).expect("Windows command lines are Unicode")
5117    }
5118
5119    #[cfg(target_os = "linux")]
5120    fn native_command_line(pid: u32) -> String {
5121        fs::read(format!("/proc/{pid}/cmdline"))
5122            .map(|bytes| String::from_utf8_lossy(&bytes).replace('\0', " "))
5123            .expect("/proc exposes the native child command line")
5124    }
5125
5126    #[cfg(target_os = "macos")]
5127    fn native_command_line(pid: u32) -> String {
5128        let output = std::process::Command::new("ps")
5129            .args(["-o", "command=", "-p", &pid.to_string()])
5130            .output()
5131            .expect("ps can inspect the native child");
5132        assert!(output.status.success(), "native process inspection failed");
5133        String::from_utf8(output.stdout).expect("the command line is UTF-8")
5134    }
5135
5136    // -- c2: persistent slot allocation -------------------------------------
5137
5138    #[tokio::test]
5139    async fn a_persistent_repository_leases_s1_and_journals_it_before_any_github_effect() {
5140        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5141            .with_persistent_workspace(2);
5142        harness.github.watch_journal(Arc::clone(&harness.store));
5143        harness.ready().await;
5144
5145        let attempt = harness.launch().await;
5146
5147        assert_eq!(
5148            attempt.workspace(),
5149            AttemptWorkspace::persistent_slot(nz(1)),
5150            "the lowest free slot is leased"
5151        );
5152        assert_eq!(attempt.runtime_path(), harness.slot_path(1));
5153        assert!(attempt.holds_slot_lease());
5154        // The exact runtime path is journalled, not re-derived later.
5155        assert_eq!(
5156            harness.attempt(attempt.id).runtime_path(),
5157            harness.slot_path(1)
5158        );
5159
5160        // Step 7 of "Slot allocation": the lease exists before GitHub is asked
5161        // for anything, and the runner's work folder stays the relative `_work`
5162        // the slot root is laid out around.
5163        let facts = harness.github.registration_facts();
5164        assert_eq!(facts.len(), 1);
5165        assert_eq!(
5166            facts[0].leased_slots,
5167            vec![1],
5168            "the lease was journalled first"
5169        );
5170        assert_eq!(facts[0].work_folder, DEFAULT_WORK_FOLDER);
5171    }
5172
5173    #[tokio::test]
5174    async fn a_terminal_but_uncleaned_attempt_keeps_its_slot_without_holding_capacity() {
5175        let harness = Harness::new(
5176            FakeGithubLifecycle::default().fail(true),
5177            Arc::new(PersistentDemand),
5178        )
5179        .with_persistent_workspace(2);
5180        harness.ready().await;
5181
5182        // A terminal JIT refusal concludes the attempt without cleaning it.
5183        harness.launch_result().await.unwrap_err();
5184        let first = harness.store.attempts().unwrap().remove(0);
5185        assert_eq!(first.state(), AttemptState::Failed);
5186        assert!(
5187            !first.state().counts_against_capacity(),
5188            "a concluded attempt is invisible to host capacity"
5189        );
5190        assert!(
5191            first.holds_slot_lease(),
5192            "and still owns its directory, so its slot is not free"
5193        );
5194
5195        let second = harness.launch().await;
5196        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
5197        assert_eq!(second.runtime_path(), harness.slot_path(2));
5198        assert_eq!(
5199            harness
5200                .store
5201                .slot_leases_for_policy(harness.policy.id)
5202                .unwrap()
5203                .len(),
5204            2
5205        );
5206    }
5207
5208    #[tokio::test]
5209    async fn two_sequential_allocations_at_capacity_one_reuse_s1_and_its_retained_work() {
5210        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5211            .with_persistent_workspace(1);
5212        harness.ready().await;
5213
5214        let first = harness.launch().await;
5215        assert_eq!(first.runtime_path(), harness.slot_path(1));
5216
5217        // What a job leaves behind, at the path the runner writes it to.
5218        let checkout = harness.slot_path(1).join(DEFAULT_WORK_FOLDER).join("repo");
5219        fs::create_dir_all(&checkout).unwrap();
5220        fs::write(checkout.join("checkout.txt"), b"from the first job").unwrap();
5221
5222        harness.cleanup_retaining_work(first.id).await;
5223
5224        let second = harness.launch().await;
5225        assert_ne!(second.id, first.id);
5226        assert_eq!(
5227            second.workspace(),
5228            AttemptWorkspace::persistent_slot(nz(1)),
5229            "a released slot is leased again rather than skipped"
5230        );
5231        assert_eq!(
5232            second.runtime_path(),
5233            first.runtime_path(),
5234            "the same slot is the same exact path"
5235        );
5236        assert_eq!(
5237            fs::read_to_string(checkout.join("checkout.txt")).unwrap(),
5238            "from the first job",
5239            "the retained job workspace survived the second allocation"
5240        );
5241        // The attempt's own runner material was recreated for this attempt.
5242        assert!(harness.slot_path(1).join("runner-package").exists());
5243    }
5244
5245    #[tokio::test]
5246    async fn lowering_capacity_leaves_higher_slots_alone_and_raising_it_permits_them_again() {
5247        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5248            .with_persistent_workspace(2);
5249        harness.ready().await;
5250
5251        let first = harness.launch().await;
5252        let second = harness.launch().await;
5253        assert_eq!(second.runtime_path(), harness.slot_path(2));
5254        let kept = harness
5255            .slot_path(2)
5256            .join(DEFAULT_WORK_FOLDER)
5257            .join("kept.txt");
5258        fs::create_dir_all(kept.parent().unwrap()).unwrap();
5259        fs::write(&kept, b"s2 was here").unwrap();
5260        harness.cleanup_retaining_work(second.id).await;
5261
5262        // The operator lowers the ceiling while s1 is still leased.
5263        harness.policy.set_max_capacity(nz(1)).unwrap();
5264        let refusal = harness.launch_result().await.unwrap_err().to_string();
5265        assert!(
5266            refusal.contains("s1 to s1"),
5267            "the refusal names the ceiling it reached: {refusal}"
5268        );
5269        assert!(
5270            harness.slot_path(2).exists() && kept.exists(),
5271            "lowering capacity deletes nothing; the higher slot is merely unusable"
5272        );
5273
5274        // Raising it again makes the free higher slot available.
5275        harness.policy.set_max_capacity(nz(2)).unwrap();
5276        let third = harness.launch().await;
5277        assert_eq!(third.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
5278        assert_eq!(third.runtime_path(), harness.slot_path(2));
5279        assert_eq!(fs::read_to_string(&kept).unwrap(), "s2 was here");
5280        assert!(first.holds_slot_lease(), "s1 was never disturbed");
5281    }
5282
5283    #[tokio::test]
5284    async fn organization_and_ephemeral_policies_never_enter_slot_allocation() {
5285        for policy in [
5286            fixtures::policy()
5287                .organization("octo")
5288                .autoscale("home", 2)
5289                .active()
5290                .build(),
5291            fixtures::policy()
5292                .repository("octo/repo")
5293                .autoscale("home", 2)
5294                .active()
5295                .build(),
5296        ] {
5297            let mut harness =
5298                Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5299                    .with_host_runner_root();
5300            assert_eq!(policy.workspace_policy(), &WorkspacePolicy::Ephemeral);
5301            harness.policy = policy;
5302            harness.ready().await;
5303
5304            let attempt = harness.launch().await;
5305            assert_eq!(attempt.workspace(), AttemptWorkspace::Ephemeral);
5306            assert_eq!(attempt.workspace().slot_number(), None);
5307            assert!(!attempt.holds_slot_lease());
5308            assert_eq!(
5309                attempt.runtime_path().parent().unwrap(),
5310                harness.host_root(),
5311                "a disposable attempt is a child of the host root, never of a slot"
5312            );
5313            assert!(
5314                harness
5315                    .store
5316                    .slot_leases_for_policy(harness.policy.id)
5317                    .unwrap()
5318                    .is_empty()
5319            );
5320        }
5321    }
5322
5323    #[tokio::test]
5324    async fn two_concurrent_allocations_never_share_a_slot() {
5325        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5326            .with_persistent_workspace(2);
5327        harness.github.watch_journal(Arc::clone(&harness.store));
5328        harness.ready().await;
5329
5330        // Both allocators race for the same host allocation lock, which is what
5331        // orders slot *selection*; each one then journals its lease before it
5332        // asks GitHub for anything.
5333        let (first, second) = tokio::join!(harness.launch_result(), harness.launch_result());
5334        let first = first.unwrap();
5335        let second = second.unwrap();
5336
5337        let slots: BTreeSet<u16> = [&first, &second]
5338            .iter()
5339            .map(|attempt| {
5340                attempt
5341                    .workspace()
5342                    .slot_number()
5343                    .expect("a persistent attempt leases a slot")
5344            })
5345            .collect();
5346        assert_eq!(slots, BTreeSet::from([1, 2]), "one slot each, never shared");
5347        assert_ne!(first.runtime_path(), second.runtime_path());
5348        assert_eq!(
5349            harness
5350                .store
5351                .slot_leases_for_policy(harness.policy.id)
5352                .unwrap()
5353                .len(),
5354            2
5355        );
5356
5357        // Every registration saw *its own* lease already in the journal. Reading
5358        // the whole journal and asking only that it be non-empty would pass on
5359        // the other allocator's lease, which is precisely the ordering bug this
5360        // test exists to exclude.
5361        let facts = harness.github.registration_facts();
5362        assert_eq!(facts.len(), 2);
5363        for fact in facts {
5364            let attempt = [&first, &second]
5365                .into_iter()
5366                .find(|attempt| runner_name(attempt.id) == fact.runner_name)
5367                .expect("every registration belongs to one of the two attempts");
5368            let slot = attempt
5369                .workspace()
5370                .slot_number()
5371                .expect("a persistent attempt leases a slot");
5372            assert!(
5373                fact.leased_slots.contains(&slot),
5374                "a JIT request never precedes its own lease: s{slot} not in {:?}",
5375                fact.leased_slots
5376            );
5377            assert_eq!(fact.work_folder, DEFAULT_WORK_FOLDER);
5378        }
5379    }
5380
5381    #[tokio::test]
5382    async fn the_database_is_the_final_fence_against_two_attempts_in_one_slot() {
5383        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5384            .with_persistent_workspace(2);
5385        harness.ready().await;
5386        let first = harness.launch().await;
5387
5388        // What a second allocator that lost the race would write: the lock
5389        // orders selection, and this index is what catches a writer the lock
5390        // could not see.
5391        let clash = RunnerAttempt::allocate_in(
5392            AttemptId::new_random(),
5393            harness.policy.id,
5394            first.runtime_path(),
5395            AttemptWorkspace::persistent_slot(nz(1)),
5396            harness.clock.now(),
5397        );
5398        assert!(matches!(
5399            harness.store.record_attempt(&clash).unwrap_err(),
5400            StoreError::SlotAlreadyLeased { slot: 1, .. }
5401        ));
5402
5403        // And the launcher reports it as itself rather than as a generic
5404        // journal failure, so the operator reads what actually happened.
5405        let error = harness.launcher.record_allocation(&clash).unwrap_err();
5406        let rendered = error.to_string();
5407        assert!(rendered.contains("slot s1"), "{rendered}");
5408        assert!(rendered.contains("nothing was written"), "{rendered}");
5409        assert_eq!(
5410            harness.store.attempts().unwrap().len(),
5411            1,
5412            "the losing allocator journalled nothing"
5413        );
5414    }
5415
5416    #[test]
5417    fn slot_selection_fills_the_lowest_gap_and_stops_at_the_ceiling() {
5418        let leased = |slots: &[u16]| -> Vec<RunnerAttempt> {
5419            slots
5420                .iter()
5421                .map(|slot| {
5422                    RunnerAttempt::allocate_in(
5423                        AttemptId::new_random(),
5424                        fixtures::POLICY_ID,
5425                        format!("/srv/rman/acme/s{slot}"),
5426                        AttemptWorkspace::persistent_slot(nz(*slot)),
5427                        fixtures::created_at(),
5428                    )
5429                })
5430                .collect()
5431        };
5432
5433        assert_eq!(lowest_free_slot(&[], nz(1)), Some(nz(1)));
5434        assert_eq!(lowest_free_slot(&leased(&[1]), nz(4)), Some(nz(2)));
5435        // The gap a released middle slot leaves is filled before the tail.
5436        assert_eq!(lowest_free_slot(&leased(&[1, 3]), nz(4)), Some(nz(2)));
5437        // The ceiling is a refusal, never a reason to allocate past it.
5438        assert_eq!(lowest_free_slot(&leased(&[1]), nz(1)), None);
5439        assert_eq!(lowest_free_slot(&leased(&[1, 2]), nz(2)), None);
5440        // An ephemeral attempt holds no slot and cannot block one.
5441        let ephemeral = vec![RunnerAttempt::allocate(
5442            AttemptId::new_random(),
5443            fixtures::POLICY_ID,
5444            "/srv/rman/host/abc",
5445            fixtures::created_at(),
5446        )];
5447        assert_eq!(lowest_free_slot(&ephemeral, nz(1)), Some(nz(1)));
5448    }
5449
5450    #[test]
5451    fn a_slot_is_reusable_only_when_it_is_empty_or_holds_one_real_work_directory() {
5452        let root = tempfile::tempdir().unwrap();
5453        let slot = root.path().join("s1");
5454        fs::create_dir(&slot).unwrap();
5455        accept_reusable_slot(&slot).expect("an empty slot is reusable");
5456
5457        fs::create_dir(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
5458        accept_reusable_slot(&slot).expect("a retained job workspace is reusable");
5459
5460        // Runner material a previous attempt left behind is refused rather than
5461        // reused or removed: deciding those bytes are safe is cleanup's job.
5462        fs::create_dir(slot.join("bin")).unwrap();
5463        fs::write(slot.join(".github-runner-id"), b"73").unwrap();
5464        let refusal = accept_reusable_slot(&slot).unwrap_err().to_string();
5465        assert!(refusal.contains("bin"), "{refusal}");
5466        assert!(refusal.contains(".github-runner-id"), "{refusal}");
5467
5468        // A `_work` that is not a real directory is not a job workspace.
5469        let file_work = root.path().join("s2");
5470        fs::create_dir(&file_work).unwrap();
5471        fs::write(file_work.join(DEFAULT_WORK_FOLDER), b"not a directory").unwrap();
5472        assert!(accept_reusable_slot(&file_work).is_err());
5473    }
5474
5475    #[cfg(unix)]
5476    #[test]
5477    fn a_link_shaped_work_directory_is_refused_rather_than_followed() {
5478        // Windows needs a privilege to create either kind of link, so the
5479        // link-shaped cases are asserted here; the rule itself is
5480        // platform-independent because it is `symlink_metadata`'s answer.
5481        let root = tempfile::tempdir().unwrap();
5482        let elsewhere = root.path().join("elsewhere");
5483        fs::create_dir(&elsewhere).unwrap();
5484
5485        let slot = root.path().join("s1");
5486        fs::create_dir(&slot).unwrap();
5487        std::os::unix::fs::symlink(&elsewhere, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
5488        assert!(accept_reusable_slot(&slot).is_err());
5489
5490        let linked_slot = root.path().join("s2");
5491        std::os::unix::fs::symlink(&elsewhere, &linked_slot).unwrap();
5492        assert!(create_or_validate_slot(&linked_slot).is_err());
5493    }
5494
5495    #[test]
5496    fn a_slot_standing_where_a_file_is_refuses_rather_than_replacing_it() {
5497        let root = tempfile::tempdir().unwrap();
5498        let occupied = root.path().join("s1");
5499        fs::write(&occupied, b"an operator's file").unwrap();
5500        let refusal = create_or_validate_slot(&occupied).unwrap_err().to_string();
5501        assert!(refusal.contains("is not a directory"), "{refusal}");
5502        assert_eq!(fs::read_to_string(&occupied).unwrap(), "an operator's file");
5503
5504        let fresh = root.path().join("s2");
5505        create_or_validate_slot(&fresh).expect("a missing slot is created");
5506        assert!(fresh.is_dir());
5507        create_or_validate_slot(&fresh).expect("an existing directory is accepted");
5508    }
5509
5510    #[test]
5511    fn the_retained_work_directory_is_matched_the_way_the_filesystem_matches_it() {
5512        assert!(is_work_folder(OsStr::new(DEFAULT_WORK_FOLDER)));
5513        assert!(!is_work_folder(OsStr::new("_work2")));
5514        // A Windows filesystem is case-insensitive, so `_Work` *is* the retained
5515        // job workspace there and must never be removed as a leftover; on a
5516        // case-sensitive filesystem it is a different directory entirely.
5517        assert_eq!(is_work_folder(OsStr::new("_Work")), cfg!(windows));
5518    }
5519
5520    #[test]
5521    fn package_materialization_never_overwrites_or_follows_a_retained_work_directory() {
5522        let root = tempfile::tempdir().unwrap();
5523        let package = root.path().join("package");
5524        fs::create_dir_all(package.join("bin")).unwrap();
5525        fs::write(package.join("bin").join("Runner.Listener"), b"binary").unwrap();
5526        // A nested `_work` inside the package's own tree is an ordinary name.
5527        fs::create_dir_all(package.join("externals").join(DEFAULT_WORK_FOLDER)).unwrap();
5528
5529        let slot = root.path().join("s1");
5530        let retained = slot.join(DEFAULT_WORK_FOLDER).join("repo");
5531        fs::create_dir_all(&retained).unwrap();
5532        fs::write(retained.join("checkout.txt"), b"from the first job").unwrap();
5533
5534        copy_package_tree(&package, &slot).expect("the package lays out around `_work`");
5535        assert!(slot.join("bin").join("Runner.Listener").exists());
5536        assert!(
5537            slot.join("externals").join(DEFAULT_WORK_FOLDER).is_dir(),
5538            "the guard is top-level only"
5539        );
5540        assert_eq!(
5541            fs::read_to_string(retained.join("checkout.txt")).unwrap(),
5542            "from the first job"
5543        );
5544
5545        // A package that ever grew a top-level `_work` is refused, not merged.
5546        fs::create_dir(package.join(DEFAULT_WORK_FOLDER)).unwrap();
5547        let error = copy_package_tree(&package, &slot).unwrap_err();
5548        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
5549        assert_eq!(
5550            fs::read_to_string(retained.join("checkout.txt")).unwrap(),
5551            "from the first job"
5552        );
5553    }
5554
5555    #[test]
5556    fn rolling_back_a_materialization_keeps_a_slot_but_removes_a_disposable_directory() {
5557        let root = tempfile::tempdir().unwrap();
5558
5559        let slot = root.path().join("s1");
5560        let retained = slot.join(DEFAULT_WORK_FOLDER);
5561        fs::create_dir_all(retained.join("repo")).unwrap();
5562        fs::write(retained.join("repo").join("checkout.txt"), b"kept").unwrap();
5563        fs::create_dir_all(slot.join("bin")).unwrap();
5564        fs::write(slot.join(".github-runner-id"), b"73").unwrap();
5565        let persistent = RunnerAttempt::allocate_in(
5566            AttemptId::new_random(),
5567            fixtures::POLICY_ID,
5568            &slot,
5569            AttemptWorkspace::persistent_slot(nz(1)),
5570            fixtures::created_at(),
5571        );
5572
5573        remove_materialized_package(&persistent).unwrap();
5574        assert!(slot.is_dir(), "the slot itself is not removed");
5575        assert!(!slot.join("bin").exists());
5576        assert!(!slot.join(".github-runner-id").exists());
5577        assert_eq!(
5578            fs::read_to_string(retained.join("repo").join("checkout.txt")).unwrap(),
5579            "kept"
5580        );
5581
5582        let disposable_path = root.path().join("abcdef012345");
5583        fs::create_dir_all(disposable_path.join(DEFAULT_WORK_FOLDER)).unwrap();
5584        let disposable = RunnerAttempt::allocate(
5585            AttemptId::new_random(),
5586            fixtures::POLICY_ID,
5587            &disposable_path,
5588            fixtures::created_at(),
5589        );
5590        remove_materialized_package(&disposable).unwrap();
5591        assert!(
5592            !disposable_path.exists(),
5593            "a disposable directory is still removed whole"
5594        );
5595    }
5596
5597    // -- c3: persistent cleanup and recovery --------------------------------
5598
5599    /// The runner state one attempt leaves at a slot root, as a real attempt
5600    /// leaves it: binaries, registration identity, a JIT handoff that outlived
5601    /// its process, and this agent's own lifecycle sidecars.
5602    ///
5603    /// Driven by [`SENSITIVE_SLOT_ENTRIES`] rather than by a second copy of it,
5604    /// so a name added to the thing cleanup must prove absent is a name every
5605    /// test here starts leaving behind.
5606    fn litter_the_slot(slot: &Path) {
5607        for directory in ["bin", "externals", "_diag"] {
5608            fs::create_dir_all(slot.join(directory)).unwrap();
5609        }
5610        fs::write(slot.join("bin").join("Runner.Listener"), b"binary").unwrap();
5611        for file in SENSITIVE_SLOT_ENTRIES
5612            .iter()
5613            .filter(|entry| !slot.join(entry).is_dir())
5614        {
5615            fs::write(slot.join(file), b"runner state").unwrap();
5616        }
5617        // A handoff whose owning process died before `Drop` could delete it.
5618        fs::write(
5619            slot.join(format!(
5620                "{}0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0.tmp",
5621                RestrictiveHandoff::NAME_PREFIX
5622            )),
5623            JIT.as_bytes(),
5624        )
5625        .unwrap();
5626    }
5627
5628    /// A marker under `_work` of the kind a job leaves for the next one.
5629    fn retain_under_work(slot: &Path) -> PathBuf {
5630        let checkout = slot.join(DEFAULT_WORK_FOLDER).join("repo").join("target");
5631        fs::create_dir_all(&checkout).unwrap();
5632        let marker = checkout.join("build-output.bin");
5633        fs::write(&marker, RETAINED).unwrap();
5634        marker
5635    }
5636
5637    /// What a job leaves under `_work` for the next job to reuse.
5638    const RETAINED: &str = "a Git-ignored build output the next job reuses";
5639
5640    /// Every direct entry of a directory, sorted, as plain strings.
5641    fn entries_of(directory: &Path) -> Vec<String> {
5642        let mut names: Vec<String> = fs::read_dir(directory)
5643            .unwrap()
5644            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
5645            .collect();
5646        names.sort();
5647        names
5648    }
5649
5650    /// The one entry a cleaned slot is allowed to hold.
5651    fn only_the_job_workspace() -> Vec<String> {
5652        vec![DEFAULT_WORK_FOLDER.to_owned()]
5653    }
5654
5655    /// One slot entry that refuses to be removed, and the undo that lets the
5656    /// temporary directory be torn down afterwards.
5657    ///
5658    /// The two operating systems refuse for different reasons and there is no
5659    /// portable third. Windows will not open a file for deletion while a handle
5660    /// with share mode zero is held on it; Unix will not unlink from a directory
5661    /// the caller cannot write. Both are states a real machine reaches -- a
5662    /// scanner holding a file open, a job that left a directory read-only -- so
5663    /// the injection is a filesystem fact rather than a seam cut into the
5664    /// product for a test to pull.
5665    ///
5666    /// The Unix half is a permission, and permissions do not apply to `root`.
5667    /// [`Self::inject`] proves the block on a throwaway directory before
5668    /// claiming it, so a suite running as `root` says it could not inject rather
5669    /// than asserting nothing and passing.
5670    struct BlockedDeletion {
5671        directory: PathBuf,
5672        #[cfg(windows)]
5673        _handle: fs::File,
5674    }
5675
5676    impl BlockedDeletion {
5677        const HELD: &'static str = "held-open";
5678
5679        /// Fill `directory` with a file that cannot be removed, or answer `None`
5680        /// when this account cannot be stopped from removing anything.
5681        fn inject(directory: &Path) -> Option<Self> {
5682            #[cfg(unix)]
5683            if !Self::refusal_is_possible() {
5684                return None;
5685            }
5686            fs::create_dir_all(directory).unwrap();
5687            fs::write(
5688                directory.join(Self::HELD),
5689                b"a file the scrub cannot remove",
5690            )
5691            .unwrap();
5692            #[cfg(windows)]
5693            let handle = {
5694                use std::os::windows::fs::OpenOptionsExt;
5695
5696                fs::OpenOptions::new()
5697                    .read(true)
5698                    .share_mode(0)
5699                    .open(directory.join(Self::HELD))
5700                    .expect("the blocking handle opens")
5701            };
5702            #[cfg(unix)]
5703            Self::set_mode(directory, 0o555);
5704            Some(Self {
5705                directory: directory.to_path_buf(),
5706                #[cfg(windows)]
5707                _handle: handle,
5708            })
5709        }
5710
5711        fn release(self) {
5712            drop(self);
5713        }
5714
5715        #[cfg(unix)]
5716        fn refusal_is_possible() -> bool {
5717            let probe = tempfile::tempdir().unwrap();
5718            let directory = probe.path().join("probe");
5719            fs::create_dir(&directory).unwrap();
5720            fs::write(directory.join("file"), b"probe").unwrap();
5721            Self::set_mode(&directory, 0o555);
5722            let refused = fs::remove_dir_all(&directory).is_err();
5723            Self::set_mode(&directory, 0o755);
5724            refused
5725        }
5726
5727        #[cfg(unix)]
5728        fn set_mode(directory: &Path, mode: u32) {
5729            use std::os::unix::fs::PermissionsExt;
5730
5731            let mut permissions = fs::metadata(directory).unwrap().permissions();
5732            permissions.set_mode(mode);
5733            fs::set_permissions(directory, permissions).unwrap();
5734        }
5735    }
5736
5737    impl Drop for BlockedDeletion {
5738        fn drop(&mut self) {
5739            #[cfg(unix)]
5740            Self::set_mode(&self.directory, 0o755);
5741            #[cfg(not(unix))]
5742            let _ = &self.directory;
5743        }
5744    }
5745
5746    #[tokio::test]
5747    async fn two_sequential_jobs_keep_the_checkout_and_start_without_the_earlier_runner_state() {
5748        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5749            .with_persistent_workspace(1);
5750        harness.ready().await;
5751
5752        let first = harness.launch().await;
5753        let slot = harness.slot_path(1);
5754        assert_eq!(first.runtime_path(), slot);
5755        assert_eq!(
5756            read_runner_id(&slot),
5757            Some(73),
5758            "the attempt registered, so its identity is on disk"
5759        );
5760        let marker = retain_under_work(&slot);
5761        litter_the_slot(&slot);
5762
5763        harness.cleanup_retaining_work(first.id).await;
5764
5765        // The allowlist is exactly one entry, so this assertion is the security
5766        // property in full: what is retained, and that nothing else is.
5767        assert_eq!(entries_of(&slot), only_the_job_workspace());
5768        assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
5769        assert_eq!(
5770            read_runner_id(&slot),
5771            None,
5772            "the first attempt's registration identity is gone before the second starts"
5773        );
5774        assert_eq!(harness.attempt(first.id).state(), AttemptState::Cleaned);
5775        assert!(!harness.attempt(first.id).holds_slot_lease());
5776
5777        let second = harness.launch().await;
5778        assert_ne!(second.id, first.id);
5779        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(1)));
5780        assert_eq!(
5781            second.runtime_path(),
5782            slot,
5783            "the same slot, so the same retained `_work`"
5784        );
5785        assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
5786    }
5787
5788    #[tokio::test]
5789    async fn cleaning_a_persistent_slot_needs_no_policy_and_scans_no_directory_for_ownership() {
5790        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5791            .with_persistent_workspace(1);
5792        harness.ready().await;
5793        let attempt = harness.launch().await;
5794        let slot = harness.slot_path(1);
5795        let marker = retain_under_work(&slot);
5796        litter_the_slot(&slot);
5797        harness.conclude(attempt.id);
5798
5799        // A repository removed from the product between the attempt concluding
5800        // and the sweep reaching it. The journalled runtime path and slot are
5801        // the only facts left, and `04-security-recovery.md` requires them to be
5802        // enough: the alternative is scanning a root to work out which
5803        // directories were ours, which invariant 6 forbids.
5804        harness
5805            .store
5806            .remove_policy(harness.policy.id, harness.policy.revision())
5807            .unwrap();
5808        assert!(harness.store.policy(harness.policy.id).unwrap().is_none());
5809
5810        harness
5811            .launcher
5812            .clean(attempt.id)
5813            .await
5814            .expect("journal facts alone are enough to clean the slot");
5815
5816        assert_eq!(entries_of(&slot), only_the_job_workspace());
5817        assert!(marker.exists());
5818        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
5819    }
5820
5821    #[tokio::test]
5822    async fn an_injected_partial_deletion_quarantines_the_slot_across_a_restart() {
5823        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5824            .with_persistent_workspace(2);
5825        harness.ready().await;
5826        let first = harness.launch().await;
5827        let slot = harness.slot_path(1);
5828        let marker = retain_under_work(&slot);
5829        litter_the_slot(&slot);
5830        harness.conclude(first.id);
5831
5832        let Some(block) = BlockedDeletion::inject(&slot.join("bin")) else {
5833            eprintln!(
5834                "skipped: this account cannot be refused a deletion, so no partial deletion can \
5835                 be injected"
5836            );
5837            return;
5838        };
5839
5840        let refusal = harness
5841            .launcher
5842            .clean(first.id)
5843            .await
5844            .expect_err("a deletion that failed may not report a cleaned slot");
5845        let rendered = refusal.reason.to_string();
5846        assert!(rendered.contains("could not be removed"), "{rendered}");
5847
5848        let held = harness.attempt(first.id);
5849        assert_eq!(held.state(), AttemptState::Failed, "still not cleaned");
5850        assert!(held.holds_slot_lease(), "so the slot is still leased");
5851        assert!(
5852            !held.state().counts_against_capacity(),
5853            "and a concluded attempt still costs the host no capacity"
5854        );
5855
5856        // The same journal and the same directories, under a launcher that
5857        // remembers nothing. Recovery must complete: a host that can launch
5858        // nothing at all because one slot is stuck is not what "does not count
5859        // as active host capacity" means.
5860        let restarted = harness.restart();
5861        restarted
5862            .recover_startup(std::slice::from_ref(&harness.policy))
5863            .await
5864            .expect("one quarantined slot does not stop the host recovering");
5865        assert_eq!(
5866            harness.attempt(first.id).state(),
5867            AttemptState::Failed,
5868            "the quarantine survived the restart"
5869        );
5870        assert!(
5871            harness
5872                .reconcile_events
5873                .events()
5874                .iter()
5875                .any(|event| matches!(
5876                    event,
5877                    LifecycleEvent::AttemptCleanFailed {
5878                        reason: "slot_entry_could_not_be_removed",
5879                        ..
5880                    }
5881                )),
5882            "the refusal is reported rather than retried in silence"
5883        );
5884
5885        // Capacity two, slot one quarantined: the next attempt goes to s2 and
5886        // never to the slot still holding runner state.
5887        let guard = harness.allocation_lock.acquire().await.unwrap();
5888        let second = restarted
5889            .launch(LaunchRequest {
5890                host: &harness.host,
5891                policy: &harness.policy,
5892                allocation_guard: &guard,
5893            })
5894            .await
5895            .expect("the host can still launch");
5896        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
5897        drop(guard);
5898
5899        // And the same cleanup succeeds once the obstruction is gone, which is
5900        // what "retry through normal recovery" has to mean.
5901        block.release();
5902        restarted
5903            .clean(first.id)
5904            .await
5905            .expect("the retried cleanup completes");
5906        assert_eq!(entries_of(&slot), only_the_job_workspace());
5907        assert!(marker.exists());
5908        assert_eq!(harness.attempt(first.id).state(), AttemptState::Cleaned);
5909    }
5910
5911    /// The disposable half of the same injection, which had no test of its own.
5912    ///
5913    /// `scrub_workspace`'s ephemeral arm turns a failed `remove_dir_all` into
5914    /// `"attempt workspace could not be removed"`, and until now that branch was
5915    /// only reachable in theory: every injected-deletion test drove a persistent
5916    /// slot. The property is the same one and matters for the same reason --
5917    /// `04-security-recovery.md`'s "Cleanup partly fails and the slot is reused
5918    /// anyway" -- but the disposable guarantee is stronger, so a cleanup that
5919    /// reported success over a directory it had not removed would be the
5920    /// contamination gate failing silently rather than a slot being held.
5921    #[tokio::test]
5922    async fn an_injected_deletion_failure_leaves_a_disposable_attempt_uncleaned() {
5923        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
5924        harness.ready().await;
5925        let attempt = harness.launch().await;
5926        let runtime = attempt.runtime_path().to_path_buf();
5927        assert_eq!(attempt.workspace(), AttemptWorkspace::Ephemeral);
5928        harness.conclude(attempt.id);
5929
5930        let Some(block) = BlockedDeletion::inject(&runtime.join("held-open-subdirectory")) else {
5931            eprintln!(
5932                "skipped: this account cannot be refused a deletion, so no partial deletion can be injected"
5933            );
5934            return;
5935        };
5936
5937        let refusal = harness
5938            .launcher
5939            .clean(attempt.id)
5940            .await
5941            .expect_err("a deletion that failed may not report a removed workspace");
5942        let rendered = refusal.reason.to_string();
5943        assert!(
5944            rendered.contains("could not be removed"),
5945            "the refusal names what happened: {rendered}"
5946        );
5947        assert_ne!(
5948            harness.attempt(attempt.id).state(),
5949            AttemptState::Cleaned,
5950            "an attempt whose directory is still on disk is not cleaned"
5951        );
5952        assert!(
5953            runtime.is_dir(),
5954            "the directory the removal could not finish is still there, which is the fact the journal must keep agreeing with"
5955        );
5956
5957        // And the ordinary retry -- the reconciler's next terminal sweep --
5958        // finishes it once the obstruction is gone.
5959        block.release();
5960        harness
5961            .launcher
5962            .clean(attempt.id)
5963            .await
5964            .expect("the retried cleanup completes");
5965        assert!(!runtime.exists(), "the whole attempt directory goes");
5966        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
5967    }
5968
5969    #[tokio::test]
5970    async fn changing_a_repository_back_to_ephemeral_leaves_every_old_slot_untouched() {
5971        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5972            .with_persistent_workspace(1);
5973        harness.ready().await;
5974        let first = harness.launch().await;
5975        let slot = harness.slot_path(1);
5976        let marker = retain_under_work(&slot);
5977        harness.cleanup_retaining_work(first.id).await;
5978
5979        // Every attempt for this policy is cleaned, so the mutation is allowed
5980        // (`04-security-recovery.md`, "Recovery rules"). What it must not do is
5981        // move or delete anything the operator still owns.
5982        harness
5983            .policy
5984            .set_workspace_policy(WorkspacePolicy::Ephemeral)
5985            .unwrap();
5986
5987        let second = harness.launch().await;
5988        assert_eq!(second.workspace(), AttemptWorkspace::Ephemeral);
5989        assert_eq!(
5990            second.runtime_path().parent().unwrap(),
5991            harness.host_root(),
5992            "a disposable attempt is a child of the host root"
5993        );
5994        assert!(slot.is_dir(), "the old slot is left where it stands");
5995        assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
5996
5997        // And cleaning the disposable attempt removes its own directory whole
5998        // without reaching the retained slot beside it.
5999        harness.conclude(second.id);
6000        harness.launcher.clean(second.id).await.unwrap();
6001        assert!(!second.runtime_path().exists());
6002        assert!(marker.exists());
6003    }
6004
6005    #[tokio::test]
6006    async fn a_persistent_slot_is_scrubbed_only_after_the_process_is_signalled_and_gone() {
6007        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
6008            .with_persistent_workspace(1);
6009        harness.ready().await;
6010        let slot = harness.slot_path(1);
6011        fs::create_dir_all(&slot).unwrap();
6012        let marker = retain_under_work(&slot);
6013        litter_the_slot(&slot);
6014
6015        let id = AttemptId::new_random();
6016        let mut attempt = RunnerAttempt::allocate_in(
6017            id,
6018            harness.policy.id,
6019            &slot,
6020            AttemptWorkspace::persistent_slot(nz(1)),
6021            harness.clock.now(),
6022        );
6023        attempt.jit_received(harness.clock.now()).unwrap();
6024        attempt.started(4242, harness.clock.now()).unwrap();
6025        harness.store.record_attempt(&attempt).unwrap();
6026        harness.clock.advance_secs(11);
6027        harness.processes.set_alive(true);
6028        harness
6029            .github
6030            .observe(GithubRunnerObservation::NotRegistered);
6031
6032        harness.launcher.supervise(&harness.policy).await.unwrap();
6033
6034        // The identity and termination ordering `e3` established is unchanged by
6035        // the workspace kind: the intent is durable before the signal, and the
6036        // slot is scrubbed only once the process is gone.
6037        let actions = harness.processes.actions.lock().unwrap().clone();
6038        let intent = actions
6039            .iter()
6040            .position(|action| *action == "terminate_intent")
6041            .unwrap();
6042        let signal = actions
6043            .iter()
6044            .position(|action| *action == "terminate")
6045            .unwrap();
6046        assert!(intent < signal, "{actions:?}");
6047        assert!(!harness.processes.alive.load(Ordering::SeqCst));
6048
6049        let cleaned = harness.attempt(id);
6050        assert_eq!(cleaned.state(), AttemptState::Cleaned);
6051        assert!(matches!(
6052            cleaned.outcome(),
6053            Some(AttemptOutcome::Failed {
6054                reason: FailureReason::TerminatedAfterRegistrationTimeout
6055            })
6056        ));
6057        assert_eq!(entries_of(&slot), only_the_job_workspace());
6058        assert!(marker.exists());
6059    }
6060
6061    #[test]
6062    fn a_scrub_retains_one_real_work_directory_and_removes_every_other_entry() {
6063        let root = tempfile::tempdir().unwrap();
6064        let slot = root.path().join("s1");
6065        fs::create_dir(&slot).unwrap();
6066        let marker = retain_under_work(&slot);
6067        litter_the_slot(&slot);
6068        fs::write(slot.join("runner-package"), b"verified").unwrap();
6069
6070        scrub_slot_entries(&slot).expect("a slot of ordinary runner state scrubs");
6071        verify_slot_scrubbed(&slot).expect("and proves it afterwards");
6072
6073        assert_eq!(entries_of(&slot), only_the_job_workspace());
6074        assert!(marker.exists());
6075    }
6076
6077    #[test]
6078    fn a_residue_refusal_never_reports_the_under_count_as_the_fact() {
6079        let slot = Path::new("/runners/s1");
6080
6081        // The ordinary case: the listing counted, so the count is the fact and
6082        // the published names qualify it.
6083        let counted = residue_detail(slot, 2, &["`bin`".to_owned()]);
6084        assert!(counted.contains("2 entries other than"), "{counted}");
6085        assert!(counted.contains("including `bin`"), "{counted}");
6086        assert_eq!(
6087            residue_detail(slot, 1, &[]),
6088            format!(
6089                "1 entry other than `{DEFAULT_WORK_FOLDER}` survived cleanup of {}",
6090                slot.display()
6091            )
6092        );
6093
6094        // The race the second pass exists for: the listing saw nothing and the
6095        // filesystem answered otherwise. Saying "0 entries survived" here would
6096        // state the under-count as the fact and contradict the rest of the
6097        // sentence.
6098        let raced = residue_detail(slot, 0, &["`.credentials`".to_owned()]);
6099        assert!(!raced.contains('0'), "{raced}");
6100        assert!(raced.contains("reported nothing but"), "{raced}");
6101        assert!(raced.contains("`.credentials` survived cleanup"), "{raced}");
6102    }
6103
6104    #[test]
6105    fn verification_asks_the_filesystem_rather_than_the_listing_that_missed_an_entry() {
6106        let root = tempfile::tempdir().unwrap();
6107        let slot = root.path().join("s1");
6108        fs::create_dir(&slot).unwrap();
6109        fs::create_dir(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
6110        verify_slot_scrubbed(&slot).expect("only `_work` is a clean slot");
6111
6112        // Runner binaries, registration identity, process identity and this
6113        // agent's lifecycle marks, one at a time, so a scrub that skipped
6114        // exactly one is still caught.
6115        for survivor in ["bin", ".credentials", IDENTITY_FILE, RUNNER_ID_FILE] {
6116            fs::write(slot.join(survivor), b"left behind").unwrap();
6117            let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
6118            assert_eq!(quarantine.refusal, SlotRefusal::Residue);
6119            assert!(
6120                quarantine.detail.contains(&format!("`{survivor}`")),
6121                "{quarantine}"
6122            );
6123            fs::remove_file(slot.join(survivor)).unwrap();
6124        }
6125
6126        // A handoff is named by its published prefix, never by the UUID that
6127        // follows it, and never by the payload it holds.
6128        let handoff = slot.join(format!("{}whatever.tmp", RestrictiveHandoff::NAME_PREFIX));
6129        fs::write(&handoff, JIT.as_bytes()).unwrap();
6130        let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
6131        assert!(
6132            quarantine.detail.contains("an encoded JIT handoff"),
6133            "{quarantine}"
6134        );
6135        assert!(!quarantine.detail.contains(JIT), "{quarantine}");
6136        fs::remove_file(&handoff).unwrap();
6137
6138        // A name a workflow chose is counted and never echoed: a slot root is
6139        // writable by the job, so a file named after a secret would be published
6140        // by any message that repeated the listing.
6141        fs::write(slot.join("ghp_DO_NOT_LEAK"), b"named by the job").unwrap();
6142        let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
6143        assert!(
6144            quarantine.detail.contains("1 entry other than"),
6145            "{quarantine}"
6146        );
6147        assert!(
6148            !quarantine.detail.contains("ghp_DO_NOT_LEAK"),
6149            "{quarantine}"
6150        );
6151    }
6152
6153    #[test]
6154    fn a_slot_is_derived_from_the_journal_and_refused_when_it_disagrees() {
6155        let root = tempfile::tempdir().unwrap();
6156        let configured =
6157            LocalAbsolutePath::new(root.path().to_str().unwrap()).expect("a local absolute root");
6158        let slot = configured.as_path().join("s1");
6159        fs::create_dir(&slot).unwrap();
6160
6161        verify_journalled_slot(&slot, nz(1), Some(&configured))
6162            .expect("the journalled slot agrees");
6163        verify_journalled_slot(&slot, nz(1), None)
6164            .expect("and a policy that is gone removes a check, not the ability to clean");
6165
6166        // The journalled slot number is what names the directory. `s1` recorded
6167        // as slot two is corrupt state, not a slot to clean.
6168        assert_eq!(
6169            verify_journalled_slot(&slot, nz(2), None)
6170                .unwrap_err()
6171                .refusal,
6172            SlotRefusal::NotTheJournalledSlot
6173        );
6174        for stray in ["s1/nested", "not-a-slot", "s01"] {
6175            let path = configured.as_path().join(stray);
6176            assert_eq!(
6177                verify_journalled_slot(&path, nz(1), None)
6178                    .unwrap_err()
6179                    .refusal,
6180                SlotRefusal::NotTheJournalledSlot,
6181                "{}",
6182                path.display()
6183            );
6184        }
6185
6186        // A surviving policy that names a different root does not get to have
6187        // its disagreement resolved by deleting something.
6188        let elsewhere = tempfile::tempdir().unwrap();
6189        let other =
6190            LocalAbsolutePath::new(elsewhere.path().to_str().unwrap()).expect("a second root");
6191        assert_eq!(
6192            verify_journalled_slot(&slot, nz(1), Some(&other))
6193                .unwrap_err()
6194                .refusal,
6195            SlotRefusal::PolicyRootDisagrees
6196        );
6197    }
6198
6199    #[cfg(unix)]
6200    #[test]
6201    fn a_substituted_work_directory_quarantines_the_slot_and_deletes_nothing_outside_it() {
6202        // Windows needs a privilege to create a junction or a symlink, so the
6203        // substitution is made here; the rule is platform-independent because it
6204        // is `symlink_metadata`'s answer plus the reparse attribute.
6205        let root = tempfile::tempdir().unwrap();
6206        let outside = root.path().join("operator-data");
6207        fs::create_dir(&outside).unwrap();
6208        let sentinel = outside.join("do-not-delete.txt");
6209        fs::write(
6210            &sentinel,
6211            b"an operator's data, outside every approved root",
6212        )
6213        .unwrap();
6214
6215        let slot = root.path().join("s1");
6216        fs::create_dir(&slot).unwrap();
6217        fs::create_dir(slot.join("bin")).unwrap();
6218        std::os::unix::fs::symlink(&outside, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
6219
6220        let quarantine = scrub_slot_entries(&slot).unwrap_err();
6221        assert_eq!(quarantine.refusal, SlotRefusal::WorkNotADirectory);
6222        assert!(
6223            sentinel.exists(),
6224            "the deletion followed the link out of the slot"
6225        );
6226        assert!(outside.is_dir());
6227        assert!(
6228            slot.join(DEFAULT_WORK_FOLDER).symlink_metadata().is_ok(),
6229            "the substituted link is left for the operator, never unlinked as if it were ours"
6230        );
6231
6232        // A `_work` that is a plain file is the same refusal for the same
6233        // reason: it is not a job workspace, and this is not the code that
6234        // decides what to do about it.
6235        let file_work = root.path().join("s2");
6236        fs::create_dir(&file_work).unwrap();
6237        fs::write(file_work.join(DEFAULT_WORK_FOLDER), b"not a directory").unwrap();
6238        assert_eq!(
6239            scrub_slot_entries(&file_work).unwrap_err().refusal,
6240            SlotRefusal::WorkNotADirectory
6241        );
6242    }
6243
6244    #[cfg(unix)]
6245    #[test]
6246    fn a_slot_replaced_by_a_link_out_of_its_root_is_refused_before_anything_is_read() {
6247        let root = tempfile::tempdir().unwrap();
6248        let outside = root.path().join("operator-data");
6249        fs::create_dir(&outside).unwrap();
6250        let sentinel = outside.join("do-not-delete.txt");
6251        fs::write(
6252            &sentinel,
6253            b"an operator's data, outside every approved root",
6254        )
6255        .unwrap();
6256
6257        // The lexical half of containment passes -- the name is right and the
6258        // parent is right -- and canonical resolution is what catches it.
6259        let inside = root.path().join("inside");
6260        fs::create_dir(&inside).unwrap();
6261        let slot = inside.join("s1");
6262        std::os::unix::fs::symlink(&outside, &slot).unwrap();
6263
6264        assert_eq!(
6265            verify_journalled_slot(&slot, nz(1), None)
6266                .unwrap_err()
6267                .refusal,
6268            SlotRefusal::Containment
6269        );
6270        assert!(sentinel.exists());
6271        assert!(
6272            slot.symlink_metadata().is_ok(),
6273            "the link is left for the operator rather than removed as if it were ours"
6274        );
6275    }
6276
6277    /// The Windows half of the case above.
6278    ///
6279    /// Containment was proven only on Unix, and a symbolic link is the wrong
6280    /// instrument to prove it with on Windows: creating one needs a privilege an
6281    /// ordinary workflow does not have, so it is not the substitution an
6282    /// attacker would reach for. A **junction** needs none, which makes it both
6283    /// the realistic attack and the one this repository must refuse -- and
6284    /// `04-security-recovery.md` names it in the same breath as the symlink for
6285    /// exactly that reason.
6286    #[cfg(windows)]
6287    #[test]
6288    fn a_slot_root_replaced_by_a_junction_is_refused_before_anything_is_read() {
6289        let root = tempfile::tempdir().unwrap();
6290        let outside = root.path().join("operator-data");
6291        fs::create_dir(&outside).unwrap();
6292        let sentinel = outside.join("do-not-delete.txt");
6293        fs::write(
6294            &sentinel,
6295            b"an operator's data, outside every approved root",
6296        )
6297        .unwrap();
6298
6299        // The lexical half of containment passes -- `s1` under the root the
6300        // journal names -- and canonical resolution is what catches it.
6301        let inside = root.path().join("inside");
6302        fs::create_dir(&inside).unwrap();
6303        let slot = inside.join("s1");
6304        let Some(()) = plant_junction(&slot, &outside) else {
6305            eprintln!("skipped: this machine would not create a directory junction");
6306            return;
6307        };
6308
6309        assert_eq!(
6310            verify_journalled_slot(&slot, nz(1), None)
6311                .unwrap_err()
6312                .refusal,
6313            SlotRefusal::Containment
6314        );
6315        assert!(
6316            sentinel.exists(),
6317            "the refusal resolved the junction and reached the operator's data"
6318        );
6319        assert!(
6320            slot.symlink_metadata().is_ok(),
6321            "the junction is left for the operator rather than removed as if it were ours"
6322        );
6323    }
6324
6325    /// Plant a directory junction at `link` pointing at `target`.
6326    ///
6327    /// A junction is the Windows substitution this has to refuse, and unlike a
6328    /// symbolic link it needs no privilege — which is exactly why it is the one
6329    /// an unprivileged workflow would reach for. `mklink` is a `cmd` builtin, so
6330    /// there is no binary to find and nothing to install; `None` means this
6331    /// machine would not make one and the caller says so rather than asserting
6332    /// nothing.
6333    #[cfg(windows)]
6334    fn plant_junction(link: &Path, target: &Path) -> Option<()> {
6335        let made = std::process::Command::new("cmd")
6336            .arg("/C")
6337            .arg("mklink")
6338            .arg("/J")
6339            .arg(link)
6340            .arg(target)
6341            .output()
6342            .ok()?;
6343        (made.status.success() && link.symlink_metadata().is_ok()).then_some(())
6344    }
6345
6346    #[cfg(windows)]
6347    #[test]
6348    fn a_work_directory_replaced_by_a_junction_fails_closed_and_deletes_nothing_beyond_it() {
6349        let root = tempfile::tempdir().unwrap();
6350        let outside = root.path().join("operator-data");
6351        fs::create_dir(&outside).unwrap();
6352        let sentinel = outside.join("do-not-delete.txt");
6353        fs::write(
6354            &sentinel,
6355            b"an operator's data, outside every approved root",
6356        )
6357        .unwrap();
6358
6359        let slot = root.path().join("s1");
6360        fs::create_dir(&slot).unwrap();
6361        fs::create_dir(slot.join("bin")).unwrap();
6362        let Some(()) = plant_junction(&slot.join(DEFAULT_WORK_FOLDER), &outside) else {
6363            eprintln!("skipped: this machine would not create a directory junction");
6364            return;
6365        };
6366
6367        // The reparse point is what `is_link_like` answers on, so a junction is
6368        // refused for the same reason a symbolic link is and neither is
6369        // descended into.
6370        let work = fs::symlink_metadata(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
6371        assert!(is_link_like(&work), "a junction is a reparse point");
6372        let quarantine = scrub_slot_entries(&slot).unwrap_err();
6373        assert_eq!(quarantine.refusal, SlotRefusal::WorkNotADirectory);
6374        assert!(
6375            sentinel.exists(),
6376            "the deletion followed the junction out of the slot"
6377        );
6378        assert!(outside.is_dir());
6379
6380        // A junction standing where an ordinary entry was is unlinked rather
6381        // than followed, so the removal still cannot reach through it.
6382        let elsewhere = root.path().join("s2");
6383        fs::create_dir(&elsewhere).unwrap();
6384        fs::create_dir(elsewhere.join(DEFAULT_WORK_FOLDER)).unwrap();
6385        if plant_junction(&elsewhere.join("externals"), &outside).is_some() {
6386            scrub_slot_entries(&elsewhere).expect("an ordinary entry is removed, junction or not");
6387            verify_slot_scrubbed(&elsewhere).expect("and the slot verifies");
6388            assert!(sentinel.exists(), "the junction was followed, not unlinked");
6389            assert_eq!(entries_of(&elsewhere), only_the_job_workspace());
6390        }
6391    }
6392
6393    #[cfg(unix)]
6394    #[tokio::test]
6395    async fn a_substituted_work_directory_leaves_the_attempt_uncleaned_and_still_leased() {
6396        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
6397            .with_persistent_workspace(2);
6398        harness.ready().await;
6399        let first = harness.launch().await;
6400        let slot = harness.slot_path(1);
6401        harness.conclude(first.id);
6402
6403        let outside = harness._root.path().join("operator-data");
6404        fs::create_dir_all(&outside).unwrap();
6405        let sentinel = outside.join("do-not-delete.txt");
6406        fs::write(&sentinel, b"outside every approved root").unwrap();
6407        std::os::unix::fs::symlink(&outside, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
6408
6409        harness
6410            .launcher
6411            .clean(first.id)
6412            .await
6413            .expect_err("a slot whose `_work` was substituted is quarantined");
6414        assert!(sentinel.exists());
6415
6416        let held = harness.attempt(first.id);
6417        assert_eq!(held.state(), AttemptState::Failed);
6418        assert!(held.holds_slot_lease());
6419
6420        // The quarantined slot is not silently chosen again.
6421        let second = harness.launch().await;
6422        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
6423    }
6424
6425    #[test]
6426    fn a_slot_that_is_a_file_is_refused_and_a_slot_that_is_gone_is_not() {
6427        let root = tempfile::tempdir().unwrap();
6428        let occupied = root.path().join("s1");
6429        fs::write(&occupied, b"an operator's file").unwrap();
6430        // The journal check passes -- it is the right name under the right root
6431        // -- and the shape check is what refuses.
6432        verify_journalled_slot(&occupied, nz(1), None).expect("the path is the journalled slot");
6433        assert_eq!(
6434            slot_is_present(&occupied).unwrap_err().refusal,
6435            SlotRefusal::SlotNotADirectory
6436        );
6437        assert_eq!(fs::read_to_string(&occupied).unwrap(), "an operator's file");
6438
6439        // A directory that is simply not there leaves nothing to remove and
6440        // nothing to prove absent, so it is not a refusal.
6441        assert!(!slot_is_present(&root.path().join("s2")).unwrap());
6442        let present = root.path().join("s3");
6443        fs::create_dir(&present).unwrap();
6444        assert!(slot_is_present(&present).unwrap());
6445    }
6446
6447    #[test]
6448    fn cleanup_dispatches_on_the_journalled_kind_and_not_on_what_the_directory_holds() {
6449        let root = tempfile::tempdir().unwrap();
6450
6451        // A disposable directory that happens to contain a `_work` still goes
6452        // whole: the workspace kind is immutable so that the shape of a
6453        // directory a workflow can write to cannot choose its own algorithm.
6454        let disposable = root.path().join("abcdef012345");
6455        fs::create_dir_all(disposable.join(DEFAULT_WORK_FOLDER).join("repo")).unwrap();
6456        let ephemeral = RunnerAttempt::allocate(
6457            AttemptId::new_random(),
6458            fixtures::POLICY_ID,
6459            &disposable,
6460            fixtures::created_at(),
6461        );
6462        remove_materialized_package(&ephemeral).unwrap();
6463        assert!(!disposable.exists());
6464
6465        // And a slot keeps its `_work` with the same contents beneath it.
6466        let slot = root.path().join("s1");
6467        fs::create_dir_all(slot.join(DEFAULT_WORK_FOLDER).join("repo")).unwrap();
6468        fs::create_dir_all(slot.join("bin")).unwrap();
6469        let persistent = RunnerAttempt::allocate_in(
6470            AttemptId::new_random(),
6471            fixtures::POLICY_ID,
6472            &slot,
6473            AttemptWorkspace::persistent_slot(nz(1)),
6474            fixtures::created_at(),
6475        );
6476        remove_materialized_package(&persistent).unwrap();
6477        assert_eq!(entries_of(&slot), only_the_job_workspace());
6478        assert!(slot.join(DEFAULT_WORK_FOLDER).join("repo").is_dir());
6479    }
6480
6481    #[test]
6482    fn every_slot_refusal_names_a_distinct_event_class_and_keeps_the_lease() {
6483        let refusals = [
6484            SlotRefusal::NotTheJournalledSlot,
6485            SlotRefusal::PolicyRootDisagrees,
6486            SlotRefusal::Containment,
6487            SlotRefusal::SlotNotADirectory,
6488            SlotRefusal::Enumeration,
6489            SlotRefusal::WorkNotADirectory,
6490            SlotRefusal::Deletion,
6491            SlotRefusal::Residue,
6492        ];
6493        let classes: BTreeSet<&str> = refusals.iter().map(|refusal| refusal.class()).collect();
6494        assert_eq!(
6495            classes.len(),
6496            refusals.len(),
6497            "an event class shared by two refusals tells an operator less than it appears to"
6498        );
6499        for refusal in refusals {
6500            // The event field is a closed vocabulary, so it has to look like
6501            // one: `d1`'s sink allows the name verbatim.
6502            assert!(
6503                refusal
6504                    .class()
6505                    .chars()
6506                    .all(|c| c.is_ascii_lowercase() || c == '_'),
6507                "{}",
6508                refusal.class()
6509            );
6510            assert!(
6511                refusal.remediation().contains("slot lease"),
6512                "every refusal has to say the lease is still held: {}",
6513                refusal.class()
6514            );
6515        }
6516    }
6517
6518    #[test]
6519    fn copy_package_tree_copies_files_and_preserves_paths_with_spaces() {
6520        let root = tempfile::tempdir().unwrap();
6521        let source = root.path().join("source with spaces");
6522        let dest = root.path().join("dest with spaces");
6523
6524        fs::create_dir_all(&source).unwrap();
6525        fs::write(source.join("file1.txt"), b"hello").unwrap();
6526
6527        let nested = source.join("nested dir");
6528        fs::create_dir_all(&nested).unwrap();
6529        fs::write(nested.join("file2.txt"), b"world").unwrap();
6530
6531        // This is not a top-level `_work`, so it should be allowed
6532        let nested_work = nested.join(DEFAULT_WORK_FOLDER);
6533        fs::create_dir_all(&nested_work).unwrap();
6534        fs::write(nested_work.join("allowed.txt"), b"allowed").unwrap();
6535
6536        copy_package_tree(&source, &dest).unwrap();
6537
6538        assert_eq!(fs::read_to_string(dest.join("file1.txt")).unwrap(), "hello");
6539        assert_eq!(
6540            fs::read_to_string(dest.join("nested dir").join("file2.txt")).unwrap(),
6541            "world"
6542        );
6543        assert_eq!(
6544            fs::read_to_string(
6545                dest.join("nested dir")
6546                    .join(DEFAULT_WORK_FOLDER)
6547                    .join("allowed.txt")
6548            )
6549            .unwrap(),
6550            "allowed"
6551        );
6552    }
6553
6554    #[test]
6555    fn copy_package_tree_refuses_top_level_work_folder() {
6556        let root = tempfile::tempdir().unwrap();
6557        let source = root.path().join("source");
6558        let dest = root.path().join("dest");
6559
6560        fs::create_dir_all(&source).unwrap();
6561        fs::write(source.join("file1.txt"), b"hello").unwrap();
6562
6563        // Top-level `_work` should be refused
6564        let top_work = source.join(DEFAULT_WORK_FOLDER);
6565        fs::create_dir_all(&top_work).unwrap();
6566
6567        let err = copy_package_tree(&source, &dest).unwrap_err();
6568        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
6569    }
6570}