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, IsolationProviderFailure,
26    RecoveryDecision, RecoveryObservation, RecoveryTimeouts, RunnerAttempt, authorize,
27    recovery_decision,
28};
29use runner_manager_domain::execution::{AttemptExecution, Backend, ImageReference};
30use runner_manager_domain::model::{AttemptId, Clock, HostId, PolicyId, ScaleTarget};
31use runner_manager_domain::path::LocalAbsolutePath;
32use runner_manager_domain::policy::{RoutingLabels, ScalePolicy};
33use runner_manager_domain::store::{Store, StoreError};
34use runner_manager_domain::workspace::{AttemptWorkspace, WorkspacePolicy};
35use runner_manager_github::jit::{
36    DEFAULT_WORK_FOLDER, EncodedJitConfig, JitError, JitGateway, JitRegistration, JitRunnerRequest,
37};
38use runner_manager_github::rest::{CancelToken, InventoryGateway};
39use runner_manager_platform::process::{
40    Adoption, ChildProcess, ProcessIdentity, RestrictiveHandoff, SpawnSpec, Termination,
41};
42use runner_manager_platform::runner_env::{self, RunnerEnv, RunnerPlatform};
43use runner_manager_platform::runner_root::{
44    self, RootOwner, RootPreflight, RunnerRootError, default_runner_root,
45};
46use secrecy::SecretString;
47
48use crate::dependency_caches::DependencyCaches;
49use crate::oci::OciProcesses;
50use crate::package::{PackageCache, PackageError, RunnerVersion};
51use crate::reconcile::{
52    AllocationGuard, CleanBackoff, EventSink, LaunchFailure, LaunchRequest, LifecycleEvent,
53    OutcomeKind, ReplacementIntent, RunnerLauncher, failure_reason_kind,
54};
55
56mod windows_hyperv;
57pub use windows_hyperv::{WindowsHyperVContainers, WindowsHyperVHostState};
58
59const IDENTITY_FILE: &str = ".runner-process.json";
60const FALLBACK_IDENTITY_FILE: &str = ".runner-process.recovery.json";
61const UNRESOLVED_PROCESS_FILE: &str = ".runner-process.unresolved";
62const RUNNER_ID_FILE: &str = ".github-runner-id";
63const TERMINATE_INTENT_FILE: &str = ".terminate-registration-timeout";
64const MAX_POST_SPAWN_STOP_ATTEMPTS: usize = 3;
65
66/// Slot-root names a cleaned persistent attempt must not have left behind.
67///
68/// This is not the rule — the rule is that *nothing* but a real `_work`
69/// survives, and [`verify_slot_scrubbed`] enforces that by counting. This list
70/// is the second, independent question asked of the same directory: each name
71/// is stat-ed directly, so a scrub that skipped one is caught even if the
72/// enumeration that was supposed to find it under-reported. Every entry is one
73/// of the things `04-security-recovery.md` requires to be proven absent before a
74/// slot is released; the encoded JIT handoff is the one exception, matched by
75/// its published prefix in [`verify_slot_scrubbed`] because the rest of its name
76/// is a UUID. Being compile-time constants, these are also the only entry names
77/// a refusal message is allowed to print.
78const SENSITIVE_SLOT_ENTRIES: &[&str] = &[
79    // Runner binaries and the launchers beside them.
80    "bin",
81    "externals",
82    "run.sh",
83    "run.cmd",
84    "config.sh",
85    "config.cmd",
86    // The registration identity GitHub's runner writes for itself, and the
87    // per-run environment it reads back.
88    ".runner",
89    ".credentials",
90    ".credentials_rsaparams",
91    ".env",
92    ".path",
93    "_diag",
94    // This agent's own process-identity and lifecycle sidecars.
95    IDENTITY_FILE,
96    FALLBACK_IDENTITY_FILE,
97    UNRESOLVED_PROCESS_FILE,
98    RUNNER_ID_FILE,
99    TERMINATE_INTENT_FILE,
100];
101#[cfg(test)]
102const TEST_LISTENER_READY: &str = ".test-listener-ready";
103
104/// GitHub Runner v2.336.0 accepts JIT configuration for `run` through its
105/// secret `ACTIONS_RUNNER_INPUT_JITCONFIG` input. The platform spawn boundary
106/// supplies that input from the restrictive handoff; the listener command line
107/// must contain only the supported `run` command.
108///
109/// The environment is the daemon's plus [`runner_env::platform_defaults`], then
110/// the dependency caches (`caches`, from [`DependencyCaches::for_launch`]), then
111/// the host's `runner.env`, which wins over either of the others.
112/// The per-attempt temporary directory goes last and `runner.env` cannot name
113/// it. On macOS a runner that still starts throttled is reported
114/// ([`SpawnSpec::expect_normal_scheduling`]).
115fn runner_listener_spec(
116    program: PathBuf,
117    runtime: &Path,
118    caches: Vec<(&'static str, std::ffi::OsString)>,
119    host_env: &RunnerEnv,
120) -> SpawnSpec {
121    let tmp = runtime.join("tmp");
122    let _ = std::fs::create_dir_all(&tmp);
123    let defaults = runner_env::platform_defaults(
124        RunnerPlatform::current(),
125        runtime,
126        &runner_env::Inherited::current(),
127        Path::exists,
128    );
129    // The Windows profile the defaults point at. Created even when
130    // `runner.env` overrides part of it: it is inside the attempt, so it costs
131    // nothing and goes with the attempt.
132    for (name, dir) in &defaults {
133        if runner_env::DIRECTORY_VARIABLES.contains(name) {
134            let _ = std::fs::create_dir_all(dir);
135        }
136    }
137    let mut spec = SpawnSpec::new(program)
138        .arg("run")
139        .working_dir(runtime)
140        .expect_normal_scheduling();
141    for (name, value) in runner_env::runner_environment(defaults, caches, host_env) {
142        spec = spec.env(name, value);
143    }
144    spec.env("TMPDIR", &tmp).env("TEMP", &tmp).env("TMP", &tmp)
145}
146
147/// Retry bounds for failures that can resolve without operator action.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub struct RetryPolicy {
150    pub max_attempts: u32,
151    pub initial: Duration,
152    pub maximum: Duration,
153}
154
155impl RetryPolicy {
156    #[must_use]
157    pub const fn bounded(max_attempts: u32, initial: Duration, maximum: Duration) -> Self {
158        Self {
159            max_attempts,
160            initial,
161            maximum,
162        }
163    }
164
165    pub(crate) fn delay(self, failure_index: u32) -> Duration {
166        let shift = failure_index.saturating_sub(1).min(31);
167        self.initial
168            .saturating_mul(1_u32 << shift)
169            .min(self.maximum)
170    }
171}
172
173/// Non-secret lifecycle evidence.  Payloads are identifiers and closed enums;
174/// neither the encoded configuration nor child output can enter this type.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub enum AttemptEvent {
177    State {
178        attempt: AttemptId,
179        state: AttemptState,
180    },
181    Retry {
182        attempt: AttemptId,
183        operation: &'static str,
184        delay: Duration,
185    },
186    /// How long each step of a launch took, whether or not it started a
187    /// runner, so a slow or failed start can be attributed to the wait for the
188    /// allocation lock, the package copy, the JIT request, or the process start.
189    Launched {
190        attempt: AttemptId,
191        started: bool,
192        timings: LaunchTimings,
193    },
194    Adopted {
195        attempt: AttemptId,
196    },
197    RemoteIdentityRecovered {
198        attempt: AttemptId,
199        runner_id: u64,
200    },
201    TerminateIntent {
202        attempt: AttemptId,
203    },
204    Terminated {
205        attempt: AttemptId,
206    },
207    /// The attempt's GitHub registration was removed by this agent. Carries the
208    /// runner id because that is the identifier an operator sees in the
209    /// target's runner settings, and the attempt id is not shown there.
210    Deregistered {
211        attempt: AttemptId,
212        runner_id: u64,
213    },
214    Concluded {
215        attempt: AttemptId,
216        outcome: OutcomeKind,
217    },
218    Cleaned {
219        attempt: AttemptId,
220        outcome: OutcomeKind,
221    },
222    QuarantinedOwnedResource {
223        attempt: AttemptId,
224    },
225}
226
227pub trait AttemptEventSink: fmt::Debug + Send + Sync {
228    fn emit(&self, event: AttemptEvent);
229}
230
231#[derive(Debug, Default)]
232pub struct AttemptEventLog(Mutex<Vec<AttemptEvent>>);
233
234impl AttemptEventLog {
235    #[must_use]
236    pub fn events(&self) -> Vec<AttemptEvent> {
237        self.0
238            .lock()
239            .map(|events| events.clone())
240            .unwrap_or_default()
241    }
242}
243
244impl AttemptEventSink for AttemptEventLog {
245    fn emit(&self, event: AttemptEvent) {
246        if let Ok(mut events) = self.0.lock() {
247            events.push(event);
248        }
249    }
250}
251
252#[derive(Debug, Clone, Copy, Default)]
253pub struct NoAttemptEvents;
254
255impl AttemptEventSink for NoAttemptEvents {
256    fn emit(&self, _event: AttemptEvent) {}
257}
258
259/// Where one launch spent its time. A step the launch never reached is zero.
260#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
261pub struct LaunchTimings {
262    /// Waiting for the host allocation lock, which another launch may hold.
263    pub lock_wait: Duration,
264    pub materialize: Duration,
265    pub register: Duration,
266    pub spawn: Duration,
267}
268
269impl LaunchTimings {
270    #[must_use]
271    pub fn total(&self) -> Duration {
272        self.lock_wait + self.materialize + self.register + self.spawn
273    }
274}
275
276#[derive(Debug, Clone, Copy)]
277enum LaunchStep {
278    Materialize,
279    Register,
280    Spawn,
281}
282
283/// Times a launch's steps; beginning one ends the one before, so an early
284/// return still leaves the step it failed in measured once [`Self::finish`]
285/// runs.
286#[derive(Debug)]
287struct LaunchStopwatch {
288    timings: LaunchTimings,
289    running: Option<(LaunchStep, std::time::Instant)>,
290}
291
292impl LaunchStopwatch {
293    fn new(lock_wait: Duration) -> Self {
294        Self {
295            timings: LaunchTimings {
296                lock_wait,
297                ..LaunchTimings::default()
298            },
299            running: None,
300        }
301    }
302
303    fn begin(&mut self, step: LaunchStep) {
304        self.finish();
305        self.running = Some((step, std::time::Instant::now()));
306    }
307
308    fn finish(&mut self) {
309        if let Some((step, since)) = self.running.take() {
310            let slot = match step {
311                LaunchStep::Materialize => &mut self.timings.materialize,
312                LaunchStep::Register => &mut self.timings.register,
313                LaunchStep::Spawn => &mut self.timings.spawn,
314            };
315            *slot = since.elapsed();
316        }
317    }
318}
319
320/// A launch slower than this is logged as a warning, with its steps.
321///
322/// A healthy launch is a few seconds; a queued job waits for all of it, and
323/// the daemon's default filter drops the `info` line that times every launch.
324const SLOW_LAUNCH: Duration = Duration::from_secs(60);
325
326/// The daemon's sink for retries and launch timings; the other attempt events
327/// already reach the log through the reconcile sink.
328///
329/// Every field name is on `d1`'s allow-list, or the redacting layer would log
330/// `[redacted]` in its place; `tests::every_field_name_the_attempt_sink_emits_is_allowed`
331/// keeps that true.
332#[derive(Debug, Clone, Copy, Default)]
333pub struct TracingAttemptEvents;
334
335impl AttemptEventSink for TracingAttemptEvents {
336    fn emit(&self, event: AttemptEvent) {
337        match event {
338            AttemptEvent::Retry {
339                attempt,
340                operation,
341                delay,
342            } => tracing::warn!(
343                event = "attempt_retry",
344                attempt_id = %attempt,
345                reason = operation,
346                retry_in_ms = millis(delay),
347            ),
348            AttemptEvent::Launched {
349                attempt,
350                started,
351                timings,
352            } => {
353                macro_rules! launched {
354                    ($level:ident, $name:literal) => {
355                        tracing::$level!(
356                            event = $name,
357                            attempt_id = %attempt,
358                            duration_ms = millis(timings.total()),
359                            lock_wait_ms = millis(timings.lock_wait),
360                            materialize_ms = millis(timings.materialize),
361                            register_ms = millis(timings.register),
362                            spawn_ms = millis(timings.spawn),
363                        )
364                    };
365                }
366                if !started {
367                    launched!(warn, "attempt_launch_failed");
368                } else if timings.total() >= SLOW_LAUNCH {
369                    launched!(warn, "attempt_launch_slow");
370                } else {
371                    launched!(info, "attempt_launched");
372                }
373            }
374            _ => {}
375        }
376    }
377}
378
379fn millis(duration: Duration) -> u64 {
380    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
381}
382
383/// Whether the demand that justified a retry still exists.
384#[async_trait]
385pub trait DemandPersistence: fmt::Debug + Send + Sync {
386    async fn persists(&self, policy: PolicyId) -> bool;
387}
388
389#[derive(Debug, Clone, Copy, Default)]
390pub struct PersistentDemand;
391
392#[async_trait]
393impl DemandPersistence for PersistentDemand {
394    async fn persists(&self, _policy: PolicyId) -> bool {
395        true
396    }
397}
398
399#[async_trait]
400pub trait RetryDelay: fmt::Debug + Send + Sync {
401    async fn wait(&self, duration: Duration);
402}
403
404#[derive(Debug, Clone, Copy, Default)]
405pub struct TokioRetryDelay;
406
407#[async_trait]
408impl RetryDelay for TokioRetryDelay {
409    async fn wait(&self, duration: Duration) {
410        tokio::time::sleep(duration).await;
411    }
412}
413
414#[derive(Debug, Clone, PartialEq, Eq)]
415pub struct JitRequestFailure {
416    pub terminal: bool,
417    pub reason: FailureReason,
418    pub retry_after: Option<Duration>,
419}
420
421/// GitHub's authoritative runner state plus the identity returned by inventory.
422/// The id is carried independently of the local sidecar so recovery can close
423/// the crash boundary immediately after a successful remote registration.
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425pub struct LifecycleGithubObservation {
426    pub status: GithubRunnerObservation,
427    pub runner_id: Option<u64>,
428}
429
430impl LifecycleGithubObservation {
431    #[must_use]
432    pub const fn unreachable() -> Self {
433        Self {
434            status: GithubRunnerObservation::Unreachable,
435            runner_id: None,
436        }
437    }
438
439    #[must_use]
440    pub const fn not_registered() -> Self {
441        Self {
442            status: GithubRunnerObservation::NotRegistered,
443            runner_id: None,
444        }
445    }
446
447    #[must_use]
448    pub const fn registered(runner_id: u64, busy: bool) -> Self {
449        Self {
450            status: GithubRunnerObservation::Registered { busy },
451            runner_id: Some(runner_id),
452        }
453    }
454}
455
456/// The two GitHub views the lifecycle needs, combined so one fake can drive
457/// registration and authoritative runner telemetry.
458#[async_trait]
459pub trait LifecycleGithub: fmt::Debug + Send + Sync {
460    async fn register(
461        &self,
462        target: &ScaleTarget,
463        request: &JitRunnerRequest,
464        cancel: &CancelToken,
465    ) -> Result<JitRegistration, JitRequestFailure>;
466
467    async fn observe(
468        &self,
469        target: &ScaleTarget,
470        attempt: AttemptId,
471        cancel: &CancelToken,
472    ) -> LifecycleGithubObservation;
473
474    /// Remove one runner registration this agent created.
475    ///
476    /// Answers whether the registration is gone, and is deliberately not
477    /// fallible in the `Result` sense: no caller may abandon a conclusion
478    /// because GitHub was unreachable. See
479    /// [`LifecycleLauncher::deregister_runner`].
480    async fn deregister(&self, target: &ScaleTarget, runner_id: u64, cancel: &CancelToken) -> bool;
481}
482
483#[async_trait]
484impl<T> LifecycleGithub for T
485where
486    T: JitGateway + InventoryGateway + fmt::Debug + Send + Sync,
487{
488    async fn register(
489        &self,
490        target: &ScaleTarget,
491        request: &JitRunnerRequest,
492        cancel: &CancelToken,
493    ) -> Result<JitRegistration, JitRequestFailure> {
494        self.generate_jit_config(target, request, cancel)
495            .await
496            .map_err(|error| {
497                let reason = if matches!(&error, JitError::Forbidden { .. }) {
498                    FailureReason::Other(
499                        "GitHub refused JIT registration with 403; check the App's runner permission and runner-group access"
500                            .into(),
501                    )
502                } else {
503                    FailureReason::JitRequestFailed
504                };
505                JitRequestFailure {
506                    terminal: error.is_terminal(),
507                    reason,
508                    retry_after: error
509                        .rate_limited()
510                        .map(|limit| limit.delay_from(self.now())),
511                }
512            })
513    }
514
515    async fn observe(
516        &self,
517        target: &ScaleTarget,
518        attempt: AttemptId,
519        cancel: &CancelToken,
520    ) -> LifecycleGithubObservation {
521        let expected_name = runner_name(attempt);
522        match self.list_runners(target, cancel).await {
523            Ok(inventory) => inventory
524                .runners()
525                .iter()
526                .find(|runner| runner.name == expected_name)
527                .map_or(LifecycleGithubObservation::not_registered(), |runner| {
528                    LifecycleGithubObservation::registered(runner.id, runner.busy)
529                }),
530            Err(_) => LifecycleGithubObservation::unreachable(),
531        }
532    }
533
534    async fn deregister(&self, target: &ScaleTarget, runner_id: u64, cancel: &CancelToken) -> bool {
535        self.remove_runner(target, runner_id, cancel).await.is_ok()
536    }
537}
538
539/// Package/cache operations used by one attempt.
540#[async_trait]
541pub trait RuntimePackages: fmt::Debug + Send + Sync {
542    async fn materialize(&self, attempt: &RunnerAttempt) -> Result<RunnerVersion, FailureReason>;
543    fn release(&self, attempt: AttemptId) -> Result<(), FailureReason>;
544    fn prune_obsolete_guarded(
545        &self,
546        authority: PruneAuthority<'_>,
547        current: &RunnerVersion,
548        attempts: &[RunnerAttempt],
549    ) -> Result<(), FailureReason>;
550}
551
552/// Unforgeable evidence that pruning was reached through e1's launch request.
553/// The type is public only because it appears in the public adapter trait; its
554/// private field and constructor prevent callers from substituting a guard
555/// acquired from an unrelated lock.
556pub struct PruneAuthority<'a> {
557    _guard: &'a AllocationGuard,
558}
559
560impl fmt::Debug for PruneAuthority<'_> {
561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562        f.write_str("PruneAuthority")
563    }
564}
565
566impl<'a> PruneAuthority<'a> {
567    fn from_launch_request(guard: &'a AllocationGuard) -> Self {
568        Self { _guard: guard }
569    }
570}
571
572/// Production package adapter.  It takes an e2 lease before returning, so a
573/// cache entry can never look unused while its runtime is starting.
574#[derive(Debug)]
575pub struct CachedRuntimePackages {
576    cache: Arc<PackageCache>,
577    trusted: Arc<TrustedTrees>,
578}
579
580impl CachedRuntimePackages {
581    /// Run `work` against a package tree on the blocking pool: a fingerprint
582    /// walks ~9,000 entries and a copy can take minutes.
583    async fn blocking<T: Send + 'static>(
584        &self,
585        root: &Path,
586        work: impl FnOnce(&TrustedTrees, &Path) -> T + Send + 'static,
587    ) -> Result<T, FailureReason> {
588        let trusted = Arc::clone(&self.trusted);
589        let root = root.to_path_buf();
590        tokio::task::spawn_blocking(move || work(&trusted, &root))
591            .await
592            .map_err(|_| FailureReason::ProcessStartFailed)
593    }
594
595    #[must_use]
596    pub fn new(cache: Arc<PackageCache>) -> Self {
597        Self {
598            cache,
599            trusted: Arc::default(),
600        }
601    }
602}
603
604#[async_trait]
605impl RuntimePackages for CachedRuntimePackages {
606    async fn materialize(&self, attempt: &RunnerAttempt) -> Result<RunnerVersion, FailureReason> {
607        let (mut installed, downloaded) = self
608            .cache
609            .ensure_installed_reporting()
610            .await
611            .map_err(package_failure)?;
612        // A cache entry this process did not install, or one that has changed
613        // since, may hold a job's edits; replace it with one downloaded and
614        // verified now. One this call just downloaded is trusted as it lands.
615        // See `TrustedTrees`.
616        let fresh = if downloaded {
617            true
618        } else if self.blocking(installed.root(), TrustedTrees::holds).await? {
619            false
620        } else {
621            installed = self.cache.reinstall().await.map_err(package_failure)?;
622            true
623        };
624        if fresh {
625            self.blocking(installed.root(), TrustedTrees::record)
626                .await?
627                .map_err(|_| FailureReason::ProcessStartFailed)?;
628        }
629        // Off the async thread: the daemon runs a current-thread runtime, and a
630        // copy (or a seed rebuild) can take minutes on a busy disk.
631        let destination = attempt.runtime_path().to_path_buf();
632        let copied = self
633            .blocking(installed.root(), move |trusted, source| {
634                copy_package_tree(source, &destination, trusted)?;
635                // Checked again after the copy: an edit a job made while it ran
636                // moved the entry's print, and the runtime may hold it.
637                if trusted.holds(source) {
638                    Ok(())
639                } else {
640                    Err(std::io::Error::other(
641                        "the runner package changed while copied",
642                    ))
643                }
644            })
645            .await?;
646        if copied.is_err() {
647            // Nothing a failed or tainted copy left may reach a retry's copy,
648            // which lays out over the same runtime.
649            let _ = remove_materialized_package(attempt);
650            return Err(FailureReason::ProcessStartFailed);
651        }
652        if let Err(error) = self.cache.lease(attempt, installed.version()) {
653            // Undoing the copy must not undo the *job* workspace: a persistent
654            // slot's `_work` is retained across attempts, and this rollback
655            // runs before the attempt that would have owned it ever started.
656            let _ = remove_materialized_package(attempt);
657            return Err(package_failure(error));
658        }
659        Ok(installed.version().clone())
660    }
661
662    fn release(&self, attempt: AttemptId) -> Result<(), FailureReason> {
663        self.cache.release(attempt).map_err(package_failure)
664    }
665
666    fn prune_obsolete_guarded(
667        &self,
668        _authority: PruneAuthority<'_>,
669        current: &RunnerVersion,
670        attempts: &[RunnerAttempt],
671    ) -> Result<(), FailureReason> {
672        for installed in self.cache.installed().map_err(package_failure)? {
673            if installed.version() != current {
674                match self.cache.prune(installed.version(), attempts) {
675                    Ok(()) | Err(PackageError::VersionInUse { .. }) => {}
676                    Err(error) => return Err(package_failure(error)),
677                }
678            }
679        }
680        Ok(())
681    }
682}
683
684fn package_failure(error: PackageError) -> FailureReason {
685    error.failure_reason().unwrap_or(FailureReason::Other(
686        "runner package cache operation failed".into(),
687    ))
688}
689
690fn package_failure_is_terminal(reason: &FailureReason) -> bool {
691    matches!(
692        reason,
693        FailureReason::RunnerPackageUnverified | FailureReason::RunnerVersionRejected
694    )
695}
696
697/// How many hex characters of the attempt id name its workspace.
698///
699/// # Why this is not the whole identifier, and why the policy is not in the path
700///
701/// Windows refuses a path over `MAX_PATH`, and the runner writes deep inside
702/// this directory: `_work/<repo>/<repo>/.git/objects/pack/pack-<40 hex>.keep`
703/// is 100 characters on its own before the repository is named twice. The
704/// layout used to add two full identifiers -- the policy's and the attempt's,
705/// 74 characters between them -- and that was enough to put a real checkout
706/// over the line. Measured, not guessed: this repository's own CI failed here
707/// three times in a row at 264 characters against a limit of 260, with
708/// `fatal: cannot write keep file ...: Filename too long`. A repository whose
709/// name is ten characters longer would have missed by fourteen.
710///
711/// The policy identifier is simply redundant -- an attempt identifier is
712/// unique on its own, and nothing reads the directory tree to find a policy's
713/// attempts, because [`crate::lifecycle::LifecycleLauncher`] asks the journal.
714/// Twelve hex characters of the attempt is 48 bits, which for the handful of
715/// directories one host holds at once is not a collision anybody will see, and
716/// the journal keeps the full identifier either way.
717///
718/// Together that is 61 characters returned to the repository name.
719const WORKSPACE_NAME_LEN: usize = 12;
720
721/// The directory name for one attempt's workspace.
722fn workspace_name(id: AttemptId) -> String {
723    let full = id.to_string();
724    full.chars()
725        .filter(|c| *c != '-')
726        .take(WORKSPACE_NAME_LEN)
727        .collect()
728}
729
730/// Where one attempt's files go, and which cleanup algorithm they are owed.
731///
732/// The pair travels together because journalling them apart is exactly the bug
733/// `AttemptWorkspace` exists to prevent: a `runtime_path` under a persistent
734/// root recorded as ephemeral would be removed whole, taking the retained job
735/// workspace with it.
736#[derive(Debug, Clone)]
737struct Placement {
738    runtime: PathBuf,
739    workspace: AttemptWorkspace,
740}
741
742/// A runner-root refusal, rendered for the operator who has to fix it.
743///
744/// `RunnerRootError`'s `Display` already names the path, the relation and the
745/// remediation command, and none of its variants can carry a credential — they
746/// are paths, and `03-migration-rollout.md` requires the remediation command to
747/// reach the operator verbatim.
748fn root_failure(error: RunnerRootError) -> LifecycleError {
749    // Logged here because here is the last place this is known at all. A launch
750    // refused by the runner root fails *before* `record_allocation`, so no
751    // attempt row is ever written: `b2` has nothing to carry the failure on and
752    // `g2` has nothing to show it from. The lifecycle event keeps only
753    // `reason=other`, by `failure_reason_kind`'s rule that no free text may
754    // reach an event -- which left the whole refusal reading
755    // `runner_start_failed reason=other`, once per poll, naming nothing.
756    //
757    // What travels is the *kind* and not the sentence, and that is forced rather
758    // than chosen: `crate::logging` redacts every field it does not allow-list
759    // and then scrubs anything path-shaped out of the ones it does, so a
760    // rendered `RunnerRootError` -- which is mostly paths -- reaches the log as
761    // `[redacted]`. `error_kind` is allow-listed and `RunnerRootError::kind` is
762    // a closed vocabulary that survives the scrub, so this names which of a
763    // dozen causes the operator has. The paths and the remediation reach them
764    // through the command line, which is not redacted.
765    tracing::warn!(
766        error_kind = error.kind(),
767        "the runner root refused this launch, so no attempt was created; the host will \
768         retry every poll until the cause is resolved. Re-running `host set-runtime-root` \
769         with the same path re-runs this check and prints the directory and the \
770         remediation in full"
771    );
772    LifecycleError::Failed(FailureReason::Other(error.to_string()))
773}
774
775/// The lowest positive slot inside `ceiling` that no uncleaned attempt holds.
776///
777/// `leases` is the journal's answer to "which slots are leased"
778/// (`Store::slot_leases_for_policy`), which deliberately includes a terminal
779/// attempt whose cleanup has not finished: that attempt still owns its
780/// directory, so its slot is not free even though it no longer counts against
781/// host capacity. `None` means the ceiling is reached, which is a refusal and
782/// not a reason to allocate `s(ceiling + 1)`.
783fn lowest_free_slot(leases: &[RunnerAttempt], ceiling: NonZeroU16) -> Option<NonZeroU16> {
784    let held: BTreeSet<u16> = leases
785        .iter()
786        .filter_map(|attempt| attempt.workspace().slot_number())
787        .collect();
788    (1..=ceiling.get())
789        .find(|slot| !held.contains(slot))
790        .and_then(NonZeroU16::new)
791}
792
793/// Create `<root>/sN`, or prove that what is already there is a real directory.
794///
795/// A symlink, junction or reparse point standing where the slot should be is
796/// refused rather than followed: it is the one thing that could put an attempt's
797/// files outside the root the operator configured, and
798/// `04-security-recovery.md` requires that case to fail closed rather than to
799/// be repaired here.
800fn create_or_validate_slot(slot: &Path) -> Result<(), LifecycleError> {
801    match fs::symlink_metadata(slot) {
802        // [`is_link_like`] and not `is_symlink`, so that this is the same
803        // question cleanup asks in [`slot_is_present`]: a reparse tag the
804        // standard library has no name for is refused here rather than
805        // allocated into and then quarantined forever by a cleanup that will
806        // not scrub it.
807        Ok(metadata) if is_link_like(&metadata) => Err(slot_refusal(
808            slot,
809            "is a symbolic link, junction or other reparse point, which could place runner \
810             files outside the configured root",
811        )),
812        Ok(metadata) if !metadata.is_dir() => Err(slot_refusal(slot, "is not a directory")),
813        Ok(_) => Ok(()),
814        Err(error) if error.kind() == std::io::ErrorKind::NotFound => fs::create_dir(slot)
815            .map_err(|source| slot_refusal(slot, format!("could not be created: {source}"))),
816        Err(source) => Err(slot_refusal(
817            slot,
818            format!("could not be inspected: {source}"),
819        )),
820    }
821}
822
823/// Accept a slot for reuse only when it is empty or holds one real `_work`.
824///
825/// `02-target-architecture.md`: "Before materialization, a reusable slot must
826/// contain only a valid real `_work` directory or be empty." Everything else —
827/// a leftover `bin/`, a link-shaped `_work`, a stray file — is refused here
828/// rather than cleaned, because deciding whether those bytes are safe is
829/// cleanup's and recovery's job (`c3`), and quietly reusing them would hand one
830/// repository's retained state to the next attempt without anybody choosing to.
831///
832/// The inspection is one level deep and uses `symlink_metadata`, so nothing is
833/// followed while it is being judged.
834fn accept_reusable_slot(slot: &Path) -> Result<(), LifecycleError> {
835    let unreadable =
836        |source: std::io::Error| slot_refusal(slot, format!("could not be read: {source}"));
837    let entries = fs::read_dir(slot).map_err(unreadable)?;
838    let mut refused: Vec<String> = Vec::new();
839    for entry in entries {
840        let entry = entry.map_err(unreadable)?;
841        let name = entry.file_name();
842        let metadata = fs::symlink_metadata(entry.path()).map_err(|source| {
843            slot_refusal(
844                slot,
845                format!("entry {name:?} could not be inspected: {source}"),
846            )
847        })?;
848        // The same predicate cleanup retains by, so a `_work` this accepts is
849        // one [`scrub_slot_entries`] will keep rather than refuse: a link, a
850        // junction or any other reparse point is not a job workspace to either
851        // of them.
852        if is_retainable_work_folder(&name, &metadata) {
853            continue;
854        }
855        refused.push(name.to_string_lossy().into_owned());
856    }
857    if refused.is_empty() {
858        return Ok(());
859    }
860    refused.sort();
861    Err(slot_refusal(
862        slot,
863        format!(
864            "holds {} that this attempt may not reuse: [{}]. A reusable slot is empty or holds \
865             one real `{DEFAULT_WORK_FOLDER}` directory and nothing else; remove or move the \
866             entries listed, or let cleanup and recovery resolve them",
867            if refused.len() == 1 {
868                "an entry"
869            } else {
870                "entries"
871            },
872            refused.join(", ")
873        ),
874    ))
875}
876
877fn slot_refusal(slot: &Path, detail: impl fmt::Display) -> LifecycleError {
878    LifecycleError::Failed(FailureReason::Other(format!(
879        "the persistent slot {} {detail}",
880        slot.display()
881    )))
882}
883
884/// Whether a directory entry names the retained job workspace.
885///
886/// The comparison folds case on Windows because the filesystem does: there
887/// `_Work` and `_work` are one directory, so a case-sensitive test would let
888/// [`scrub_slot_entries`] delete the very directory it exists to keep, let
889/// [`accept_reusable_slot`] refuse a slot that holds nothing but a valid job
890/// workspace, and let a package's top-level `_Work` merge itself into the
891/// previous attempt's `_work`. Elsewhere the two names really are two
892/// directories and only the exact one is the job workspace.
893fn is_work_folder(name: &OsStr) -> bool {
894    if cfg!(windows) {
895        name.eq_ignore_ascii_case(DEFAULT_WORK_FOLDER)
896    } else {
897        name == OsStr::new(DEFAULT_WORK_FOLDER)
898    }
899}
900
901/// Whether the operating system would follow this entry somewhere else.
902///
903/// `FileType::is_symlink` is the whole answer on Unix. On Windows it is not:
904/// the standard library reports only the symlink and mount-point reparse tags,
905/// and the substitution this has to refuse is *any* reparse point standing
906/// where a real directory should be. So the attribute bit is the test there,
907/// and a tag the standard library has no name for fails closed with the two it
908/// does.
909fn is_link_like(metadata: &fs::Metadata) -> bool {
910    if metadata.file_type().is_symlink() {
911        return true;
912    }
913    #[cfg(windows)]
914    {
915        use std::os::windows::fs::MetadataExt;
916
917        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
918        metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
919    }
920    #[cfg(not(windows))]
921    false
922}
923
924/// Whether an entry is the retained job workspace and is safe to retain.
925///
926/// The two halves are one question. A `_work` that is a file, a symlink, a
927/// junction or any other reparse point is not a job workspace, and it is also
928/// the exact substitution a hostile workflow makes to send cleanup somewhere
929/// else (`04-security-recovery.md`, "A workflow replaces `_work` with a
930/// junction or symlink to escape cleanup").
931fn is_retainable_work_folder(name: &OsStr, metadata: &fs::Metadata) -> bool {
932    is_work_folder(name) && metadata.is_dir() && !is_link_like(metadata)
933}
934
935/// Undo one package materialization, dispatching on the journalled workspace.
936///
937/// The ephemeral half is what this always did: the directory is the attempt's
938/// alone, so it goes whole. The persistent half removes the copy and nothing
939/// else, because the slot's `_work` predates this attempt and outlives it
940/// (`02-target-architecture.md`, "Persistent repository").
941fn remove_materialized_package(attempt: &RunnerAttempt) -> std::io::Result<()> {
942    match attempt.workspace() {
943        AttemptWorkspace::Ephemeral => remove_runtime_tree(attempt.runtime_path()),
944        AttemptWorkspace::PersistentSlot { .. } => scrub_slot_entries(attempt.runtime_path())
945            .map_err(|quarantine| std::io::Error::other(quarantine.to_string())),
946    }
947}
948
949/// Remove a disposable runner tree without opening workflow-created special files.
950///
951/// On Unix, `remove_dir_all` 1.0 can open a FIFO while walking a directory and
952/// wait forever for its peer. The .NET runner routinely leaves diagnostic FIFOs
953/// in its private `tmp`, so use the standard library's fd-relative Unix remover,
954/// which unlinks non-directories without opening them. Keep the external remover
955/// on Windows for its existing read-only and long-path handling; when it is
956/// refused, [`unlink_reparse_points`] takes every link out of its way and it
957/// runs once more.
958fn remove_runtime_tree(path: &Path) -> std::io::Result<()> {
959    #[cfg(windows)]
960    {
961        match remove_dir_all::remove_dir_all(path) {
962            Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
963                unlink_reparse_points(path);
964                remove_dir_all::remove_dir_all(path)
965            }
966            other => other,
967        }
968    }
969    #[cfg(not(windows))]
970    {
971        fs::remove_dir_all(path)
972    }
973}
974
975/// Remove every symlink, junction and other reparse point under `dir` as a
976/// link, without ever descending into one.
977///
978/// WinINet creates `…\INetCache\Content.IE5` as a junction whose own DACL denies
979/// `Everyone` the right to list it, and a job that points `USERPROFILE` or
980/// `LOCALAPPDATA` into its workspace gets one there. Both `remove_dir_all` 1.0
981/// and `std::fs::remove_dir_all` then fail on the whole tree with
982/// `ERROR_ACCESS_DENIED`, so the attempt could never be cleaned. Removing the
983/// link itself is a different operation (`RemoveDirectoryW` on the reparse
984/// point) that the deny entry does not cover, and once the links are gone the
985/// tree is ordinary.
986///
987/// Only walked after a refusal, so an ordinary tree is traversed once. The
988/// metadata comes from the directory listing itself, which on Windows
989/// describes a reparse point without opening it.
990///
991/// Best effort: a failure here is not reported, because
992/// [`remove_runtime_tree`]'s second `remove_dir_all` runs next and its result
993/// is the authority on whether the tree went.
994#[cfg(windows)]
995fn unlink_reparse_points(dir: &Path) {
996    let Ok(entries) = fs::read_dir(dir) else {
997        return;
998    };
999    for entry in entries.flatten() {
1000        let path = entry.path();
1001        let Ok(metadata) = entry.metadata() else {
1002            continue;
1003        };
1004        if is_link_like(&metadata) {
1005            let _ = fs::remove_dir(&path).or_else(|_| fs::remove_file(&path));
1006        } else if metadata.is_dir() {
1007            unlink_reparse_points(&path);
1008        }
1009    }
1010}
1011
1012// ---------------------------------------------------------------------------
1013// Persistent cleanup (`04-security-recovery.md`, "Safe path handling")
1014// ---------------------------------------------------------------------------
1015
1016/// Why a persistent slot could not be proven safe to scrub.
1017///
1018/// A closed set rather than a formatted string, for two reasons that point the
1019/// same way. [`LifecycleEvent::AttemptCleanFailed`] takes a `&'static str` for
1020/// exactly the reason [`crate::reconcile::failure_reason_kind`] documents —
1021/// free text is the one shape that can carry a credential past a field
1022/// allow-list. And the entries under a slot root are *workflow-controlled*: a
1023/// job that writes a file named after a secret would publish it through any
1024/// message that echoed a directory listing, which is why nothing here ever
1025/// renders an entry name that did not come from this module's own constants.
1026#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1027enum SlotRefusal {
1028    /// The journalled runtime path is not `<root>/sN` for the journalled slot.
1029    NotTheJournalledSlot,
1030    /// A policy that still exists names a different root than the journal does.
1031    PolicyRootDisagrees,
1032    /// The slot is not strictly inside its root once components resolve.
1033    Containment,
1034    /// The slot itself is a file, a link, or could not be inspected.
1035    SlotNotADirectory,
1036    /// The slot's direct entries could not be listed.
1037    Enumeration,
1038    /// `_work` is a file, a symlink, a junction or another reparse point.
1039    WorkNotADirectory,
1040    /// An entry that had to go could not be removed.
1041    Deletion,
1042    /// Something other than the job workspace survived removal.
1043    Residue,
1044}
1045
1046impl SlotRefusal {
1047    /// The event field: a fixed vocabulary, never operator or workflow text.
1048    const fn class(self) -> &'static str {
1049        match self {
1050            Self::NotTheJournalledSlot => "slot_path_is_not_the_journalled_slot",
1051            Self::PolicyRootDisagrees => "slot_root_disagrees_with_policy",
1052            Self::Containment => "slot_escapes_its_root",
1053            Self::SlotNotADirectory => "slot_is_not_a_directory",
1054            Self::Enumeration => "slot_could_not_be_enumerated",
1055            Self::WorkNotADirectory => "retained_work_is_not_a_directory",
1056            Self::Deletion => "slot_entry_could_not_be_removed",
1057            Self::Residue => "slot_still_holds_runner_state",
1058        }
1059    }
1060
1061    /// What the operator has to do, in one sentence and with no path in it.
1062    const fn remediation(self) -> &'static str {
1063        match self {
1064            Self::NotTheJournalledSlot | Self::PolicyRootDisagrees | Self::Containment => {
1065                "the attempt keeps its slot lease and nothing was removed; correct the \
1066                 repository's persistent workspace path, or remove the slot directory by hand \
1067                 once you have confirmed what is in it"
1068            }
1069            Self::SlotNotADirectory | Self::WorkNotADirectory => {
1070                "the attempt keeps its slot lease and nothing was removed; a job replaced the \
1071                 slot or its `_work` with a link, so inspect it before deleting anything and \
1072                 treat the retained workspace as untrusted"
1073            }
1074            Self::Enumeration | Self::Deletion | Self::Residue => {
1075                "the attempt keeps its slot lease and will be cleaned again on the next pass; \
1076                 release whatever is holding the files open, or remove the slot's contents by \
1077                 hand leaving only `_work`"
1078            }
1079        }
1080    }
1081}
1082
1083/// A refusal that leaves one persistent slot quarantined.
1084///
1085/// `detail` is redacted by construction: it may hold paths this product
1086/// configured, `std::io::ErrorKind` values, counts, and names drawn from
1087/// [`SENSITIVE_SLOT_ENTRIES`] — and nothing that came out of a directory
1088/// listing.
1089#[derive(Debug, Clone, PartialEq, Eq)]
1090struct SlotQuarantine {
1091    refusal: SlotRefusal,
1092    detail: String,
1093}
1094
1095impl SlotQuarantine {
1096    fn new(refusal: SlotRefusal, detail: impl Into<String>) -> Self {
1097        Self {
1098            refusal,
1099            detail: detail.into(),
1100        }
1101    }
1102}
1103
1104impl fmt::Display for SlotQuarantine {
1105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1106        write!(f, "{}; {}", self.detail, self.refusal.remediation())
1107    }
1108}
1109
1110/// Steps 1 to 3: the journalled root, the journalled slot, and containment.
1111///
1112/// Everything comes from the two immutable allocation facts — the exact runtime
1113/// path and the slot number. Not from the filesystem: scanning a root to decide
1114/// which directories are "mine" is what invariant 6 forbids, and it is also
1115/// impossible for an attempt whose policy has since been deleted. `configured`
1116/// is therefore a *cross-check* and not a source. A policy that survives has to
1117/// agree; a policy that does not survive removes a check rather than the
1118/// ability to clean the directory the journal already names.
1119///
1120/// The name test comes before the parent is used, so `<root>/s1` for a journal
1121/// row that says `s2` — and anything at all that is not one `sN` component —
1122/// is refused before a root is derived from it.
1123fn verify_journalled_slot(
1124    runtime: &Path,
1125    slot: NonZeroU16,
1126    configured: Option<&LocalAbsolutePath>,
1127) -> Result<(), SlotQuarantine> {
1128    let mislaid = || {
1129        SlotQuarantine::new(
1130            SlotRefusal::NotTheJournalledSlot,
1131            format!(
1132                "the journalled runtime {} is not the slot s{slot} this attempt was allocated as",
1133                runtime.display()
1134            ),
1135        )
1136    };
1137    let local = |path: &Path| {
1138        path.to_str()
1139            .and_then(|raw| LocalAbsolutePath::new(raw).ok())
1140            .ok_or_else(mislaid)
1141    };
1142
1143    let runtime_path = local(runtime)?;
1144    let root = local(runtime.parent().ok_or_else(mislaid)?)?;
1145    // Containment's lexical half, by construction: `derive_child` accepts one
1146    // component, so the equality below can only hold when the journalled path
1147    // really is this root's `sN` and nothing else.
1148    // The directory name comes from the domain that allocation named it with,
1149    // never from a second `s{n}` spelled out here: a convention with two
1150    // spellings would let cleanup refuse every slot the allocator created.
1151    let name = AttemptWorkspace::persistent_slot(slot)
1152        .slot_directory_name()
1153        .expect("a persistent workspace names its slot directory");
1154    let derived = runner_root::derive_child(&root, &name).map_err(|_| mislaid())?;
1155    if derived != runtime_path {
1156        return Err(mislaid());
1157    }
1158    if let Some(configured) = configured
1159        && configured != &root
1160    {
1161        return Err(SlotQuarantine::new(
1162            SlotRefusal::PolicyRootDisagrees,
1163            format!(
1164                "the journalled slot {} is not under the repository's configured persistent root \
1165                 {}",
1166                runtime.display(),
1167                configured.as_str()
1168            ),
1169        ));
1170    }
1171    // And containment's canonical half, which is what a junction planted inside
1172    // the root between allocation and cleanup has to get past.
1173    runner_root::verify_containment(&root, &derived).map_err(|source| {
1174        SlotQuarantine::new(
1175            SlotRefusal::Containment,
1176            format!("the journalled slot is not inside the root it was allocated from: {source}"),
1177        )
1178    })
1179}
1180
1181/// Whether the slot is there to be scrubbed at all, before its entries are.
1182///
1183/// `Ok(false)` — the directory is gone — is not a refusal. There is nothing to
1184/// remove and nothing to prove absent, which is the same tolerance the
1185/// disposable arm has always had for a runtime that vanished under it.
1186///
1187/// A slot that is a file, a link, a junction or any other reparse point *is* a
1188/// refusal, and it is checked here rather than inside the enumeration so that
1189/// the reason an operator reads names the shape rather than reporting that a
1190/// directory could not be listed.
1191fn slot_is_present(slot: &Path) -> Result<bool, SlotQuarantine> {
1192    match fs::symlink_metadata(slot) {
1193        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
1194        Err(source) => Err(SlotQuarantine::new(
1195            SlotRefusal::SlotNotADirectory,
1196            format!(
1197                "the slot {} could not be inspected: {:?}",
1198                slot.display(),
1199                source.kind()
1200            ),
1201        )),
1202        Ok(metadata) if !metadata.is_dir() || is_link_like(&metadata) => Err(SlotQuarantine::new(
1203            SlotRefusal::SlotNotADirectory,
1204            format!(
1205                "the slot {} is a link or a file rather than a real directory",
1206                slot.display()
1207            ),
1208        )),
1209        Ok(_) => Ok(true),
1210    }
1211}
1212
1213/// Steps 4 to 6: list the slot's direct entries, keep one real `_work`, remove
1214/// every other one.
1215///
1216/// Every call is a literal filesystem API against a path built from the slot
1217/// root and one entry name — no glob, no shell string, no repository-controlled
1218/// fragment. Nothing is followed: `symlink_metadata` says what each entry *is*,
1219/// and a link-shaped entry is unlinked rather than descended into, so a junction
1220/// planted where `bin` used to be cannot take the deletion outside the slot.
1221///
1222/// A `_work` that is not a real directory is the one entry this refuses to act
1223/// on at all. Removing it could destroy an operator's data if the link were
1224/// theirs; keeping it would hand the next attempt a workspace pointing
1225/// anywhere. `04-security-recovery.md` requires that case to quarantine the
1226/// slot, so the whole scrub stops there with nothing removed after it.
1227fn scrub_slot_entries(slot: &Path) -> Result<(), SlotQuarantine> {
1228    let unreadable = |source: std::io::Error| {
1229        SlotQuarantine::new(
1230            SlotRefusal::Enumeration,
1231            format!(
1232                "the entries of {} could not be listed: {:?}",
1233                slot.display(),
1234                source.kind()
1235            ),
1236        )
1237    };
1238    for entry in fs::read_dir(slot).map_err(unreadable)? {
1239        let name = entry.map_err(unreadable)?.file_name();
1240        let path = slot.join(&name);
1241        // Nothing is assumed from an entry that vanished: `verify_slot_scrubbed`
1242        // asks the filesystem again afterwards and refuses if it is still there.
1243        let Some(metadata) = listed_entry_metadata(&path).map_err(unreadable)? else {
1244            continue;
1245        };
1246        if is_work_folder(&name) {
1247            if is_retainable_work_folder(&name, &metadata) {
1248                continue;
1249            }
1250            return Err(SlotQuarantine::new(
1251                SlotRefusal::WorkNotADirectory,
1252                format!(
1253                    "the retained `{DEFAULT_WORK_FOLDER}` in {} is a link or a file rather than a \
1254                     real directory",
1255                    slot.display()
1256                ),
1257            ));
1258        }
1259        remove_slot_entry(&path, &metadata).map_err(|source| {
1260            SlotQuarantine::new(
1261                SlotRefusal::Deletion,
1262                format!(
1263                    "an entry of {} could not be removed: {:?}",
1264                    slot.display(),
1265                    source.kind()
1266                ),
1267            )
1268        })?;
1269    }
1270    Ok(())
1271}
1272
1273/// What a listed entry *is*, or `None` when it is no longer there.
1274///
1275/// An entry named by a listing and gone by the time it is stat-ed is absent,
1276/// which is a fact both passes over a slot want rather than an enumeration that
1277/// failed. Nothing is followed: `symlink_metadata` reports a link as a link.
1278fn listed_entry_metadata(path: &Path) -> std::io::Result<Option<fs::Metadata>> {
1279    match fs::symlink_metadata(path) {
1280        Ok(metadata) => Ok(Some(metadata)),
1281        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
1282        Err(source) => Err(source),
1283    }
1284}
1285
1286/// Remove one slot entry without following it.
1287///
1288/// An entry that is already gone is removed: the post-condition this serves is
1289/// "not there", and racing with whatever removed it first is not a refusal.
1290fn remove_slot_entry(path: &Path, metadata: &fs::Metadata) -> std::io::Result<()> {
1291    let removed = if is_link_like(metadata) {
1292        // A file symlink unlinks with `remove_file`; a directory symlink or a
1293        // Windows junction needs `remove_dir`. Neither follows the link.
1294        fs::remove_file(path).or_else(|_| fs::remove_dir(path))
1295    } else if metadata.is_dir() {
1296        remove_runtime_tree(path)
1297    } else {
1298        fs::remove_file(path)
1299    };
1300    match removed {
1301        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1302        other => other,
1303    }
1304}
1305
1306/// Step 7: prove that nothing but the retained job workspace is left.
1307///
1308/// Two passes, deliberately independent, because the interesting failure is an
1309/// enumeration that under-reports. The first asks the directory what remains
1310/// and counts everything that is not a real `_work`. The second ignores the
1311/// listing entirely and stats the names an attempt is known to write — the
1312/// runner's binaries, the registration identity it stores beside them, the
1313/// process-identity sidecars and this agent's lifecycle marks — so a scrub that
1314/// silently skipped one is caught by a question that never consulted the
1315/// listing that skipped it.
1316///
1317/// Only the second pass names anything, and the encoded JIT handoff is reported
1318/// by its published prefix rather than by the UUID that follows it. A slot root
1319/// is workflow-writable, so a job that named a file after a secret would publish
1320/// it through any message that echoed the listing; the first pass therefore
1321/// reports a count.
1322fn verify_slot_scrubbed(slot: &Path) -> Result<(), SlotQuarantine> {
1323    let unreadable = |source: std::io::Error| {
1324        SlotQuarantine::new(
1325            SlotRefusal::Enumeration,
1326            format!(
1327                "the entries of {} could not be listed to verify the scrub: {:?}",
1328                slot.display(),
1329                source.kind()
1330            ),
1331        )
1332    };
1333    let mut residue = 0_usize;
1334    let mut named: Vec<String> = Vec::new();
1335    for entry in fs::read_dir(slot).map_err(unreadable)? {
1336        let name = entry.map_err(unreadable)?.file_name();
1337        // Absent is what this pass is here to establish. The named half below
1338        // stats every sensitive entry again, so an entry that only *looks*
1339        // absent to this listing is still caught.
1340        let Some(metadata) = listed_entry_metadata(&slot.join(&name)).map_err(unreadable)? else {
1341            continue;
1342        };
1343        if is_retainable_work_folder(&name, &metadata) {
1344            continue;
1345        }
1346        residue = residue.saturating_add(1);
1347        if name
1348            .to_string_lossy()
1349            .starts_with(RestrictiveHandoff::NAME_PREFIX)
1350        {
1351            named.push("an encoded JIT handoff".to_owned());
1352        }
1353    }
1354    named.extend(
1355        SENSITIVE_SLOT_ENTRIES
1356            .iter()
1357            .filter(|entry| fs::symlink_metadata(slot.join(entry)).is_ok())
1358            .map(|entry| format!("`{entry}`")),
1359    );
1360    if residue == 0 && named.is_empty() {
1361        return Ok(());
1362    }
1363    named.sort_unstable();
1364    named.dedup();
1365    Err(SlotQuarantine::new(
1366        SlotRefusal::Residue,
1367        residue_detail(slot, residue, &named),
1368    ))
1369}
1370
1371/// Word a [`SlotRefusal::Residue`] refusal from the two facts that produced it.
1372///
1373/// Separate from [`verify_slot_scrubbed`] because the disagreement it has to
1374/// report — a listing that counted nothing and a filesystem that answered
1375/// otherwise — is a race no test can stage, and a message that contradicts
1376/// itself is exactly what an operator reads at three in the morning.
1377///
1378/// `named` is the sanitized half: entries this crate published the names of.
1379/// A name a workflow chose is only ever counted, never echoed.
1380fn residue_detail(slot: &Path, residue: usize, named: &[String]) -> String {
1381    if residue == 0 {
1382        // The whole reason the second pass ignores the listing: the listing
1383        // reported a clean slot and the filesystem disagrees. Saying "0
1384        // entries survived" here would report the under-count as the fact.
1385        format!(
1386            "the listing of {} reported nothing but `{DEFAULT_WORK_FOLDER}`, yet {} survived \
1387                 cleanup",
1388            slot.display(),
1389            named.join(", ")
1390        )
1391    } else {
1392        format!(
1393            "{residue} entr{} other than `{DEFAULT_WORK_FOLDER}` survived cleanup of {}{}",
1394            if residue == 1 { "y" } else { "ies" },
1395            slot.display(),
1396            if named.is_empty() {
1397                String::new()
1398            } else {
1399                format!(", including {}", named.join(", "))
1400            }
1401        )
1402    }
1403}
1404
1405fn replacement_operation(outcome: &AttemptOutcome) -> Option<&'static str> {
1406    match outcome {
1407        AttemptOutcome::Failed {
1408            reason: FailureReason::JitExpired,
1409        } => Some("jit_expired_replacement"),
1410        AttemptOutcome::Failed {
1411            reason: FailureReason::ProcessExitedUnexpectedly,
1412        } => Some("exit_before_acceptance_replacement"),
1413        _ => None,
1414    }
1415}
1416
1417/// Lay the verified runner package out *around* whatever the slot retains.
1418///
1419/// `02-target-architecture.md`: "The verified runner package is copied into the
1420/// slot for the attempt", beside a `_work` that survives every attempt. Two
1421/// properties make that safe, and both are structural rather than documented:
1422///
1423/// * the walk is of the **source** tree, so a retained `_work` in the
1424///   destination is never opened, never descended into, and cannot be followed
1425///   wherever it might point;
1426/// * a top-level source entry named `_work` is refused rather than copied, so a
1427///   package that ever grew one could not merge itself into, or replace, the
1428///   job workspace of the attempt before it. The refusal is top-level only,
1429///   because the retained directory is a direct child of the slot; a `_work`
1430///   nested inside the package's own tree is an ordinary name.
1431///
1432/// On Unix the copy is a copy-on-write clone where the filesystem offers one,
1433/// taken from a [`package_seed`] on the destination's own volume. A plain
1434/// byte copy of the ~9,000-file package across volumes took four minutes on a
1435/// host whose runner root shared a busy disk with a build, and a queued job
1436/// waits for every second of it.
1437fn copy_package_tree(
1438    source: &Path,
1439    destination: &Path,
1440    seeds: &TrustedTrees,
1441) -> std::io::Result<()> {
1442    refuse_work_folder(source)?;
1443
1444    #[cfg(unix)]
1445    {
1446        // A seed that cannot be made is a slower launch, not a failed one.
1447        // The seed sits under the runner root, beside job runtimes, so the
1448        // refusal is re-checked on it; a seed that fails it is bypassed.
1449        let origin = package_seed(source, destination, seeds)
1450            .ok()
1451            .filter(|seed| refuse_work_folder(seed).is_ok())
1452            .unwrap_or_else(|| source.to_path_buf());
1453        clone_tree(&origin, destination)?;
1454        // A seed a job edited during the clone no longer holds; the caller
1455        // re-checks the cache entry itself.
1456        if origin != source && !seeds.holds(&origin) {
1457            return Err(std::io::Error::other(
1458                "the package seed changed while cloned",
1459            ));
1460        }
1461        Ok(())
1462    }
1463    #[cfg(not(unix))]
1464    {
1465        let _ = seeds;
1466        copy_package_entries(source, destination, true)
1467    }
1468}
1469
1470fn refuse_work_folder(source: &Path) -> std::io::Result<()> {
1471    if source.join(DEFAULT_WORK_FOLDER).exists() {
1472        return Err(std::io::Error::new(
1473            std::io::ErrorKind::InvalidData,
1474            "a cached runner package contains a _work folder, which means it was used \
1475             to run a job before it was archived; the cache must only contain clean \
1476             extracts to prevent data leakage",
1477        ));
1478    }
1479    Ok(())
1480}
1481
1482/// Where runtime copies of the package are cloned from, beside the runtimes.
1483#[cfg(unix)]
1484const PACKAGE_SEED_DIR: &str = ".runner-package";
1485
1486/// A copy of the cache entry on the destination's volume, so that every
1487/// runtime after the first is a same-volume clone rather than a cross-volume
1488/// byte copy. Returns `source` itself when it already shares the volume.
1489///
1490/// The seed lives at `<runner root>/.runner-package/<version>` and is replaced
1491/// whenever its manifest stops matching the cache entry's, which covers both a
1492/// new version and a reinstalled one. Superseded versions and interrupted
1493/// stagings are removed on that same pass. Launches hold the host allocation
1494/// lock for the whole materialization, so no other launch is cloning from a
1495/// seed while it is replaced.
1496///
1497/// The seed sits one `..` from every job's runtime and is owned by the account
1498/// jobs run as, so it is only reused while it is provably the tree this
1499/// process built: see [`TrustedTrees`].
1500///
1501/// Only on macOS, where the runner root is all but certainly APFS and a clone
1502/// is free. On a Linux filesystem without reflinks a seed would only move every
1503/// copy's reads onto the runner root's own, possibly busy, disk.
1504#[cfg(unix)]
1505fn package_seed(
1506    source: &Path,
1507    destination: &Path,
1508    seeds: &TrustedTrees,
1509) -> std::io::Result<PathBuf> {
1510    use std::os::unix::fs::MetadataExt as _;
1511
1512    if !cfg!(target_os = "macos") {
1513        return Ok(source.to_path_buf());
1514    }
1515    let root = destination
1516        .parent()
1517        .ok_or_else(|| std::io::Error::other("a runtime directory has no parent"))?;
1518    if fs::metadata(source)?.dev() == fs::metadata(root)?.dev() {
1519        return Ok(source.to_path_buf());
1520    }
1521    refresh_package_seed(source, &root.join(PACKAGE_SEED_DIR), seeds)
1522}
1523
1524/// The package trees this process built or installed, and what each looked
1525/// like right after: the cache entry runtimes are copied from and the seeds
1526/// they are cloned from.
1527///
1528/// Both are owned by the account jobs run as, so a job can edit any file in
1529/// them, and nothing on disk can say what they should hold: the published
1530/// digest covers the archive, not the extracted tree, and a record kept on disk
1531/// could be rewritten by the same account. So a tree is trusted only while its
1532/// [`tree_fingerprint`] matches the one recorded here. Every edit, replacement
1533/// or rename moves the change time (`ctime`) of the entry or of its directory,
1534/// and only the superuser can set a change time. A tree without a record, as
1535/// every tree has after a restart, is rebuilt before it is used.
1536///
1537/// Unix only. On Windows every tree is trusted, as before.
1538#[derive(Debug, Default)]
1539pub(crate) struct TrustedTrees {
1540    #[cfg_attr(not(unix), allow(dead_code))]
1541    prints: Mutex<std::collections::HashMap<PathBuf, [u8; 32]>>,
1542}
1543
1544impl TrustedTrees {
1545    /// Whether `root` is a tree recorded here and still looks as it did.
1546    fn holds(&self, root: &Path) -> bool {
1547        #[cfg(unix)]
1548        {
1549            let recorded = self
1550                .prints
1551                .lock()
1552                .unwrap_or_else(std::sync::PoisonError::into_inner)
1553                .get(root)
1554                .copied();
1555            recorded.is_some_and(|recorded| {
1556                tree_fingerprint(root).is_ok_and(|current| current == recorded)
1557            })
1558        }
1559        #[cfg(not(unix))]
1560        {
1561            let _ = root;
1562            true
1563        }
1564    }
1565
1566    /// Trust `root` as it is now; called right after this process made it.
1567    fn record(&self, root: &Path) -> std::io::Result<()> {
1568        #[cfg(unix)]
1569        {
1570            let print = tree_fingerprint(root)?;
1571            self.prints
1572                .lock()
1573                .unwrap_or_else(std::sync::PoisonError::into_inner)
1574                .insert(root.to_path_buf(), print);
1575        }
1576        #[cfg(not(unix))]
1577        let _ = root;
1578        Ok(())
1579    }
1580}
1581
1582/// A digest of every entry under `root`: its relative path, inode, size, mode,
1583/// owner and change time.
1584#[cfg(unix)]
1585fn tree_fingerprint(root: &Path) -> std::io::Result<[u8; 32]> {
1586    use sha2::{Digest as _, Sha256};
1587    use std::os::unix::fs::MetadataExt as _;
1588
1589    fn walk(root: &Path, path: &Path, hasher: &mut Sha256) -> std::io::Result<()> {
1590        let metadata = fs::symlink_metadata(path)?;
1591        let relative = path.strip_prefix(root).unwrap_or(path);
1592        hasher.update(relative.as_os_str().as_encoded_bytes());
1593        hasher.update([0]);
1594        for field in [
1595            metadata.ino(),
1596            metadata.size(),
1597            u64::from(metadata.mode()),
1598            u64::from(metadata.uid()),
1599            u64::from(metadata.gid()),
1600        ] {
1601            hasher.update(field.to_le_bytes());
1602        }
1603        hasher.update(metadata.ctime().to_le_bytes());
1604        hasher.update(metadata.ctime_nsec().to_le_bytes());
1605        if metadata.is_dir() {
1606            let mut children = fs::read_dir(path)?
1607                .map(|entry| entry.map(|entry| entry.path()))
1608                .collect::<std::io::Result<Vec<_>>>()?;
1609            children.sort();
1610            for child in children {
1611                walk(root, &child, hasher)?;
1612            }
1613        }
1614        Ok(())
1615    }
1616
1617    let mut hasher = Sha256::new();
1618    walk(root, root, &mut hasher)?;
1619    Ok(hasher.finalize().into())
1620}
1621
1622/// The seed of `source` under `seeds`, rebuilt unless its manifest matches the
1623/// cache entry's and its fingerprint the one this process recorded.
1624#[cfg(unix)]
1625fn refresh_package_seed(
1626    source: &Path,
1627    seeds: &Path,
1628    trusted: &TrustedTrees,
1629) -> std::io::Result<PathBuf> {
1630    use crate::package::MANIFEST_FILE;
1631
1632    let version = source
1633        .file_name()
1634        .ok_or_else(|| std::io::Error::other("a cache entry has no name"))?;
1635    let seed = seeds.join(version);
1636    let manifest = fs::read(source.join(MANIFEST_FILE))?;
1637    if fs::read(seed.join(MANIFEST_FILE)).is_ok_and(|held| held == manifest) && trusted.holds(&seed)
1638    {
1639        return Ok(seed);
1640    }
1641
1642    // Superseded versions, a stale seed and interrupted stagings all go.
1643    match remove_runtime_tree(seeds) {
1644        Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error),
1645        _ => {}
1646    }
1647    fs::create_dir_all(seeds)?;
1648    let staging = seeds.join(format!(".staging-{}", uuid::Uuid::new_v4()));
1649    fs::create_dir(&staging)?;
1650    // A half-made staging would hold the disk space the fallback copy needs.
1651    if let Err(error) = clone_tree(source, &staging).and_then(|()| fs::rename(&staging, &seed)) {
1652        let _ = remove_runtime_tree(&staging);
1653        return Err(error);
1654    }
1655    // After the rename, which itself moves the seed directory's change time.
1656    trusted.record(&seed)?;
1657    Ok(seed)
1658}
1659
1660/// `cp -a`, asking for a copy-on-write clone where the platform's `cp` can.
1661///
1662/// macOS `cp -c` and GNU `--reflink=auto` both fall back to a byte copy across
1663/// volumes; a `cp` that does not know the flag at all gets a plain `cp -a`.
1664#[cfg(unix)]
1665fn clone_tree(source: &Path, destination: &Path) -> std::io::Result<()> {
1666    #[cfg(target_os = "macos")]
1667    const CLONE: &[&str] = &["-c"];
1668    #[cfg(target_os = "linux")]
1669    const CLONE: &[&str] = &["--reflink=auto"];
1670    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
1671    const CLONE: &[&str] = &[];
1672
1673    let from = format!("{}/.", source.display());
1674    let cp = |extra: &[&str]| {
1675        std::process::Command::new("cp")
1676            .arg("-a")
1677            .args(extra)
1678            .arg(&from)
1679            .arg(destination)
1680            .status()
1681    };
1682    if cp(CLONE)?.success() || cp(&[])?.success() {
1683        Ok(())
1684    } else {
1685        Err(std::io::Error::other("cp failed"))
1686    }
1687}
1688
1689#[cfg(not(unix))]
1690fn copy_package_entries(source: &Path, destination: &Path, top_level: bool) -> std::io::Result<()> {
1691    fs::create_dir_all(destination)?;
1692    for entry in fs::read_dir(source)? {
1693        let entry = entry?;
1694        if top_level && is_work_folder(&entry.file_name()) {
1695            return Err(std::io::Error::new(
1696                std::io::ErrorKind::InvalidData,
1697                format!(
1698                    "the runner package holds a top-level `{DEFAULT_WORK_FOLDER}`; copying \
1699                     it would overwrite the job workspace a persistent slot retains"
1700                ),
1701            ));
1702        }
1703        let target = destination.join(entry.file_name());
1704        if entry.file_type()?.is_dir() {
1705            copy_package_entries(&entry.path(), &target, false)?;
1706        } else {
1707            fs::copy(entry.path(), target)?;
1708        }
1709    }
1710    Ok(())
1711}
1712
1713/// Process operations are attempt-addressed so a recovered process and a child
1714/// started in this invocation are supervised through one port.
1715#[derive(Debug, Clone, PartialEq, Eq)]
1716pub struct ProcessStartFailure {
1717    pub reason: FailureReason,
1718    /// False once a child existed: the one-shot JIT value may have been
1719    /// consumed, so retrying it could start a duplicate.
1720    pub retryable: bool,
1721    /// Set only when cleanup could not prove the spawned process dead.  The
1722    /// caller must journal `starting` and retain capacity/supervision.
1723    pub live_pid: Option<u32>,
1724}
1725
1726impl ProcessStartFailure {
1727    pub(crate) fn before_spawn(reason: FailureReason) -> Self {
1728        Self {
1729            reason,
1730            retryable: true,
1731            live_pid: None,
1732        }
1733    }
1734
1735    fn after_spawn_stopped() -> Self {
1736        Self {
1737            reason: FailureReason::ProcessStartFailed,
1738            retryable: false,
1739            live_pid: None,
1740        }
1741    }
1742
1743    fn after_spawn_live(pid: u32) -> Self {
1744        Self::after_spawn_live_with_reason(pid, FailureReason::ProcessStartFailed)
1745    }
1746
1747    fn after_spawn_live_with_reason(pid: u32, reason: FailureReason) -> Self {
1748        Self {
1749            reason,
1750            retryable: false,
1751            live_pid: Some(pid),
1752        }
1753    }
1754}
1755
1756/// A credential-free capability report. An isolated policy never treats a
1757/// native-ready result as permission to launch.
1758#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1759pub enum ProviderCapability {
1760    Ready,
1761    Unsupported,
1762    NotInstalled,
1763    PermissionDenied,
1764    ImageUnavailableOrIncompatible,
1765    DiskQuotaUnavailable,
1766    Degraded,
1767}
1768
1769impl ProviderCapability {
1770    #[must_use]
1771    pub const fn display_name(self) -> &'static str {
1772        match self {
1773            Self::Ready => "ready",
1774            Self::Unsupported => "unsupported",
1775            Self::NotInstalled => "not installed",
1776            Self::PermissionDenied => "permission denied",
1777            Self::ImageUnavailableOrIncompatible => "image unavailable or incompatible",
1778            Self::DiskQuotaUnavailable => "disk quota unavailable",
1779            Self::Degraded => "degraded",
1780        }
1781    }
1782
1783    pub(crate) fn refusal(self) -> FailureReason {
1784        FailureReason::IsolationProvider(match self {
1785            Self::Ready | Self::Degraded => IsolationProviderFailure::Degraded,
1786            Self::Unsupported => IsolationProviderFailure::Unsupported,
1787            Self::NotInstalled => IsolationProviderFailure::NotInstalled,
1788            Self::PermissionDenied => IsolationProviderFailure::PermissionDenied,
1789            Self::ImageUnavailableOrIncompatible => {
1790                IsolationProviderFailure::ImageUnavailableOrIncompatible
1791            }
1792            Self::DiskQuotaUnavailable => IsolationProviderFailure::DiskQuotaUnavailable,
1793        })
1794    }
1795}
1796
1797/// Only the closed isolation category may cross from an adapter into the
1798/// attempt journal or operator error. Arbitrary adapter text could echo JIT.
1799fn safe_isolation_reason(
1800    reason: FailureReason,
1801    fallback: IsolationProviderFailure,
1802) -> FailureReason {
1803    match reason {
1804        FailureReason::IsolationProvider(_) => reason,
1805        _ => FailureReason::IsolationProvider(fallback),
1806    }
1807}
1808
1809#[derive(Debug, Clone, PartialEq, Eq)]
1810pub struct PreparedEnvironment {
1811    attempt: AttemptId,
1812    identity: Option<EnvironmentIdentity>,
1813    /// The target whose dependency-cache namespace a native runner uses:
1814    /// `prepare` sees the policy and `start` does not.
1815    cache_target: Option<runner_manager_domain::model::ScaleTarget>,
1816}
1817
1818impl PreparedEnvironment {
1819    /// An adapter must return the identity independently recorded on its resource.
1820    #[must_use]
1821    pub fn isolated(attempt: AttemptId, identity: EnvironmentIdentity) -> Self {
1822        Self {
1823            attempt,
1824            identity: Some(identity),
1825            cache_target: None,
1826        }
1827    }
1828
1829    #[must_use]
1830    pub fn identity(&self) -> Option<&EnvironmentIdentity> {
1831        self.identity.as_ref()
1832    }
1833}
1834
1835#[derive(Debug, Clone, PartialEq, Eq)]
1836pub struct ResolvedEnvironment {
1837    pub provider_kind: Backend,
1838    pub image: ImageReference,
1839}
1840
1841/// Closed, non-secret provider diagnostics; adapters cannot attach arbitrary output.
1842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1843pub enum ProviderDiagnostic {
1844    CapabilityUnavailable,
1845    ImageRejected,
1846    PrepareFailed,
1847    StartFailed,
1848    OwnershipMismatch,
1849    CleanupDeferred,
1850}
1851
1852#[derive(Debug, Clone, PartialEq, Eq)]
1853pub enum EnvironmentIdentity {
1854    NativeProcess(u32),
1855    Isolated {
1856        host: HostId,
1857        attempt: AttemptId,
1858        provider_kind: Backend,
1859        environment_id: String,
1860        resolved_image: ImageReference,
1861        generation: String,
1862    },
1863}
1864
1865#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1866pub enum EnvironmentState {
1867    Starting,
1868    Running,
1869    Exited,
1870    Missing,
1871}
1872
1873#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1874pub enum ProviderStop {
1875    Stopped,
1876    StillRunning,
1877}
1878
1879#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1880pub enum ProviderDestroy {
1881    Destroyed,
1882    Deferred(&'static str),
1883}
1884
1885fn identity_matches_intent(
1886    host: HostId,
1887    attempt: &RunnerAttempt,
1888    identity: &EnvironmentIdentity,
1889) -> bool {
1890    identity_same_allocation(host, attempt, identity)
1891        && match (attempt.execution(), identity) {
1892            (
1893                AttemptExecution::Isolated { environment_id, .. },
1894                EnvironmentIdentity::Isolated {
1895                    environment_id: id, ..
1896                },
1897            ) => environment_id
1898                .as_ref()
1899                .is_none_or(|journal_id| journal_id == id),
1900            _ => false,
1901        }
1902}
1903
1904fn identity_same_allocation(
1905    host: HostId,
1906    attempt: &RunnerAttempt,
1907    identity: &EnvironmentIdentity,
1908) -> bool {
1909    match (attempt.execution(), identity) {
1910        (
1911            AttemptExecution::Isolated {
1912                provider_kind,
1913                environment_id: _,
1914                resolved_image,
1915                generation,
1916            },
1917            EnvironmentIdentity::Isolated {
1918                host: owner,
1919                attempt: owner_attempt,
1920                provider_kind: kind,
1921                environment_id: _,
1922                resolved_image: image,
1923                generation: resource_generation,
1924            },
1925        ) => {
1926            *owner == host
1927                && *owner_attempt == attempt.id
1928                && provider_kind == kind
1929                && resolved_image == image
1930                && generation == resource_generation
1931        }
1932        _ => false,
1933    }
1934}
1935
1936/// The JIT value can be passed into a provider start exactly once. It must never
1937/// become a provider identity, label, argument, persisted configuration or log field.
1938pub struct OneTimeJitHandoff<'a> {
1939    config: &'a EncodedJitConfig,
1940}
1941
1942impl fmt::Debug for OneTimeJitHandoff<'_> {
1943    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1944        f.write_str("OneTimeJitHandoff([redacted])")
1945    }
1946}
1947
1948impl<'a> OneTimeJitHandoff<'a> {
1949    pub(crate) fn new(config: &'a EncodedJitConfig) -> Self {
1950        Self { config }
1951    }
1952
1953    /// Consuming the handoff prevents the same token being delivered twice by one call.
1954    pub fn consume(self) -> &'a EncodedJitConfig {
1955        self.config
1956    }
1957}
1958
1959/// Provider lifecycle and native process supervision. The default lifecycle
1960/// methods adapt the existing native spawn/recovery implementation, and refuse
1961/// every isolated allocation. Future platform adapters must implement their
1962/// own prepare/start/inspect/stop/destroy paths rather than fall back here.
1963pub trait ExecutionProvider: fmt::Debug + Send + Sync {
1964    fn probe(&self, policy: &ScalePolicy) -> ProviderCapability {
1965        if policy.execution_policy().is_native() {
1966            ProviderCapability::Ready
1967        } else {
1968            ProviderCapability::Unsupported
1969        }
1970    }
1971
1972    /// Resolve Auto and image identity before allocation or GitHub JIT. Native has no image.
1973    fn resolve(&self, policy: &ScalePolicy) -> Result<Option<ResolvedEnvironment>, FailureReason> {
1974        if policy.execution_policy().is_native() {
1975            Ok(None)
1976        } else {
1977            Err(FailureReason::Other(
1978                "execution provider unavailable".into(),
1979            ))
1980        }
1981    }
1982
1983    fn prepare(
1984        &self,
1985        attempt: &RunnerAttempt,
1986        policy: &ScalePolicy,
1987    ) -> Result<PreparedEnvironment, FailureReason> {
1988        if !attempt.execution().is_native() || !policy.execution_policy().is_native() {
1989            return Err(FailureReason::Other(
1990                "execution provider unavailable".into(),
1991            ));
1992        }
1993        Ok(PreparedEnvironment {
1994            attempt: attempt.id,
1995            identity: None,
1996            cache_target: None,
1997        })
1998    }
1999
2000    fn start(
2001        &self,
2002        prepared: PreparedEnvironment,
2003        attempt: &RunnerAttempt,
2004        handoff: OneTimeJitHandoff<'_>,
2005    ) -> Result<EnvironmentIdentity, ProcessStartFailure> {
2006        if prepared.attempt != attempt.id || !attempt.execution().is_native() {
2007            return Err(ProcessStartFailure::before_spawn(FailureReason::Other(
2008                "execution provider identity mismatch".into(),
2009            )));
2010        }
2011        self.spawn(attempt, handoff.consume())
2012            .map(EnvironmentIdentity::NativeProcess)
2013    }
2014
2015    fn inspect(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
2016        if !attempt.execution().is_native() {
2017            return Err(FailureReason::Other(
2018                "execution provider unavailable".into(),
2019            ));
2020        }
2021        self.is_alive(attempt).map(|alive| {
2022            if alive {
2023                EnvironmentState::Running
2024            } else {
2025                EnvironmentState::Missing
2026            }
2027        })
2028    }
2029
2030    fn stop(&self, attempt: &RunnerAttempt) -> Result<ProviderStop, FailureReason> {
2031        if !attempt.execution().is_native() {
2032            return Err(FailureReason::Other(
2033                "execution provider unavailable".into(),
2034            ));
2035        }
2036        self.terminate(attempt).map(|()| ProviderStop::Stopped)
2037    }
2038
2039    fn destroy(&self, attempt: &RunnerAttempt) -> Result<ProviderDestroy, FailureReason> {
2040        if !attempt.execution().is_native() {
2041            return Err(FailureReason::Other(
2042                "execution provider unavailable".into(),
2043            ));
2044        }
2045        // Native termination is already settled by the existing recovery
2046        // decision before workspace cleanup. There is no separate sandbox
2047        // resource to destroy, and repeating an observation here changes the
2048        // established native cleanup behaviour.
2049        Ok(ProviderDestroy::Destroyed)
2050    }
2051
2052    fn recover(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
2053        self.inspect(attempt)
2054    }
2055
2056    fn enumerate_owned(&self, _host_id: HostId) -> Vec<EnvironmentIdentity> {
2057        Vec::new() // Native processes have no independent provider resources.
2058    }
2059
2060    fn diagnostics(&self, _attempt: &RunnerAttempt) -> Vec<ProviderDiagnostic> {
2061        Vec::new() // No job or JIT output enters provider metadata.
2062    }
2063
2064    /// Independent resource metadata must match the journal before destructive calls.
2065    fn owns(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
2066        Ok(attempt.execution().is_native())
2067    }
2068
2069    fn spawn(
2070        &self,
2071        attempt: &RunnerAttempt,
2072        config: &EncodedJitConfig,
2073    ) -> Result<u32, ProcessStartFailure>;
2074    fn is_alive(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason>;
2075    /// Durable identity observed for a process that spawned before the
2076    /// `starting` journal write survived.
2077    fn recovered_pid(&self, attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason>;
2078    /// True only for a child this invocation owned and reaped with a successful
2079    /// exit status.  A recovered process that is merely gone answers false.
2080    fn completed_successfully(&self, attempt: &RunnerAttempt) -> bool;
2081    fn record_terminate_intent(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason>;
2082    fn has_terminate_intent(&self, attempt: &RunnerAttempt) -> bool;
2083    fn terminate(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason>;
2084}
2085
2086/// Compatibility name for existing native process tests and callers.
2087pub use ExecutionProvider as ProcessSupervisor;
2088
2089/// Native process supervision.  The start token is stored beside the runtime;
2090/// recovery never trusts a recycled PID merely because SQLite contains it.
2091#[derive(Debug, Default)]
2092pub struct NativeProcesses {
2093    children: Mutex<BTreeMap<AttemptId, ChildProcess>>,
2094    successful_exits: Mutex<BTreeMap<AttemptId, bool>>,
2095    /// The host's `runner.env`, read at every launch so that `host env set`
2096    /// reaches the next runner without a daemon restart. `None` applies none.
2097    runner_env_file: Option<PathBuf>,
2098    /// Persistent dependency caches. `None` gives runners none.
2099    dependency_caches: Option<DependencyCaches>,
2100    docker_cleanup: Option<crate::docker_cleanup::DockerCleanup>,
2101    #[cfg(test)]
2102    post_spawn_faults: Mutex<VecDeque<PostSpawnBoundary>>,
2103    #[cfg(test)]
2104    post_spawn_reaps: std::sync::atomic::AtomicUsize,
2105    #[cfg(test)]
2106    post_spawn_stop_failures: std::sync::atomic::AtomicUsize,
2107    #[cfg(test)]
2108    use_long_lived_test_listener: std::sync::atomic::AtomicBool,
2109}
2110
2111/// Production provider set. Native and isolated allocations are routed by the
2112/// immutable execution kind in the policy/journal; an unavailable isolated
2113/// backend can never fall through to native process launch.
2114#[derive(Debug)]
2115pub struct PlatformExecutionProvider {
2116    native: NativeProcesses,
2117    oci: OciProcesses,
2118    windows_hyper_v: WindowsHyperVContainers,
2119}
2120
2121impl PlatformExecutionProvider {
2122    #[must_use]
2123    pub fn new(host_id: HostId) -> Self {
2124        Self {
2125            native: NativeProcesses::new(),
2126            oci: OciProcesses::new(host_id),
2127            windows_hyper_v: WindowsHyperVContainers::new(host_id),
2128        }
2129    }
2130
2131    /// Applies the host's `runner.env` at `path` to every native runner.
2132    /// Isolated runners do not get it: their environment is the image's.
2133    #[must_use]
2134    pub fn with_runner_env_file(mut self, path: PathBuf) -> Self {
2135        self.native = self.native.with_runner_env_file(path);
2136        self
2137    }
2138
2139    /// Gives every native runner persistent dependency caches. Isolated
2140    /// runners do not get them: their providers mount no host directory.
2141    #[must_use]
2142    pub fn with_dependency_caches(mut self, caches: DependencyCaches) -> Self {
2143        self.native = self.native.with_dependency_caches(caches);
2144        self
2145    }
2146
2147    #[must_use]
2148    pub fn with_docker_cleanup(mut self, cleanup: crate::docker_cleanup::DockerCleanup) -> Self {
2149        self.native.docker_cleanup = Some(cleanup);
2150        self
2151    }
2152
2153    fn isolated_provider(&self, backend: Backend) -> Option<&dyn ExecutionProvider> {
2154        match backend {
2155            Backend::Auto => {
2156                #[cfg(target_os = "windows")]
2157                {
2158                    Some(&self.windows_hyper_v)
2159                }
2160                #[cfg(not(target_os = "windows"))]
2161                {
2162                    Some(&self.oci)
2163                }
2164            }
2165            Backend::Oci => Some(&self.oci),
2166            Backend::WindowsHyperVContainer => Some(&self.windows_hyper_v),
2167            Backend::VirtualMachine => None,
2168        }
2169    }
2170
2171    fn provider_for_attempt(&self, attempt: &RunnerAttempt) -> Option<&dyn ExecutionProvider> {
2172        match attempt.execution() {
2173            AttemptExecution::Native { .. } => Some(&self.native),
2174            AttemptExecution::Isolated { provider_kind, .. } => {
2175                self.isolated_provider(*provider_kind)
2176            }
2177        }
2178    }
2179
2180    fn required_provider_for_attempt(
2181        &self,
2182        attempt: &RunnerAttempt,
2183    ) -> Result<&dyn ExecutionProvider, FailureReason> {
2184        self.provider_for_attempt(attempt)
2185            .ok_or_else(|| FailureReason::Other("execution provider unavailable".into()))
2186    }
2187}
2188
2189impl ExecutionProvider for PlatformExecutionProvider {
2190    fn probe(&self, policy: &ScalePolicy) -> ProviderCapability {
2191        match policy.execution_policy() {
2192            runner_manager_domain::execution::ExecutionPolicy::Native => self.native.probe(policy),
2193            runner_manager_domain::execution::ExecutionPolicy::Isolated { backend, .. } => self
2194                .isolated_provider(*backend)
2195                .map_or(ProviderCapability::Unsupported, |provider| {
2196                    provider.probe(policy)
2197                }),
2198        }
2199    }
2200
2201    fn resolve(&self, policy: &ScalePolicy) -> Result<Option<ResolvedEnvironment>, FailureReason> {
2202        match policy.execution_policy() {
2203            runner_manager_domain::execution::ExecutionPolicy::Native => {
2204                self.native.resolve(policy)
2205            }
2206            runner_manager_domain::execution::ExecutionPolicy::Isolated { backend, .. } => self
2207                .isolated_provider(*backend)
2208                .ok_or_else(|| FailureReason::Other("execution provider unavailable".into()))?
2209                .resolve(policy),
2210        }
2211    }
2212
2213    fn prepare(
2214        &self,
2215        attempt: &RunnerAttempt,
2216        policy: &ScalePolicy,
2217    ) -> Result<PreparedEnvironment, FailureReason> {
2218        match policy.execution_policy() {
2219            runner_manager_domain::execution::ExecutionPolicy::Native => {
2220                self.native.prepare(attempt, policy)
2221            }
2222            runner_manager_domain::execution::ExecutionPolicy::Isolated { backend, .. } => self
2223                .isolated_provider(*backend)
2224                .ok_or_else(|| FailureReason::Other("execution provider unavailable".into()))?
2225                .prepare(attempt, policy),
2226        }
2227    }
2228
2229    fn start(
2230        &self,
2231        prepared: PreparedEnvironment,
2232        attempt: &RunnerAttempt,
2233        handoff: OneTimeJitHandoff<'_>,
2234    ) -> Result<EnvironmentIdentity, ProcessStartFailure> {
2235        self.provider_for_attempt(attempt)
2236            .ok_or_else(|| {
2237                ProcessStartFailure::before_spawn(FailureReason::Other(
2238                    "execution provider unavailable".into(),
2239                ))
2240            })?
2241            .start(prepared, attempt, handoff)
2242    }
2243
2244    fn inspect(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
2245        self.required_provider_for_attempt(attempt)?
2246            .inspect(attempt)
2247    }
2248
2249    fn stop(&self, attempt: &RunnerAttempt) -> Result<ProviderStop, FailureReason> {
2250        self.required_provider_for_attempt(attempt)?.stop(attempt)
2251    }
2252
2253    fn destroy(&self, attempt: &RunnerAttempt) -> Result<ProviderDestroy, FailureReason> {
2254        self.required_provider_for_attempt(attempt)?
2255            .destroy(attempt)
2256    }
2257
2258    fn recover(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
2259        self.required_provider_for_attempt(attempt)?
2260            .recover(attempt)
2261    }
2262
2263    fn enumerate_owned(&self, host_id: HostId) -> Vec<EnvironmentIdentity> {
2264        let mut owned = self.oci.enumerate_owned(host_id);
2265        owned.extend(self.windows_hyper_v.enumerate_owned(host_id));
2266        owned
2267    }
2268
2269    fn diagnostics(&self, attempt: &RunnerAttempt) -> Vec<ProviderDiagnostic> {
2270        self.provider_for_attempt(attempt)
2271            .map_or_else(Vec::new, |provider| provider.diagnostics(attempt))
2272    }
2273
2274    fn owns(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
2275        self.required_provider_for_attempt(attempt)?.owns(attempt)
2276    }
2277
2278    fn spawn(
2279        &self,
2280        attempt: &RunnerAttempt,
2281        config: &EncodedJitConfig,
2282    ) -> Result<u32, ProcessStartFailure> {
2283        if !attempt.execution().is_native() {
2284            return Err(ProcessStartFailure::before_spawn(FailureReason::Other(
2285                "native process launch refused for an isolated allocation".into(),
2286            )));
2287        }
2288        self.native.spawn(attempt, config)
2289    }
2290
2291    fn is_alive(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
2292        self.required_provider_for_attempt(attempt)?
2293            .is_alive(attempt)
2294    }
2295
2296    fn recovered_pid(&self, attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
2297        self.required_provider_for_attempt(attempt)?
2298            .recovered_pid(attempt)
2299    }
2300
2301    fn completed_successfully(&self, attempt: &RunnerAttempt) -> bool {
2302        self.provider_for_attempt(attempt)
2303            .is_some_and(|provider| provider.completed_successfully(attempt))
2304    }
2305
2306    fn record_terminate_intent(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
2307        self.required_provider_for_attempt(attempt)?
2308            .record_terminate_intent(attempt)
2309    }
2310
2311    fn has_terminate_intent(&self, attempt: &RunnerAttempt) -> bool {
2312        self.provider_for_attempt(attempt)
2313            .is_some_and(|provider| provider.has_terminate_intent(attempt))
2314    }
2315
2316    fn terminate(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
2317        self.required_provider_for_attempt(attempt)?
2318            .terminate(attempt)
2319    }
2320}
2321
2322#[cfg(test)]
2323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2324enum PostSpawnBoundary {
2325    HandoffDelete,
2326    IdentitySerialize,
2327    IdentityWrite,
2328    ChildMapInsert,
2329}
2330
2331impl NativeProcesses {
2332    #[must_use]
2333    pub fn new() -> Self {
2334        Self::default()
2335    }
2336
2337    /// Applies the host's `runner.env` at `path` to every runner launched.
2338    #[must_use]
2339    pub fn with_runner_env_file(mut self, path: PathBuf) -> Self {
2340        self.runner_env_file = Some(path);
2341        self
2342    }
2343
2344    /// Gives every runner launched persistent dependency caches.
2345    #[must_use]
2346    pub fn with_dependency_caches(mut self, caches: DependencyCaches) -> Self {
2347        self.dependency_caches = Some(caches);
2348        self
2349    }
2350
2351    /// The cache variables for `attempt`, when `prepare` named its target.
2352    fn cache_env(
2353        &self,
2354        attempt: &RunnerAttempt,
2355        target: Option<&runner_manager_domain::model::ScaleTarget>,
2356        host_env: &RunnerEnv,
2357    ) -> Vec<(&'static str, std::ffi::OsString)> {
2358        match (&self.dependency_caches, target) {
2359            (Some(caches), Some(target)) => {
2360                caches.for_launch(target, attempt.runtime_path(), host_env)
2361            }
2362            _ => Vec::new(),
2363        }
2364    }
2365
2366    /// Starts `Runner.Listener` for `attempt`, with the dependency caches of
2367    /// `cache_target` when there is one.
2368    fn spawn_listener(
2369        &self,
2370        attempt: &RunnerAttempt,
2371        config: &EncodedJitConfig,
2372        cache_target: Option<&runner_manager_domain::model::ScaleTarget>,
2373    ) -> Result<u32, ProcessStartFailure> {
2374        let handoff = RestrictiveHandoff::create(
2375            attempt.runtime_path(),
2376            SecretString::from(config.expose().to_owned()),
2377        )
2378        .map_err(|_| ProcessStartFailure::before_spawn(FailureReason::ProcessStartFailed))?;
2379        #[cfg(windows)]
2380        let program = attempt
2381            .runtime_path()
2382            .join("bin")
2383            .join("Runner.Listener.exe");
2384        #[cfg(not(windows))]
2385        let program = attempt.runtime_path().join("bin").join("Runner.Listener");
2386        // Checked after the handoff exists on purpose: the error path below is
2387        // a real post-handoff launch failure, and unwinding must delete it.
2388        if !program.is_file() {
2389            return Err(ProcessStartFailure::before_spawn(
2390                FailureReason::ProcessStartFailed,
2391            ));
2392        }
2393        let host_env = self.host_env().map_err(ProcessStartFailure::before_spawn)?;
2394        let caches = self.cache_env(attempt, cache_target, &host_env);
2395        #[cfg(test)]
2396        let spec = if self
2397            .use_long_lived_test_listener
2398            .load(std::sync::atomic::Ordering::SeqCst)
2399        {
2400            SpawnSpec::new(program)
2401                .args([
2402                    "--ignored",
2403                    "--exact",
2404                    "lifecycle::tests::long_lived_native_listener_helper",
2405                    "--nocapture",
2406                ])
2407                .env(
2408                    "RUNNER_MANAGER_TEST_LISTENER_READY",
2409                    attempt.runtime_path().join(TEST_LISTENER_READY),
2410                )
2411                .working_dir(attempt.runtime_path())
2412        } else {
2413            runner_listener_spec(program, attempt.runtime_path(), caches, &host_env)
2414        };
2415        #[cfg(not(test))]
2416        let spec = runner_listener_spec(program, attempt.runtime_path(), caches, &host_env);
2417        let (spec, docker_proxy) = if let Some(cleanup) = &self.docker_cleanup {
2418            let repository = cache_target.map(ToString::to_string).unwrap_or_default();
2419            match cleanup.launch_environment(attempt.id, &repository, &host_env) {
2420                Ok(Some(endpoint)) => (
2421                    spec.env("DOCKER_HOST", endpoint),
2422                    Some(cleanup.root.join(attempt.id.to_string())),
2423                ),
2424                Ok(None) => (spec, None),
2425                Err(error) => {
2426                    tracing::warn!(attempt_id = %attempt.id, event = "docker_accounting_unavailable", reason = ?error.kind(), "native Docker accounting could not start");
2427                    if crate::docker_cleanup::Config::load(&cleanup.config).map_or(true, |config| {
2428                        config.mode == crate::docker_cleanup::Mode::Apply
2429                    }) {
2430                        return Err(ProcessStartFailure::before_spawn(
2431                            FailureReason::ProcessStartFailed,
2432                        ));
2433                    }
2434                    (spec, None)
2435                }
2436            }
2437        } else {
2438            (spec, None)
2439        };
2440        let child = spec
2441            .spawn_runner_with_handoff(&handoff)
2442            .map_err(|_| ProcessStartFailure::before_spawn(FailureReason::ProcessStartFailed))?;
2443        // The payload is gone before any state saying "starting" is persisted.
2444        #[cfg(test)]
2445        if self.faults_at(PostSpawnBoundary::HandoffDelete) {
2446            drop(handoff);
2447            return Err(self.abort_spawned_child(child, attempt, false));
2448        }
2449        if handoff.delete().is_err() {
2450            return Err(self.abort_spawned_child(child, attempt, false));
2451        }
2452        #[cfg(test)]
2453        if self.faults_at(PostSpawnBoundary::IdentitySerialize) {
2454            return Err(self.abort_spawned_child(child, attempt, false));
2455        }
2456        let identity = match serde_json::to_vec(child.identity()) {
2457            Ok(identity) => identity,
2458            Err(_) => {
2459                return Err(self.abort_spawned_child(child, attempt, false));
2460            }
2461        };
2462        if self.persist_identity(attempt, &identity).is_err() {
2463            return Err(self.abort_spawned_child(child, attempt, true));
2464        }
2465        if let Some(directory) = docker_proxy
2466            && crate::docker_cleanup::write_json(&directory.join("runner.json"), child.identity())
2467                .is_err()
2468        {
2469            return Err(self.abort_spawned_child(child, attempt, true));
2470        }
2471        let pid = child.pid();
2472        #[cfg(test)]
2473        if self.faults_at(PostSpawnBoundary::ChildMapInsert) {
2474            return Err(self.abort_spawned_child(child, attempt, true));
2475        }
2476        let mut children = self
2477            .children
2478            .lock()
2479            .unwrap_or_else(std::sync::PoisonError::into_inner);
2480        children.insert(attempt.id, child);
2481        Ok(pid)
2482    }
2483
2484    /// The host's `runner.env`, read now.
2485    ///
2486    /// A file that cannot be read or parsed fails the launch rather than
2487    /// starting a runner without the environment the operator configured.
2488    /// [`ExecutionProvider::prepare`] asks first, before a JIT runner is
2489    /// registered, so a broken file costs no registration. The reason names
2490    /// the file and the line or variable, never a value.
2491    fn host_env(&self) -> Result<RunnerEnv, FailureReason> {
2492        let Some(path) = &self.runner_env_file else {
2493            return Ok(RunnerEnv::default());
2494        };
2495        RunnerEnv::load(path).map_err(|error| {
2496            tracing::warn!(
2497                reason = "runner_env_file_invalid",
2498                "runner.env could not be applied, so no runner starts until it is fixed: {error}"
2499            );
2500            FailureReason::Other(format!(
2501                "runner.env cannot be applied ({error}); fix it with `runner-manager host env`"
2502            ))
2503        })
2504    }
2505
2506    #[cfg(test)]
2507    fn fail_post_spawn_at(&self, boundary: PostSpawnBoundary) {
2508        self.post_spawn_faults.lock().unwrap().push_back(boundary);
2509    }
2510
2511    #[cfg(test)]
2512    fn faults_at(&self, boundary: PostSpawnBoundary) -> bool {
2513        let mut faults = self.post_spawn_faults.lock().unwrap();
2514        if faults.front() == Some(&boundary) {
2515            faults.pop_front();
2516            true
2517        } else {
2518            false
2519        }
2520    }
2521
2522    #[cfg(test)]
2523    fn fail_post_spawn_stops(&self, count: usize) {
2524        self.post_spawn_stop_failures
2525            .fetch_add(count, std::sync::atomic::Ordering::SeqCst);
2526    }
2527
2528    #[cfg(test)]
2529    fn fail_next_post_spawn_stop(&self) {
2530        self.fail_post_spawn_stops(1);
2531    }
2532
2533    #[cfg(test)]
2534    fn use_long_lived_test_listener(&self) {
2535        self.use_long_lived_test_listener
2536            .store(true, std::sync::atomic::Ordering::SeqCst);
2537    }
2538
2539    fn stop_spawned_child(&self, child: &mut ChildProcess) -> Result<(), FailureReason> {
2540        #[cfg(test)]
2541        if self
2542            .post_spawn_stop_failures
2543            .fetch_update(
2544                std::sync::atomic::Ordering::SeqCst,
2545                std::sync::atomic::Ordering::SeqCst,
2546                |left| if left > 0 { Some(left - 1) } else { None },
2547            )
2548            .is_ok()
2549        {
2550            return Err(FailureReason::Other("injected runner stop failure".into()));
2551        }
2552        child
2553            .stop(Duration::from_secs(1))
2554            .map(|_| ())
2555            .map_err(|_| FailureReason::Other("spawned runner process could not be stopped".into()))
2556    }
2557
2558    fn abort_spawned_child(
2559        &self,
2560        mut child: ChildProcess,
2561        attempt: &RunnerAttempt,
2562        remove_identity: bool,
2563    ) -> ProcessStartFailure {
2564        let mut reaped = self.stop_spawned_child(&mut child).is_ok();
2565        if reaped {
2566            if remove_identity {
2567                Self::remove_identity_files(attempt);
2568            }
2569        } else {
2570            // A failed stop is not a failed attempt yet.  Persist enough truth
2571            // for crash recovery, and retain the owned child when possible.
2572            let identity_durable =
2573                serde_json::to_vec(child.identity())
2574                    .ok()
2575                    .is_some_and(|identity| {
2576                        self.persist_identity(attempt, &identity).is_ok()
2577                            || self.persist_fallback_identity(attempt, &identity).is_ok()
2578                    });
2579            if !identity_durable {
2580                // Returning a live PID as though recovery were complete would
2581                // make the next boot trust a recyclable PID. Reaping is bounded;
2582                // if it cannot finish, the durable `starting` journal entry is
2583                // deliberately unresolved on restart and blocks new launches.
2584                for _ in 1..MAX_POST_SPAWN_STOP_ATTEMPTS {
2585                    if self.stop_spawned_child(&mut child).is_ok() {
2586                        reaped = true;
2587                        break;
2588                    }
2589                }
2590                if !reaped {
2591                    // The attempt journal will durably record `starting` and
2592                    // its PID. Recovery treats a missing full identity as
2593                    // unresolved and starts nothing, so bounded stop failure
2594                    // cannot turn into either a hang or a duplicate runner.
2595                    let pid = child.pid();
2596                    let marker = write_durable_file(
2597                        &Self::unresolved_process_path(attempt),
2598                        pid.to_string().as_bytes(),
2599                    );
2600                    self.children
2601                        .lock()
2602                        .unwrap_or_else(std::sync::PoisonError::into_inner)
2603                        .insert(attempt.id, child);
2604                    let reason = if marker.is_ok() {
2605                        FailureReason::Other(
2606                            "spawn cleanup exhausted its bounded stop attempts; the live process remains under durable unresolved supervision"
2607                                .into(),
2608                        )
2609                    } else {
2610                        FailureReason::Other(
2611                            "spawn cleanup exhausted its bounded stop attempts and the unresolved-process marker could not be journalled"
2612                                .into(),
2613                        )
2614                    };
2615                    return ProcessStartFailure::after_spawn_live_with_reason(pid, reason);
2616                }
2617            } else {
2618                let pid = child.pid();
2619                self.children
2620                    .lock()
2621                    .unwrap_or_else(std::sync::PoisonError::into_inner)
2622                    .insert(attempt.id, child);
2623                return ProcessStartFailure::after_spawn_live(pid);
2624            }
2625        }
2626        #[cfg(test)]
2627        if reaped {
2628            self.post_spawn_reaps
2629                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2630        }
2631        #[cfg(not(test))]
2632        let _ = reaped;
2633        ProcessStartFailure::after_spawn_stopped()
2634    }
2635
2636    fn identity_path(attempt: &RunnerAttempt) -> PathBuf {
2637        attempt.runtime_path().join(IDENTITY_FILE)
2638    }
2639
2640    fn fallback_identity_path(attempt: &RunnerAttempt) -> PathBuf {
2641        attempt.runtime_path().join(FALLBACK_IDENTITY_FILE)
2642    }
2643
2644    fn unresolved_process_path(attempt: &RunnerAttempt) -> PathBuf {
2645        attempt.runtime_path().join(UNRESOLVED_PROCESS_FILE)
2646    }
2647
2648    fn remove_identity_files(attempt: &RunnerAttempt) {
2649        let _ = fs::remove_file(Self::identity_path(attempt));
2650        let _ = fs::remove_file(Self::fallback_identity_path(attempt));
2651        let _ = fs::remove_file(Self::unresolved_process_path(attempt));
2652    }
2653
2654    fn persist_identity(&self, attempt: &RunnerAttempt, bytes: &[u8]) -> std::io::Result<()> {
2655        self.persist_identity_at(&Self::identity_path(attempt), bytes)
2656    }
2657
2658    fn persist_fallback_identity(
2659        &self,
2660        attempt: &RunnerAttempt,
2661        bytes: &[u8],
2662    ) -> std::io::Result<()> {
2663        self.persist_identity_at(&Self::fallback_identity_path(attempt), bytes)
2664    }
2665
2666    fn persist_identity_at(&self, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
2667        #[cfg(test)]
2668        if self.faults_at(PostSpawnBoundary::IdentityWrite) {
2669            return Err(std::io::Error::other("injected identity write failure"));
2670        }
2671        write_durable_file(path, bytes)
2672    }
2673
2674    fn intent_path(attempt: &RunnerAttempt) -> PathBuf {
2675        attempt.runtime_path().join(TERMINATE_INTENT_FILE)
2676    }
2677
2678    fn read_identity(attempt: &RunnerAttempt) -> Result<Option<ProcessIdentity>, FailureReason> {
2679        match Self::read_identity_at(&Self::identity_path(attempt))? {
2680            Some(identity) => Ok(Some(identity)),
2681            None => Self::read_identity_at(&Self::fallback_identity_path(attempt)),
2682        }
2683    }
2684
2685    fn read_identity_at(path: &Path) -> Result<Option<ProcessIdentity>, FailureReason> {
2686        match fs::read(path) {
2687            Ok(bytes) => serde_json::from_slice(&bytes)
2688                .map(Some)
2689                .map_err(|_| FailureReason::Other("process identity journal is unreadable".into())),
2690            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2691            Err(_) => Err(FailureReason::Other(
2692                "process identity journal could not be read".into(),
2693            )),
2694        }
2695    }
2696}
2697
2698impl ProcessSupervisor for NativeProcesses {
2699    fn destroy(&self, attempt: &RunnerAttempt) -> Result<ProviderDestroy, FailureReason> {
2700        if !attempt.execution().is_native() {
2701            return Err(FailureReason::Other(
2702                "execution provider unavailable".into(),
2703            ));
2704        }
2705        // Existing native reconciliation has already settled process termination
2706        // before this boundary. Capture before ephemeral workspace deletion.
2707        if let Some(caches) = &self.dependency_caches {
2708            caches.capture_git(attempt.runtime_path());
2709        }
2710        Ok(ProviderDestroy::Destroyed)
2711    }
2712
2713    fn prepare(
2714        &self,
2715        attempt: &RunnerAttempt,
2716        policy: &ScalePolicy,
2717    ) -> Result<PreparedEnvironment, FailureReason> {
2718        if !attempt.execution().is_native() || !policy.execution_policy().is_native() {
2719            return Err(FailureReason::Other(
2720                "execution provider unavailable".into(),
2721            ));
2722        }
2723        self.host_env()?;
2724        // Asked here, before the JIT registration, for the reason `host_env`
2725        // is: a broken file must cost no registration.
2726        let cache_target = match &self.dependency_caches {
2727            Some(caches) => {
2728                caches.config()?;
2729                Some(policy.target.clone())
2730            }
2731            None => None,
2732        };
2733        Ok(PreparedEnvironment {
2734            attempt: attempt.id,
2735            identity: None,
2736            cache_target,
2737        })
2738    }
2739
2740    fn start(
2741        &self,
2742        prepared: PreparedEnvironment,
2743        attempt: &RunnerAttempt,
2744        handoff: OneTimeJitHandoff<'_>,
2745    ) -> Result<EnvironmentIdentity, ProcessStartFailure> {
2746        if prepared.attempt != attempt.id || !attempt.execution().is_native() {
2747            return Err(ProcessStartFailure::before_spawn(FailureReason::Other(
2748                "execution provider identity mismatch".into(),
2749            )));
2750        }
2751        self.spawn_listener(attempt, handoff.consume(), prepared.cache_target.as_ref())
2752            .map(EnvironmentIdentity::NativeProcess)
2753    }
2754
2755    fn spawn(
2756        &self,
2757        attempt: &RunnerAttempt,
2758        config: &EncodedJitConfig,
2759    ) -> Result<u32, ProcessStartFailure> {
2760        self.spawn_listener(attempt, config, None)
2761    }
2762
2763    fn is_alive(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
2764        let mut children = self
2765            .children
2766            .lock()
2767            .unwrap_or_else(std::sync::PoisonError::into_inner);
2768        if let Some(child) = children.get_mut(&attempt.id) {
2769            return match child
2770                .try_exit_status()
2771                .map_err(|_| FailureReason::Other("runner process could not be observed".into()))?
2772            {
2773                None => Ok(true),
2774                Some(status) => {
2775                    if let Ok(mut exits) = self.successful_exits.lock() {
2776                        exits.insert(attempt.id, status.success());
2777                    }
2778                    Ok(false)
2779                }
2780            };
2781        }
2782        let Some(identity) = Self::read_identity(attempt)? else {
2783            if attempt.process_id().is_some() || Self::unresolved_process_path(attempt).is_file() {
2784                return Err(FailureReason::Other(
2785                    "runner process identity is missing; refusing recovery until the process is resolved"
2786                        .into(),
2787                ));
2788            }
2789            return Ok(false);
2790        };
2791        match identity.recheck() {
2792            Ok(Adoption::Live) => Ok(true),
2793            Ok(Adoption::Gone | Adoption::PidRecycled { .. }) => Ok(false),
2794            Err(_) => Ok(false),
2795        }
2796    }
2797
2798    fn recovered_pid(&self, attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
2799        Ok(Self::read_identity(attempt)?.map(|identity| identity.pid()))
2800    }
2801
2802    fn completed_successfully(&self, attempt: &RunnerAttempt) -> bool {
2803        self.successful_exits
2804            .lock()
2805            .ok()
2806            .and_then(|exits| exits.get(&attempt.id).copied())
2807            .unwrap_or(false)
2808    }
2809
2810    fn record_terminate_intent(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
2811        let path = Self::intent_path(attempt);
2812        write_durable_file(&path, b"registration-timeout\n")
2813            .map_err(|_| FailureReason::Other("terminate intent could not be journalled".into()))
2814    }
2815
2816    fn has_terminate_intent(&self, attempt: &RunnerAttempt) -> bool {
2817        Self::intent_path(attempt).is_file()
2818    }
2819
2820    fn terminate(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
2821        let mut children = self
2822            .children
2823            .lock()
2824            .unwrap_or_else(std::sync::PoisonError::into_inner);
2825        if let Some(child) = children.get_mut(&attempt.id) {
2826            child
2827                .stop(Duration::from_secs(10))
2828                .map_err(|_| FailureReason::Other("runner process could not be stopped".into()))?;
2829            return Ok(());
2830        }
2831        let Some(identity) = Self::read_identity(attempt)? else {
2832            return Ok(());
2833        };
2834        match identity
2835            .terminate(Duration::from_secs(10))
2836            .map_err(|_| FailureReason::Other("runner process could not be stopped".into()))?
2837        {
2838            Termination::Terminated | Termination::AlreadyGone => Ok(()),
2839            Termination::RefusedPidRecycled { .. } => Err(FailureReason::Other(
2840                "runner PID was recycled; refusing to signal it".into(),
2841            )),
2842        }
2843    }
2844}
2845
2846pub struct LifecyclePorts {
2847    pub store: Arc<dyn Store>,
2848    pub github: Arc<dyn LifecycleGithub>,
2849    pub packages: Arc<dyn RuntimePackages>,
2850    pub processes: Arc<dyn ExecutionProvider>,
2851    pub clock: Arc<dyn Clock>,
2852    pub demand: Arc<dyn DemandPersistence>,
2853    pub delay: Arc<dyn RetryDelay>,
2854    pub events: Arc<dyn AttemptEventSink>,
2855    pub reconcile_events: Arc<dyn EventSink>,
2856}
2857
2858impl fmt::Debug for LifecyclePorts {
2859    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2860        f.debug_struct("LifecyclePorts")
2861            .field("store", &self.store)
2862            .field("github", &self.github)
2863            .field("packages", &self.packages)
2864            .field("processes", &self.processes)
2865            .finish_non_exhaustive()
2866    }
2867}
2868
2869#[derive(Debug, thiserror::Error)]
2870pub enum LifecycleError {
2871    #[error("attempt journal operation failed")]
2872    Journal,
2873    #[error("attempt {0} is not in the journal")]
2874    Missing(AttemptId),
2875    #[error("attempt lifecycle transition was refused")]
2876    Transition,
2877    #[error("startup recovery has not completed")]
2878    RecoveryIncomplete,
2879    /// A persistent slot could not be proven safe to scrub, so the attempt keeps
2880    /// its uncleaned state and, with it, its slot lease.
2881    ///
2882    /// Separate from [`Self::Failed`] because the two demand opposite handling
2883    /// from the same call sites. A failure aborts the pass; a quarantine must
2884    /// not, or one stuck slot would stop the host launching anything at all —
2885    /// which is precisely what `04-security-recovery.md` rules out when it says
2886    /// such an attempt "does not count as active host capacity" and "recovery
2887    /// retries the same cleanup".
2888    #[error("the persistent slot was not cleaned: {detail}")]
2889    SlotQuarantined {
2890        /// The closed-vocabulary event field; never operator or workflow text.
2891        class: &'static str,
2892        detail: String,
2893    },
2894    /// An ephemeral runtime is still held by a late process. Its journal state
2895    /// remains unchanged and ordinary supervision retries it, but startup
2896    /// recovery must not take unrelated repositories offline because of it.
2897    #[error("{}", FailureReason::WorkspaceCleanupDeferred)]
2898    WorkspaceCleanupDeferred,
2899    #[error("isolated environment cleanup is deferred")]
2900    EnvironmentCleanupDeferred,
2901    #[error("runner lifecycle failed: {0}")]
2902    Failed(FailureReason),
2903}
2904
2905impl LifecycleError {
2906    fn reason(&self) -> FailureReason {
2907        match self {
2908            Self::Failed(reason) => reason.clone(),
2909            Self::RecoveryIncomplete => FailureReason::Other("startup recovery incomplete".into()),
2910            Self::Journal => FailureReason::Other("attempt journal operation failed".into()),
2911            Self::Missing(_) => FailureReason::Other("attempt disappeared from the journal".into()),
2912            Self::Transition => FailureReason::Other("attempt transition was refused".into()),
2913            // Rendered through `Display` rather than a second copy of the same
2914            // sentence, so the two cannot drift apart.
2915            Self::SlotQuarantined { .. } => FailureReason::Other(self.to_string()),
2916            Self::WorkspaceCleanupDeferred => FailureReason::WorkspaceCleanupDeferred,
2917            Self::EnvironmentCleanupDeferred => FailureReason::Other(self.to_string()),
2918        }
2919    }
2920}
2921
2922/// Production implementation of e1's launcher port.
2923#[derive(Debug)]
2924pub struct LifecycleLauncher {
2925    host_id: HostId,
2926    app_paths: runner_manager_platform::paths::AppPaths,
2927    diagnostics_root: PathBuf,
2928    runner_group_id: u64,
2929    timeouts: RecoveryTimeouts,
2930    retry: RetryPolicy,
2931    cancel: CancelToken,
2932    ports: LifecyclePorts,
2933    recovery_complete: Mutex<bool>,
2934    versions: Mutex<BTreeMap<AttemptId, RunnerVersion>>,
2935    pending_replacements: Mutex<BTreeMap<AttemptId, ReplacementIntent>>,
2936    /// Backoff for cleanups [`Self::supervise`] tolerates and retries, so a
2937    /// workspace that cannot be removed is not retried and reported on every
2938    /// pass.
2939    cleanup_retries: Mutex<CleanBackoff>,
2940}
2941
2942#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2943enum ReconcileProgress {
2944    Reconciled,
2945    Deferred,
2946    Replacement {
2947        attempt: AttemptId,
2948        operation: &'static str,
2949    },
2950}
2951
2952impl LifecycleLauncher {
2953    #[must_use]
2954    pub fn new(
2955        host_id: HostId,
2956        app_paths: runner_manager_platform::paths::AppPaths,
2957        diagnostics_root: impl Into<PathBuf>,
2958        runner_group_id: u64,
2959        timeouts: RecoveryTimeouts,
2960        retry: RetryPolicy,
2961        ports: LifecyclePorts,
2962    ) -> Self {
2963        Self {
2964            host_id,
2965            app_paths,
2966            diagnostics_root: diagnostics_root.into(),
2967            runner_group_id,
2968            timeouts,
2969            retry,
2970            cancel: CancelToken::new(),
2971            ports,
2972            recovery_complete: Mutex::new(false),
2973            versions: Mutex::new(BTreeMap::new()),
2974            pending_replacements: Mutex::new(BTreeMap::new()),
2975            cleanup_retries: Mutex::new(CleanBackoff::default()),
2976        }
2977    }
2978
2979    /// Reconcile the entire journal before allowing a launch.  Unknown-policy
2980    /// attempts are left untouched rather than being acted on without an
2981    /// ownership proof.
2982    pub async fn recover_startup(
2983        &self,
2984        policies: &[ScalePolicy],
2985    ) -> Result<Vec<ReplacementIntent>, LifecycleError> {
2986        *self
2987            .recovery_complete
2988            .lock()
2989            .map_err(|_| LifecycleError::Journal)? = false;
2990        let by_id: BTreeMap<_, _> = policies.iter().map(|policy| (policy.id, policy)).collect();
2991        let attempts = self
2992            .ports
2993            .store
2994            .attempts()
2995            .map_err(|_| LifecycleError::Journal)?;
2996        let owned = self.ports.processes.enumerate_owned(self.host_id);
2997        for identity in &owned {
2998            if let EnvironmentIdentity::Isolated { attempt: id, .. } = identity
2999                && !attempts.iter().any(|attempt| {
3000                    attempt.state() != AttemptState::Cleaned
3001                        && identity_matches_intent(self.host_id, attempt, identity)
3002                })
3003            {
3004                // Enumeration is discovery, not authority to delete.
3005                self.ports
3006                    .events
3007                    .emit(AttemptEvent::QuarantinedOwnedResource { attempt: *id });
3008                tracing::warn!(host_id = %self.host_id, attempt_id = %id, reason = "owned_isolated_resource_without_matching_journal", "provider resource quarantined for operator review");
3009            }
3010        }
3011        let mut unresolved = false;
3012        for mut attempt in attempts {
3013            let Some(policy) = by_id.get(&attempt.policy_id) else {
3014                if attempt.counts_against_capacity() {
3015                    unresolved = true;
3016                }
3017                continue;
3018            };
3019            authorize(self.host_id, policy, &attempt).map_err(|_| LifecycleError::Journal)?;
3020            let allocation_resources = owned
3021                .iter()
3022                .filter(|identity| identity_same_allocation(self.host_id, &attempt, identity))
3023                .collect::<Vec<_>>();
3024            if allocation_resources.len() > 1 {
3025                self.ports
3026                    .events
3027                    .emit(AttemptEvent::QuarantinedOwnedResource {
3028                        attempt: attempt.id,
3029                    });
3030                tracing::warn!(attempt_id = %attempt.id, reason = "duplicate_isolated_resource_ownership", "provider resources quarantined for operator review");
3031            }
3032            if attempt.state() != AttemptState::Cleaned
3033                && matches!(
3034                    attempt.execution(),
3035                    AttemptExecution::Isolated {
3036                        environment_id: None,
3037                        ..
3038                    }
3039                )
3040                && allocation_resources.len() == 1
3041                && let Some(EnvironmentIdentity::Isolated { environment_id, .. }) =
3042                    allocation_resources.first().copied()
3043            {
3044                attempt
3045                    .prepared_environment(environment_id.clone())
3046                    .map_err(|_| LifecycleError::Transition)?;
3047                if attempt.state() == AttemptState::Preparing {
3048                    attempt
3049                        .mark_prepared(self.ports.clock.now())
3050                        .map_err(|_| LifecycleError::Transition)?;
3051                }
3052                self.record(&attempt)?;
3053            }
3054            match self.reconcile_one(policy, attempt).await? {
3055                ReconcileProgress::Deferred => {
3056                    if policy.execution_policy().is_native() {
3057                        unresolved = true;
3058                    }
3059                }
3060                ReconcileProgress::Replacement { attempt, operation } => {
3061                    self.pending_replacements
3062                        .lock()
3063                        .map_err(|_| LifecycleError::Journal)?
3064                        .insert(
3065                            attempt,
3066                            ReplacementIntent {
3067                                policy: policy.id,
3068                                previous_attempt: attempt,
3069                                operation,
3070                            },
3071                        );
3072                }
3073                ReconcileProgress::Reconciled => {}
3074            }
3075        }
3076        if unresolved {
3077            return Err(LifecycleError::RecoveryIncomplete);
3078        }
3079        *self
3080            .recovery_complete
3081            .lock()
3082            .map_err(|_| LifecycleError::Journal)? = true;
3083        Ok(self
3084            .pending_replacements
3085            .lock()
3086            .map_err(|_| LifecycleError::Journal)?
3087            .values()
3088            .copied()
3089            .collect())
3090    }
3091
3092    /// Supervise all attempts of one policy during an ordinary poll.
3093    pub async fn supervise(
3094        &self,
3095        policy: &ScalePolicy,
3096    ) -> Result<Vec<ReplacementIntent>, LifecycleError> {
3097        let mut replacements = Vec::new();
3098        self.pending_replacements
3099            .lock()
3100            .map_err(|_| LifecycleError::Journal)?
3101            .retain(|_, intent| {
3102                if intent.policy == policy.id {
3103                    replacements.push(*intent);
3104                    false
3105                } else {
3106                    true
3107                }
3108            });
3109        let attempts = self
3110            .ports
3111            .store
3112            .attempts_for_policy(policy.id)
3113            .map_err(|_| LifecycleError::Journal)?;
3114        for attempt in attempts {
3115            authorize(self.host_id, policy, &attempt).map_err(|_| LifecycleError::Journal)?;
3116            if let ReconcileProgress::Replacement { attempt, operation } =
3117                self.reconcile_one(policy, attempt).await?
3118            {
3119                replacements.push(ReplacementIntent {
3120                    policy: policy.id,
3121                    previous_attempt: attempt,
3122                    operation,
3123                });
3124            }
3125        }
3126        Ok(replacements)
3127    }
3128
3129    async fn reconcile_one(
3130        &self,
3131        policy: &ScalePolicy,
3132        mut attempt: RunnerAttempt,
3133    ) -> Result<ReconcileProgress, LifecycleError> {
3134        if !attempt.execution().is_native() {
3135            return self.reconcile_isolated_one(policy, attempt).await;
3136        }
3137        if attempt.state() == AttemptState::Cleaned {
3138            // A child of Runner.Worker can outlive the runner process briefly.
3139            // If it recreates `_work` after `clean_attempt` removed the tree but
3140            // before the journal's final write, the journal truthfully reaches
3141            // `cleaned` and the directory appears again afterwards. Cleaned
3142            // attempts used to return here forever, making that late residue
3143            // invisible. The journalled ephemeral mode is the ownership proof:
3144            // retry the whole-tree removal, while a persistent slot deliberately
3145            // remains on disk with its retained `_work`.
3146            if matches!(attempt.workspace(), AttemptWorkspace::Ephemeral)
3147                && attempt.runtime_path().exists()
3148            {
3149                // The attempt is already terminal, has released its package
3150                // lease, and consumes no capacity. A late child may still hold
3151                // one of its recreated files open on Windows, so failure here
3152                // is residue to retry, not a reason to abort startup recovery
3153                // and take every unrelated repository offline.
3154                // Retried with backoff; the event is the one report, which the
3155                // event sink logs as a warning.
3156                let now = self.ports.clock.now();
3157                if !self.cleanup_retries().is_due(attempt.id, now) {
3158                    return Ok(ReconcileProgress::Reconciled);
3159                }
3160                match self.scrub_workspace(&attempt) {
3161                    Ok(()) => self.cleanup_retries().succeeded(attempt.id),
3162                    Err(LifecycleError::WorkspaceCleanupDeferred) => {
3163                        self.cleanup_retries().failed(attempt.id, now);
3164                        self.ports
3165                            .reconcile_events
3166                            .emit(LifecycleEvent::AttemptCleanFailed {
3167                                policy: attempt.policy_id,
3168                                attempt: attempt.id,
3169                                reason: "late_ephemeral_workspace_could_not_be_removed",
3170                            });
3171                    }
3172                    Err(error) => return Err(error),
3173                }
3174            }
3175            return Ok(ReconcileProgress::Reconciled);
3176        }
3177        if attempt.is_terminal() {
3178            self.clean_or_quarantine(&mut attempt)?;
3179            return Ok(ReconcileProgress::Reconciled);
3180        }
3181        let process_alive = self
3182            .ports
3183            .processes
3184            .inspect(&attempt)
3185            .map_err(LifecycleError::Failed)?
3186            == EnvironmentState::Running;
3187        let github = self
3188            .ports
3189            .github
3190            .observe(&policy.target, attempt.id, &self.cancel)
3191            .await;
3192
3193        // If the agent died after GitHub accepted the registration but before
3194        // the non-secret runner-id sidecar landed, inventory closes the gap.
3195        // Persist it before making any state decision so a second crash moves
3196        // the boundary forward rather than repeating it.
3197        if let Some(runner_id) = github.runner_id
3198            && read_runner_id(attempt.runtime_path()).is_none()
3199        {
3200            write_runner_id(attempt.runtime_path(), runner_id)?;
3201            self.ports
3202                .events
3203                .emit(AttemptEvent::RemoteIdentityRecovered {
3204                    attempt: attempt.id,
3205                    runner_id,
3206                });
3207        }
3208
3209        // The child identity is synced before `spawn` returns.  If the agent
3210        // crashed before the following `starting` journal write, recover that
3211        // exact PID and take the legal `jit_received -> starting` edge before
3212        // applying GitHub's authoritative idle/busy observation below.
3213        if attempt.state() == AttemptState::JitReceived
3214            && process_alive
3215            && let Some(pid) = self
3216                .ports
3217                .processes
3218                .recovered_pid(&attempt)
3219                .map_err(LifecycleError::Failed)?
3220        {
3221            attempt
3222                .started(pid, self.ports.clock.now())
3223                .map_err(|_| LifecycleError::Transition)?;
3224            self.record(&attempt)?;
3225        }
3226
3227        // What the runner's own diagnostics say about whether it ran a job.
3228        // Read before anything below can conclude the attempt, because cleanup
3229        // deletes `_diag` with the rest of the runtime directory.
3230        // A one-shot child owned by this invocation exited successfully. This
3231        // concludes the *runner attempt*, never the workflow outcome; GitHub
3232        // remains authoritative for that. GitHub's inventory is a sampled
3233        // witness: a job of a few seconds starts and ends between two passes,
3234        // and an assignment GitHub shows can be one the runner never took up.
3235        // The runner's own diagnostics decide, read before cleanup deletes
3236        // them, and GitHub's sample only decides when they say nothing. Not
3237        // while GitHub is unreachable: a registration still listed there could
3238        // not be removed, and nothing visits a concluded attempt again.
3239        if !process_alive
3240            && github.status != GithubRunnerObservation::Unreachable
3241            && matches!(
3242                attempt.state(),
3243                AttemptState::Starting | AttemptState::Idle | AttemptState::Busy
3244            )
3245            && self.ports.processes.completed_successfully(&attempt)
3246        {
3247            let state = attempt.state();
3248            let outcome = match (state, JobEvidence::of(attempt.runtime_path())) {
3249                // Without a runner id there is no edge to `busy`; the recovery
3250                // path below concludes the attempt without one.
3251                (AttemptState::Starting | AttemptState::Idle, JobEvidence::RanAJob) => {
3252                    known_runner_id(&attempt, github.runner_id)
3253                        .map(|runner_id| (Some(runner_id), AttemptOutcome::CompletedJob))
3254                }
3255                (AttemptState::Busy, JobEvidence::RanAJob) => {
3256                    Some((None, AttemptOutcome::CompletedJob))
3257                }
3258                (AttemptState::Busy, JobEvidence::NoJob) => {
3259                    Some((None, AttemptOutcome::ExitedIdleWithoutWork))
3260                }
3261                (AttemptState::Busy, JobEvidence::Unknown)
3262                    if github.status == GithubRunnerObservation::NotRegistered =>
3263                {
3264                    Some((None, AttemptOutcome::CompletedJob))
3265                }
3266                _ => None,
3267            };
3268            if let Some((walk_to_busy, outcome)) = outcome {
3269                // An ephemeral runner leaves GitHub's list a little after its
3270                // process exits; one still listed is removed here rather than
3271                // left for GitHub to time out. First, so the journal's last
3272                // intermediate state and the conclusion are written back to back:
3273                // an agent that dies between them recovers from the state it was
3274                // in before this pass.
3275                if matches!(github.status, GithubRunnerObservation::Registered { .. }) {
3276                    self.deregister_runner(policy, &attempt).await;
3277                }
3278                let now = self.ports.clock.now();
3279                match (walk_to_busy, &outcome) {
3280                    (Some(runner_id), _) => {
3281                        self.transition(&mut attempt, |a| a.assigned_job(runner_id, now))?;
3282                    }
3283                    (None, AttemptOutcome::ExitedIdleWithoutWork) => {
3284                        self.transition(&mut attempt, |a| a.assignment_not_taken(now))?;
3285                    }
3286                    (None, _) => {}
3287                }
3288                self.conclude(&mut attempt, outcome)?;
3289                self.clean_or_quarantine(&mut attempt)?;
3290                return Ok(ReconcileProgress::Reconciled);
3291            }
3292        }
3293
3294        // A live runner journalled `busy` that GitHub now shows waiting, and
3295        // whose diagnostics show no job: the assignment was never taken up.
3296        // Back to `idle`, where the idle timeout applies to it again; the
3297        // `busy` arm below would otherwise adopt it for as long as it runs.
3298        if process_alive
3299            && attempt.state() == AttemptState::Busy
3300            && github.status == (GithubRunnerObservation::Registered { busy: false })
3301            && JobEvidence::of(attempt.runtime_path()) == JobEvidence::NoJob
3302        {
3303            let now = self.ports.clock.now();
3304            self.transition(&mut attempt, |a| a.assignment_not_taken(now))?;
3305            return Ok(ReconcileProgress::Reconciled);
3306        }
3307
3308        // This durable mark is more authoritative than a later observation
3309        // which cannot distinguish an agent kill from a crash.
3310        if self.ports.processes.has_terminate_intent(&attempt) && !process_alive {
3311            self.deregister_runner(policy, &attempt).await;
3312            self.conclude(
3313                &mut attempt,
3314                AttemptOutcome::failed(FailureReason::TerminatedAfterRegistrationTimeout),
3315            )?;
3316            self.clean_or_quarantine(&mut attempt)?;
3317            return Ok(ReconcileProgress::Replacement {
3318                attempt: attempt.id,
3319                operation: "registration_timeout_replacement",
3320            });
3321        }
3322
3323        // A remote registration with no surviving process has lost its
3324        // one-shot JIT secret.  Walking it to `starting` would require inventing
3325        // a PID; retrying the same registration would require inventing the
3326        // secret.  Record the configuration as expired and let the bounded
3327        // replacement path request a fresh one only if demand remains.
3328        if matches!(
3329            attempt.state(),
3330            AttemptState::Allocated | AttemptState::JitReceived
3331        ) && !process_alive
3332            && matches!(github.status, GithubRunnerObservation::Registered { .. })
3333        {
3334            if attempt.state() == AttemptState::Allocated {
3335                attempt
3336                    .jit_received(self.ports.clock.now())
3337                    .map_err(|_| LifecycleError::Transition)?;
3338                self.record(&attempt)?;
3339            }
3340            self.deregister_runner(policy, &attempt).await;
3341            self.conclude(
3342                &mut attempt,
3343                AttemptOutcome::failed(FailureReason::JitExpired),
3344            )?;
3345            self.clean_or_quarantine(&mut attempt)?;
3346            return Ok(ReconcileProgress::Replacement {
3347                attempt: attempt.id,
3348                operation: "jit_expired_replacement",
3349            });
3350        }
3351
3352        match recovery_decision(
3353            &attempt,
3354            RecoveryObservation {
3355                process_alive,
3356                github: github.status,
3357            },
3358            self.timeouts,
3359            self.ports.clock.as_ref(),
3360        ) {
3361            RecoveryDecision::Nothing | RecoveryDecision::Wait => Ok(ReconcileProgress::Reconciled),
3362            RecoveryDecision::Defer => Ok(ReconcileProgress::Deferred),
3363            RecoveryDecision::Adopt => {
3364                self.ports.events.emit(AttemptEvent::Adopted {
3365                    attempt: attempt.id,
3366                });
3367                Ok(ReconcileProgress::Reconciled)
3368            }
3369            RecoveryDecision::Clean => {
3370                self.clean_or_quarantine(&mut attempt)?;
3371                Ok(ReconcileProgress::Reconciled)
3372            }
3373            RecoveryDecision::Observe(state) => {
3374                let runner_id = known_runner_id(&attempt, github.runner_id)
3375                    .ok_or(LifecycleError::Transition)?;
3376                match state {
3377                    AttemptState::JitReceived => attempt
3378                        .jit_received(self.ports.clock.now())
3379                        .map_err(|_| LifecycleError::Transition)?,
3380                    AttemptState::Starting => {
3381                        let pid = attempt.process_id().ok_or(LifecycleError::Transition)?;
3382                        attempt
3383                            .started(pid, self.ports.clock.now())
3384                            .map_err(|_| LifecycleError::Transition)?;
3385                    }
3386                    AttemptState::Idle => attempt
3387                        .registered_idle(runner_id, self.ports.clock.now())
3388                        .map_err(|_| LifecycleError::Transition)?,
3389                    AttemptState::Busy => attempt
3390                        .assigned_job(runner_id, self.ports.clock.now())
3391                        .map_err(|_| LifecycleError::Transition)?,
3392                    _ => return Err(LifecycleError::Transition),
3393                }
3394                self.record(&attempt)?;
3395                Ok(ReconcileProgress::Reconciled)
3396            }
3397            RecoveryDecision::Conclude(outcome) => {
3398                let replacement = replacement_operation(&outcome);
3399                // Only when GitHub still holds one. Every other conclusion here
3400                // was reached *because* the observation was `NotRegistered`, and
3401                // spending a DELETE to be told so again would put a request per
3402                // concluded attempt on a budget `rest.rs` prices to the request.
3403                if matches!(github.status, GithubRunnerObservation::Registered { .. }) {
3404                    self.deregister_runner(policy, &attempt).await;
3405                }
3406                self.conclude(&mut attempt, outcome)?;
3407                self.clean_or_quarantine(&mut attempt)?;
3408                Ok(
3409                    replacement.map_or(ReconcileProgress::Reconciled, |operation| {
3410                        ReconcileProgress::Replacement {
3411                            attempt: attempt.id,
3412                            operation,
3413                        }
3414                    }),
3415                )
3416            }
3417            RecoveryDecision::Terminate(payload) => {
3418                // The mark is synced first, and what proves the process died is
3419                // the `is_alive` re-read below -- not the outcome recorded after
3420                // it. Which outcome that is depends on why the termination was
3421                // ordered, and only the payload knows: a `starting` runner that
3422                // never registered is a failure this agent then stopped, while
3423                // an `idle` one past its timeout is flow 2.7's surplus exit and
3424                // no failure at all. Hardcoding the first reason here labelled
3425                // the second as a registration timeout and asked the allocator
3426                // for a replacement to boot.
3427                let idle_exit = payload.is_idle_exit();
3428                self.ports
3429                    .processes
3430                    .record_terminate_intent(&attempt)
3431                    .map_err(LifecycleError::Failed)?;
3432                self.ports.events.emit(AttemptEvent::TerminateIntent {
3433                    attempt: attempt.id,
3434                });
3435                if self
3436                    .ports
3437                    .processes
3438                    .stop(&attempt)
3439                    .map_err(LifecycleError::Failed)?
3440                    == ProviderStop::StillRunning
3441                {
3442                    return Ok(ReconcileProgress::Deferred);
3443                }
3444                if self
3445                    .ports
3446                    .processes
3447                    .inspect(&attempt)
3448                    .map_err(LifecycleError::Failed)?
3449                    == EnvironmentState::Running
3450                {
3451                    return Ok(ReconcileProgress::Deferred);
3452                }
3453                self.ports.events.emit(AttemptEvent::Terminated {
3454                    attempt: attempt.id,
3455                });
3456                // The registration-timeout path keeps deriving its own reason
3457                // rather than applying the payload: on the pass that reads the
3458                // journalled mark back the process is dead, and
3459                // `TerminatedAfterRegistrationTimeout` is the reason that stays
3460                // true of a dead process. See `RecoveryDecision::Terminate`.
3461                let outcome = if idle_exit {
3462                    AttemptOutcome::ExitedIdleWithoutWork
3463                } else {
3464                    AttemptOutcome::failed(FailureReason::TerminatedAfterRegistrationTimeout)
3465                };
3466                self.deregister_runner(policy, &attempt).await;
3467                self.conclude(&mut attempt, outcome)?;
3468                self.clean_or_quarantine(&mut attempt)?;
3469                // A surplus runner is not replaced. It was stopped precisely
3470                // because the work it was started for went elsewhere; asking the
3471                // allocator for another one rebuilds it every idle timeout.
3472                if idle_exit {
3473                    Ok(ReconcileProgress::Reconciled)
3474                } else {
3475                    Ok(ReconcileProgress::Replacement {
3476                        attempt: attempt.id,
3477                        operation: "registration_timeout_replacement",
3478                    })
3479                }
3480            }
3481        }
3482    }
3483
3484    async fn reconcile_isolated_one(
3485        &self,
3486        policy: &ScalePolicy,
3487        mut attempt: RunnerAttempt,
3488    ) -> Result<ReconcileProgress, LifecycleError> {
3489        if attempt.state() == AttemptState::Cleaned {
3490            return Ok(ReconcileProgress::Reconciled);
3491        }
3492        if attempt.is_terminal() {
3493            self.clean_or_quarantine(&mut attempt)?;
3494            return Ok(ReconcileProgress::Reconciled);
3495        }
3496        if matches!(
3497            attempt.state(),
3498            AttemptState::Allocated | AttemptState::Preparing | AttemptState::Prepared
3499        ) {
3500            // No JIT was requested yet. Restart can safely retire this attempt;
3501            // a matching owned resource is stopped by the durable cleanup path.
3502            self.conclude(
3503                &mut attempt,
3504                AttemptOutcome::failed(FailureReason::Other(
3505                    "isolated preparation interrupted".into(),
3506                )),
3507            )?;
3508            self.clean_or_quarantine(&mut attempt)?;
3509            return Ok(ReconcileProgress::Reconciled);
3510        }
3511        let Ok(provider_state) = self.ports.processes.recover(&attempt) else {
3512            return Ok(ReconcileProgress::Deferred);
3513        };
3514        if provider_state != EnvironmentState::Missing {
3515            let Ok(owned) = self.ports.processes.owns(&attempt) else {
3516                return Ok(ReconcileProgress::Deferred);
3517            };
3518            if !owned {
3519                self.ports
3520                    .events
3521                    .emit(AttemptEvent::QuarantinedOwnedResource {
3522                        attempt: attempt.id,
3523                    });
3524                tracing::warn!(attempt_id = %attempt.id, reason = "isolated_resource_ownership_mismatch", "provider resource quarantined for operator review");
3525                return Ok(ReconcileProgress::Deferred);
3526            }
3527        }
3528        let live = matches!(
3529            provider_state,
3530            EnvironmentState::Starting | EnvironmentState::Running
3531        );
3532        if attempt.state() == AttemptState::JitReceived && live {
3533            attempt
3534                .started_isolated(self.ports.clock.now())
3535                .map_err(|_| LifecycleError::Transition)?;
3536            self.record(&attempt)?;
3537        }
3538        let github = self
3539            .ports
3540            .github
3541            .observe(&policy.target, attempt.id, &self.cancel)
3542            .await;
3543        if let Some(runner_id) = github.runner_id
3544            && read_runner_id(attempt.runtime_path()).is_none()
3545        {
3546            write_runner_id(attempt.runtime_path(), runner_id)?;
3547        }
3548        // A successfully reaped one-shot listener is stronger evidence than a
3549        // missing registration. Recovered guests have no attached child and
3550        // still follow the conservative orphan path below.
3551        if attempt.state() == AttemptState::Busy
3552            && !live
3553            && github.status == GithubRunnerObservation::NotRegistered
3554            && self.ports.processes.completed_successfully(&attempt)
3555        {
3556            self.conclude(&mut attempt, AttemptOutcome::CompletedJob)?;
3557            self.clean_or_quarantine(&mut attempt)?;
3558            return Ok(ReconcileProgress::Reconciled);
3559        }
3560        match recovery_decision(
3561            &attempt,
3562            RecoveryObservation {
3563                process_alive: live,
3564                github: github.status,
3565            },
3566            self.timeouts,
3567            self.ports.clock.as_ref(),
3568        ) {
3569            RecoveryDecision::Nothing | RecoveryDecision::Wait => Ok(ReconcileProgress::Reconciled),
3570            RecoveryDecision::Defer => Ok(ReconcileProgress::Deferred),
3571            RecoveryDecision::Adopt => {
3572                self.ports.events.emit(AttemptEvent::Adopted {
3573                    attempt: attempt.id,
3574                });
3575                Ok(ReconcileProgress::Reconciled)
3576            }
3577            RecoveryDecision::Clean => {
3578                self.clean_or_quarantine(&mut attempt)?;
3579                Ok(ReconcileProgress::Reconciled)
3580            }
3581            RecoveryDecision::Observe(state) => {
3582                let runner_id = github
3583                    .runner_id
3584                    .or_else(|| read_runner_id(attempt.runtime_path()))
3585                    .ok_or(LifecycleError::Transition)?;
3586                match state {
3587                    AttemptState::Idle => attempt
3588                        .registered_idle(runner_id, self.ports.clock.now())
3589                        .map_err(|_| LifecycleError::Transition)?,
3590                    AttemptState::Busy => attempt
3591                        .assigned_job(runner_id, self.ports.clock.now())
3592                        .map_err(|_| LifecycleError::Transition)?,
3593                    _ => return Err(LifecycleError::Transition),
3594                }
3595                self.record(&attempt)?;
3596                Ok(ReconcileProgress::Reconciled)
3597            }
3598            RecoveryDecision::Conclude(outcome) | RecoveryDecision::Terminate(outcome) => {
3599                let replacement = replacement_operation(&outcome);
3600                if matches!(github.status, GithubRunnerObservation::Registered { .. }) {
3601                    self.deregister_runner(policy, &attempt).await;
3602                }
3603                self.conclude(&mut attempt, outcome)?;
3604                self.clean_or_quarantine(&mut attempt)?;
3605                Ok(
3606                    replacement.map_or(ReconcileProgress::Reconciled, |operation| {
3607                        ReconcileProgress::Replacement {
3608                            attempt: attempt.id,
3609                            operation,
3610                        }
3611                    }),
3612                )
3613            }
3614        }
3615    }
3616
3617    /// Takes one domain edge and journals it.
3618    fn transition(
3619        &self,
3620        attempt: &mut RunnerAttempt,
3621        edge: impl FnOnce(
3622            &mut RunnerAttempt,
3623        ) -> Result<(), runner_manager_domain::attempt::AttemptError>,
3624    ) -> Result<(), LifecycleError> {
3625        edge(attempt).map_err(|_| LifecycleError::Transition)?;
3626        self.record(attempt)
3627    }
3628
3629    fn record(&self, attempt: &RunnerAttempt) -> Result<(), LifecycleError> {
3630        self.ports
3631            .store
3632            .record_attempt(attempt)
3633            .map_err(|_| LifecycleError::Journal)?;
3634        self.ports.events.emit(AttemptEvent::State {
3635            attempt: attempt.id,
3636            state: attempt.state(),
3637        });
3638        Ok(())
3639    }
3640
3641    /// Remove the GitHub registration an attempt is about to leave behind.
3642    ///
3643    /// # Why this is not fallible, and does not block the conclusion
3644    ///
3645    /// GitHub retires an ephemeral runner itself once that runner *completes a
3646    /// job*, and for the ordinary path that is the whole story. The paths that
3647    /// reach here are the ones where it does not: a runner stopped before it
3648    /// was ever assigned work, a registration whose process died still holding
3649    /// it, a JIT configuration that expired. Nothing else deletes those, and
3650    /// before this existed nothing did — they accumulated in the target's
3651    /// runner settings, one row per attempt, for the life of the repository.
3652    ///
3653    /// It returns `()` rather than a `Result` because the alternative is worse
3654    /// in both directions. The attempt is over: its process is gone and its
3655    /// slot has to come back, so a failed delete may not abort the conclusion
3656    /// or the host leaks capacity every time GitHub is unreachable. And a
3657    /// registration that outlives this call is not lost — it is exactly the
3658    /// `Registered` + dead-process observation that
3659    /// [`AttemptOutcome::Orphaned`] already names, which a later pass can still
3660    /// see. So a failure is logged and stepped over, deliberately.
3661    async fn deregister_runner(&self, policy: &ScalePolicy, attempt: &RunnerAttempt) {
3662        let Some(runner_id) = attempt
3663            .github_runner_id()
3664            .or_else(|| read_runner_id(attempt.runtime_path()))
3665        else {
3666            return;
3667        };
3668        if self
3669            .ports
3670            .github
3671            .deregister(&policy.target, runner_id, &self.cancel)
3672            .await
3673        {
3674            self.ports.events.emit(AttemptEvent::Deregistered {
3675                attempt: attempt.id,
3676                runner_id,
3677            });
3678        } else {
3679            tracing::warn!(
3680                attempt = %attempt.id,
3681                runner_id,
3682                "the runner registration could not be removed from GitHub; it will show in the \
3683                 target's runner settings until GitHub retires it or a later pass removes it"
3684            );
3685        }
3686    }
3687
3688    fn conclude(
3689        &self,
3690        attempt: &mut RunnerAttempt,
3691        outcome: AttemptOutcome,
3692    ) -> Result<(), LifecycleError> {
3693        attempt
3694            .conclude(outcome.clone(), self.ports.clock.now())
3695            .map_err(|_| LifecycleError::Transition)?;
3696        self.record(attempt)?;
3697        self.ports.events.emit(AttemptEvent::Concluded {
3698            attempt: attempt.id,
3699            outcome: OutcomeKind::of(&outcome),
3700        });
3701        Ok(())
3702    }
3703
3704    /// Clean a concluded attempt, tolerating a quarantined persistent slot.
3705    ///
3706    /// The quarantine is reported and stepped over rather than raised, because
3707    /// raising it aborts the whole pass: on the startup path that leaves
3708    /// `recovery_complete` false and stops the host launching anything, which is
3709    /// the opposite of `04-security-recovery.md`'s "it does not count as active
3710    /// host capacity" and "recovery retries the same cleanup". The attempt keeps
3711    /// its state, so it keeps its slot lease and its directory, and the next
3712    /// pass — [`crate::reconcile::Reconciler`]'s terminal sweep on every poll,
3713    /// or the next startup — attempts exactly the same cleanup again.
3714    ///
3715    /// A persistent-slot quarantine and an ephemeral directory still held by a
3716    /// late process are tolerated. A journal failure or a package lease that
3717    /// cannot be released still propagates: those are not one workspace's
3718    /// problem.
3719    ///
3720    /// A tolerated failure is retried with per-attempt backoff: until it is
3721    /// due again the attempt is skipped silently rather than re-tried and
3722    /// re-reported on every pass.
3723    fn clean_or_quarantine(&self, attempt: &mut RunnerAttempt) -> Result<(), LifecycleError> {
3724        let now = self.ports.clock.now();
3725        if !self.cleanup_retries().is_due(attempt.id, now) {
3726            return Ok(());
3727        }
3728        let reason = match self.clean_attempt(attempt) {
3729            Err(LifecycleError::SlotQuarantined { class, .. }) => class,
3730            Err(LifecycleError::WorkspaceCleanupDeferred) => {
3731                failure_reason_kind(&FailureReason::WorkspaceCleanupDeferred)
3732            }
3733            Err(LifecycleError::EnvironmentCleanupDeferred) => {
3734                "isolated_environment_cleanup_deferred"
3735            }
3736            other => {
3737                if other.is_ok() {
3738                    self.cleanup_retries().succeeded(attempt.id);
3739                }
3740                return other;
3741            }
3742        };
3743        self.cleanup_retries().failed(attempt.id, now);
3744        self.ports
3745            .reconcile_events
3746            .emit(LifecycleEvent::AttemptCleanFailed {
3747                policy: attempt.policy_id,
3748                attempt: attempt.id,
3749                reason,
3750            });
3751        Ok(())
3752    }
3753
3754    fn cleanup_retries(&self) -> std::sync::MutexGuard<'_, CleanBackoff> {
3755        self.cleanup_retries
3756            .lock()
3757            .unwrap_or_else(std::sync::PoisonError::into_inner)
3758    }
3759
3760    fn clean_attempt(&self, attempt: &mut RunnerAttempt) -> Result<(), LifecycleError> {
3761        if !attempt.execution().is_native() {
3762            return self.clean_isolated_attempt(attempt);
3763        }
3764        match self
3765            .ports
3766            .processes
3767            .destroy(attempt)
3768            .map_err(LifecycleError::Failed)?
3769        {
3770            ProviderDestroy::Destroyed => {}
3771            ProviderDestroy::Deferred(reason) => {
3772                return Err(LifecycleError::Failed(FailureReason::Other(reason.into())));
3773            }
3774        }
3775        let outcome = attempt
3776            .outcome()
3777            .cloned()
3778            .ok_or(LifecycleError::Transition)?;
3779        self.preserve_diagnostics(attempt, &outcome)?;
3780        self.scrub_workspace(attempt)?;
3781        self.ports
3782            .packages
3783            .release(attempt.id)
3784            .map_err(LifecycleError::Failed)?;
3785        attempt
3786            .clean(self.ports.clock.now())
3787            .map_err(|_| LifecycleError::Transition)?;
3788        self.record(attempt)?;
3789        let kind = OutcomeKind::of(&outcome);
3790        self.ports.events.emit(AttemptEvent::Cleaned {
3791            attempt: attempt.id,
3792            outcome: kind,
3793        });
3794        self.ports
3795            .reconcile_events
3796            .emit(LifecycleEvent::AttemptCleaned {
3797                policy: attempt.policy_id,
3798                attempt: attempt.id,
3799                outcome: kind,
3800            });
3801        Ok(())
3802    }
3803
3804    fn clean_isolated_attempt(&self, attempt: &mut RunnerAttempt) -> Result<(), LifecycleError> {
3805        if attempt.state() != AttemptState::Destroying {
3806            attempt
3807                .begin_destroy(self.ports.clock.now())
3808                .map_err(|_| LifecycleError::Transition)?;
3809            self.record(attempt)?;
3810        }
3811        let provider = self.ports.processes.as_ref();
3812        let allocation_resources = provider.enumerate_owned(self.host_id);
3813        let matching_allocation = allocation_resources
3814            .iter()
3815            .filter(|identity| identity_same_allocation(self.host_id, attempt, identity))
3816            .collect::<Vec<_>>();
3817        if matching_allocation.len() > 1
3818            || matching_allocation
3819                .iter()
3820                .any(|identity| !identity_matches_intent(self.host_id, attempt, identity))
3821        {
3822            self.ports
3823                .events
3824                .emit(AttemptEvent::QuarantinedOwnedResource {
3825                    attempt: attempt.id,
3826                });
3827            tracing::warn!(attempt_id = %attempt.id, reason = "duplicate_or_mismatched_isolated_ownership", "provider resources quarantined for operator review");
3828            return Err(self.defer_environment_cleanup(attempt)?);
3829        }
3830        let has_identity = matches!(
3831            attempt.execution(),
3832            AttemptExecution::Isolated {
3833                environment_id: Some(_),
3834                ..
3835            }
3836        );
3837        if !has_identity
3838            && allocation_resources
3839                .iter()
3840                .any(|identity| identity_matches_intent(self.host_id, attempt, identity))
3841        {
3842            return Err(self.defer_environment_cleanup(attempt)?);
3843        }
3844        let current = if has_identity {
3845            provider.inspect(attempt)
3846        } else {
3847            // A prepare effect may have succeeded before its identity could be
3848            // journalled. Empty enumeration alone is not proof of absence.
3849            provider.recover(attempt)
3850        };
3851        let current = match current {
3852            Ok(state) => state,
3853            Err(_) => return Err(self.defer_environment_cleanup(attempt)?),
3854        };
3855        if !has_identity && current != EnvironmentState::Missing {
3856            return Err(self.defer_environment_cleanup(attempt)?);
3857        }
3858        if current != EnvironmentState::Missing {
3859            if !matches!(provider.owns(attempt), Ok(true)) {
3860                self.ports
3861                    .events
3862                    .emit(AttemptEvent::QuarantinedOwnedResource {
3863                        attempt: attempt.id,
3864                    });
3865                tracing::warn!(attempt_id = %attempt.id, reason = "isolated_resource_ownership_mismatch", "provider resource quarantined for operator review");
3866                return Err(self.defer_environment_cleanup(attempt)?);
3867            }
3868            if matches!(
3869                current,
3870                EnvironmentState::Starting | EnvironmentState::Running
3871            ) && !matches!(provider.stop(attempt), Ok(ProviderStop::Stopped))
3872            {
3873                return Err(self.defer_environment_cleanup(attempt)?);
3874            }
3875            if !matches!(provider.destroy(attempt), Ok(ProviderDestroy::Destroyed)) {
3876                return Err(self.defer_environment_cleanup(attempt)?);
3877            }
3878            if !matches!(provider.inspect(attempt), Ok(EnvironmentState::Missing)) {
3879                return Err(self.defer_environment_cleanup(attempt)?);
3880            }
3881        }
3882        if provider
3883            .enumerate_owned(self.host_id)
3884            .iter()
3885            .any(|identity| identity_same_allocation(self.host_id, attempt, identity))
3886        {
3887            return Err(self.defer_environment_cleanup(attempt)?);
3888        }
3889        let outcome = attempt
3890            .outcome()
3891            .cloned()
3892            .ok_or(LifecycleError::Transition)?;
3893        // Provider diagnostics are a closed vocabulary and bounded before they
3894        // can enter tracing, even if an adapter returns an unbounded vector.
3895        for diagnostic in provider.diagnostics(attempt).into_iter().take(32) {
3896            tracing::debug!(attempt_id = %attempt.id, provider_diagnostic = ?diagnostic, "provider lifecycle diagnostic");
3897        }
3898        self.preserve_diagnostics(attempt, &outcome)?;
3899        self.scrub_workspace(attempt)?;
3900        self.ports
3901            .packages
3902            .release(attempt.id)
3903            .map_err(LifecycleError::Failed)?;
3904        attempt
3905            .clean_isolated(self.ports.clock.now())
3906            .map_err(|_| LifecycleError::Transition)?;
3907        self.record(attempt)?;
3908        self.ports.events.emit(AttemptEvent::Cleaned {
3909            attempt: attempt.id,
3910            outcome: OutcomeKind::of(&outcome),
3911        });
3912        self.ports
3913            .reconcile_events
3914            .emit(LifecycleEvent::AttemptCleaned {
3915                policy: attempt.policy_id,
3916                attempt: attempt.id,
3917                outcome: OutcomeKind::of(&outcome),
3918            });
3919        Ok(())
3920    }
3921
3922    fn defer_environment_cleanup(
3923        &self,
3924        attempt: &mut RunnerAttempt,
3925    ) -> Result<LifecycleError, LifecycleError> {
3926        attempt
3927            .defer_cleanup(self.ports.clock.now())
3928            .map_err(|_| LifecycleError::Transition)?;
3929        self.record(attempt)?;
3930        Ok(LifecycleError::EnvironmentCleanupDeferred)
3931    }
3932
3933    /// Undo an attempt's placement by the algorithm its journalled workspace
3934    /// kind makes legal (`02-target-architecture.md`, "Cleanup and recovery").
3935    ///
3936    /// The dispatch is on the *journal*, never on what the directory looks like
3937    /// now. A slot whose `_work` was replaced by a junction is still scrubbed as
3938    /// a slot rather than removed whole, and a disposable directory that happens
3939    /// to contain a `_work` still goes whole rather than being spared: the
3940    /// workspace kind is immutable precisely so that the shape of a directory a
3941    /// workflow can write to cannot choose the algorithm applied to it.
3942    fn scrub_workspace(&self, attempt: &RunnerAttempt) -> Result<(), LifecycleError> {
3943        #[cfg(test)]
3944        {
3945            // The two contamination mutants `f1` drives the security gates with.
3946            // They sit in front of the dispatch rather than inside one arm so
3947            // that a skipped cleanup is equally observable in both modes.
3948            if matches!(
3949                std::env::var("RUNNER_MANAGER_TEST_MUTANT").as_deref(),
3950                Ok("skip_workspace_cleanup" | "reuse_job_workspace")
3951            ) {
3952                return Ok(());
3953            }
3954        }
3955        match attempt.workspace() {
3956            AttemptWorkspace::Ephemeral => match remove_runtime_tree(attempt.runtime_path()) {
3957                Ok(()) => Ok(()),
3958                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
3959                Err(_) => Err(LifecycleError::WorkspaceCleanupDeferred),
3960            },
3961            AttemptWorkspace::PersistentSlot { slot } => self.scrub_persistent_slot(attempt, slot),
3962        }
3963    }
3964
3965    /// Retain exactly `_work` and prove everything else is gone.
3966    ///
3967    /// The seven ordered checks of `04-security-recovery.md`, "Safe path
3968    /// handling": the journalled root and slot, a surviving policy's agreement,
3969    /// lexical and canonical containment, a literal enumeration, the one-entry
3970    /// allowlist, and a verification pass before the caller releases the package
3971    /// lease and marks the attempt cleaned. Any of them may refuse, and a
3972    /// refusal removes nothing after it.
3973    ///
3974    /// A slot directory that is already gone is not a refusal. There is nothing
3975    /// to scrub and nothing to prove absent, which is the same tolerance the
3976    /// disposable arm has always had for a runtime that vanished under it.
3977    fn scrub_persistent_slot(
3978        &self,
3979        attempt: &RunnerAttempt,
3980        slot: NonZeroU16,
3981    ) -> Result<(), LifecycleError> {
3982        // The policy is read from the journal, never inferred from the
3983        // directory tree, and its absence is legal: `Reconciler` cleans every
3984        // concluded attempt whether or not its policy still exists, and this
3985        // one's root is already journalled on the attempt itself.
3986        let configured = self
3987            .ports
3988            .store
3989            .policy(attempt.policy_id)
3990            .map_err(|_| LifecycleError::Journal)?
3991            .and_then(|policy| match policy.workspace_policy() {
3992                WorkspacePolicy::Persistent { root } => Some(root.clone()),
3993                WorkspacePolicy::Ephemeral => None,
3994            });
3995        let runtime = attempt.runtime_path();
3996        self.quarantine_on_refusal(
3997            attempt,
3998            verify_journalled_slot(runtime, slot, configured.as_ref())
3999                .and_then(|()| slot_is_present(runtime))
4000                .and_then(|present| {
4001                    if present {
4002                        scrub_slot_entries(runtime).and_then(|()| verify_slot_scrubbed(runtime))
4003                    } else {
4004                        Ok(())
4005                    }
4006                }),
4007        )
4008    }
4009
4010    /// Turn a slot refusal into the error that keeps the attempt uncleaned.
4011    ///
4012    /// The warning is emitted here, at the one place a quarantine is minted, so
4013    /// that both routes out of cleanup carry it: the reconciler's terminal sweep,
4014    /// which receives the error through the launcher port, and
4015    /// [`Self::clean_or_quarantine`], which swallows it to keep the pass alive.
4016    /// Everything logged is either a path this product configured or a constant
4017    /// from this module — see [`SlotQuarantine`] for why that matters.
4018    fn quarantine_on_refusal(
4019        &self,
4020        attempt: &RunnerAttempt,
4021        outcome: Result<(), SlotQuarantine>,
4022    ) -> Result<(), LifecycleError> {
4023        let Err(quarantine) = outcome else {
4024            return Ok(());
4025        };
4026        let detail = quarantine.to_string();
4027        tracing::warn!(
4028            attempt = %attempt.id,
4029            policy = %attempt.policy_id,
4030            slot = attempt.workspace().slot_number(),
4031            refusal = quarantine.refusal.class(),
4032            "{detail}"
4033        );
4034        Err(LifecycleError::SlotQuarantined {
4035            class: quarantine.refusal.class(),
4036            detail,
4037        })
4038    }
4039
4040    fn preserve_diagnostics(
4041        &self,
4042        attempt: &RunnerAttempt,
4043        outcome: &AttemptOutcome,
4044    ) -> Result<(), LifecycleError> {
4045        fs::create_dir_all(&self.diagnostics_root).map_err(|_| {
4046            LifecycleError::Failed(FailureReason::Other(
4047                "diagnostics directory could not be created".into(),
4048            ))
4049        })?;
4050        // Intentionally constructed from typed local facts, not runner output.
4051        // Raw child output can contain workflow secrets and is never copied.
4052        let reason_kind = match outcome {
4053            AttemptOutcome::Failed { reason } => failure_reason_kind(reason),
4054            _ => "none",
4055        };
4056        let diagnostic = format!(
4057            "attempt_id={}\npolicy_id={}\noutcome={}\nreason={}\n",
4058            attempt.id,
4059            attempt.policy_id,
4060            OutcomeKind::of(outcome).as_str(),
4061            reason_kind,
4062        );
4063        fs::write(
4064            self.diagnostics_root.join(format!("{}.log", attempt.id)),
4065            diagnostic,
4066        )
4067        .map_err(|_| {
4068            LifecycleError::Failed(FailureReason::Other(
4069                "redacted diagnostics could not be preserved".into(),
4070            ))
4071        })
4072    }
4073
4074    async fn materialize_with_retry(
4075        &self,
4076        policy: &ScalePolicy,
4077        attempt: &RunnerAttempt,
4078    ) -> Result<RunnerVersion, FailureReason> {
4079        let mut issued = 0_u32;
4080        loop {
4081            issued = issued.saturating_add(1);
4082            match self.ports.packages.materialize(attempt).await {
4083                Ok(version) => return Ok(version),
4084                Err(reason)
4085                    if package_failure_is_terminal(&reason)
4086                        || issued >= self.retry.max_attempts.max(1) =>
4087                {
4088                    return Err(reason);
4089                }
4090                Err(reason) => {
4091                    if !self.ports.demand.persists(policy.id).await {
4092                        return Err(reason);
4093                    }
4094                    let delay = self.retry.delay(issued);
4095                    self.ports.events.emit(AttemptEvent::Retry {
4096                        attempt: attempt.id,
4097                        operation: "package_materialization",
4098                        delay,
4099                    });
4100                    self.ports.delay.wait(delay).await;
4101                    if !self.ports.demand.persists(policy.id).await {
4102                        return Err(reason);
4103                    }
4104                }
4105            }
4106        }
4107    }
4108
4109    async fn register_with_retry(
4110        &self,
4111        policy: &ScalePolicy,
4112        attempt: AttemptId,
4113        request: &JitRunnerRequest,
4114    ) -> Result<JitRegistration, LifecycleError> {
4115        let mut issued = 0_u32;
4116        loop {
4117            issued = issued.saturating_add(1);
4118            match self
4119                .ports
4120                .github
4121                .register(&policy.target, request, &self.cancel)
4122                .await
4123            {
4124                Ok(registration) => return Ok(registration),
4125                Err(error) if error.terminal => {
4126                    return Err(LifecycleError::Failed(error.reason));
4127                }
4128                Err(error) => {
4129                    if issued >= self.retry.max_attempts.max(1)
4130                        || !self.ports.demand.persists(policy.id).await
4131                    {
4132                        return Err(LifecycleError::Failed(error.reason));
4133                    }
4134                    let delay = error
4135                        .retry_after
4136                        .unwrap_or_else(|| self.retry.delay(issued));
4137                    self.ports.events.emit(AttemptEvent::Retry {
4138                        attempt,
4139                        operation: "jit_request",
4140                        delay,
4141                    });
4142                    self.ports.delay.wait(delay).await;
4143                    if !self.ports.demand.persists(policy.id).await {
4144                        return Err(LifecycleError::Failed(error.reason));
4145                    }
4146                }
4147            }
4148        }
4149    }
4150
4151    /// Where one attempt's files go, decided while the host allocation lock is
4152    /// held and before anything external happens.
4153    ///
4154    /// The branch is on the *repository's configured* workspace policy, so an
4155    /// organization policy and an ephemeral repository never reach slot
4156    /// selection at all: a persistent policy is unrepresentable for an
4157    /// organization target (D7, refused by `WorkspacePolicy::permitted_for` in
4158    /// both the constructor and the loader), and an ephemeral repository takes
4159    /// the disposable arm that existed before slots did.
4160    fn allocate_workspace(
4161        &self,
4162        policy: &ScalePolicy,
4163        id: AttemptId,
4164    ) -> Result<Placement, LifecycleError> {
4165        let placement = match policy.workspace_policy() {
4166            // Precedence (`02-target-architecture.md`): the repository's
4167            // persistent root is selected *before* the host root, which is why
4168            // this arm is first and why it never makes resolving the host
4169            // default a precondition of its own success.
4170            WorkspacePolicy::Persistent { root } => self.allocate_persistent_slot(policy, root),
4171            WorkspacePolicy::Ephemeral => self.allocate_disposable(policy, id),
4172        };
4173        // Here rather than inside the two arms, so that every path a root can
4174        // accept clears the record and none can be forgotten.
4175        if placement.is_ok() {
4176            self.root_accepted(policy.id);
4177        }
4178        placement
4179    }
4180
4181    /// `Host.runner_root_override`, read from the journal.
4182    ///
4183    /// Separated from [`Self::effective_host_root`] so that the two failures it
4184    /// folds together stay apart: an unreadable or missing host row is a journal
4185    /// problem and is always fatal, while an unresolvable *platform default* is
4186    /// only fatal to a placement that actually needs the host root.
4187    fn configured_host_root(&self) -> Result<Option<LocalAbsolutePath>, LifecycleError> {
4188        let host = self
4189            .ports
4190            .store
4191            .host(self.host_id)
4192            .map_err(|_| LifecycleError::Journal)?
4193            .ok_or_else(|| LifecycleError::Failed(FailureReason::Other("host not found".into())))?;
4194        Ok(host.runner_root_override.clone())
4195    }
4196
4197    /// `Host.runner_root_override`, or the platform default when that resolves;
4198    /// `None` when neither does. Unlike [`Self::effective_host_root`] it records
4199    /// no refusal, for callers to whom an unresolvable root is not a failure.
4200    fn resolvable_host_root(&self) -> Result<Option<LocalAbsolutePath>, LifecycleError> {
4201        Ok(self
4202            .configured_host_root()?
4203            .or_else(|| default_runner_root(&self.app_paths).ok()))
4204    }
4205
4206    /// `Host.runner_root_override`, or the platform default standing in for it.
4207    ///
4208    /// Takes the policy because an unresolvable default is a refusal like any
4209    /// other, and the record it leaves is that policy's.
4210    fn effective_host_root(
4211        &self,
4212        policy: &ScalePolicy,
4213    ) -> Result<LocalAbsolutePath, LifecycleError> {
4214        match self.configured_host_root()? {
4215            Some(configured) => Ok(configured),
4216            None => default_runner_root(&self.app_paths).map_err(|error| {
4217                // No root resolved, so there is no path to name but the one the
4218                // platform would have produced.
4219                self.root_refused(policy.id, "the platform default runner root", error)
4220            }),
4221        }
4222    }
4223
4224    /// Turns a runner-root refusal into a failure, and leaves the sentence
4225    /// somewhere an operator can read it.
4226    ///
4227    /// Per policy, because the policies on a host do not share a fate: one with
4228    /// its own persistent root places runners while another on a withheld
4229    /// volume places none, and a host-wide record would have the first clear
4230    /// the second's on the same pass.
4231    ///
4232    /// The recording is best-effort and its failure is deliberately swallowed:
4233    /// this runs on the path that is already failing, and a host that cannot
4234    /// write a diagnostic file must still report the refusal it came to report.
4235    /// `service status` says so itself when the file is unreadable.
4236    fn root_refused(&self, policy: PolicyId, root: &str, error: RunnerRootError) -> LifecycleError {
4237        let _ = runner_manager_platform::service::record_runner_root_refusal(
4238            &self.app_paths,
4239            &policy.to_string(),
4240            self.ports.clock.now(),
4241            error.kind(),
4242            root,
4243            &error.to_string(),
4244        );
4245        root_failure(error)
4246    }
4247
4248    /// Clears that policy's record, because its root accepted a placement.
4249    ///
4250    /// Called on every successful placement rather than only after a failure:
4251    /// the daemon that recovers is often not the process that failed -- a
4252    /// self-update restarts it -- so "clear it if we wrote it" would leave a
4253    /// stale note on `service status` for as long as the host ran.
4254    fn root_accepted(&self, policy: PolicyId) {
4255        let _ = runner_manager_platform::service::clear_runner_root_refusal(
4256            &self.app_paths,
4257            &policy.to_string(),
4258        );
4259    }
4260
4261    /// D3's disposable placement: a unique child of the effective host root,
4262    /// removed whole on cleanup. `c1`'s behaviour, moved behind the branch.
4263    fn allocate_disposable(
4264        &self,
4265        policy: &ScalePolicy,
4266        id: AttemptId,
4267    ) -> Result<Placement, LifecycleError> {
4268        let effective_root = self.effective_host_root(policy)?;
4269        RootPreflight::new(&self.app_paths)
4270            .check(&RootOwner::Host, &effective_root)
4271            .map_err(|error| self.root_refused(policy.id, effective_root.as_str(), error))?;
4272        let runtime = effective_root.as_path().join({
4273            #[cfg(test)]
4274            {
4275                if std::env::var("RUNNER_MANAGER_TEST_MUTANT").as_deref()
4276                    == Ok("reuse_job_workspace")
4277                {
4278                    "mutant-shared-workspace".to_owned()
4279                } else {
4280                    workspace_name(id)
4281                }
4282            }
4283            #[cfg(not(test))]
4284            {
4285                workspace_name(id)
4286            }
4287        });
4288        fs::create_dir_all(&runtime)
4289            .map_err(|_| LifecycleError::Failed(FailureReason::ProcessStartFailed))?;
4290        Ok(Placement {
4291            runtime,
4292            workspace: AttemptWorkspace::Ephemeral,
4293        })
4294    }
4295
4296    /// D4/D5's persistent placement: the lowest free `sN` under the repository's
4297    /// configured root.
4298    ///
4299    /// Steps 1 to 6 of `02-target-architecture.md`, "Slot allocation", in order;
4300    /// step 7 is the journal write [`Self::record_allocation`] owns. All of them
4301    /// run under the host allocation lock, because [`Self::launch_attempt`] is
4302    /// reachable only through a `LaunchRequest` and that carries the guard.
4303    ///
4304    /// **The filesystem is never consulted to decide which slots are taken**
4305    /// (invariant 6). The leases come from the journal; the directory is
4306    /// inspected only to decide whether *this* slot is safe to reuse.
4307    fn allocate_persistent_slot(
4308        &self,
4309        policy: &ScalePolicy,
4310        root: &LocalAbsolutePath,
4311    ) -> Result<Placement, LifecycleError> {
4312        // 1-4. The lowest positive slot no uncleaned attempt holds, refused
4313        // above the policy ceiling.
4314        let ceiling = policy.max_capacity().ok_or_else(|| {
4315            LifecycleError::Failed(FailureReason::Other(
4316                "a persistent workspace needs the policy's max_capacity to bound its slots"
4317                    .to_string(),
4318            ))
4319        })?;
4320        let leases = self
4321            .ports
4322            .store
4323            .slot_leases_for_policy(policy.id)
4324            .map_err(|_| LifecycleError::Journal)?;
4325        let slot = lowest_free_slot(&leases, ceiling).ok_or_else(|| {
4326            LifecycleError::Failed(FailureReason::Other(format!(
4327                "every persistent slot s1 to s{ceiling} for {} is leased by an attempt that has \
4328                 not been cleaned, so no slot is free; raise the repository's max capacity, or \
4329                 finish cleaning a concluded attempt",
4330                policy.target
4331            )))
4332        })?;
4333        let workspace = AttemptWorkspace::persistent_slot(slot);
4334        let name = workspace
4335            .slot_directory_name()
4336            .expect("a persistent allocation names its slot directory");
4337
4338        // The operational preflight, for the reasons the host root gets one: a
4339        // root that is remote, unwritable, or overlapping application data has
4340        // to fail before a directory is created rather than after. The host
4341        // root is registered only as something *not* to overlap; a host default
4342        // that cannot be resolved is a host-root problem and does not block a
4343        // repository that configured a root of its own.
4344        //
4345        // Only *that* failure is tolerated. An unreadable host row is a journal
4346        // failure and propagates, because silently continuing would drop the
4347        // overlap check entirely and accept a repository root that sits inside
4348        // the host root — the pair `RootPreflight` exists to refuse.
4349        let host_root = self.resolvable_host_root()?;
4350        let mut preflight = RootPreflight::new(&self.app_paths);
4351        if let Some(host_root) = host_root {
4352            preflight = preflight.against(RootOwner::Host, host_root);
4353        }
4354        let checked = preflight
4355            .check(&RootOwner::Repository(policy.target.to_string()), root)
4356            .map_err(|error| self.root_refused(policy.id, root.as_str(), error))?;
4357        if let Some(leaf) = checked.leaf_to_create() {
4358            fs::create_dir(leaf).map_err(|source| {
4359                LifecycleError::Failed(FailureReason::Other(format!(
4360                    "the persistent workspace root {} could not be created: {source}",
4361                    leaf.display()
4362                )))
4363            })?;
4364        }
4365
4366        // 5-6. `<root>/sN`, contained lexically by construction, then created or
4367        // validated, then contained canonically now that it resolves, and only
4368        // then accepted for reuse.
4369        let slot_path = runner_root::derive_child(root, &name)
4370            .map_err(|error| self.root_refused(policy.id, root.as_str(), error))?;
4371        create_or_validate_slot(slot_path.as_path())?;
4372        runner_root::verify_containment(root, &slot_path)
4373            .map_err(|error| self.root_refused(policy.id, root.as_str(), error))?;
4374        accept_reusable_slot(slot_path.as_path())?;
4375        Ok(Placement {
4376            runtime: slot_path.as_path().to_path_buf(),
4377            workspace,
4378        })
4379    }
4380
4381    /// The first journal write of an attempt, where a duplicate slot lease is
4382    /// still possible and has to be reported as itself.
4383    ///
4384    /// [`Self::record`] flattens every store failure into
4385    /// [`LifecycleError::Journal`], which is right for a state transition and
4386    /// wrong here: the partial unique index
4387    /// `one_uncleaned_persistent_attempt_per_slot` is the final race fence
4388    /// (`04-security-recovery.md`, "two attempts use one slot concurrently"),
4389    /// and an operator who reaches it needs to read that rather than "attempt
4390    /// journal operation failed". Nothing was written, so the caller returns
4391    /// without concluding an attempt that is not in the journal.
4392    fn record_allocation(&self, attempt: &RunnerAttempt) -> Result<(), LifecycleError> {
4393        match self.ports.store.record_attempt(attempt) {
4394            Ok(()) => {
4395                self.ports.events.emit(AttemptEvent::State {
4396                    attempt: attempt.id,
4397                    state: attempt.state(),
4398                });
4399                Ok(())
4400            }
4401            Err(error @ StoreError::SlotAlreadyLeased { .. }) => Err(LifecycleError::Failed(
4402                FailureReason::Other(error.to_string()),
4403            )),
4404            Err(_) => Err(LifecycleError::Journal),
4405        }
4406    }
4407
4408    async fn launch_attempt(
4409        &self,
4410        policy: &ScalePolicy,
4411        allocation_guard: &AllocationGuard,
4412        lock_wait: Duration,
4413    ) -> Result<RunnerAttempt, LifecycleError> {
4414        let (attempt, labels) = self.allocate_attempt(policy)?;
4415        let id = attempt.id;
4416        let mut stopwatch = LaunchStopwatch::new(lock_wait);
4417        let result = self
4418            .launch_steps(policy, allocation_guard, attempt, labels, &mut stopwatch)
4419            .await;
4420        stopwatch.finish();
4421        self.ports.events.emit(AttemptEvent::Launched {
4422            attempt: id,
4423            started: result.is_ok(),
4424            timings: stopwatch.timings,
4425        });
4426        result
4427    }
4428
4429    /// Place and journal a new attempt: everything before its first external
4430    /// effect, and so before there is anything to time.
4431    fn allocate_attempt<'p>(
4432        &self,
4433        policy: &'p ScalePolicy,
4434    ) -> Result<(RunnerAttempt, &'p RoutingLabels), LifecycleError> {
4435        if !*self
4436            .recovery_complete
4437            .lock()
4438            .map_err(|_| LifecycleError::Journal)?
4439        {
4440            return Err(LifecycleError::RecoveryIncomplete);
4441        }
4442        let capability = self.ports.processes.probe(policy);
4443        if capability != ProviderCapability::Ready {
4444            return Err(LifecycleError::Failed(capability.refusal()));
4445        }
4446        let resolved = self.ports.processes.resolve(policy).map_err(|reason| {
4447            LifecycleError::Failed(if policy.execution_policy().is_native() {
4448                reason
4449            } else {
4450                safe_isolation_reason(reason, IsolationProviderFailure::RuntimeOperationFailed)
4451            })
4452        })?;
4453        if policy.execution_policy().is_native() != resolved.is_none() {
4454            return Err(LifecycleError::Failed(FailureReason::Other(
4455                "provider resolution mismatch".into(),
4456            )));
4457        }
4458        if let Some(resolution) = &resolved {
4459            if resolution.provider_kind == Backend::Auto {
4460                return Err(LifecycleError::Failed(FailureReason::Other(
4461                    "provider resolution mismatch".into(),
4462                )));
4463            }
4464            AttemptExecution::Isolated {
4465                provider_kind: resolution.provider_kind,
4466                environment_id: None,
4467                resolved_image: resolution.image.clone(),
4468                generation: "generation-check".into(),
4469            }
4470            .validate()
4471            .map_err(|_| {
4472                LifecycleError::Failed(FailureReason::Other(
4473                    "resolved image is incompatible".into(),
4474                ))
4475            })?;
4476        }
4477        let labels = policy
4478            .routing_labels()
4479            .ok_or(LifecycleError::Failed(FailureReason::JitRequestFailed))?;
4480        let id = AttemptId::new_random();
4481        let placement = self.allocate_workspace(policy, id)?;
4482        let mut attempt = RunnerAttempt::allocate_in(
4483            id,
4484            policy.id,
4485            placement.runtime,
4486            placement.workspace,
4487            self.ports.clock.now(),
4488        );
4489        if let Some(resolution) = &resolved {
4490            attempt
4491                .allocate_execution(AttemptExecution::Isolated {
4492                    provider_kind: resolution.provider_kind,
4493                    environment_id: None,
4494                    resolved_image: resolution.image.clone(),
4495                    generation: uuid::Uuid::new_v4().to_string(),
4496                })
4497                .map_err(|_| LifecycleError::Transition)?;
4498        }
4499        // This is deliberately the first effect after directory allocation, and
4500        // for a persistent attempt it is also what makes the slot lease durable
4501        // before any package or GitHub effect
4502        // (`02-target-architecture.md`, "Slot allocation", step 7).
4503        self.record_allocation(&attempt)?;
4504        Ok((attempt, labels))
4505    }
4506
4507    async fn launch_steps(
4508        &self,
4509        policy: &ScalePolicy,
4510        allocation_guard: &AllocationGuard,
4511        mut attempt: RunnerAttempt,
4512        labels: &RoutingLabels,
4513        stopwatch: &mut LaunchStopwatch,
4514    ) -> Result<RunnerAttempt, LifecycleError> {
4515        let id = attempt.id;
4516        let isolated = !attempt.execution().is_native();
4517        stopwatch.begin(LaunchStep::Materialize);
4518        let version = match self.materialize_with_retry(policy, &attempt).await {
4519            Ok(version) => version,
4520            Err(reason) => return self.fail_launch(&mut attempt, reason),
4521        };
4522        self.prune_under_allocation_lock(allocation_guard, &version)?;
4523        self.versions
4524            .lock()
4525            .map_err(|_| LifecycleError::Journal)?
4526            .insert(id, version);
4527
4528        if isolated {
4529            attempt
4530                .begin_prepare(self.ports.clock.now())
4531                .map_err(|_| LifecycleError::Transition)?;
4532            self.record(&attempt)?;
4533        }
4534        let prepared = match self.ports.processes.prepare(&attempt, policy) {
4535            Ok(prepared) => prepared,
4536            Err(reason) => {
4537                let safe_reason = if isolated {
4538                    safe_isolation_reason(reason, IsolationProviderFailure::RuntimeOperationFailed)
4539                } else {
4540                    reason
4541                };
4542                return self.fail_launch(&mut attempt, safe_reason);
4543            }
4544        };
4545        if isolated {
4546            let Some(identity) = prepared.identity() else {
4547                return Err(LifecycleError::Failed(FailureReason::IsolationProvider(
4548                    IsolationProviderFailure::OwnershipMismatch,
4549                )));
4550            };
4551            if !identity_matches_intent(self.host_id, &attempt, identity) {
4552                return Err(LifecycleError::Failed(FailureReason::IsolationProvider(
4553                    IsolationProviderFailure::OwnershipMismatch,
4554                )));
4555            }
4556            let EnvironmentIdentity::Isolated { environment_id, .. } = identity else {
4557                unreachable!()
4558            };
4559            attempt
4560                .prepared_environment(environment_id.clone())
4561                .map_err(|_| LifecycleError::Transition)?;
4562            attempt
4563                .mark_prepared(self.ports.clock.now())
4564                .map_err(|_| LifecycleError::Transition)?;
4565            self.record(&attempt)?;
4566        }
4567
4568        stopwatch.begin(LaunchStep::Register);
4569        let jit_request =
4570            JitRunnerRequest::for_policy(runner_name(id), self.runner_group_id, labels);
4571        let registration = match self.register_with_retry(policy, id, &jit_request).await {
4572            Ok(registration) => registration,
4573            Err(error) => return self.fail_launch(&mut attempt, error.reason()),
4574        };
4575        stopwatch.begin(LaunchStep::Spawn);
4576        let runner_id = registration.runner().id;
4577        write_runner_id(attempt.runtime_path(), runner_id)?;
4578        attempt
4579            .jit_received(self.ports.clock.now())
4580            .map_err(|_| LifecycleError::Transition)?;
4581        self.record(&attempt)?;
4582        let config = registration.into_config();
4583        if isolated {
4584            let started = self
4585                .ports
4586                .processes
4587                .start(prepared, &attempt, OneTimeJitHandoff::new(&config))
4588                .map_err(|failure| {
4589                    LifecycleError::Failed(safe_isolation_reason(
4590                        failure.reason,
4591                        IsolationProviderFailure::RuntimeOperationFailed,
4592                    ))
4593                })?;
4594            if !identity_matches_intent(self.host_id, &attempt, &started) {
4595                return Err(LifecycleError::Failed(FailureReason::IsolationProvider(
4596                    IsolationProviderFailure::OwnershipMismatch,
4597                )));
4598            }
4599            attempt
4600                .started_isolated(self.ports.clock.now())
4601                .map_err(|_| LifecycleError::Transition)?;
4602            self.record(&attempt)?;
4603            return Ok(attempt);
4604        }
4605        let mut issued = 0_u32;
4606        let pid = loop {
4607            issued = issued.saturating_add(1);
4608            match self.ports.processes.start(
4609                prepared.clone(),
4610                &attempt,
4611                OneTimeJitHandoff::new(&config),
4612            ) {
4613                Ok(EnvironmentIdentity::NativeProcess(pid)) => break pid,
4614                Ok(EnvironmentIdentity::Isolated { .. }) => {
4615                    // No isolated launch sequence is wired in this task. Keep
4616                    // the nonterminal JIT journal as a capacity fence rather
4617                    // than treating an unexpected resource as a native PID.
4618                    return Err(LifecycleError::Failed(FailureReason::Other(
4619                        "unexpected isolated environment identity".into(),
4620                    )));
4621                }
4622                Err(error) => {
4623                    if let Some(pid) = error.live_pid {
4624                        attempt
4625                            .started(pid, self.ports.clock.now())
4626                            .map_err(|_| LifecycleError::Transition)?;
4627                        self.record(&attempt)?;
4628                        return Err(LifecycleError::Failed(error.reason));
4629                    }
4630                    if !error.retryable
4631                        || issued >= self.retry.max_attempts.max(1)
4632                        || !self.ports.demand.persists(policy.id).await
4633                    {
4634                        return self.fail_launch(&mut attempt, error.reason);
4635                    }
4636                    let delay = self.retry.delay(issued);
4637                    self.ports.events.emit(AttemptEvent::Retry {
4638                        attempt: attempt.id,
4639                        operation: "process_start",
4640                        delay,
4641                    });
4642                    self.ports.delay.wait(delay).await;
4643                    if !self.ports.demand.persists(policy.id).await {
4644                        return self.fail_launch(&mut attempt, error.reason);
4645                    }
4646                }
4647            }
4648        };
4649        attempt
4650            .started(pid, self.ports.clock.now())
4651            .map_err(|_| LifecycleError::Transition)?;
4652        self.record(&attempt)?;
4653        Ok(attempt)
4654    }
4655
4656    fn fail_launch<T>(
4657        &self,
4658        attempt: &mut RunnerAttempt,
4659        reason: FailureReason,
4660    ) -> Result<T, LifecycleError> {
4661        self.conclude(attempt, AttemptOutcome::failed(reason.clone()))?;
4662        Err(LifecycleError::Failed(reason))
4663    }
4664
4665    /// e2's prune guard is invoked only with e1's allocation guard borrowed.
4666    /// The otherwise-unused argument is a compile-time witness of the ordering.
4667    fn prune_under_allocation_lock(
4668        &self,
4669        guard: &AllocationGuard,
4670        version: &RunnerVersion,
4671    ) -> Result<(), LifecycleError> {
4672        let attempts = self
4673            .ports
4674            .store
4675            .attempts()
4676            .map_err(|_| LifecycleError::Journal)?;
4677        self.ports
4678            .packages
4679            .prune_obsolete_guarded(
4680                PruneAuthority::from_launch_request(guard),
4681                version,
4682                &attempts,
4683            )
4684            .map_err(LifecycleError::Failed)?;
4685        #[cfg(target_os = "macos")]
4686        self.prune_abandoned_seeds(&attempts);
4687        Ok(())
4688    }
4689
4690    /// Remove the package seed from every runner root this host once placed a
4691    /// runtime in and no longer does: a changed host root override, a removed
4692    /// persistent policy, or one that moved its workspace.
4693    ///
4694    /// The roots ever used are the parents of the journal's runtime paths; the
4695    /// roots in use are the effective host root and every persistent policy's
4696    /// root. When the effective host root cannot be resolved nothing is
4697    /// removed, because a seed still in use cannot then be told apart. Runs
4698    /// under the allocation lock, so no launch is cloning from a seed it
4699    /// removes, and it is best-effort: a seed left behind costs disk, never a
4700    /// launch.
4701    #[cfg(target_os = "macos")]
4702    fn prune_abandoned_seeds(&self, attempts: &[RunnerAttempt]) {
4703        let Ok(policies) = self.ports.store.policies() else {
4704            return;
4705        };
4706        let Ok(Some(host_root)) = self.resolvable_host_root() else {
4707            return;
4708        };
4709        let in_use: BTreeSet<PathBuf> = policies
4710            .iter()
4711            .filter_map(|policy| match policy.workspace_policy() {
4712                WorkspacePolicy::Persistent { root } => Some(canonical_or_raw(root.as_path())),
4713                WorkspacePolicy::Ephemeral => None,
4714            })
4715            .chain(std::iter::once(canonical_or_raw(host_root.as_path())))
4716            .collect();
4717        // Distinct parents first: the journal keeps every attempt ever made.
4718        let used: BTreeSet<&Path> = attempts
4719            .iter()
4720            .filter_map(|attempt| attempt.runtime_path().parent())
4721            .collect();
4722        for root in used.into_iter().map(canonical_or_raw) {
4723            if !in_use.contains(&root) {
4724                let _ = remove_runtime_tree(&root.join(PACKAGE_SEED_DIR));
4725            }
4726        }
4727    }
4728}
4729
4730#[cfg(target_os = "macos")]
4731fn canonical_or_raw(path: &Path) -> PathBuf {
4732    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
4733}
4734
4735#[async_trait]
4736impl RunnerLauncher for LifecycleLauncher {
4737    async fn supervise(
4738        &self,
4739        policy: &ScalePolicy,
4740    ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
4741        LifecycleLauncher::supervise(self, policy)
4742            .await
4743            .map_err(|error| LaunchFailure::new(error.reason()))
4744    }
4745
4746    async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
4747        self.ports.store.attempts().map_err(|_| {
4748            LaunchFailure::new(FailureReason::Other(
4749                "attempt journal could not be read".into(),
4750            ))
4751        })
4752    }
4753
4754    async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure> {
4755        self.launch_attempt(request.policy, request.allocation_guard, request.lock_wait)
4756            .await
4757            .map_err(|error| LaunchFailure::new(error.reason()))
4758    }
4759
4760    async fn clean(&self, id: AttemptId) -> Result<(), LaunchFailure> {
4761        let mut attempt = self
4762            .ports
4763            .store
4764            .attempt(id)
4765            .map_err(|_| {
4766                LaunchFailure::new(FailureReason::Other(
4767                    "attempt journal could not be read".into(),
4768                ))
4769            })?
4770            .ok_or_else(|| {
4771                LaunchFailure::new(FailureReason::Other(
4772                    "attempt disappeared from the journal".into(),
4773                ))
4774            })?;
4775        self.clean_attempt(&mut attempt)
4776            .map_err(|error| LaunchFailure::new(error.reason()))?;
4777        self.cleanup_retries().succeeded(id);
4778        Ok(())
4779    }
4780}
4781
4782fn runner_name(attempt: AttemptId) -> String {
4783    format!("runner-manager-{attempt}")
4784}
4785
4786/// How long reading a runner's diagnostics may take.
4787const EVIDENCE_DEADLINE: Duration = Duration::from_secs(2);
4788
4789/// What a native runner's own diagnostics say about whether it ran a job.
4790///
4791/// `Runner.Listener` writes `_diag/Runner_*.log` when it starts, and starts
4792/// `Runner.Worker` -- which writes `_diag/Worker_*.log` -- only for a job it has
4793/// acquired. So a worker log is proof a job ran, and a listener log without one
4794/// is proof none did. With neither, the directory is not where the listener
4795/// wrote, and nothing is concluded from it. `_diag` is scrubbed with the rest of
4796/// the runtime after every attempt, persistent slots included, so a log found
4797/// here belongs to this attempt.
4798#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4799enum JobEvidence {
4800    RanAJob,
4801    NoJob,
4802    Unknown,
4803}
4804
4805impl JobEvidence {
4806    fn of(runtime: &Path) -> Self {
4807        let diag = runtime.join("_diag");
4808        // Bounded: the daemon's loop runs on one thread, and a runtime on a
4809        // volume that does not answer (a hung disk, a pending macOS question)
4810        // must not stall it for longer than this.
4811        if runner_manager_platform::host_fitness::directory_responds(&diag, EVIDENCE_DEADLINE)
4812            != runner_manager_platform::host_fitness::Responsiveness::Responds
4813        {
4814            return Self::Unknown;
4815        }
4816        let Ok(entries) = fs::read_dir(diag) else {
4817            return Self::Unknown;
4818        };
4819        let mut listener = false;
4820        for entry in entries.flatten() {
4821            let name = entry.file_name();
4822            let name = name.to_string_lossy();
4823            if !name.ends_with(".log") {
4824                continue;
4825            }
4826            if name.starts_with("Worker_") {
4827                return Self::RanAJob;
4828            }
4829            listener |= name.starts_with("Runner_");
4830        }
4831        if listener { Self::NoJob } else { Self::Unknown }
4832    }
4833}
4834
4835/// The attempt's GitHub runner id: journalled, observed, or from the sidecar
4836/// written at registration.
4837fn known_runner_id(attempt: &RunnerAttempt, observed: Option<u64>) -> Option<u64> {
4838    attempt
4839        .github_runner_id()
4840        .or(observed)
4841        .or_else(|| read_runner_id(attempt.runtime_path()))
4842}
4843
4844fn read_runner_id(runtime: &Path) -> Option<u64> {
4845    fs::read_to_string(runtime.join(RUNNER_ID_FILE))
4846        .ok()?
4847        .trim()
4848        .parse()
4849        .ok()
4850}
4851
4852fn write_runner_id(runtime: &Path, runner_id: u64) -> Result<(), LifecycleError> {
4853    let target = runtime.join(RUNNER_ID_FILE);
4854    if let Some(existing) = read_runner_id(runtime) {
4855        return (existing == runner_id)
4856            .then_some(())
4857            .ok_or(LifecycleError::Journal);
4858    }
4859    let temporary = runtime.join(format!("{RUNNER_ID_FILE}.{}.tmp", uuid::Uuid::new_v4()));
4860    write_durable_file(&temporary, runner_id.to_string().as_bytes())
4861        .map_err(|_| LifecycleError::Journal)?;
4862    match fs::rename(&temporary, &target) {
4863        Ok(()) => sync_directory(runtime).map_err(|_| LifecycleError::Journal),
4864        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
4865            let _ = fs::remove_file(&temporary);
4866            (read_runner_id(runtime) == Some(runner_id))
4867                .then_some(())
4868                .ok_or(LifecycleError::Journal)
4869        }
4870        Err(_) => {
4871            let _ = fs::remove_file(&temporary);
4872            Err(LifecycleError::Journal)
4873        }
4874    }
4875}
4876
4877fn write_durable_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
4878    let mut file = fs::OpenOptions::new()
4879        .create(true)
4880        .truncate(true)
4881        .write(true)
4882        .open(path)?;
4883    file.write_all(bytes)?;
4884    file.sync_all()?;
4885    let parent = path.parent().ok_or_else(|| {
4886        std::io::Error::new(
4887            std::io::ErrorKind::InvalidInput,
4888            "file has no parent directory",
4889        )
4890    })?;
4891    sync_directory(parent)
4892}
4893
4894#[cfg(unix)]
4895fn sync_directory(path: &Path) -> std::io::Result<()> {
4896    fs::File::open(path)?.sync_all()
4897}
4898
4899#[cfg(windows)]
4900fn sync_directory(path: &Path) -> std::io::Result<()> {
4901    use std::os::windows::fs::OpenOptionsExt;
4902
4903    const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
4904    const FILE_SHARE_ALL: u32 = 0x0000_0007;
4905    const GENERIC_WRITE: u32 = 0x4000_0000;
4906    fs::OpenOptions::new()
4907        .access_mode(GENERIC_WRITE)
4908        .share_mode(FILE_SHARE_ALL)
4909        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
4910        .open(path)?
4911        .sync_all()
4912}
4913
4914#[cfg(test)]
4915mod tests {
4916    use super::*;
4917    use std::collections::BTreeSet;
4918    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
4919
4920    use crate::reconcile::{AllocationLock, InProcessAllocationLock};
4921    use runner_manager_domain::model::{Elapsed, TargetScope};
4922    use runner_manager_domain::store::SqliteStore;
4923    use runner_manager_github::jit::JitRunner;
4924    use runner_manager_testkit::clock::FakeClock;
4925    use runner_manager_testkit::fixtures;
4926
4927    #[test]
4928    fn production_provider_set_routes_every_implemented_isolated_backend() {
4929        let providers = PlatformExecutionProvider::new(HostId::from_u128(1));
4930        assert!(providers.isolated_provider(Backend::Auto).is_some());
4931        assert!(providers.isolated_provider(Backend::Oci).is_some());
4932        assert!(
4933            providers
4934                .isolated_provider(Backend::WindowsHyperVContainer)
4935                .is_some()
4936        );
4937        assert!(
4938            providers
4939                .isolated_provider(Backend::VirtualMachine)
4940                .is_none()
4941        );
4942    }
4943
4944    /// One event's fields, in the order they were recorded.
4945    type CapturedFields = Vec<(String, String)>;
4946
4947    /// Keeps the `(name, value)` fields of every `tracing` event emitted while
4948    /// it is installed.
4949    ///
4950    /// The names are kept and not just the rendered line, so a test can hold the
4951    /// event to `crate::logging`'s two rules -- the field allow-list and the
4952    /// value scrub -- instead of asserting that some string was passed to a
4953    /// macro.
4954    #[derive(Clone, Default)]
4955    struct CapturedEvents(std::sync::Arc<std::sync::Mutex<Vec<CapturedFields>>>);
4956
4957    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for CapturedEvents {
4958        fn on_event(
4959            &self,
4960            event: &tracing::Event<'_>,
4961            _context: tracing_subscriber::layer::Context<'_, S>,
4962        ) {
4963            struct Collect(Vec<(String, String)>);
4964            impl tracing::field::Visit for Collect {
4965                fn record_debug(
4966                    &mut self,
4967                    field: &tracing::field::Field,
4968                    value: &dyn std::fmt::Debug,
4969                ) {
4970                    // `{value:?}` on a `&str` field would keep the quotes, and
4971                    // the redaction rules are about the value, not its literal.
4972                    self.0.push((
4973                        field.name().to_owned(),
4974                        format!("{value:?}").trim_matches('"').to_owned(),
4975                    ));
4976                }
4977            }
4978            let mut collected = Collect(Vec::new());
4979            event.record(&mut collected);
4980            self.0
4981                .lock()
4982                .expect("the capture mutex is not poisoned")
4983                .push(collected.0);
4984        }
4985    }
4986
4987    /// The regression behind a three-hour outage that showed nothing an operator
4988    /// could act on.
4989    ///
4990    /// A root the daemon cannot use refuses the launch *before*
4991    /// `record_allocation`, so no attempt row is ever written: `b2` has nothing
4992    /// to carry the failure on and `g2` has nothing to show it from. The
4993    /// lifecycle event keeps only the variant -- `failure_reason_kind` allows no
4994    /// free text on an event -- so the whole failure read
4995    /// `runner_start_failed reason=other`, once per poll, for hours.
4996    ///
4997    /// The assertion is deliberately made against the **production redaction
4998    /// rules** and not merely against what was emitted. An earlier attempt at
4999    /// this fix logged the rendered error on a `detail` field and passed a test
5000    /// exactly like this one, while shipping `detail="[redacted]"`: the field
5001    /// was not allow-listed, and had it been, the value is mostly paths and
5002    /// would have been scrubbed to `[path]`. A test that does not ask
5003    /// `crate::logging` what survives is a test that proves nothing.
5004    #[test]
5005    fn a_launch_the_runner_root_refused_names_the_cause_in_the_log_that_ships() {
5006        use runner_manager_platform::logging;
5007        use tracing_subscriber::layer::SubscriberExt as _;
5008
5009        let captured = CapturedEvents::default();
5010        let error = RunnerRootError::DeniedByPrivacyPolicy {
5011            requested: PathBuf::from("/Volumes/NVME/runners"),
5012            refused: PathBuf::from("/Volumes/NVME"),
5013            remediation: RootOwner::Host.remediation(),
5014        };
5015        let kind = error.kind();
5016
5017        let failure = tracing::subscriber::with_default(
5018            tracing_subscriber::registry().with(captured.clone()),
5019            || root_failure(error),
5020        );
5021
5022        // The reason still carries the whole sentence. Nothing on *this* path
5023        // renders it -- there is no attempt row, and the event carries only the
5024        // variant -- so this is a guard against a refactor that drops the detail
5025        // before some future surface can show it, and not a claim that one does.
5026        assert!(
5027            matches!(
5028                &failure,
5029                LifecycleError::Failed(FailureReason::Other(detail))
5030                    if detail.contains("/Volumes/NVME/runners")
5031                        && detail.contains("Full Disk Access")
5032            ),
5033            "the reason must still carry the detail: {failure:?}"
5034        );
5035
5036        let events = captured
5037            .0
5038            .lock()
5039            .expect("the capture mutex is not poisoned")
5040            .clone();
5041        let event = events
5042            .iter()
5043            .find(|fields| fields.iter().any(|(_, value)| value.contains(kind)))
5044            .unwrap_or_else(|| panic!("the refusal did not name its cause: {events:?}"));
5045
5046        // Held to the rules the real sink applies, by name and by value. An
5047        // earlier fix put the rendered error on an unlisted `detail` field and
5048        // shipped `[redacted]`; asserting only that something was emitted would
5049        // have passed then too.
5050        for (name, value) in event {
5051            assert!(
5052                logging::is_field_allowed(name),
5053                "`{name}` is not allow-listed, so it ships as `{}`: {event:?}",
5054                logging::REDACTION
5055            );
5056            assert_eq!(
5057                &logging::redact(value),
5058                value,
5059                "`{name}` does not survive value-shape scrubbing: {event:?}"
5060            );
5061        }
5062    }
5063
5064    /// A slot number, for the tests that name one.
5065    fn nz(slot: u16) -> NonZeroU16 {
5066        NonZeroU16::new(slot).expect("a positive slot")
5067    }
5068
5069    const JIT: &str = "eyJzZWNyZXQiOiJnaHBfRE9fTk9UX0xFQUsifQ==";
5070
5071    #[derive(Debug, Default)]
5072    struct FakeGithubLifecycle {
5073        registration_failures: Mutex<VecDeque<bool>>,
5074        observations: Mutex<VecDeque<LifecycleGithubObservation>>,
5075        registrations: AtomicUsize,
5076        remaining_runners: AtomicUsize,
5077        /// Every runner id `deregister` was asked to remove, in order. A count
5078        /// would not do: the assertions worth making are that the *right*
5079        /// registration was deleted and that it was deleted once.
5080        deregistrations: Mutex<Vec<u64>>,
5081        /// Set to make `deregister` answer `false`, standing for a GitHub that
5082        /// could not be reached at the moment the attempt concluded.
5083        deregistration_fails: AtomicBool,
5084        /// The journal to read *during* a registration, for the ordering
5085        /// assertion `02-target-architecture.md` makes: the slot lease is
5086        /// written "before package or GitHub effects". Reading it afterwards
5087        /// would pass even if the write happened second.
5088        journal: Mutex<Option<Arc<SqliteStore>>>,
5089        /// One entry per registration, in order.
5090        registration_facts: Mutex<Vec<RegistrationFact>>,
5091    }
5092
5093    /// What one JIT registration saw of the world at the moment it was issued.
5094    ///
5095    /// `runner_name` is what ties the other two fields to *one* attempt: with
5096    /// two allocators racing, "some slot was journalled" is a much weaker claim
5097    /// than "the slot this very request belongs to was journalled", and only the
5098    /// name distinguishes them.
5099    #[derive(Debug, Clone)]
5100    struct RegistrationFact {
5101        /// The persistent slots the journal already held.
5102        leased_slots: Vec<u16>,
5103        /// The `work_folder` the request carried.
5104        work_folder: String,
5105        /// The runner name the request carried, i.e. [`runner_name`] of the
5106        /// registering attempt.
5107        runner_name: String,
5108        journal_states: Vec<AttemptState>,
5109    }
5110
5111    impl FakeGithubLifecycle {
5112        fn fail(mut self, terminal: bool) -> Self {
5113            self.registration_failures
5114                .get_mut()
5115                .expect("unpoisoned")
5116                .push_back(terminal);
5117            self
5118        }
5119
5120        fn watch_journal(&self, store: Arc<SqliteStore>) {
5121            *self.journal.lock().unwrap() = Some(store);
5122        }
5123
5124        fn registration_facts(&self) -> Vec<RegistrationFact> {
5125            self.registration_facts.lock().unwrap().clone()
5126        }
5127
5128        fn observe(&self, observation: GithubRunnerObservation) {
5129            let observation = match observation {
5130                GithubRunnerObservation::Unreachable => LifecycleGithubObservation::unreachable(),
5131                GithubRunnerObservation::NotRegistered => {
5132                    LifecycleGithubObservation::not_registered()
5133                }
5134                GithubRunnerObservation::Registered { busy } => {
5135                    LifecycleGithubObservation::registered(73, busy)
5136                }
5137            };
5138            self.observations.lock().unwrap().push_back(observation);
5139        }
5140    }
5141
5142    #[async_trait]
5143    impl LifecycleGithub for FakeGithubLifecycle {
5144        async fn register(
5145            &self,
5146            _target: &ScaleTarget,
5147            request: &JitRunnerRequest,
5148            _cancel: &CancelToken,
5149        ) -> Result<JitRegistration, JitRequestFailure> {
5150            self.registrations.fetch_add(1, Ordering::SeqCst);
5151            if let Some(store) = self.journal.lock().unwrap().as_ref() {
5152                let attempts = store.attempts().expect("the journal is readable");
5153                let slots = attempts
5154                    .iter()
5155                    .filter_map(|attempt| attempt.workspace().slot_number())
5156                    .collect();
5157                self.registration_facts
5158                    .lock()
5159                    .unwrap()
5160                    .push(RegistrationFact {
5161                        leased_slots: slots,
5162                        work_folder: request.work_folder().to_string(),
5163                        runner_name: request.name().to_string(),
5164                        journal_states: attempts.iter().map(RunnerAttempt::state).collect(),
5165                    });
5166            }
5167            if let Some(terminal) = self.registration_failures.lock().unwrap().pop_front() {
5168                return Err(JitRequestFailure {
5169                    terminal,
5170                    reason: if terminal {
5171                        FailureReason::Other("GitHub refused JIT registration with 403".into())
5172                    } else {
5173                        FailureReason::JitRequestFailed
5174                    },
5175                    retry_after: None,
5176                });
5177            }
5178            self.remaining_runners.store(1, Ordering::SeqCst);
5179            Ok(JitRegistration::new(
5180                EncodedJitConfig::new(JIT),
5181                JitRunner {
5182                    id: 73,
5183                    name: request.name().to_string(),
5184                    os: "windows".into(),
5185                    status: "offline".into(),
5186                    busy: false,
5187                    runner_group_id: Some(1),
5188                    labels: request.labels().to_vec(),
5189                },
5190            ))
5191        }
5192
5193        async fn observe(
5194            &self,
5195            _target: &ScaleTarget,
5196            _attempt: AttemptId,
5197            _cancel: &CancelToken,
5198        ) -> LifecycleGithubObservation {
5199            let observation = self
5200                .observations
5201                .lock()
5202                .unwrap()
5203                .pop_front()
5204                .unwrap_or(LifecycleGithubObservation::not_registered());
5205            if observation.status == GithubRunnerObservation::NotRegistered {
5206                self.remaining_runners.store(0, Ordering::SeqCst);
5207            }
5208            observation
5209        }
5210
5211        async fn deregister(
5212            &self,
5213            _target: &ScaleTarget,
5214            runner_id: u64,
5215            _cancel: &CancelToken,
5216        ) -> bool {
5217            self.deregistrations.lock().unwrap().push(runner_id);
5218            if self.deregistration_fails.load(Ordering::SeqCst) {
5219                return false;
5220            }
5221            self.remaining_runners.store(0, Ordering::SeqCst);
5222            true
5223        }
5224    }
5225
5226    #[derive(Debug)]
5227    struct FakePackages {
5228        version: RunnerVersion,
5229        leases: Mutex<BTreeSet<AttemptId>>,
5230        materializations: AtomicUsize,
5231        materialization_failures: AtomicUsize,
5232        release_failures: AtomicUsize,
5233        releases: AtomicUsize,
5234        prunes: AtomicUsize,
5235        prune_currents: Mutex<Vec<RunnerVersion>>,
5236    }
5237
5238    impl Default for FakePackages {
5239        fn default() -> Self {
5240            Self {
5241                version: RunnerVersion::parse("2.330.0").unwrap(),
5242                leases: Mutex::new(BTreeSet::new()),
5243                materializations: AtomicUsize::new(0),
5244                materialization_failures: AtomicUsize::new(0),
5245                release_failures: AtomicUsize::new(0),
5246                releases: AtomicUsize::new(0),
5247                prunes: AtomicUsize::new(0),
5248                prune_currents: Mutex::new(Vec::new()),
5249            }
5250        }
5251    }
5252
5253    impl FakePackages {
5254        fn fail_materializations(&self, count: usize) {
5255            self.materialization_failures.store(count, Ordering::SeqCst);
5256        }
5257
5258        fn fail_releases(&self, count: usize) {
5259            self.release_failures.store(count, Ordering::SeqCst);
5260        }
5261    }
5262
5263    #[async_trait]
5264    impl RuntimePackages for FakePackages {
5265        async fn materialize(
5266            &self,
5267            attempt: &RunnerAttempt,
5268        ) -> Result<RunnerVersion, FailureReason> {
5269            self.materializations.fetch_add(1, Ordering::SeqCst);
5270            if self
5271                .materialization_failures
5272                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
5273                    if left > 0 { Some(left - 1) } else { None }
5274                })
5275                .is_ok()
5276            {
5277                return Err(FailureReason::Other(
5278                    "runner package materialization failed transiently".into(),
5279                ));
5280            }
5281            fs::create_dir_all(attempt.runtime_path()).unwrap();
5282            fs::write(attempt.runtime_path().join("runner-package"), b"verified").unwrap();
5283            self.leases.lock().unwrap().insert(attempt.id);
5284            Ok(self.version.clone())
5285        }
5286
5287        fn release(&self, attempt: AttemptId) -> Result<(), FailureReason> {
5288            if self
5289                .release_failures
5290                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
5291                    if left > 0 { Some(left - 1) } else { None }
5292                })
5293                .is_ok()
5294            {
5295                return Err(FailureReason::Other(
5296                    "runner package lease could not be released".into(),
5297                ));
5298            }
5299            self.leases.lock().unwrap().remove(&attempt);
5300            self.releases.fetch_add(1, Ordering::SeqCst);
5301            Ok(())
5302        }
5303
5304        fn prune_obsolete_guarded(
5305            &self,
5306            _authority: PruneAuthority<'_>,
5307            current: &RunnerVersion,
5308            _attempts: &[RunnerAttempt],
5309        ) -> Result<(), FailureReason> {
5310            self.prunes.fetch_add(1, Ordering::SeqCst);
5311            self.prune_currents.lock().unwrap().push(current.clone());
5312            Ok(())
5313        }
5314    }
5315
5316    #[derive(Debug, Default)]
5317    struct FakeProcesses {
5318        alive: AtomicBool,
5319        completed_successfully: AtomicBool,
5320        spawns: AtomicUsize,
5321        spawn_failures: AtomicUsize,
5322        live_spawn_failure: AtomicBool,
5323        terminations: AtomicUsize,
5324        intent: AtomicBool,
5325        intent_failure: AtomicBool,
5326        actions: Mutex<Vec<&'static str>>,
5327        saw_secret: AtomicBool,
5328    }
5329
5330    impl FakeProcesses {
5331        fn fail_spawns(&self, count: usize) {
5332            self.spawn_failures.store(count, Ordering::SeqCst);
5333        }
5334
5335        fn fail_spawn_with_live_child(&self) {
5336            self.live_spawn_failure.store(true, Ordering::SeqCst);
5337        }
5338
5339        fn set_alive(&self, alive: bool) {
5340            self.alive.store(alive, Ordering::SeqCst);
5341        }
5342
5343        fn finish_successfully(&self) {
5344            self.completed_successfully.store(true, Ordering::SeqCst);
5345            self.alive.store(false, Ordering::SeqCst);
5346        }
5347
5348        fn fail_intent(&self) {
5349            self.intent_failure.store(true, Ordering::SeqCst);
5350        }
5351    }
5352
5353    impl ProcessSupervisor for FakeProcesses {
5354        fn spawn(
5355            &self,
5356            attempt: &RunnerAttempt,
5357            config: &EncodedJitConfig,
5358        ) -> Result<u32, ProcessStartFailure> {
5359            self.spawns.fetch_add(1, Ordering::SeqCst);
5360            // Model the production handoff on both paths: the sensitive file is
5361            // scoped to this call and absent when it returns.
5362            let handoff = RestrictiveHandoff::create(
5363                attempt.runtime_path(),
5364                SecretString::from(config.expose().to_owned()),
5365            )
5366            .unwrap();
5367            self.saw_secret
5368                .store(config.expose() == JIT, Ordering::SeqCst);
5369            let handoff_path = handoff.path().to_path_buf();
5370            let failing = self
5371                .spawn_failures
5372                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
5373                    if left > 0 { Some(left - 1) } else { None }
5374                })
5375                .is_ok();
5376            drop(handoff);
5377            assert!(!handoff_path.exists(), "handoff must be absent on return");
5378            if self.live_spawn_failure.swap(false, Ordering::SeqCst) {
5379                self.alive.store(true, Ordering::SeqCst);
5380                return Err(ProcessStartFailure::after_spawn_live(4242));
5381            }
5382            if failing {
5383                return Err(ProcessStartFailure::before_spawn(
5384                    FailureReason::ProcessStartFailed,
5385                ));
5386            }
5387            self.alive.store(true, Ordering::SeqCst);
5388            Ok(4242)
5389        }
5390
5391        fn is_alive(&self, _attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
5392            self.actions.lock().unwrap().push("observe_process");
5393            Ok(self.alive.load(Ordering::SeqCst))
5394        }
5395
5396        fn recovered_pid(&self, _attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
5397            Ok(self.alive.load(Ordering::SeqCst).then_some(4242))
5398        }
5399
5400        fn completed_successfully(&self, _attempt: &RunnerAttempt) -> bool {
5401            self.completed_successfully.load(Ordering::SeqCst)
5402        }
5403
5404        fn record_terminate_intent(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
5405            self.actions.lock().unwrap().push("terminate_intent");
5406            if self.intent_failure.load(Ordering::SeqCst) {
5407                return Err(FailureReason::Other(
5408                    "terminate intent directory sync failed".into(),
5409                ));
5410            }
5411            self.intent.store(true, Ordering::SeqCst);
5412            Ok(())
5413        }
5414
5415        fn has_terminate_intent(&self, _attempt: &RunnerAttempt) -> bool {
5416            self.intent.load(Ordering::SeqCst)
5417        }
5418
5419        fn terminate(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
5420            assert!(
5421                self.intent.load(Ordering::SeqCst),
5422                "the durable intent must exist before signalling"
5423            );
5424            self.actions.lock().unwrap().push("terminate");
5425            self.terminations.fetch_add(1, Ordering::SeqCst);
5426            self.alive.store(false, Ordering::SeqCst);
5427            Ok(())
5428        }
5429    }
5430
5431    #[derive(Debug, Default)]
5432    struct FakeIsolatedProvider {
5433        resources: Mutex<BTreeMap<AttemptId, (EnvironmentIdentity, EnvironmentState)>>,
5434        extra_resources: Mutex<Vec<EnvironmentIdentity>>,
5435        unsupported_host: AtomicBool,
5436        permission_denied: AtomicBool,
5437        incompatible_image: AtomicBool,
5438        prepare_failure: AtomicBool,
5439        recovery_unavailable: AtomicBool,
5440        destroy_deferred: AtomicBool,
5441        handoffs: AtomicUsize,
5442        completed_successfully: AtomicBool,
5443        native_calls: AtomicUsize,
5444        actions: Mutex<Vec<&'static str>>,
5445    }
5446
5447    impl FakeIsolatedProvider {
5448        fn identity(attempt: &RunnerAttempt, host: HostId) -> EnvironmentIdentity {
5449            let AttemptExecution::Isolated {
5450                provider_kind,
5451                resolved_image,
5452                generation,
5453                ..
5454            } = attempt.execution()
5455            else {
5456                panic!("isolated intent required")
5457            };
5458            EnvironmentIdentity::Isolated {
5459                host,
5460                attempt: attempt.id,
5461                provider_kind: *provider_kind,
5462                environment_id: format!("environment-{}", attempt.id),
5463                resolved_image: resolved_image.clone(),
5464                generation: generation.clone(),
5465            }
5466        }
5467
5468        fn resource_count(&self) -> usize {
5469            self.resources.lock().unwrap().len()
5470        }
5471    }
5472
5473    impl ExecutionProvider for FakeIsolatedProvider {
5474        fn probe(&self, policy: &ScalePolicy) -> ProviderCapability {
5475            if self.unsupported_host.load(Ordering::SeqCst) {
5476                ProviderCapability::Unsupported
5477            } else if self.permission_denied.load(Ordering::SeqCst) {
5478                ProviderCapability::PermissionDenied
5479            } else if policy.execution_policy().is_native() {
5480                ProviderCapability::Unsupported
5481            } else {
5482                ProviderCapability::Ready
5483            }
5484        }
5485
5486        fn resolve(
5487            &self,
5488            policy: &ScalePolicy,
5489        ) -> Result<Option<ResolvedEnvironment>, FailureReason> {
5490            let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
5491                policy.execution_policy()
5492            else {
5493                return Err(FailureReason::Other("isolated policy required".into()));
5494            };
5495            Ok(Some(ResolvedEnvironment {
5496                provider_kind: Backend::Oci,
5497                image: if self.incompatible_image.load(Ordering::SeqCst) {
5498                    ImageReference::new("vm-version:wrong-provider")
5499                        .expect("valid but incompatible")
5500                } else {
5501                    image.clone()
5502                },
5503            }))
5504        }
5505
5506        fn prepare(
5507            &self,
5508            attempt: &RunnerAttempt,
5509            policy: &ScalePolicy,
5510        ) -> Result<PreparedEnvironment, FailureReason> {
5511            assert_eq!(
5512                attempt.state(),
5513                AttemptState::Preparing,
5514                "intent must be durable before provider effect"
5515            );
5516            self.actions.lock().unwrap().push("prepare");
5517            let identity = Self::identity(attempt, policy.host_id);
5518            self.resources
5519                .lock()
5520                .unwrap()
5521                .insert(attempt.id, (identity.clone(), EnvironmentState::Starting));
5522            if self.prepare_failure.swap(false, Ordering::SeqCst) {
5523                return Err(FailureReason::Other("provider-secret-needle".into()));
5524            }
5525            Ok(PreparedEnvironment::isolated(attempt.id, identity))
5526        }
5527
5528        fn start(
5529            &self,
5530            prepared: PreparedEnvironment,
5531            attempt: &RunnerAttempt,
5532            handoff: OneTimeJitHandoff<'_>,
5533        ) -> Result<EnvironmentIdentity, ProcessStartFailure> {
5534            assert_eq!(prepared.attempt, attempt.id);
5535            assert_eq!(attempt.state(), AttemptState::JitReceived);
5536            assert_eq!(handoff.consume().expose(), JIT);
5537            self.handoffs.fetch_add(1, Ordering::SeqCst);
5538            self.actions.lock().unwrap().push("start");
5539            let mut resources = self.resources.lock().unwrap();
5540            let (identity, state) = resources.get_mut(&attempt.id).expect("prepared resource");
5541            *state = EnvironmentState::Running;
5542            Ok(identity.clone())
5543        }
5544
5545        fn inspect(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
5546            self.actions.lock().unwrap().push("inspect");
5547            Ok(self
5548                .resources
5549                .lock()
5550                .unwrap()
5551                .get(&attempt.id)
5552                .map_or(EnvironmentState::Missing, |(_, state)| *state))
5553        }
5554
5555        fn recover(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
5556            if self.recovery_unavailable.load(Ordering::SeqCst) {
5557                return Err(FailureReason::Other(
5558                    "provider discovery unavailable".into(),
5559                ));
5560            }
5561            self.inspect(attempt)
5562        }
5563
5564        fn owns(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
5565            Ok(self
5566                .resources
5567                .lock()
5568                .unwrap()
5569                .get(&attempt.id)
5570                .is_some_and(|(identity, _)| {
5571                    identity_matches_intent(attempt_host(identity), attempt, identity)
5572                }))
5573        }
5574
5575        fn stop(&self, attempt: &RunnerAttempt) -> Result<ProviderStop, FailureReason> {
5576            assert!(self.owns(attempt)?);
5577            self.actions.lock().unwrap().push("stop");
5578            if let Some((_, state)) = self.resources.lock().unwrap().get_mut(&attempt.id) {
5579                *state = EnvironmentState::Exited;
5580            }
5581            Ok(ProviderStop::Stopped)
5582        }
5583
5584        fn destroy(&self, attempt: &RunnerAttempt) -> Result<ProviderDestroy, FailureReason> {
5585            assert!(self.owns(attempt)?);
5586            self.actions.lock().unwrap().push("destroy");
5587            if self.destroy_deferred.load(Ordering::SeqCst) {
5588                return Ok(ProviderDestroy::Deferred("provider busy"));
5589            }
5590            self.resources.lock().unwrap().remove(&attempt.id);
5591            Ok(ProviderDestroy::Destroyed)
5592        }
5593
5594        fn enumerate_owned(&self, host: HostId) -> Vec<EnvironmentIdentity> {
5595            let mut owned = self
5596                .resources
5597                .lock()
5598                .unwrap()
5599                .values()
5600                .filter(|(identity, _)| attempt_host(identity) == host)
5601                .map(|(identity, _)| identity.clone())
5602                .collect::<Vec<_>>();
5603            owned.extend(
5604                self.extra_resources
5605                    .lock()
5606                    .unwrap()
5607                    .iter()
5608                    .filter(|identity| attempt_host(identity) == host)
5609                    .cloned(),
5610            );
5611            owned
5612        }
5613
5614        fn diagnostics(&self, _attempt: &RunnerAttempt) -> Vec<ProviderDiagnostic> {
5615            vec![ProviderDiagnostic::CleanupDeferred; 40]
5616        }
5617
5618        fn spawn(
5619            &self,
5620            _attempt: &RunnerAttempt,
5621            _config: &EncodedJitConfig,
5622        ) -> Result<u32, ProcessStartFailure> {
5623            self.native_calls.fetch_add(1, Ordering::SeqCst);
5624            panic!("isolated provider must never spawn natively")
5625        }
5626        fn is_alive(&self, _attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
5627            panic!("native fallback")
5628        }
5629        fn recovered_pid(&self, _attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
5630            panic!("native fallback")
5631        }
5632        fn completed_successfully(&self, _attempt: &RunnerAttempt) -> bool {
5633            self.completed_successfully.load(Ordering::SeqCst)
5634        }
5635        fn record_terminate_intent(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
5636            panic!("native fallback")
5637        }
5638        fn has_terminate_intent(&self, _attempt: &RunnerAttempt) -> bool {
5639            false
5640        }
5641        fn terminate(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
5642            panic!("native fallback")
5643        }
5644    }
5645
5646    fn attempt_host(identity: &EnvironmentIdentity) -> HostId {
5647        let EnvironmentIdentity::Isolated { host, .. } = identity else {
5648            panic!("isolated identity")
5649        };
5650        *host
5651    }
5652
5653    #[derive(Debug, Default)]
5654    struct FakeDemand {
5655        answers: Mutex<VecDeque<bool>>,
5656    }
5657
5658    impl FakeDemand {
5659        fn answering(answers: impl IntoIterator<Item = bool>) -> Self {
5660            Self {
5661                answers: Mutex::new(answers.into_iter().collect()),
5662            }
5663        }
5664    }
5665
5666    #[async_trait]
5667    impl DemandPersistence for FakeDemand {
5668        async fn persists(&self, _policy: PolicyId) -> bool {
5669            self.answers.lock().unwrap().pop_front().unwrap_or(true)
5670        }
5671    }
5672
5673    #[derive(Debug, Default)]
5674    struct FakeDelay(Mutex<Vec<Duration>>);
5675
5676    #[async_trait]
5677    impl RetryDelay for FakeDelay {
5678        async fn wait(&self, duration: Duration) {
5679            self.0.lock().unwrap().push(duration);
5680        }
5681    }
5682
5683    struct Harness {
5684        _root: tempfile::TempDir,
5685        app_paths: runner_manager_platform::paths::AppPaths,
5686        launcher: LifecycleLauncher,
5687        demand: Arc<dyn DemandPersistence>,
5688        store: Arc<SqliteStore>,
5689        github: Arc<FakeGithubLifecycle>,
5690        packages: Arc<FakePackages>,
5691        processes: Arc<FakeProcesses>,
5692        clock: Arc<FakeClock>,
5693        events: Arc<AttemptEventLog>,
5694        reconcile_events: Arc<crate::reconcile::EventLog>,
5695        delay: Arc<FakeDelay>,
5696        host: runner_manager_domain::model::Host,
5697        policy: ScalePolicy,
5698        allocation_lock: InProcessAllocationLock,
5699        /// The repository persistent root, once one is configured.
5700        workspace_root: Option<LocalAbsolutePath>,
5701    }
5702
5703    impl Harness {
5704        fn new(github: FakeGithubLifecycle, demand: Arc<dyn DemandPersistence>) -> Self {
5705            let root = tempfile::tempdir().unwrap();
5706            let paths = runner_manager_platform::paths::AppPaths::rooted_at(root.path());
5707            paths.create_all().unwrap();
5708            let policy = fixtures::policy()
5709                .repository("octo/repo")
5710                .autoscale("home", 2)
5711                .active()
5712                .build();
5713            // A unit harness must never inspect or write the workstation's
5714            // production runner root. On Windows that is C:\rman, which is
5715            // intentionally inaccessible to an ordinary account after a boot
5716            // service is installed. Using it made the same suite pass on a
5717            // clean CI image and fail on a correctly secured developer host.
5718            let host_root = root.path().join("host-root");
5719            fs::create_dir_all(&host_root).unwrap();
5720            let mut host = fixtures::host().build();
5721            host.runner_root_override = Some(
5722                LocalAbsolutePath::new(host_root.to_str().expect("a UTF-8 temporary path"))
5723                    .expect("a local absolute host root"),
5724            );
5725            let store = Arc::new(SqliteStore::open_in_memory().unwrap());
5726            store.put_host(&host).unwrap();
5727            let github = Arc::new(github);
5728            let packages = Arc::new(FakePackages::default());
5729            let processes = Arc::new(FakeProcesses::default());
5730            let clock = Arc::new(FakeClock::default());
5731            let events = Arc::new(AttemptEventLog::default());
5732            let reconcile_events = Arc::new(crate::reconcile::EventLog::new());
5733            let delay = Arc::new(FakeDelay::default());
5734            let ports = LifecyclePorts {
5735                store: Arc::clone(&store) as Arc<dyn Store>,
5736                github: Arc::clone(&github) as Arc<dyn LifecycleGithub>,
5737                packages: Arc::clone(&packages) as Arc<dyn RuntimePackages>,
5738                processes: Arc::clone(&processes) as Arc<dyn ProcessSupervisor>,
5739                clock: Arc::clone(&clock) as Arc<dyn Clock>,
5740                demand: Arc::clone(&demand),
5741                delay: Arc::clone(&delay) as Arc<dyn RetryDelay>,
5742                events: Arc::clone(&events) as Arc<dyn AttemptEventSink>,
5743                reconcile_events: Arc::clone(&reconcile_events) as Arc<dyn EventSink>,
5744            };
5745            let launcher = Self::launcher_over(policy.host_id, &paths, ports);
5746            Self {
5747                _root: root,
5748                app_paths: paths,
5749                launcher,
5750                demand,
5751                store,
5752                github,
5753                packages,
5754                processes,
5755                clock,
5756                events,
5757                reconcile_events,
5758                delay,
5759                host,
5760                policy,
5761                allocation_lock: InProcessAllocationLock::new(),
5762                workspace_root: None,
5763            }
5764        }
5765
5766        /// Put disposable attempts under a host root of this harness's own.
5767        ///
5768        /// Without it the launcher resolves the *platform* default, which on
5769        /// Windows is `%SystemDrive%\rman` — a real directory on the machine
5770        /// running the suite. Every test added by `c2` places its files inside
5771        /// its own temporary directory instead.
5772        fn with_host_runner_root(mut self) -> Self {
5773            let host_root = self.host_root();
5774            fs::create_dir_all(&host_root).unwrap();
5775            self.host.runner_root_override = Some(
5776                LocalAbsolutePath::new(host_root.to_str().expect("a UTF-8 temporary path"))
5777                    .expect("a local absolute host root"),
5778            );
5779            self.store.put_host(&self.host).unwrap();
5780            self
5781        }
5782
5783        /// Opt this harness's repository into a persistent workspace (D4).
5784        fn with_persistent_workspace(mut self, capacity: u16) -> Self {
5785            self = self.with_host_runner_root();
5786            let root = self._root.path().join("persist");
5787            let root = LocalAbsolutePath::new(root.to_str().expect("a UTF-8 temporary path"))
5788                .expect("a local absolute workspace root");
5789            self.policy = fixtures::policy()
5790                .repository("octo/repo")
5791                .autoscale("home", capacity)
5792                .active()
5793                .build();
5794            self.policy
5795                .set_workspace_policy(
5796                    WorkspacePolicy::persistent(root.clone(), TargetScope::Repository)
5797                        .expect("a repository may be persistent"),
5798                )
5799                .expect("a repository may be persistent");
5800            self.workspace_root = Some(root);
5801            // The journal's copy, so that cleanup's cross-check against a
5802            // surviving policy is exercised rather than skipped.
5803            self.store.insert_policy(&self.policy).unwrap();
5804            self
5805        }
5806
5807        fn workspace_root(&self) -> &LocalAbsolutePath {
5808            self.workspace_root
5809                .as_ref()
5810                .expect("this harness configured a persistent workspace")
5811        }
5812
5813        fn slot_path(&self, slot: u16) -> PathBuf {
5814            self.workspace_root().as_path().join(format!("s{slot}"))
5815        }
5816
5817        fn host_root(&self) -> PathBuf {
5818            self._root.path().join("host-root")
5819        }
5820
5821        fn attempt(&self, id: AttemptId) -> RunnerAttempt {
5822            self.store
5823                .attempt(id)
5824                .unwrap()
5825                .expect("the attempt is journalled")
5826        }
5827
5828        /// Conclude an attempt and run the real cleanup over it.
5829        fn conclude(&self, id: AttemptId) -> RunnerAttempt {
5830            let mut attempt = self.attempt(id);
5831            attempt
5832                .conclude(
5833                    AttemptOutcome::failed(FailureReason::ProcessExitedUnexpectedly),
5834                    self.clock.now(),
5835                )
5836                .unwrap();
5837            self.store.record_attempt(&attempt).unwrap();
5838            attempt
5839        }
5840
5841        async fn cleanup_retaining_work(&self, id: AttemptId) {
5842            self.conclude(id);
5843            self.launcher
5844                .clean(id)
5845                .await
5846                .expect("the slot is scrubbed and the lease released");
5847        }
5848
5849        /// The launcher configuration every launcher in this harness shares, so
5850        /// that the one a restart mints cannot drift from the original.
5851        fn launcher_over(
5852            host: HostId,
5853            paths: &runner_manager_platform::paths::AppPaths,
5854            ports: LifecyclePorts,
5855        ) -> LifecycleLauncher {
5856            LifecycleLauncher::new(
5857                host,
5858                paths.clone(),
5859                paths.logs_dir(),
5860                1,
5861                RecoveryTimeouts::new(
5862                    Elapsed::seconds(10),
5863                    Elapsed::seconds(10),
5864                    Elapsed::seconds(10),
5865                ),
5866                RetryPolicy::bounded(3, Duration::from_millis(10), Duration::from_millis(25)),
5867                ports,
5868            )
5869        }
5870
5871        /// The same journal, the same directories, a launcher that remembers
5872        /// nothing — which is what a daemon restart is.
5873        fn restart(&self) -> LifecycleLauncher {
5874            Self::launcher_over(
5875                self.policy.host_id,
5876                &self.app_paths,
5877                LifecyclePorts {
5878                    store: Arc::clone(&self.store) as Arc<dyn Store>,
5879                    github: Arc::clone(&self.github) as Arc<dyn LifecycleGithub>,
5880                    packages: Arc::clone(&self.packages) as Arc<dyn RuntimePackages>,
5881                    processes: Arc::clone(&self.processes) as Arc<dyn ProcessSupervisor>,
5882                    clock: Arc::clone(&self.clock) as Arc<dyn Clock>,
5883                    demand: Arc::clone(&self.demand),
5884                    delay: Arc::clone(&self.delay) as Arc<dyn RetryDelay>,
5885                    events: Arc::clone(&self.events) as Arc<dyn AttemptEventSink>,
5886                    reconcile_events: Arc::clone(&self.reconcile_events) as Arc<dyn EventSink>,
5887                },
5888            )
5889        }
5890
5891        async fn ready(&self) {
5892            self.launcher
5893                .recover_startup(std::slice::from_ref(&self.policy))
5894                .await
5895                .unwrap();
5896        }
5897
5898        async fn launch(&self) -> RunnerAttempt {
5899            self.launch_result().await.unwrap()
5900        }
5901
5902        async fn launch_result(&self) -> Result<RunnerAttempt, LaunchFailure> {
5903            self.launch_after_waiting(Duration::ZERO).await
5904        }
5905
5906        async fn launch_after_waiting(
5907            &self,
5908            lock_wait: Duration,
5909        ) -> Result<RunnerAttempt, LaunchFailure> {
5910            let guard = self.allocation_lock.acquire().await.unwrap();
5911            self.launcher
5912                .launch(LaunchRequest {
5913                    host: &self.host,
5914                    policy: &self.policy,
5915                    allocation_guard: &guard,
5916                    lock_wait,
5917                })
5918                .await
5919        }
5920
5921        fn only_attempt(&self) -> RunnerAttempt {
5922            self.store.attempts().unwrap().into_iter().next().unwrap()
5923        }
5924    }
5925
5926    fn isolated_harness() -> Harness {
5927        use runner_manager_domain::execution::{ExecutionPolicy, ResourceLimits};
5928        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5929            .with_host_runner_root();
5930        let image =
5931            ImageReference::new(format!("registry.example/runner@sha256:{}", "a".repeat(64)))
5932                .expect("pinned image");
5933        harness
5934            .policy
5935            .set_execution_policy(ExecutionPolicy::Isolated {
5936                backend: Backend::Oci,
5937                image,
5938                resources: ResourceLimits {
5939                    cpu_millis: 1000,
5940                    memory_mib: 1024,
5941                    disk_mib: 4096,
5942                },
5943            })
5944            .expect("isolated policy");
5945        harness.github.watch_journal(Arc::clone(&harness.store));
5946        harness
5947    }
5948
5949    fn launcher_with_isolated(
5950        harness: &Harness,
5951        provider: Arc<FakeIsolatedProvider>,
5952    ) -> LifecycleLauncher {
5953        Harness::launcher_over(
5954            harness.policy.host_id,
5955            &harness.app_paths,
5956            LifecyclePorts {
5957                store: Arc::clone(&harness.store) as Arc<dyn Store>,
5958                github: Arc::clone(&harness.github) as Arc<dyn LifecycleGithub>,
5959                packages: Arc::clone(&harness.packages) as Arc<dyn RuntimePackages>,
5960                processes: provider as Arc<dyn ExecutionProvider>,
5961                clock: Arc::clone(&harness.clock) as Arc<dyn Clock>,
5962                demand: Arc::clone(&harness.demand),
5963                delay: Arc::clone(&harness.delay) as Arc<dyn RetryDelay>,
5964                events: Arc::clone(&harness.events) as Arc<dyn AttemptEventSink>,
5965                reconcile_events: Arc::clone(&harness.reconcile_events) as Arc<dyn EventSink>,
5966            },
5967        )
5968    }
5969
5970    #[tokio::test]
5971    async fn isolated_policy_and_journal_never_enter_native_provider_or_jit() {
5972        use runner_manager_domain::execution::{
5973            AttemptExecution, Backend, ExecutionPolicy, ImageReference, ResourceLimits,
5974        };
5975
5976        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5977            .with_host_runner_root();
5978        let image =
5979            ImageReference::new(format!("registry.example/runner@sha256:{}", "a".repeat(64)))
5980                .expect("pinned image");
5981        harness
5982            .policy
5983            .set_execution_policy(ExecutionPolicy::Isolated {
5984                backend: Backend::Oci,
5985                image: image.clone(),
5986                resources: ResourceLimits {
5987                    cpu_millis: 1000,
5988                    memory_mib: 1024,
5989                    disk_mib: 4096,
5990                },
5991            })
5992            .expect("valid isolated profile");
5993
5994        harness.ready().await;
5995        assert_eq!(
5996            harness.processes.probe(&harness.policy),
5997            ProviderCapability::Unsupported
5998        );
5999        let failure = harness
6000            .launch_result()
6001            .await
6002            .expect_err("provider is unavailable");
6003        assert_eq!(
6004            failure.reason,
6005            FailureReason::IsolationProvider(IsolationProviderFailure::Unsupported)
6006        );
6007
6008        let runtime = harness.host_root().join("isolated-owned-environment");
6009        fs::create_dir_all(&runtime).expect("provider resource fixture");
6010        fs::write(runtime.join("owned-marker"), "non-secret").expect("fixture marker");
6011        let mut attempt = RunnerAttempt::allocate(
6012            AttemptId::from_u128(0x123),
6013            harness.policy.id,
6014            runtime.clone(),
6015            harness.clock.now(),
6016        );
6017        attempt
6018            .allocate_execution(AttemptExecution::Isolated {
6019                provider_kind: Backend::Oci,
6020                environment_id: None,
6021                resolved_image: image,
6022                generation: "generation-123".into(),
6023            })
6024            .expect("isolated intent");
6025        attempt
6026            .prepared_environment("environment-123".into())
6027            .expect("prepared identity");
6028        harness
6029            .store
6030            .record_attempt(&attempt)
6031            .expect("durable isolated journal");
6032
6033        harness
6034            .launcher
6035            .recover_startup(std::slice::from_ref(&harness.policy))
6036            .await
6037            .expect("unsupported isolated cleanup is profile-local");
6038        let failure = harness
6039            .launch_result()
6040            .await
6041            .expect_err("provider unavailable for this policy");
6042        assert_eq!(
6043            failure.reason,
6044            FailureReason::IsolationProvider(IsolationProviderFailure::Unsupported)
6045        );
6046        harness
6047            .launcher
6048            .supervise(&harness.policy)
6049            .await
6050            .expect("unavailable attempt is deferred");
6051        assert!(harness.launcher.clean(attempt.id).await.is_err());
6052        assert_eq!(
6053            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
6054            AttemptState::CleanupDeferred
6055        );
6056        assert!(matches!(
6057            harness.launcher.recover_startup(&[]).await,
6058            Err(LifecycleError::RecoveryIncomplete)
6059        ));
6060        assert!(
6061            runtime.join("owned-marker").is_file(),
6062            "native cleanup touched the isolated environment"
6063        );
6064        assert!(
6065            harness.processes.actions.lock().unwrap().is_empty(),
6066            "native recovery inspected an isolated identity"
6067        );
6068        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
6069        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
6070        assert_eq!(harness.packages.materializations.load(Ordering::SeqCst), 0);
6071    }
6072
6073    #[tokio::test]
6074    async fn isolated_prepare_is_durable_before_jit_and_start_uses_one_handoff() {
6075        let harness = isolated_harness();
6076        let provider = Arc::new(FakeIsolatedProvider::default());
6077        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6078        launcher
6079            .recover_startup(std::slice::from_ref(&harness.policy))
6080            .await
6081            .expect("ready");
6082        let guard = harness.allocation_lock.acquire().await.unwrap();
6083        let attempt = launcher
6084            .launch(LaunchRequest {
6085                host: &harness.host,
6086                policy: &harness.policy,
6087                allocation_guard: &guard,
6088                lock_wait: Duration::ZERO,
6089            })
6090            .await
6091            .expect("isolated launch");
6092        assert_eq!(attempt.state(), AttemptState::Starting);
6093        assert_eq!(provider.resource_count(), 1);
6094        assert_eq!(provider.handoffs.load(Ordering::SeqCst), 1);
6095        assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6096        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
6097        let fact = harness
6098            .github
6099            .registration_facts()
6100            .pop()
6101            .expect("JIT registration");
6102        assert_eq!(
6103            fact.journal_states,
6104            vec![AttemptState::Prepared],
6105            "provider readiness preceded GitHub JIT"
6106        );
6107        assert_eq!(
6108            harness
6109                .events
6110                .events()
6111                .into_iter()
6112                .filter_map(|event| match event {
6113                    AttemptEvent::State { state, .. } => Some(state),
6114                    _ => None,
6115                })
6116                .collect::<Vec<_>>(),
6117            vec![
6118                AttemptState::Allocated,
6119                AttemptState::Preparing,
6120                AttemptState::Prepared,
6121                AttemptState::JitReceived,
6122                AttemptState::Starting
6123            ]
6124        );
6125        let restarted = launcher_with_isolated(&harness, Arc::clone(&provider));
6126        restarted
6127            .recover_startup(std::slice::from_ref(&harness.policy))
6128            .await
6129            .expect("adopt live sandbox");
6130        assert_eq!(provider.resource_count(), 1);
6131        assert_eq!(
6132            harness.github.registrations.load(Ordering::SeqCst),
6133            1,
6134            "restart cannot issue duplicate JIT"
6135        );
6136        harness
6137            .github
6138            .observe(GithubRunnerObservation::Registered { busy: true });
6139        restarted
6140            .supervise(&harness.policy)
6141            .await
6142            .expect("job observed");
6143        assert_eq!(
6144            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
6145            AttemptState::Busy
6146        );
6147        provider
6148            .resources
6149            .lock()
6150            .unwrap()
6151            .get_mut(&attempt.id)
6152            .unwrap()
6153            .1 = EnvironmentState::Exited;
6154        harness
6155            .github
6156            .observe(GithubRunnerObservation::NotRegistered);
6157        restarted
6158            .supervise(&harness.policy)
6159            .await
6160            .expect("terminal cleanup");
6161        assert_eq!(provider.resource_count(), 0);
6162        assert_eq!(
6163            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
6164            AttemptState::Cleaned
6165        );
6166    }
6167
6168    #[tokio::test]
6169    async fn attached_isolated_job_exit_is_recorded_as_completed() {
6170        let harness = isolated_harness();
6171        let provider = Arc::new(FakeIsolatedProvider::default());
6172        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6173        launcher
6174            .recover_startup(std::slice::from_ref(&harness.policy))
6175            .await
6176            .unwrap();
6177        let guard = harness.allocation_lock.acquire().await.unwrap();
6178        let attempt = launcher
6179            .launch(LaunchRequest {
6180                host: &harness.host,
6181                policy: &harness.policy,
6182                allocation_guard: &guard,
6183                lock_wait: Duration::ZERO,
6184            })
6185            .await
6186            .unwrap();
6187        harness
6188            .github
6189            .observe(GithubRunnerObservation::Registered { busy: true });
6190        launcher.supervise(&harness.policy).await.unwrap();
6191        provider
6192            .resources
6193            .lock()
6194            .unwrap()
6195            .get_mut(&attempt.id)
6196            .unwrap()
6197            .1 = EnvironmentState::Exited;
6198        provider
6199            .completed_successfully
6200            .store(true, Ordering::SeqCst);
6201        harness
6202            .github
6203            .observe(GithubRunnerObservation::NotRegistered);
6204        launcher.supervise(&harness.policy).await.unwrap();
6205        let cleaned = harness.store.attempt(attempt.id).unwrap().unwrap();
6206        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
6207        assert_eq!(cleaned.state(), AttemptState::Cleaned);
6208    }
6209
6210    #[tokio::test]
6211    async fn isolated_prepare_failure_stays_local_and_crash_gap_recovers_owned_resource() {
6212        let harness = isolated_harness();
6213        let provider = Arc::new(FakeIsolatedProvider::default());
6214        provider.prepare_failure.store(true, Ordering::SeqCst);
6215        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6216        launcher
6217            .recover_startup(std::slice::from_ref(&harness.policy))
6218            .await
6219            .expect("ready");
6220        let guard = harness.allocation_lock.acquire().await.unwrap();
6221        let failure = launcher
6222            .launch(LaunchRequest {
6223                host: &harness.host,
6224                policy: &harness.policy,
6225                allocation_guard: &guard,
6226                lock_wait: Duration::ZERO,
6227            })
6228            .await
6229            .expect_err("prepare failed after creating resource");
6230        assert_eq!(
6231            failure.reason,
6232            FailureReason::IsolationProvider(IsolationProviderFailure::RuntimeOperationFailed)
6233        );
6234        assert_eq!(provider.resource_count(), 1);
6235        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
6236        assert!(
6237            !harness
6238                .store
6239                .dump_text()
6240                .unwrap()
6241                .contains("provider-secret-needle")
6242        );
6243        let id = harness.store.attempts().unwrap()[0].id;
6244        assert_eq!(
6245            harness.store.attempt(id).unwrap().unwrap().outcome(),
6246            Some(&AttemptOutcome::failed(FailureReason::IsolationProvider(
6247                IsolationProviderFailure::RuntimeOperationFailed
6248            )))
6249        );
6250        let restarted = launcher_with_isolated(&harness, Arc::clone(&provider));
6251        restarted
6252            .recover_startup(std::slice::from_ref(&harness.policy))
6253            .await
6254            .expect("profile-local recovery");
6255        assert_eq!(
6256            provider.resource_count(),
6257            0,
6258            "the exact owned resource was destroyed once"
6259        );
6260        assert_eq!(
6261            harness.store.attempt(id).unwrap().unwrap().state(),
6262            AttemptState::Cleaned
6263        );
6264        let diagnostic =
6265            fs::read_to_string(restarted.diagnostics_root.join(format!("{id}.log"))).unwrap();
6266        assert!(diagnostic.contains("reason=isolation_runtime_operation_failed"));
6267        assert!(!diagnostic.contains("provider-secret-needle"));
6268        assert_eq!(
6269            provider
6270                .actions
6271                .lock()
6272                .unwrap()
6273                .iter()
6274                .filter(|action| **action == "destroy")
6275                .count(),
6276            1
6277        );
6278        assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6279    }
6280
6281    #[test]
6282    fn isolation_capability_and_adapter_failures_keep_closed_categories() {
6283        let cases = [
6284            (
6285                ProviderCapability::NotInstalled,
6286                IsolationProviderFailure::NotInstalled,
6287            ),
6288            (
6289                ProviderCapability::PermissionDenied,
6290                IsolationProviderFailure::PermissionDenied,
6291            ),
6292            (
6293                ProviderCapability::ImageUnavailableOrIncompatible,
6294                IsolationProviderFailure::ImageUnavailableOrIncompatible,
6295            ),
6296            (
6297                ProviderCapability::DiskQuotaUnavailable,
6298                IsolationProviderFailure::DiskQuotaUnavailable,
6299            ),
6300            (
6301                ProviderCapability::Degraded,
6302                IsolationProviderFailure::Degraded,
6303            ),
6304        ];
6305        for (capability, category) in cases {
6306            assert_eq!(
6307                capability.refusal(),
6308                FailureReason::IsolationProvider(category)
6309            );
6310        }
6311        let raw = FailureReason::Other("ghp_secret_from_provider".into());
6312        let safe = safe_isolation_reason(raw, IsolationProviderFailure::RuntimeOperationFailed);
6313        assert_eq!(
6314            safe,
6315            FailureReason::IsolationProvider(IsolationProviderFailure::RuntimeOperationFailed)
6316        );
6317        assert!(!safe.to_string().contains("ghp_secret"));
6318        assert_eq!(
6319            safe_isolation_reason(
6320                FailureReason::IsolationProvider(IsolationProviderFailure::PermissionDenied),
6321                IsolationProviderFailure::RuntimeOperationFailed,
6322            ),
6323            FailureReason::IsolationProvider(IsolationProviderFailure::PermissionDenied)
6324        );
6325    }
6326
6327    #[tokio::test]
6328    async fn isolated_permission_and_image_failures_stop_before_jit_without_native_fallback() {
6329        for image_failure in [false, true] {
6330            let harness = isolated_harness();
6331            let provider = Arc::new(FakeIsolatedProvider::default());
6332            provider
6333                .permission_denied
6334                .store(!image_failure, Ordering::SeqCst);
6335            provider
6336                .incompatible_image
6337                .store(image_failure, Ordering::SeqCst);
6338            let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6339            launcher
6340                .recover_startup(std::slice::from_ref(&harness.policy))
6341                .await
6342                .unwrap();
6343            let guard = harness.allocation_lock.acquire().await.unwrap();
6344            let error = launcher
6345                .launch(LaunchRequest {
6346                    host: &harness.host,
6347                    policy: &harness.policy,
6348                    allocation_guard: &guard,
6349                    lock_wait: Duration::ZERO,
6350                })
6351                .await
6352                .expect_err("pre-JIT refusal");
6353            let expected = if image_failure {
6354                "resolved image is incompatible"
6355            } else {
6356                "permission denied"
6357            };
6358            assert!(error.reason.to_string().contains(expected));
6359            assert!(
6360                harness.store.attempts().unwrap().is_empty(),
6361                "no allocation was journalled"
6362            );
6363            assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
6364            assert_eq!(provider.handoffs.load(Ordering::SeqCst), 0);
6365            assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6366        }
6367    }
6368
6369    #[tokio::test]
6370    async fn unsupported_host_stops_before_jit_without_allocation_or_native_fallback() {
6371        let harness = isolated_harness();
6372        let provider = Arc::new(FakeIsolatedProvider::default());
6373        provider.unsupported_host.store(true, Ordering::SeqCst);
6374        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6375        launcher
6376            .recover_startup(std::slice::from_ref(&harness.policy))
6377            .await
6378            .unwrap();
6379        let guard = harness.allocation_lock.acquire().await.unwrap();
6380        let error = launcher
6381            .launch(LaunchRequest {
6382                host: &harness.host,
6383                policy: &harness.policy,
6384                allocation_guard: &guard,
6385                lock_wait: Duration::ZERO,
6386            })
6387            .await
6388            .expect_err("unsupported host must be refused before JIT");
6389
6390        assert_eq!(
6391            error.reason,
6392            FailureReason::IsolationProvider(IsolationProviderFailure::Unsupported)
6393        );
6394        assert!(harness.store.attempts().unwrap().is_empty());
6395        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
6396        assert_eq!(provider.handoffs.load(Ordering::SeqCst), 0);
6397        assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6398        assert!(provider.actions.lock().unwrap().is_empty());
6399    }
6400
6401    #[tokio::test]
6402    async fn no_journalled_environment_id_waits_for_provider_absence_proof() {
6403        let harness = isolated_harness();
6404        let provider = Arc::new(FakeIsolatedProvider::default());
6405        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6406        let runtime = harness.host_root().join("prepare-without-identity");
6407        fs::create_dir_all(&runtime).unwrap();
6408        let mut attempt = RunnerAttempt::allocate(
6409            AttemptId::from_u128(0x9191),
6410            harness.policy.id,
6411            runtime,
6412            harness.clock.now(),
6413        );
6414        let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6415            harness.policy.execution_policy()
6416        else {
6417            unreachable!()
6418        };
6419        attempt
6420            .allocate_execution(AttemptExecution::Isolated {
6421                provider_kind: Backend::Oci,
6422                environment_id: None,
6423                resolved_image: image.clone(),
6424                generation: "prepare-generation".into(),
6425            })
6426            .unwrap();
6427        attempt.begin_prepare(harness.clock.now()).unwrap();
6428        attempt
6429            .conclude(
6430                AttemptOutcome::failed(FailureReason::Other("prepare interrupted".into())),
6431                harness.clock.now(),
6432            )
6433            .unwrap();
6434        harness.store.record_attempt(&attempt).unwrap();
6435
6436        provider.recovery_unavailable.store(true, Ordering::SeqCst);
6437        launcher
6438            .clean(attempt.id)
6439            .await
6440            .expect_err("absence unproven");
6441        let deferred = harness.store.attempt(attempt.id).unwrap().unwrap();
6442        assert_eq!(deferred.state(), AttemptState::CleanupDeferred);
6443        assert!(deferred.counts_against_capacity());
6444
6445        provider.recovery_unavailable.store(false, Ordering::SeqCst);
6446        launcher.clean(attempt.id).await.expect("absence proven");
6447        assert_eq!(
6448            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
6449            AttemptState::Cleaned
6450        );
6451    }
6452
6453    #[tokio::test]
6454    async fn isolated_terminal_capacity_waits_for_confirmed_absence_and_generation_matches() {
6455        let harness = isolated_harness();
6456        let provider = Arc::new(FakeIsolatedProvider::default());
6457        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6458        launcher
6459            .recover_startup(std::slice::from_ref(&harness.policy))
6460            .await
6461            .expect("ready");
6462        let guard = harness.allocation_lock.acquire().await.unwrap();
6463        let mut attempt = launcher
6464            .launch(LaunchRequest {
6465                host: &harness.host,
6466                policy: &harness.policy,
6467                allocation_guard: &guard,
6468                lock_wait: Duration::ZERO,
6469            })
6470            .await
6471            .expect("launch");
6472        attempt
6473            .conclude(
6474                AttemptOutcome::failed(FailureReason::ProcessStartFailed),
6475                harness.clock.now(),
6476            )
6477            .unwrap();
6478        harness.store.record_attempt(&attempt).unwrap();
6479        provider.destroy_deferred.store(true, Ordering::SeqCst);
6480        launcher
6481            .clean(attempt.id)
6482            .await
6483            .expect_err("provider deferred destroy");
6484        let deferred = harness.store.attempt(attempt.id).unwrap().unwrap();
6485        assert_eq!(deferred.state(), AttemptState::CleanupDeferred);
6486        assert!(deferred.counts_against_capacity());
6487        assert_eq!(provider.resource_count(), 1);
6488        provider.destroy_deferred.store(false, Ordering::SeqCst);
6489        let restarted = launcher_with_isolated(&harness, Arc::clone(&provider));
6490        restarted
6491            .recover_startup(std::slice::from_ref(&harness.policy))
6492            .await
6493            .expect("retry cleanup");
6494        assert_eq!(provider.resource_count(), 0);
6495        assert!(
6496            !harness
6497                .store
6498                .attempt(attempt.id)
6499                .unwrap()
6500                .unwrap()
6501                .counts_against_capacity()
6502        );
6503
6504        // A reused runtime name with a different generation is not ours to delete.
6505        let second_id = AttemptId::from_u128(0x9999);
6506        let second_runtime = harness.host_root().join("generation-mismatch");
6507        fs::create_dir_all(&second_runtime).unwrap();
6508        let mut terminal = RunnerAttempt::allocate(
6509            second_id,
6510            harness.policy.id,
6511            second_runtime,
6512            harness.clock.now(),
6513        );
6514        let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6515            harness.policy.execution_policy()
6516        else {
6517            unreachable!()
6518        };
6519        terminal
6520            .allocate_execution(AttemptExecution::Isolated {
6521                provider_kind: Backend::Oci,
6522                environment_id: None,
6523                resolved_image: image.clone(),
6524                generation: "expected-generation".into(),
6525            })
6526            .unwrap();
6527        let mut stranger = FakeIsolatedProvider::identity(&terminal, harness.policy.host_id);
6528        let EnvironmentIdentity::Isolated { environment_id, .. } = &stranger else {
6529            unreachable!()
6530        };
6531        terminal.begin_prepare(harness.clock.now()).unwrap();
6532        terminal
6533            .prepared_environment(environment_id.clone())
6534            .unwrap();
6535        terminal.mark_prepared(harness.clock.now()).unwrap();
6536        terminal.jit_received(harness.clock.now()).unwrap();
6537        terminal.started_isolated(harness.clock.now()).unwrap();
6538        terminal
6539            .conclude(
6540                AttemptOutcome::failed(FailureReason::ProcessStartFailed),
6541                harness.clock.now(),
6542            )
6543            .unwrap();
6544        harness.store.record_attempt(&terminal).unwrap();
6545        let EnvironmentIdentity::Isolated { generation, .. } = &mut stranger else {
6546            unreachable!()
6547        };
6548        *generation = "another-generation".into();
6549        provider
6550            .resources
6551            .lock()
6552            .unwrap()
6553            .insert(second_id, (stranger, EnvironmentState::Running));
6554        restarted
6555            .clean(terminal.id)
6556            .await
6557            .expect_err("ownership mismatch quarantined");
6558        assert_eq!(provider.resource_count(), 1);
6559        assert_eq!(
6560            harness.store.attempt(terminal.id).unwrap().unwrap().state(),
6561            AttemptState::CleanupDeferred
6562        );
6563        assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6564    }
6565
6566    #[tokio::test]
6567    async fn isolated_restart_at_each_transition_adopts_or_destroys_one_resource() {
6568        for stage in [
6569            AttemptState::Allocated,
6570            AttemptState::Preparing,
6571            AttemptState::Prepared,
6572            AttemptState::JitReceived,
6573            AttemptState::Starting,
6574            AttemptState::Idle,
6575            AttemptState::Busy,
6576            AttemptState::Finished,
6577            AttemptState::Failed,
6578            AttemptState::Orphaned,
6579            AttemptState::Destroying,
6580            AttemptState::CleanupDeferred,
6581        ] {
6582            let harness = isolated_harness();
6583            let provider = Arc::new(FakeIsolatedProvider::default());
6584            let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6585            let id = AttemptId::from_u128(0x1000 + stage as u128);
6586            let runtime = harness.host_root().join(format!("phase-{stage}"));
6587            fs::create_dir_all(&runtime).unwrap();
6588            let mut attempt =
6589                RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
6590            let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6591                harness.policy.execution_policy()
6592            else {
6593                unreachable!()
6594            };
6595            attempt
6596                .allocate_execution(AttemptExecution::Isolated {
6597                    provider_kind: Backend::Oci,
6598                    environment_id: None,
6599                    resolved_image: image.clone(),
6600                    generation: format!("generation-{stage}"),
6601                })
6602                .unwrap();
6603            if stage != AttemptState::Allocated {
6604                attempt.begin_prepare(harness.clock.now()).unwrap();
6605            }
6606            let identity = FakeIsolatedProvider::identity(&attempt, harness.policy.host_id);
6607            if stage != AttemptState::Allocated {
6608                let resource_state = if matches!(
6609                    stage,
6610                    AttemptState::Finished
6611                        | AttemptState::Failed
6612                        | AttemptState::Orphaned
6613                        | AttemptState::Destroying
6614                        | AttemptState::CleanupDeferred
6615                ) {
6616                    EnvironmentState::Exited
6617                } else {
6618                    EnvironmentState::Running
6619                };
6620                provider
6621                    .resources
6622                    .lock()
6623                    .unwrap()
6624                    .insert(id, (identity.clone(), resource_state));
6625            }
6626            if !matches!(stage, AttemptState::Allocated | AttemptState::Preparing) {
6627                let EnvironmentIdentity::Isolated { environment_id, .. } = &identity else {
6628                    unreachable!()
6629                };
6630                attempt
6631                    .prepared_environment(environment_id.clone())
6632                    .unwrap();
6633                attempt.mark_prepared(harness.clock.now()).unwrap();
6634            }
6635            if matches!(
6636                stage,
6637                AttemptState::JitReceived
6638                    | AttemptState::Starting
6639                    | AttemptState::Idle
6640                    | AttemptState::Busy
6641                    | AttemptState::Finished
6642                    | AttemptState::Failed
6643                    | AttemptState::Orphaned
6644                    | AttemptState::Destroying
6645                    | AttemptState::CleanupDeferred
6646            ) {
6647                attempt.jit_received(harness.clock.now()).unwrap();
6648            }
6649            if matches!(
6650                stage,
6651                AttemptState::Starting
6652                    | AttemptState::Idle
6653                    | AttemptState::Busy
6654                    | AttemptState::Finished
6655                    | AttemptState::Failed
6656                    | AttemptState::Orphaned
6657                    | AttemptState::Destroying
6658                    | AttemptState::CleanupDeferred
6659            ) {
6660                attempt.started_isolated(harness.clock.now()).unwrap();
6661            }
6662            if matches!(
6663                stage,
6664                AttemptState::Idle | AttemptState::Busy | AttemptState::Finished
6665            ) {
6666                attempt.registered_idle(73, harness.clock.now()).unwrap();
6667            }
6668            if matches!(stage, AttemptState::Busy | AttemptState::Finished) {
6669                attempt.assigned_job(73, harness.clock.now()).unwrap();
6670            }
6671            if matches!(
6672                stage,
6673                AttemptState::Finished
6674                    | AttemptState::Failed
6675                    | AttemptState::Orphaned
6676                    | AttemptState::Destroying
6677                    | AttemptState::CleanupDeferred
6678            ) {
6679                let outcome = match stage {
6680                    AttemptState::Finished => AttemptOutcome::CompletedJob,
6681                    AttemptState::Orphaned => AttemptOutcome::Orphaned,
6682                    _ => AttemptOutcome::failed(FailureReason::ProcessStartFailed),
6683                };
6684                attempt.conclude(outcome, harness.clock.now()).unwrap();
6685            }
6686            if matches!(
6687                stage,
6688                AttemptState::Destroying | AttemptState::CleanupDeferred
6689            ) {
6690                attempt.begin_destroy(harness.clock.now()).unwrap();
6691            }
6692            if stage == AttemptState::CleanupDeferred {
6693                attempt.defer_cleanup(harness.clock.now()).unwrap();
6694            }
6695            harness.store.record_attempt(&attempt).unwrap();
6696            launcher
6697                .recover_startup(std::slice::from_ref(&harness.policy))
6698                .await
6699                .unwrap_or_else(|error| panic!("restart from {stage}: {error}"));
6700            let resumed = harness.store.attempt(id).unwrap().unwrap();
6701            if matches!(
6702                stage,
6703                AttemptState::Allocated
6704                    | AttemptState::Preparing
6705                    | AttemptState::Prepared
6706                    | AttemptState::Finished
6707                    | AttemptState::Failed
6708                    | AttemptState::Orphaned
6709                    | AttemptState::Destroying
6710                    | AttemptState::CleanupDeferred
6711            ) {
6712                assert_eq!(
6713                    resumed.state(),
6714                    AttemptState::Cleaned,
6715                    "{stage} must retire after restart"
6716                );
6717            } else {
6718                assert!(resumed.counts_against_capacity(), "live {stage} is adopted");
6719                assert_eq!(provider.resource_count(), 1);
6720                provider.resources.lock().unwrap().get_mut(&id).unwrap().1 =
6721                    EnvironmentState::Exited;
6722                launcher.supervise(&harness.policy).await.unwrap();
6723                assert_eq!(
6724                    harness.store.attempt(id).unwrap().unwrap().state(),
6725                    AttemptState::Cleaned
6726                );
6727            }
6728            assert_eq!(
6729                provider.resource_count(),
6730                0,
6731                "{stage} resource cleaned exactly once"
6732            );
6733            let destroyed = provider
6734                .actions
6735                .lock()
6736                .unwrap()
6737                .iter()
6738                .filter(|action| **action == "destroy")
6739                .count();
6740            assert_eq!(
6741                destroyed,
6742                usize::from(stage != AttemptState::Allocated),
6743                "{stage} destroy count"
6744            );
6745            assert_eq!(
6746                harness.github.registrations.load(Ordering::SeqCst),
6747                0,
6748                "restart from {stage} cannot duplicate JIT"
6749            );
6750            assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6751        }
6752    }
6753
6754    #[tokio::test]
6755    async fn duplicate_provider_ownership_is_quarantined_until_unambiguous() {
6756        let harness = isolated_harness();
6757        let provider = Arc::new(FakeIsolatedProvider::default());
6758        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6759        let id = AttemptId::from_u128(0x7777);
6760        let runtime = harness.host_root().join("duplicate-provider-ownership");
6761        fs::create_dir_all(&runtime).unwrap();
6762        let mut attempt =
6763            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
6764        let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6765            harness.policy.execution_policy()
6766        else {
6767            unreachable!()
6768        };
6769        attempt
6770            .allocate_execution(AttemptExecution::Isolated {
6771                provider_kind: Backend::Oci,
6772                environment_id: None,
6773                resolved_image: image.clone(),
6774                generation: "duplicate-generation".into(),
6775            })
6776            .unwrap();
6777        attempt.begin_prepare(harness.clock.now()).unwrap();
6778        harness.store.record_attempt(&attempt).unwrap();
6779        let first = FakeIsolatedProvider::identity(&attempt, harness.policy.host_id);
6780        let mut second = first.clone();
6781        let EnvironmentIdentity::Isolated { environment_id, .. } = &mut second else {
6782            unreachable!()
6783        };
6784        *environment_id = "another-environment".into();
6785        provider
6786            .resources
6787            .lock()
6788            .unwrap()
6789            .insert(id, (first, EnvironmentState::Running));
6790        provider.extra_resources.lock().unwrap().push(second);
6791        launcher
6792            .recover_startup(std::slice::from_ref(&harness.policy))
6793            .await
6794            .expect("duplicate is local");
6795        let deferred = harness.store.attempt(id).unwrap().unwrap();
6796        assert_eq!(deferred.state(), AttemptState::CleanupDeferred);
6797        assert!(deferred.counts_against_capacity());
6798        assert_eq!(provider.resource_count(), 1);
6799        assert_eq!(
6800            provider
6801                .actions
6802                .lock()
6803                .unwrap()
6804                .iter()
6805                .filter(|action| **action == "destroy")
6806                .count(),
6807            0
6808        );
6809        provider.extra_resources.lock().unwrap().clear();
6810        // A tolerated cleanup failure is retried after its backoff delay.
6811        harness.clock.advance_secs(31);
6812        launcher
6813            .recover_startup(std::slice::from_ref(&harness.policy))
6814            .await
6815            .expect("single identity recovered");
6816        assert_eq!(provider.resource_count(), 0);
6817        assert_eq!(
6818            harness.store.attempt(id).unwrap().unwrap().state(),
6819            AttemptState::Cleaned
6820        );
6821    }
6822
6823    #[tokio::test]
6824    async fn provider_resource_without_live_journal_is_surfaced_but_never_deleted() {
6825        let harness = isolated_harness();
6826        let provider = Arc::new(FakeIsolatedProvider::default());
6827        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6828        let id = AttemptId::from_u128(0x8888);
6829        let runtime = harness.host_root().join("orphan-provider-resource");
6830        fs::create_dir_all(&runtime).unwrap();
6831        let mut attempt =
6832            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
6833        let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6834            harness.policy.execution_policy()
6835        else {
6836            unreachable!()
6837        };
6838        attempt
6839            .allocate_execution(AttemptExecution::Isolated {
6840                provider_kind: Backend::Oci,
6841                environment_id: None,
6842                resolved_image: image.clone(),
6843                generation: "orphan-generation".into(),
6844            })
6845            .unwrap();
6846        let identity = FakeIsolatedProvider::identity(&attempt, harness.policy.host_id);
6847        provider
6848            .resources
6849            .lock()
6850            .unwrap()
6851            .insert(id, (identity, EnvironmentState::Running));
6852        launcher
6853            .recover_startup(std::slice::from_ref(&harness.policy))
6854            .await
6855            .expect("orphan cannot block host");
6856        assert_eq!(provider.resource_count(), 1);
6857        assert!(
6858            harness
6859                .events
6860                .events()
6861                .contains(&AttemptEvent::QuarantinedOwnedResource { attempt: id })
6862        );
6863        assert_eq!(
6864            provider
6865                .actions
6866                .lock()
6867                .unwrap()
6868                .iter()
6869                .filter(|action| **action == "destroy")
6870                .count(),
6871            0
6872        );
6873
6874        let EnvironmentIdentity::Isolated { environment_id, .. } = provider
6875            .resources
6876            .lock()
6877            .unwrap()
6878            .get(&id)
6879            .unwrap()
6880            .0
6881            .clone()
6882        else {
6883            unreachable!()
6884        };
6885        attempt.begin_prepare(harness.clock.now()).unwrap();
6886        attempt.prepared_environment(environment_id).unwrap();
6887        attempt.mark_prepared(harness.clock.now()).unwrap();
6888        attempt.jit_received(harness.clock.now()).unwrap();
6889        attempt.started_isolated(harness.clock.now()).unwrap();
6890        attempt
6891            .conclude(
6892                AttemptOutcome::failed(FailureReason::ProcessStartFailed),
6893                harness.clock.now(),
6894            )
6895            .unwrap();
6896        attempt.begin_destroy(harness.clock.now()).unwrap();
6897        attempt.clean_isolated(harness.clock.now()).unwrap();
6898        harness.store.record_attempt(&attempt).unwrap();
6899        launcher
6900            .recover_startup(std::slice::from_ref(&harness.policy))
6901            .await
6902            .expect("cleaned row cannot authorize deletion");
6903        assert_eq!(provider.resource_count(), 1);
6904        assert_eq!(
6905            provider
6906                .actions
6907                .lock()
6908                .unwrap()
6909                .iter()
6910                .filter(|action| **action == "destroy")
6911                .count(),
6912            0
6913        );
6914    }
6915
6916    /// The wiring the three-hour outage needed and did not have.
6917    ///
6918    /// A root that refuses a launch does so before `record_allocation`, so no
6919    /// attempt row carries it, and the daemon's log scrubs the paths out of the
6920    /// sentence. The record this asserts is the only surface left, and
6921    /// `service status` reads it -- so if this wiring is ever dropped, the
6922    /// failure goes back to reading `runner_start_failed reason=other` once per
6923    /// poll and nothing else.
6924    #[tokio::test]
6925    async fn a_root_that_refuses_a_launch_is_recorded_and_cleared_when_one_succeeds() {
6926        use runner_manager_platform::service::{clear_runner_root_refusal, runner_root_refusals};
6927
6928        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
6929            .with_host_runner_root();
6930        harness.ready().await;
6931
6932        // A root under two directories that do not exist: refused by the
6933        // preflight, for a reason that has nothing to do with this platform, so
6934        // the assertion holds on all three.
6935        let unusable = harness
6936            ._root
6937            .path()
6938            .join("absent")
6939            .join("deeper")
6940            .join("runners");
6941        let mut host = harness.host.clone();
6942        host.runner_root_override = Some(
6943            LocalAbsolutePath::new(unusable.to_str().expect("a UTF-8 temporary path"))
6944                .expect("a local absolute host root"),
6945        );
6946        harness.store.put_host(&host).unwrap();
6947
6948        let failure = harness
6949            .launch_result()
6950            .await
6951            .expect_err("a root whose parents are missing cannot hold a runner");
6952        assert!(
6953            matches!(failure.reason, FailureReason::Other(_)),
6954            "{failure:?}"
6955        );
6956
6957        let refusals = runner_root_refusals(&harness.app_paths).expect("readable");
6958        let refusal = refusals
6959            .first()
6960            .expect("the refusal reached the one surface that can hold it");
6961        assert_eq!(refusal.policy, harness.policy.id.to_string());
6962        assert_eq!(refusal.kind, "missing_parents");
6963        assert!(
6964            refusal.root.contains("runners") && refusal.detail.contains("runners"),
6965            "the directory must be named in full: {refusal:?}"
6966        );
6967
6968        // And a root that works clears it, so a host that has been fixed stops
6969        // reporting a fault it no longer has.
6970        harness.store.put_host(&harness.host).unwrap();
6971        harness.launch().await;
6972        assert!(
6973            runner_root_refusals(&harness.app_paths)
6974                .expect("readable")
6975                .is_empty(),
6976            "a successful placement clears that policy's record"
6977        );
6978
6979        clear_runner_root_refusal(&harness.app_paths, &harness.policy.id.to_string())
6980            .expect("cleanup");
6981    }
6982
6983    #[tokio::test]
6984    async fn a_launch_reports_how_long_each_step_took() {
6985        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
6986        harness.ready().await;
6987        let started = harness.launch().await;
6988        let events = harness.events.events();
6989        let launched = events
6990            .iter()
6991            .position(|event| matches!(event, AttemptEvent::Launched { attempt, .. } if *attempt == started.id))
6992            .expect("a successful launch reports its step timings");
6993        let starting = events
6994            .iter()
6995            .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Starting } if *attempt == started.id))
6996            .unwrap();
6997        assert!(starting < launched, "timings follow the start: {events:?}");
6998    }
6999
7000    #[tokio::test]
7001    async fn a_failed_launch_still_reports_its_step_timings() {
7002        let harness = Harness::new(
7003            FakeGithubLifecycle::default().fail(true),
7004            Arc::new(PersistentDemand),
7005        );
7006        harness.ready().await;
7007        let failed = harness.launch_after_waiting(Duration::from_secs(90)).await;
7008        assert!(failed.is_err());
7009
7010        let timings = harness
7011            .events
7012            .events()
7013            .into_iter()
7014            .find_map(|event| match event {
7015                AttemptEvent::Launched {
7016                    started: false,
7017                    timings,
7018                    ..
7019                } => Some(timings),
7020                _ => None,
7021            })
7022            .expect("a launch that failed at registration reports its timings");
7023        assert_eq!(timings.lock_wait, Duration::from_secs(90));
7024        assert_eq!(timings.spawn, Duration::ZERO, "spawn was never reached");
7025        assert!(timings.total() >= Duration::from_secs(90));
7026    }
7027
7028    #[cfg(target_os = "macos")]
7029    #[tokio::test]
7030    async fn a_launch_removes_the_seed_of_a_root_no_longer_in_use() {
7031        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7032        harness.ready().await;
7033
7034        // A runtime this host once placed under a root it no longer uses.
7035        let old_root = harness._root.path().join("old-root");
7036        let old_runtime = old_root.join("abandoned");
7037        fs::create_dir_all(old_root.join(PACKAGE_SEED_DIR).join("2.335.0")).unwrap();
7038        fs::create_dir_all(&old_runtime).unwrap();
7039        let old = RunnerAttempt::allocate(
7040            AttemptId::new_random(),
7041            harness.policy.id,
7042            &old_runtime,
7043            harness.clock.now(),
7044        );
7045        harness.store.record_attempt(&old).unwrap();
7046        let kept = harness.host_root().join(PACKAGE_SEED_DIR);
7047        fs::create_dir_all(kept.join("2.336.0")).unwrap();
7048
7049        harness.launch().await;
7050
7051        assert!(
7052            !old_root.join(PACKAGE_SEED_DIR).exists(),
7053            "the abandoned root's seed is removed"
7054        );
7055        assert!(old_runtime.exists(), "only the seed is touched");
7056        assert!(kept.exists(), "the host root's own seed is kept");
7057    }
7058
7059    #[tokio::test]
7060    async fn a_job_walks_every_state_and_cleans_every_artifact() {
7061        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7062        harness.ready().await;
7063        let started = harness.launch().await;
7064        assert_eq!(started.state(), AttemptState::Starting);
7065        assert_eq!(read_runner_id(started.runtime_path()), Some(73));
7066
7067        harness
7068            .github
7069            .observe(GithubRunnerObservation::Registered { busy: false });
7070        harness.launcher.supervise(&harness.policy).await.unwrap();
7071        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7072
7073        harness
7074            .github
7075            .observe(GithubRunnerObservation::Registered { busy: true });
7076        harness.launcher.supervise(&harness.policy).await.unwrap();
7077        assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
7078
7079        harness.processes.finish_successfully();
7080        harness
7081            .github
7082            .observe(GithubRunnerObservation::NotRegistered);
7083        harness.launcher.supervise(&harness.policy).await.unwrap();
7084        let cleaned = harness.only_attempt();
7085        assert_eq!(cleaned.state(), AttemptState::Cleaned);
7086        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
7087        assert!(!started.runtime_path().exists());
7088        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7089        assert_eq!(harness.github.remaining_runners.load(Ordering::SeqCst), 0);
7090
7091        let states: Vec<_> = harness
7092            .events
7093            .events()
7094            .into_iter()
7095            .filter_map(|event| match event {
7096                AttemptEvent::State { state, .. } => Some(state),
7097                _ => None,
7098            })
7099            .collect();
7100        assert_eq!(
7101            states,
7102            vec![
7103                AttemptState::Allocated,
7104                AttemptState::JitReceived,
7105                AttemptState::Starting,
7106                AttemptState::Idle,
7107                AttemptState::Busy,
7108                AttemptState::Finished,
7109                AttemptState::Cleaned,
7110            ]
7111        );
7112    }
7113
7114    #[tokio::test]
7115    async fn a_cleaned_ephemeral_attempt_reaps_a_directory_recreated_after_cleanup() {
7116        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7117        harness.ready().await;
7118        let started = harness.launch().await;
7119        let runtime = started.runtime_path().to_path_buf();
7120
7121        harness
7122            .github
7123            .observe(GithubRunnerObservation::Registered { busy: true });
7124        harness.launcher.supervise(&harness.policy).await.unwrap();
7125        harness.processes.finish_successfully();
7126        harness
7127            .github
7128            .observe(GithubRunnerObservation::NotRegistered);
7129        harness.launcher.supervise(&harness.policy).await.unwrap();
7130
7131        assert_eq!(harness.attempt(started.id).state(), AttemptState::Cleaned);
7132        assert!(!runtime.exists());
7133        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7134
7135        // Reproduce a late orphan creating output after the successful removal
7136        // and journal transition. The next ordinary policy supervision must
7137        // remove it without replaying package release or another state change.
7138        let residue = runtime.join("_work").join("late-node-process");
7139        fs::create_dir_all(&residue).unwrap();
7140        fs::write(residue.join("node_modules.lock"), b"late residue").unwrap();
7141
7142        harness.launcher.supervise(&harness.policy).await.unwrap();
7143
7144        assert!(!runtime.exists(), "late ephemeral residue is reaped");
7145        assert_eq!(harness.attempt(started.id).state(), AttemptState::Cleaned);
7146        assert_eq!(
7147            harness.packages.releases.load(Ordering::SeqCst),
7148            1,
7149            "reaping residue does not release the package lease twice"
7150        );
7151    }
7152
7153    #[tokio::test]
7154    async fn locked_late_residue_never_blocks_startup_recovery() {
7155        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7156        harness.ready().await;
7157        let started = harness.launch().await;
7158        let runtime = started.runtime_path().to_path_buf();
7159
7160        harness
7161            .github
7162            .observe(GithubRunnerObservation::Registered { busy: true });
7163        harness.launcher.supervise(&harness.policy).await.unwrap();
7164        harness.processes.finish_successfully();
7165        harness
7166            .github
7167            .observe(GithubRunnerObservation::NotRegistered);
7168        harness.launcher.supervise(&harness.policy).await.unwrap();
7169        assert_eq!(harness.attempt(started.id).state(), AttemptState::Cleaned);
7170
7171        let held = runtime.join("_work").join("late-node-process");
7172        fs::create_dir_all(&held).unwrap();
7173        fs::write(held.join("node_modules.lock"), b"late residue").unwrap();
7174        let Some(block) = BlockedDeletion::inject(&held) else {
7175            eprintln!(
7176                "skipped: this account cannot be refused a deletion, so locked late residue cannot be injected"
7177            );
7178            return;
7179        };
7180
7181        let restarted = harness.restart();
7182        restarted
7183            .recover_startup(std::slice::from_ref(&harness.policy))
7184            .await
7185            .expect("late residue cannot take the daemon offline");
7186        assert!(runtime.exists(), "the locked residue remains for a retry");
7187        assert!(
7188            harness
7189                .reconcile_events
7190                .events()
7191                .iter()
7192                .any(|event| matches!(
7193                    event,
7194                    LifecycleEvent::AttemptCleanFailed {
7195                        attempt,
7196                        reason: "late_ephemeral_workspace_could_not_be_removed",
7197                        ..
7198                    } if *attempt == started.id
7199                )),
7200            "the non-blocking cleanup failure remains visible"
7201        );
7202
7203        block.release();
7204        // A tolerated cleanup failure is retried after its backoff delay.
7205        harness.clock.advance_secs(31);
7206        restarted
7207            .supervise(&harness.policy)
7208            .await
7209            .expect("the ordinary retry succeeds after the lock is released");
7210        assert!(!runtime.exists(), "the retry removes the late residue");
7211        assert_eq!(harness.attempt(started.id).state(), AttemptState::Cleaned);
7212        assert_eq!(
7213            harness.packages.releases.load(Ordering::SeqCst),
7214            1,
7215            "retrying residue never releases the package lease twice"
7216        );
7217    }
7218
7219    #[tokio::test]
7220    async fn mixed_locked_cleanup_residue_isolated_from_the_whole_startup_pass() {
7221        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7222        harness.ready().await;
7223
7224        // The first attempt is terminal but its initial cleanup cannot finish.
7225        // This is the state left by the original failed job on the affected
7226        // workstation.
7227        let terminal = harness.launch().await;
7228        let terminal_runtime = terminal.runtime_path().to_path_buf();
7229        harness.conclude(terminal.id);
7230        let Some(terminal_block) = BlockedDeletion::inject(&terminal_runtime.join("late-child"))
7231        else {
7232            eprintln!("skipped: this account cannot inject the two independent deletion refusals");
7233            return;
7234        };
7235
7236        // The second attempt was cleaned successfully, then a child recreated
7237        // part of `_work`. Both real-world residue shapes existed together in
7238        // the incident, and neither may short-circuit recovery of the other.
7239        let cleaned = harness.launch().await;
7240        let cleaned_runtime = cleaned.runtime_path().to_path_buf();
7241        harness.conclude(cleaned.id);
7242        harness
7243            .launcher
7244            .clean(cleaned.id)
7245            .await
7246            .expect("the second attempt initially cleans");
7247        let Some(cleaned_block) =
7248            BlockedDeletion::inject(&cleaned_runtime.join("_work").join("late-child"))
7249        else {
7250            terminal_block.release();
7251            eprintln!("skipped: this account cannot inject the two independent deletion refusals");
7252            return;
7253        };
7254
7255        let restarted = harness.restart();
7256        for _ in 0..2 {
7257            restarted
7258                .recover_startup(std::slice::from_ref(&harness.policy))
7259                .await
7260                .expect("repeated recovery remains ready while both residues are locked");
7261        }
7262        assert_ne!(
7263            harness.attempt(terminal.id).state(),
7264            AttemptState::Cleaned,
7265            "the journal does not claim the terminal workspace was removed"
7266        );
7267        assert_eq!(
7268            harness.attempt(cleaned.id).state(),
7269            AttemptState::Cleaned,
7270            "late residue does not undo an already durable cleaned transition"
7271        );
7272        assert!(terminal_runtime.exists());
7273        assert!(cleaned_runtime.exists());
7274        assert_eq!(
7275            harness.packages.releases.load(Ordering::SeqCst),
7276            1,
7277            "repeated recovery neither loses nor duplicates package leases"
7278        );
7279
7280        terminal_block.release();
7281        cleaned_block.release();
7282        // A tolerated cleanup failure is retried after its backoff delay.
7283        harness.clock.advance_secs(31);
7284        restarted
7285            .supervise(&harness.policy)
7286            .await
7287            .expect("one ordinary pass clears both residues after their locks disappear");
7288        assert!(!terminal_runtime.exists());
7289        assert!(!cleaned_runtime.exists());
7290        assert_eq!(harness.attempt(terminal.id).state(), AttemptState::Cleaned);
7291        assert_eq!(harness.attempt(cleaned.id).state(), AttemptState::Cleaned);
7292        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 2);
7293    }
7294
7295    #[tokio::test]
7296    async fn a_terminal_attempt_whose_runtime_is_already_gone_recovers_cleanly() {
7297        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7298        harness.ready().await;
7299        let attempt = harness.launch().await;
7300        let runtime = attempt.runtime_path().to_path_buf();
7301        harness.conclude(attempt.id);
7302        fs::remove_dir_all(&runtime).unwrap();
7303
7304        harness
7305            .restart()
7306            .recover_startup(std::slice::from_ref(&harness.policy))
7307            .await
7308            .expect("an already absent disposable runtime is successful cleanup");
7309
7310        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
7311        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7312    }
7313
7314    #[tokio::test]
7315    async fn a_non_workspace_cleanup_failure_still_fails_closed_and_can_retry() {
7316        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7317        harness.ready().await;
7318        let attempt = harness.launch().await;
7319        let runtime = attempt.runtime_path().to_path_buf();
7320        harness.conclude(attempt.id);
7321        harness.packages.fail_releases(1);
7322
7323        let restarted = harness.restart();
7324        let failure = restarted
7325            .recover_startup(std::slice::from_ref(&harness.policy))
7326            .await
7327            .expect_err("a package-accounting failure is not safe to downgrade to residue");
7328        assert!(
7329            failure
7330                .reason()
7331                .to_string()
7332                .contains("package lease could not be released")
7333        );
7334        assert!(
7335            !runtime.exists(),
7336            "workspace removal completed before release failed"
7337        );
7338        assert_ne!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
7339
7340        restarted
7341            .recover_startup(std::slice::from_ref(&harness.policy))
7342            .await
7343            .expect("the same journal entry retries safely after the transient failure");
7344        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
7345        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7346    }
7347
7348    #[tokio::test]
7349    async fn startup_never_scrubs_a_cleaned_persistent_work_directory() {
7350        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
7351            .with_persistent_workspace(1);
7352        harness.ready().await;
7353        let attempt = harness.launch().await;
7354        let retained = attempt.runtime_path().join("_work").join("checkout-marker");
7355        fs::create_dir_all(retained.parent().unwrap()).unwrap();
7356        fs::write(&retained, b"persistent checkout").unwrap();
7357        harness.cleanup_retaining_work(attempt.id).await;
7358
7359        harness
7360            .restart()
7361            .recover_startup(std::slice::from_ref(&harness.policy))
7362            .await
7363            .expect("a cleaned persistent slot is already reconciled");
7364
7365        assert_eq!(fs::read(&retained).unwrap(), b"persistent checkout");
7366        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7367    }
7368
7369    #[tokio::test]
7370    async fn an_idle_exit_is_not_a_failure_in_the_journal_or_events() {
7371        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7372        harness.ready().await;
7373        let started = harness.launch().await;
7374        harness
7375            .github
7376            .observe(GithubRunnerObservation::Registered { busy: false });
7377        harness.launcher.supervise(&harness.policy).await.unwrap();
7378        harness.clock.advance_secs(11);
7379        harness.processes.set_alive(false);
7380        harness
7381            .github
7382            .observe(GithubRunnerObservation::NotRegistered);
7383        harness.launcher.supervise(&harness.policy).await.unwrap();
7384
7385        let cleaned = harness.only_attempt();
7386        assert!(cleaned.outcome().unwrap().is_idle_exit());
7387        assert!(!cleaned.outcome().unwrap().is_failure());
7388        assert!(!started.runtime_path().exists());
7389        assert!(
7390            harness
7391                .reconcile_events
7392                .events()
7393                .iter()
7394                .any(|event| matches!(
7395                    event,
7396                    LifecycleEvent::AttemptCleaned {
7397                        outcome: OutcomeKind::IdleExit,
7398                        ..
7399                    }
7400                ))
7401        );
7402        assert!(!harness.events.events().iter().any(|event| matches!(
7403            event,
7404            AttemptEvent::Concluded {
7405                outcome: OutcomeKind::Failed,
7406                ..
7407            }
7408        )));
7409    }
7410
7411    #[tokio::test]
7412    async fn handoff_is_absent_after_success_and_every_failed_spawn_retry() {
7413        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7414        harness.processes.fail_spawns(2);
7415        harness.ready().await;
7416        let attempt = harness.launch().await;
7417        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 3);
7418        assert!(harness.processes.saw_secret.load(Ordering::SeqCst));
7419        let names: Vec<_> = fs::read_dir(attempt.runtime_path())
7420            .unwrap()
7421            .map(|entry| entry.unwrap().file_name())
7422            .collect();
7423        assert!(
7424            names.iter().all(|name| {
7425                !name
7426                    .to_string_lossy()
7427                    .starts_with(RestrictiveHandoff::NAME_PREFIX)
7428            }),
7429            "JIT artifact survived: {names:?}"
7430        );
7431        assert_eq!(
7432            *harness.delay.0.lock().unwrap(),
7433            vec![Duration::from_millis(10), Duration::from_millis(20)]
7434        );
7435    }
7436
7437    #[tokio::test]
7438    async fn jit_retry_stops_with_demand_and_a_terminal_403_never_retries() {
7439        let gone = Harness::new(
7440            FakeGithubLifecycle::default().fail(false),
7441            Arc::new(FakeDemand::answering([false])),
7442        );
7443        gone.ready().await;
7444        assert!(gone.launch_result().await.is_err());
7445        assert_eq!(gone.github.registrations.load(Ordering::SeqCst), 1);
7446        assert!(gone.delay.0.lock().unwrap().is_empty());
7447
7448        let forbidden = Harness::new(
7449            FakeGithubLifecycle::default().fail(true),
7450            Arc::new(PersistentDemand),
7451        );
7452        forbidden.ready().await;
7453        assert!(forbidden.launch_result().await.is_err());
7454        assert_eq!(forbidden.github.registrations.load(Ordering::SeqCst), 1);
7455        assert!(forbidden.delay.0.lock().unwrap().is_empty());
7456        assert!(matches!(
7457            forbidden.only_attempt().outcome(),
7458            Some(AttemptOutcome::Failed {
7459                reason: FailureReason::Other(action)
7460            }) if action.contains("403")
7461        ));
7462
7463        let transient = Harness::new(
7464            FakeGithubLifecycle::default().fail(false).fail(false),
7465            Arc::new(PersistentDemand),
7466        );
7467        transient.ready().await;
7468        transient.launch().await;
7469        assert_eq!(transient.github.registrations.load(Ordering::SeqCst), 3);
7470        assert_eq!(
7471            *transient.delay.0.lock().unwrap(),
7472            vec![Duration::from_millis(10), Duration::from_millis(20)]
7473        );
7474    }
7475
7476    /// The layout has to leave room for what the runner writes underneath it.
7477    ///
7478    /// Windows refuses a path over `MAX_PATH`, and this product's own CI hit
7479    /// that: 264 characters against a limit of 260, failing three checkout
7480    /// retries with `Filename too long`. The two identifiers in the old layout
7481    /// cost 74 characters between them for no benefit -- an attempt id is
7482    /// unique on its own.
7483    #[test]
7484    fn a_workspace_leaves_room_for_the_deepest_path_a_checkout_writes() {
7485        const MAX_PATH: usize = 260;
7486        // The real root on the machine this was found on.
7487        let root = r"C:\Users\IvanD\AppData\Local\IvanMurzak\runner-manager\data\runtime";
7488        // What `actions/checkout` writes at its deepest: the work directory,
7489        // the repository named twice, and a pack keep-file with a 40-character
7490        // object name.
7491        let repo = "GitHub-Runner-Scaler-UI";
7492        let deepest = format!(
7493            r"_work\{repo}\{repo}\.git\objects\pack\pack-{}.keep",
7494            "0".repeat(40)
7495        );
7496
7497        let name = workspace_name(AttemptId::new_random());
7498        assert_eq!(name.len(), WORKSPACE_NAME_LEN, "{name}");
7499        assert!(
7500            name.chars().all(|c| c.is_ascii_hexdigit()),
7501            "a directory name must not carry the identifier's dashes: {name}"
7502        );
7503
7504        let full = format!(r"{root}\{name}\{deepest}");
7505        assert!(
7506            full.len() < MAX_PATH,
7507            "the deepest path a checkout writes must fit: {} characters, limit {MAX_PATH}",
7508            full.len()
7509        );
7510
7511        // The discriminator: the layout this replaced does not fit, so a test
7512        // that passed for both would be proving nothing.
7513        let old = format!(
7514            r"{root}\{}\{}\{deepest}",
7515            PolicyId::new_random(),
7516            AttemptId::new_random()
7517        );
7518        assert!(
7519            old.len() > MAX_PATH,
7520            "the old layout is supposed to be the thing that did not fit: {} characters",
7521            old.len()
7522        );
7523    }
7524
7525    #[tokio::test]
7526    async fn two_attempts_never_share_a_workspace_even_after_failure() {
7527        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7528        harness.ready().await;
7529        let first = harness.launch().await;
7530        fs::write(first.runtime_path().join("hostile-leftover"), b"first job").unwrap();
7531        harness
7532            .github
7533            .observe(GithubRunnerObservation::Registered { busy: false });
7534        harness.launcher.supervise(&harness.policy).await.unwrap();
7535        harness.clock.advance_secs(11);
7536        harness.processes.set_alive(false);
7537        harness
7538            .github
7539            .observe(GithubRunnerObservation::NotRegistered);
7540        harness.launcher.supervise(&harness.policy).await.unwrap();
7541        assert!(!first.runtime_path().exists());
7542
7543        let second = harness.launch().await;
7544        assert_ne!(first.runtime_path(), second.runtime_path());
7545        assert!(!second.runtime_path().join("hostile-leftover").exists());
7546
7547        fs::write(
7548            second.runtime_path().join("hostile-on-failure"),
7549            b"second job",
7550        )
7551        .unwrap();
7552        harness.processes.set_alive(false);
7553        harness
7554            .github
7555            .observe(GithubRunnerObservation::NotRegistered);
7556        harness.launcher.supervise(&harness.policy).await.unwrap();
7557        assert!(
7558            !second.runtime_path().exists(),
7559            "failed workspace was retained"
7560        );
7561    }
7562
7563    #[tokio::test]
7564    async fn a_runner_that_never_gets_a_job_is_stopped_deregistered_and_not_replaced() {
7565        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7566        harness.ready().await;
7567        let attempt = harness.launch().await;
7568
7569        // Registered and waiting, which is where it stays: the fake keeps
7570        // answering the same observation, exactly as GitHub does for a runner
7571        // nobody assigns work to.
7572        harness
7573            .github
7574            .observe(GithubRunnerObservation::Registered { busy: false });
7575        harness.launcher.supervise(&harness.policy).await.unwrap();
7576        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7577
7578        // One second inside the ten-second idle timeout nothing happens, which
7579        // is what keeps this from being a test that would pass on any clock.
7580        harness.clock.advance_secs(9);
7581        harness
7582            .github
7583            .observe(GithubRunnerObservation::Registered { busy: false });
7584        let none_yet = harness.launcher.supervise(&harness.policy).await.unwrap();
7585        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7586        assert!(none_yet.is_empty());
7587        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 0);
7588
7589        // Past it, the agent ends the runner itself.
7590        harness.clock.advance_secs(1);
7591        harness
7592            .github
7593            .observe(GithubRunnerObservation::Registered { busy: false });
7594        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
7595
7596        let concluded = harness.store.attempt(attempt.id).unwrap().unwrap();
7597        assert_eq!(
7598            concluded.outcome(),
7599            Some(&AttemptOutcome::ExitedIdleWithoutWork),
7600            "a surplus runner did not fail; recording one as a failure sends an operator \
7601             hunting a fault that does not exist"
7602        );
7603        assert_eq!(concluded.state(), AttemptState::Cleaned);
7604        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 1);
7605        assert!(!attempt.runtime_path().exists());
7606
7607        // The registration goes with it. Without this the runner stays listed
7608        // in the target's runner settings after the process it named is gone.
7609        assert_eq!(
7610            *harness.github.deregistrations.lock().unwrap(),
7611            vec![73],
7612            "the attempt's own runner id, deleted exactly once"
7613        );
7614
7615        // And nothing is started in its place: the work it was launched for went
7616        // elsewhere, so a replacement would rebuild it every idle timeout.
7617        assert!(
7618            replacements.is_empty(),
7619            "a surplus exit must not request a replacement"
7620        );
7621    }
7622
7623    #[tokio::test]
7624    async fn a_registration_github_will_not_delete_still_concludes_the_attempt() {
7625        // The delete is best-effort by construction: the process is gone and the
7626        // slot has to come back. Holding the conclusion until GitHub cooperates
7627        // would leak a capacity slot on every unreachable moment.
7628        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7629        harness.ready().await;
7630        let attempt = harness.launch().await;
7631        harness
7632            .github
7633            .observe(GithubRunnerObservation::Registered { busy: false });
7634        harness.launcher.supervise(&harness.policy).await.unwrap();
7635
7636        harness
7637            .github
7638            .deregistration_fails
7639            .store(true, Ordering::SeqCst);
7640        harness.clock.advance_secs(11);
7641        harness
7642            .github
7643            .observe(GithubRunnerObservation::Registered { busy: false });
7644        harness.launcher.supervise(&harness.policy).await.unwrap();
7645
7646        assert_eq!(
7647            *harness.github.deregistrations.lock().unwrap(),
7648            vec![73],
7649            "the delete was attempted"
7650        );
7651        let concluded = harness.store.attempt(attempt.id).unwrap().unwrap();
7652        assert_eq!(
7653            concluded.outcome(),
7654            Some(&AttemptOutcome::ExitedIdleWithoutWork),
7655            "the attempt concluded anyway"
7656        );
7657        assert_eq!(concluded.state(), AttemptState::Cleaned);
7658        assert!(!attempt.runtime_path().exists());
7659    }
7660
7661    #[tokio::test]
7662    async fn exit_before_acceptance_returns_replacement_intent_without_launching() {
7663        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7664        harness.ready().await;
7665        let first = harness.launch().await;
7666        harness.processes.set_alive(false);
7667        harness
7668            .github
7669            .observe(GithubRunnerObservation::NotRegistered);
7670        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
7671        let failed = harness.store.attempt(first.id).unwrap().unwrap();
7672        assert!(matches!(
7673            failed.outcome(),
7674            Some(AttemptOutcome::Failed {
7675                reason: FailureReason::ProcessExitedUnexpectedly
7676            })
7677        ));
7678        assert!(!first.runtime_path().exists());
7679
7680        assert_eq!(
7681            replacements,
7682            vec![ReplacementIntent {
7683                policy: harness.policy.id,
7684                previous_attempt: first.id,
7685                operation: "exit_before_acceptance_replacement",
7686            }]
7687        );
7688        assert_eq!(harness.store.attempts().unwrap().len(), 1);
7689        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
7690        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
7691        assert!(harness.delay.0.lock().unwrap().is_empty());
7692    }
7693
7694    /// Writes the runner's own diagnostics: always the listener's log, and the
7695    /// job worker's when `ran_a_job`. `Runner.Listener` starts `Runner.Worker`
7696    /// only for a job it has acquired.
7697    fn write_runner_diagnostics(runtime: &Path, ran_a_job: bool) {
7698        let diag = runtime.join("_diag");
7699        fs::create_dir_all(&diag).unwrap();
7700        fs::write(diag.join("Runner_20261007-211941-utc.log"), b"listener").unwrap();
7701        if ran_a_job {
7702            fs::write(diag.join("Worker_20261007-211950-utc.log"), b"worker").unwrap();
7703        }
7704    }
7705
7706    /// The macOS field case: a job of a few seconds starts and ends between two
7707    /// passes, so GitHub was never seen reporting the runner busy -- the attempt
7708    /// is still `starting` -- and the registration is already gone. It used to be
7709    /// recorded `process_exited_unexpectedly`, with a replacement runner.
7710    #[tokio::test]
7711    async fn a_job_too_short_to_be_seen_busy_is_recorded_as_completed() {
7712        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7713        harness.ready().await;
7714        let started = harness.launch().await;
7715        assert_eq!(started.state(), AttemptState::Starting);
7716        write_runner_diagnostics(started.runtime_path(), true);
7717        harness.processes.finish_successfully();
7718        harness
7719            .github
7720            .observe(GithubRunnerObservation::NotRegistered);
7721
7722        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
7723
7724        let cleaned = harness.only_attempt();
7725        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
7726        assert_eq!(cleaned.state(), AttemptState::Cleaned);
7727        assert_eq!(cleaned.github_runner_id(), Some(73));
7728        assert!(
7729            replacements.is_empty(),
7730            "a finished job needs no replacement"
7731        );
7732        let busy_seen = harness.events.events().into_iter().any(|event| {
7733            matches!(
7734                event,
7735                AttemptEvent::State {
7736                    state: AttemptState::Busy,
7737                    ..
7738                }
7739            )
7740        });
7741        assert!(busy_seen, "the journal walks the diagram to `busy` first");
7742    }
7743
7744    /// The same from `idle`: seen registered and waiting once, then gone.
7745    #[tokio::test]
7746    async fn a_job_taken_between_two_passes_after_idle_is_recorded_as_completed() {
7747        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7748        harness.ready().await;
7749        let started = harness.launch().await;
7750        harness
7751            .github
7752            .observe(GithubRunnerObservation::Registered { busy: false });
7753        harness.launcher.supervise(&harness.policy).await.unwrap();
7754        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7755
7756        write_runner_diagnostics(started.runtime_path(), true);
7757        harness.processes.finish_successfully();
7758        harness
7759            .github
7760            .observe(GithubRunnerObservation::NotRegistered);
7761        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
7762
7763        assert_eq!(
7764            harness.only_attempt().outcome(),
7765            Some(&AttemptOutcome::CompletedJob)
7766        );
7767        assert!(replacements.is_empty());
7768    }
7769
7770    /// The reverse error, from the same sampling: GitHub showed the runner
7771    /// assigned, the runner never started the job (no worker log), and it exited
7772    /// 0. That is not a completed job.
7773    #[tokio::test]
7774    async fn an_assignment_the_runner_never_took_up_is_not_a_completed_job() {
7775        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7776        harness.ready().await;
7777        let started = harness.launch().await;
7778        harness
7779            .github
7780            .observe(GithubRunnerObservation::Registered { busy: true });
7781        harness.launcher.supervise(&harness.policy).await.unwrap();
7782        assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
7783
7784        write_runner_diagnostics(started.runtime_path(), false);
7785        harness.processes.finish_successfully();
7786        harness
7787            .github
7788            .observe(GithubRunnerObservation::NotRegistered);
7789        harness.launcher.supervise(&harness.policy).await.unwrap();
7790
7791        let cleaned = harness.only_attempt();
7792        assert_eq!(
7793            cleaned.outcome(),
7794            Some(&AttemptOutcome::ExitedIdleWithoutWork)
7795        );
7796        assert_eq!(cleaned.state(), AttemptState::Cleaned);
7797    }
7798
7799    /// The mirror case: the runner really ran its job and exited 0 before GitHub
7800    /// took it off the list. It used to be recorded `orphaned`.
7801    #[tokio::test]
7802    async fn a_finished_job_still_listed_at_github_is_completed_and_deregistered() {
7803        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7804        harness.ready().await;
7805        let started = harness.launch().await;
7806        harness
7807            .github
7808            .observe(GithubRunnerObservation::Registered { busy: true });
7809        harness.launcher.supervise(&harness.policy).await.unwrap();
7810
7811        write_runner_diagnostics(started.runtime_path(), true);
7812        harness.processes.finish_successfully();
7813        harness
7814            .github
7815            .observe(GithubRunnerObservation::Registered { busy: true });
7816        harness.launcher.supervise(&harness.policy).await.unwrap();
7817
7818        assert_eq!(
7819            harness.only_attempt().outcome(),
7820            Some(&AttemptOutcome::CompletedJob)
7821        );
7822        assert_eq!(*harness.github.deregistrations.lock().unwrap(), vec![73]);
7823    }
7824
7825    /// A live runner journalled `busy` whose assignment GitHub withdrew goes
7826    /// back to `idle`, where the idle timeout holds it again.
7827    #[tokio::test]
7828    async fn a_live_runner_whose_assignment_was_withdrawn_goes_back_to_idle() {
7829        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7830        harness.ready().await;
7831        let started = harness.launch().await;
7832        harness
7833            .github
7834            .observe(GithubRunnerObservation::Registered { busy: true });
7835        harness.launcher.supervise(&harness.policy).await.unwrap();
7836        assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
7837
7838        write_runner_diagnostics(started.runtime_path(), false);
7839        harness
7840            .github
7841            .observe(GithubRunnerObservation::Registered { busy: false });
7842        harness.launcher.supervise(&harness.policy).await.unwrap();
7843        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7844
7845        // A runner that did start its job keeps `busy` whatever GitHub says.
7846        harness
7847            .github
7848            .observe(GithubRunnerObservation::Registered { busy: true });
7849        harness.launcher.supervise(&harness.policy).await.unwrap();
7850        write_runner_diagnostics(started.runtime_path(), true);
7851        harness
7852            .github
7853            .observe(GithubRunnerObservation::Registered { busy: false });
7854        harness.launcher.supervise(&harness.policy).await.unwrap();
7855        assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
7856    }
7857
7858    /// While GitHub cannot be reached nothing is concluded, so a registration
7859    /// still listed there is removed once it answers.
7860    #[tokio::test]
7861    async fn a_clean_exit_waits_for_github_to_answer() {
7862        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7863        harness.ready().await;
7864        let started = harness.launch().await;
7865        write_runner_diagnostics(started.runtime_path(), true);
7866        harness.processes.finish_successfully();
7867        harness.github.observe(GithubRunnerObservation::Unreachable);
7868        harness.launcher.supervise(&harness.policy).await.unwrap();
7869        assert_eq!(harness.only_attempt().state(), AttemptState::Starting);
7870
7871        harness
7872            .github
7873            .observe(GithubRunnerObservation::NotRegistered);
7874        harness.launcher.supervise(&harness.policy).await.unwrap();
7875        assert_eq!(
7876            harness.only_attempt().outcome(),
7877            Some(&AttemptOutcome::CompletedJob)
7878        );
7879    }
7880
7881    /// A runner id nobody can name is not a reason to stop supervising the
7882    /// policy: the attempt is concluded the way it was before, without one.
7883    #[tokio::test]
7884    async fn a_short_job_with_no_runner_id_still_concludes() {
7885        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7886        harness.ready().await;
7887        let started = harness.launch().await;
7888        fs::remove_file(started.runtime_path().join(RUNNER_ID_FILE)).unwrap();
7889        write_runner_diagnostics(started.runtime_path(), true);
7890        harness.processes.finish_successfully();
7891        harness
7892            .github
7893            .observe(GithubRunnerObservation::NotRegistered);
7894        harness
7895            .launcher
7896            .supervise(&harness.policy)
7897            .await
7898            .expect("supervision goes on");
7899        assert!(harness.only_attempt().is_terminal());
7900    }
7901
7902    /// Without the runner's diagnostics nothing changes: a clean exit seen only
7903    /// at `starting` is still a runner that exited before taking a job.
7904    #[tokio::test]
7905    async fn without_runner_diagnostics_an_early_exit_is_still_a_failure() {
7906        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7907        harness.ready().await;
7908        harness.launch().await;
7909        harness.processes.finish_successfully();
7910        harness
7911            .github
7912            .observe(GithubRunnerObservation::NotRegistered);
7913        harness.launcher.supervise(&harness.policy).await.unwrap();
7914        assert!(matches!(
7915            harness.only_attempt().outcome(),
7916            Some(AttemptOutcome::Failed {
7917                reason: FailureReason::ProcessExitedUnexpectedly
7918            })
7919        ));
7920    }
7921
7922    #[tokio::test]
7923    async fn expired_jit_is_removed_and_does_not_reregister_after_demand_disappears() {
7924        let harness = Harness::new(
7925            FakeGithubLifecycle::default(),
7926            Arc::new(FakeDemand::answering([false])),
7927        );
7928        let id = AttemptId::new_random();
7929        let runtime = harness
7930            .launcher
7931            .app_paths
7932            .runtime_dir()
7933            .join(harness.policy.id.to_string())
7934            .join(id.to_string());
7935        fs::create_dir_all(&runtime).unwrap();
7936        let mut attempt =
7937            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
7938        attempt.jit_received(harness.clock.now()).unwrap();
7939        harness.store.record_attempt(&attempt).unwrap();
7940        harness.clock.advance_secs(11);
7941        let replacements = harness
7942            .launcher
7943            .recover_startup(std::slice::from_ref(&harness.policy))
7944            .await
7945            .unwrap();
7946        assert_eq!(
7947            replacements,
7948            vec![ReplacementIntent {
7949                policy: harness.policy.id,
7950                previous_attempt: id,
7951                operation: "jit_expired_replacement",
7952            }]
7953        );
7954
7955        let cleaned = harness.store.attempt(id).unwrap().unwrap();
7956        assert_eq!(cleaned.state(), AttemptState::Cleaned);
7957        assert!(matches!(
7958            cleaned.outcome(),
7959            Some(AttemptOutcome::Failed {
7960                reason: FailureReason::JitExpired
7961            })
7962        ));
7963        assert!(!runtime.exists());
7964        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
7965        assert!(harness.delay.0.lock().unwrap().is_empty());
7966    }
7967
7968    #[tokio::test]
7969    async fn expired_jit_returns_intent_but_never_launches_inside_lifecycle() {
7970        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7971        let id = AttemptId::new_random();
7972        let runtime = harness
7973            .launcher
7974            .app_paths
7975            .runtime_dir()
7976            .join("expired-with-demand");
7977        fs::create_dir_all(&runtime).unwrap();
7978        let mut attempt =
7979            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
7980        attempt.jit_received(harness.clock.now()).unwrap();
7981        harness.store.record_attempt(&attempt).unwrap();
7982        harness.clock.advance_secs(11);
7983        let replacements = harness
7984            .launcher
7985            .recover_startup(std::slice::from_ref(&harness.policy))
7986            .await
7987            .unwrap();
7988
7989        let attempts = harness.store.attempts().unwrap();
7990        assert_eq!(attempts.len(), 1);
7991        assert_eq!(
7992            attempts
7993                .iter()
7994                .find(|attempt| attempt.id == id)
7995                .unwrap()
7996                .state(),
7997            AttemptState::Cleaned
7998        );
7999        assert_eq!(
8000            replacements,
8001            vec![ReplacementIntent {
8002                policy: harness.policy.id,
8003                previous_attempt: id,
8004                operation: "jit_expired_replacement",
8005            }]
8006        );
8007        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
8008        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
8009        assert!(harness.delay.0.lock().unwrap().is_empty());
8010    }
8011
8012    #[tokio::test]
8013    async fn package_materialization_retries_are_bounded_and_demand_adjacent() {
8014        let persistent = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8015        persistent.packages.fail_materializations(2);
8016        persistent.ready().await;
8017        persistent.launch().await;
8018        assert_eq!(
8019            persistent.packages.materializations.load(Ordering::SeqCst),
8020            3
8021        );
8022        assert_eq!(
8023            *persistent.delay.0.lock().unwrap(),
8024            vec![Duration::from_millis(10), Duration::from_millis(20)]
8025        );
8026
8027        let gone_before_wait = Harness::new(
8028            FakeGithubLifecycle::default(),
8029            Arc::new(FakeDemand::answering([false])),
8030        );
8031        gone_before_wait.packages.fail_materializations(3);
8032        gone_before_wait.ready().await;
8033        assert!(gone_before_wait.launch_result().await.is_err());
8034        assert_eq!(
8035            gone_before_wait
8036                .packages
8037                .materializations
8038                .load(Ordering::SeqCst),
8039            1
8040        );
8041        assert!(gone_before_wait.delay.0.lock().unwrap().is_empty());
8042
8043        let gone_during_wait = Harness::new(
8044            FakeGithubLifecycle::default(),
8045            Arc::new(FakeDemand::answering([true, false])),
8046        );
8047        gone_during_wait.packages.fail_materializations(3);
8048        gone_during_wait.ready().await;
8049        assert!(gone_during_wait.launch_result().await.is_err());
8050        assert_eq!(
8051            gone_during_wait
8052                .packages
8053                .materializations
8054                .load(Ordering::SeqCst),
8055            1
8056        );
8057        assert_eq!(
8058            *gone_during_wait.delay.0.lock().unwrap(),
8059            vec![Duration::from_millis(10)]
8060        );
8061    }
8062
8063    #[tokio::test]
8064    async fn replacement_is_intent_only_and_never_launches_inside_lifecycle() {
8065        let harness = Harness::new(
8066            FakeGithubLifecycle::default(),
8067            Arc::new(FakeDemand::answering([true, false])),
8068        );
8069        harness.ready().await;
8070        let first = harness.launch().await;
8071        harness.processes.set_alive(false);
8072        harness
8073            .github
8074            .observe(GithubRunnerObservation::NotRegistered);
8075        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
8076
8077        assert_eq!(harness.store.attempts().unwrap().len(), 1);
8078        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
8079        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
8080        assert!(harness.delay.0.lock().unwrap().is_empty());
8081        assert_eq!(
8082            replacements,
8083            vec![ReplacementIntent {
8084                policy: harness.policy.id,
8085                previous_attempt: first.id,
8086                operation: "exit_before_acceptance_replacement",
8087            }]
8088        );
8089        assert_eq!(
8090            harness.store.attempt(first.id).unwrap().unwrap().state(),
8091            AttemptState::Cleaned
8092        );
8093    }
8094
8095    #[tokio::test]
8096    async fn startup_adopts_a_live_process_and_refuses_launch_before_recovery() {
8097        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8098        let before = harness.launch_result().await;
8099        assert!(before.is_err());
8100        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
8101
8102        let id = AttemptId::new_random();
8103        let runtime = harness.launcher.app_paths.runtime_dir().join("adopt");
8104        fs::create_dir_all(&runtime).unwrap();
8105        let mut attempt =
8106            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
8107        attempt.jit_received(harness.clock.now()).unwrap();
8108        attempt.started(4242, harness.clock.now()).unwrap();
8109        harness.store.record_attempt(&attempt).unwrap();
8110        harness.processes.set_alive(true);
8111        harness
8112            .github
8113            .observe(GithubRunnerObservation::NotRegistered);
8114        let replacements = harness
8115            .launcher
8116            .recover_startup(std::slice::from_ref(&harness.policy))
8117            .await
8118            .unwrap();
8119        assert!(replacements.is_empty());
8120        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
8121        assert!(
8122            harness
8123                .events
8124                .events()
8125                .contains(&AttemptEvent::Adopted { attempt: id })
8126        );
8127    }
8128
8129    #[tokio::test]
8130    async fn spawn_before_starting_crash_recovers_pid_then_completes_and_cleans() {
8131        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8132        let id = AttemptId::new_random();
8133        let runtime = harness
8134            .launcher
8135            .app_paths
8136            .runtime_dir()
8137            .join("spawn-before-starting");
8138        fs::create_dir_all(&runtime).unwrap();
8139        let mut attempt =
8140            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
8141        attempt.jit_received(harness.clock.now()).unwrap();
8142        harness.store.record_attempt(&attempt).unwrap();
8143        harness.processes.set_alive(true);
8144        harness
8145            .github
8146            .observe(GithubRunnerObservation::Registered { busy: true });
8147
8148        let replacements = harness
8149            .launcher
8150            .recover_startup(std::slice::from_ref(&harness.policy))
8151            .await
8152            .unwrap();
8153        assert!(replacements.is_empty());
8154        let recovered = harness.store.attempt(id).unwrap().unwrap();
8155        assert_eq!(recovered.state(), AttemptState::Busy);
8156        assert_eq!(recovered.process_id(), Some(4242));
8157        assert_eq!(recovered.github_runner_id(), Some(73));
8158        let events = harness.events.events();
8159        let starting = events
8160            .iter()
8161            .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Starting } if *attempt == id))
8162            .unwrap();
8163        let busy = events
8164            .iter()
8165            .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Busy } if *attempt == id))
8166            .unwrap();
8167        assert!(starting < busy, "recovery skipped a legal edge: {events:?}");
8168
8169        harness.processes.finish_successfully();
8170        harness
8171            .github
8172            .observe(GithubRunnerObservation::NotRegistered);
8173        assert!(
8174            harness
8175                .launcher
8176                .supervise(&harness.policy)
8177                .await
8178                .unwrap()
8179                .is_empty()
8180        );
8181        let cleaned = harness.store.attempt(id).unwrap().unwrap();
8182        assert_eq!(cleaned.state(), AttemptState::Cleaned);
8183        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
8184        assert!(!runtime.exists());
8185    }
8186
8187    #[tokio::test]
8188    async fn failed_post_spawn_stop_keeps_capacity_until_supervision_proves_death() {
8189        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8190        harness.processes.fail_spawn_with_live_child();
8191        harness.ready().await;
8192        assert!(harness.launch_result().await.is_err());
8193
8194        let attempt = harness.only_attempt();
8195        assert_eq!(attempt.state(), AttemptState::Starting);
8196        assert_eq!(attempt.process_id(), Some(4242));
8197        assert!(attempt.outcome().is_none());
8198        assert!(attempt.state().counts_against_capacity());
8199        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
8200        assert!(harness.delay.0.lock().unwrap().is_empty());
8201
8202        harness.processes.set_alive(false);
8203        harness
8204            .github
8205            .observe(GithubRunnerObservation::NotRegistered);
8206        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
8207        assert_eq!(replacements.len(), 1);
8208        assert_eq!(
8209            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
8210            AttemptState::Cleaned
8211        );
8212    }
8213
8214    #[tokio::test]
8215    async fn remote_runner_identity_closes_both_sides_of_the_registration_crash_boundary() {
8216        for sidecar_already_present in [false, true] {
8217            let harness = Harness::new(
8218                FakeGithubLifecycle::default(),
8219                Arc::new(FakeDemand::answering([false])),
8220            );
8221            let id = AttemptId::new_random();
8222            let runtime =
8223                harness
8224                    .launcher
8225                    .app_paths
8226                    .runtime_dir()
8227                    .join(if sidecar_already_present {
8228                        "after-id-sidecar"
8229                    } else {
8230                        "before-id-sidecar"
8231                    });
8232            fs::create_dir_all(&runtime).unwrap();
8233            let mut attempt =
8234                RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
8235            if sidecar_already_present {
8236                write_runner_id(&runtime, 73).unwrap();
8237                attempt.jit_received(harness.clock.now()).unwrap();
8238            }
8239            harness.store.record_attempt(&attempt).unwrap();
8240            harness.processes.set_alive(true);
8241            harness
8242                .github
8243                .observe(GithubRunnerObservation::Registered { busy: false });
8244            harness
8245                .launcher
8246                .recover_startup(std::slice::from_ref(&harness.policy))
8247                .await
8248                .unwrap();
8249
8250            assert_eq!(read_runner_id(&runtime), Some(73));
8251            assert!(
8252                harness
8253                    .store
8254                    .attempt(id)
8255                    .unwrap()
8256                    .unwrap()
8257                    .outcome()
8258                    .is_none()
8259            );
8260            let events = harness.events.events();
8261            let recovered = events.iter().position(|event| {
8262                matches!(
8263                    event,
8264                    AttemptEvent::RemoteIdentityRecovered {
8265                        attempt,
8266                        runner_id: 73
8267                    } if *attempt == id
8268                )
8269            });
8270            assert_eq!(recovered.is_some(), !sidecar_already_present);
8271            if let Some(recovered) = recovered {
8272                let adopted = events
8273                    .iter()
8274                    .position(|event| matches!(event, AttemptEvent::Adopted { attempt } if *attempt == id))
8275                    .unwrap();
8276                assert!(
8277                    recovered < adopted,
8278                    "identity was not durable before adoption: {events:?}"
8279                );
8280            }
8281            assert!(runtime.exists());
8282        }
8283    }
8284
8285    #[tokio::test]
8286    async fn recovery_stays_closed_for_unknown_policy_and_unreachable_attempts() {
8287        let unknown = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8288        let unknown_attempt = RunnerAttempt::allocate(
8289            AttemptId::new_random(),
8290            PolicyId::from_u128(0xfeed),
8291            unknown
8292                .launcher
8293                .app_paths
8294                .runtime_dir()
8295                .join("unknown-policy"),
8296            unknown.clock.now(),
8297        );
8298        unknown.store.record_attempt(&unknown_attempt).unwrap();
8299        let expired_id = AttemptId::new_random();
8300        let expired_runtime = unknown
8301            .launcher
8302            .app_paths
8303            .runtime_dir()
8304            .join("expired-beside-unknown");
8305        fs::create_dir_all(&expired_runtime).unwrap();
8306        let mut expired = RunnerAttempt::allocate(
8307            expired_id,
8308            unknown.policy.id,
8309            expired_runtime,
8310            unknown.clock.now(),
8311        );
8312        expired.jit_received(unknown.clock.now()).unwrap();
8313        unknown.store.record_attempt(&expired).unwrap();
8314        unknown.clock.advance_secs(11);
8315        assert!(matches!(
8316            unknown
8317                .launcher
8318                .recover_startup(std::slice::from_ref(&unknown.policy))
8319                .await,
8320            Err(LifecycleError::RecoveryIncomplete)
8321        ));
8322        assert!(unknown.launch_result().await.is_err());
8323        assert_eq!(unknown.processes.spawns.load(Ordering::SeqCst), 0);
8324        let recovered_policy = fixtures::policy()
8325            .id(PolicyId::from_u128(0xfeed))
8326            .repository("octo/repo")
8327            .autoscale("home", 2)
8328            .active()
8329            .build();
8330        let pending = unknown
8331            .launcher
8332            .recover_startup(&[unknown.policy.clone(), recovered_policy])
8333            .await
8334            .unwrap();
8335        assert_eq!(
8336            pending,
8337            vec![ReplacementIntent {
8338                policy: unknown.policy.id,
8339                previous_attempt: expired_id,
8340                operation: "jit_expired_replacement",
8341            }]
8342        );
8343        assert_eq!(unknown.processes.spawns.load(Ordering::SeqCst), 0);
8344
8345        let unreachable = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8346        let id = AttemptId::new_random();
8347        let runtime = unreachable
8348            .launcher
8349            .app_paths
8350            .runtime_dir()
8351            .join("unreachable");
8352        fs::create_dir_all(&runtime).unwrap();
8353        unreachable
8354            .store
8355            .record_attempt(&RunnerAttempt::allocate(
8356                id,
8357                unreachable.policy.id,
8358                runtime,
8359                unreachable.clock.now(),
8360            ))
8361            .unwrap();
8362        unreachable
8363            .github
8364            .observe(GithubRunnerObservation::Unreachable);
8365        assert!(matches!(
8366            unreachable
8367                .launcher
8368                .recover_startup(std::slice::from_ref(&unreachable.policy))
8369                .await,
8370            Err(LifecycleError::RecoveryIncomplete)
8371        ));
8372        assert!(unreachable.launch_result().await.is_err());
8373        assert_eq!(unreachable.processes.spawns.load(Ordering::SeqCst), 0);
8374    }
8375
8376    #[tokio::test]
8377    async fn a_dead_busy_process_unknown_to_github_is_orphaned_and_cleaned() {
8378        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8379        let id = AttemptId::new_random();
8380        let runtime = harness.launcher.app_paths.runtime_dir().join("orphan");
8381        fs::create_dir_all(&runtime).unwrap();
8382        let mut attempt =
8383            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
8384        attempt.jit_received(harness.clock.now()).unwrap();
8385        attempt.started(4242, harness.clock.now()).unwrap();
8386        attempt.assigned_job(73, harness.clock.now()).unwrap();
8387        harness.store.record_attempt(&attempt).unwrap();
8388        harness.processes.set_alive(false);
8389        harness
8390            .github
8391            .observe(GithubRunnerObservation::NotRegistered);
8392        harness
8393            .launcher
8394            .recover_startup(std::slice::from_ref(&harness.policy))
8395            .await
8396            .unwrap();
8397        let cleaned = harness.store.attempt(id).unwrap().unwrap();
8398        assert_eq!(cleaned.state(), AttemptState::Cleaned);
8399        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::Orphaned));
8400        assert!(!runtime.exists());
8401    }
8402
8403    #[tokio::test]
8404    async fn registration_timeout_journals_intent_stops_then_concludes_with_dead_reason() {
8405        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8406        harness.ready().await;
8407        let id = AttemptId::new_random();
8408        let runtime = harness.launcher.app_paths.runtime_dir().join("timeout");
8409        fs::create_dir_all(&runtime).unwrap();
8410        let mut attempt =
8411            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
8412        attempt.jit_received(harness.clock.now()).unwrap();
8413        attempt.started(4242, harness.clock.now()).unwrap();
8414        harness.store.record_attempt(&attempt).unwrap();
8415        harness.clock.advance_secs(11);
8416        harness.processes.set_alive(true);
8417        harness
8418            .github
8419            .observe(GithubRunnerObservation::NotRegistered);
8420        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
8421        assert_eq!(
8422            replacements,
8423            vec![ReplacementIntent {
8424                policy: harness.policy.id,
8425                previous_attempt: id,
8426                operation: "registration_timeout_replacement",
8427            }]
8428        );
8429
8430        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 1);
8431        assert!(!harness.processes.alive.load(Ordering::SeqCst));
8432        let actions = harness.processes.actions.lock().unwrap().clone();
8433        let intent = actions
8434            .iter()
8435            .position(|action| *action == "terminate_intent")
8436            .unwrap();
8437        let signal = actions
8438            .iter()
8439            .position(|action| *action == "terminate")
8440            .unwrap();
8441        assert!(
8442            intent < signal,
8443            "intent was not durable before signal: {actions:?}"
8444        );
8445
8446        let cleaned = harness.store.attempt(id).unwrap().unwrap();
8447        assert!(matches!(
8448            cleaned.outcome(),
8449            Some(AttemptOutcome::Failed {
8450                reason: FailureReason::TerminatedAfterRegistrationTimeout
8451            })
8452        ));
8453        let events = harness.events.events();
8454        let intent = events
8455            .iter()
8456            .position(|event| matches!(event, AttemptEvent::TerminateIntent { .. }))
8457            .unwrap();
8458        let stopped = events
8459            .iter()
8460            .position(|event| matches!(event, AttemptEvent::Terminated { .. }))
8461            .unwrap();
8462        let concluded = events
8463            .iter()
8464            .position(|event| matches!(event, AttemptEvent::Concluded { .. }))
8465            .unwrap();
8466        assert!(intent < stopped && stopped < concluded, "{events:?}");
8467    }
8468
8469    #[tokio::test]
8470    async fn timeout_crash_recovery_returns_the_same_replacement_intent() {
8471        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8472        let id = AttemptId::new_random();
8473        let runtime = harness
8474            .launcher
8475            .app_paths
8476            .runtime_dir()
8477            .join("timeout-after-crash");
8478        fs::create_dir_all(&runtime).unwrap();
8479        let mut attempt =
8480            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
8481        attempt.jit_received(harness.clock.now()).unwrap();
8482        attempt.started(4242, harness.clock.now()).unwrap();
8483        harness.store.record_attempt(&attempt).unwrap();
8484        harness.processes.intent.store(true, Ordering::SeqCst);
8485        harness.processes.set_alive(false);
8486        harness
8487            .github
8488            .observe(GithubRunnerObservation::NotRegistered);
8489
8490        let replacements = harness
8491            .launcher
8492            .recover_startup(std::slice::from_ref(&harness.policy))
8493            .await
8494            .unwrap();
8495        assert_eq!(
8496            replacements,
8497            vec![ReplacementIntent {
8498                policy: harness.policy.id,
8499                previous_attempt: id,
8500                operation: "registration_timeout_replacement",
8501            }]
8502        );
8503        let consumed = RunnerLauncher::supervise(&harness.launcher, &harness.policy)
8504            .await
8505            .unwrap();
8506        assert_eq!(consumed, replacements);
8507        assert!(
8508            RunnerLauncher::supervise(&harness.launcher, &harness.policy)
8509                .await
8510                .unwrap()
8511                .is_empty(),
8512            "startup replacement evidence must be consumed exactly once by e1"
8513        );
8514        assert!(matches!(
8515            harness.store.attempt(id).unwrap().unwrap().outcome(),
8516            Some(AttemptOutcome::Failed {
8517                reason: FailureReason::TerminatedAfterRegistrationTimeout
8518            })
8519        ));
8520    }
8521
8522    #[tokio::test]
8523    async fn terminate_intent_sync_failure_prevents_signal_and_conclusion() {
8524        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8525        let id = AttemptId::new_random();
8526        let runtime = harness
8527            .launcher
8528            .app_paths
8529            .runtime_dir()
8530            .join("timeout-sync-failure");
8531        fs::create_dir_all(&runtime).unwrap();
8532        let mut attempt =
8533            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
8534        attempt.jit_received(harness.clock.now()).unwrap();
8535        attempt.started(4242, harness.clock.now()).unwrap();
8536        harness.store.record_attempt(&attempt).unwrap();
8537        harness.clock.advance_secs(11);
8538        harness.processes.set_alive(true);
8539        harness.processes.fail_intent();
8540        harness
8541            .github
8542            .observe(GithubRunnerObservation::NotRegistered);
8543
8544        assert!(
8545            harness
8546                .launcher
8547                .recover_startup(std::slice::from_ref(&harness.policy))
8548                .await
8549                .is_err()
8550        );
8551        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 0);
8552        assert!(harness.processes.alive.load(Ordering::SeqCst));
8553        assert_eq!(
8554            harness.store.attempt(id).unwrap().unwrap().state(),
8555            AttemptState::Starting
8556        );
8557        assert!(!harness.events.events().iter().any(|event| matches!(
8558            event,
8559            AttemptEvent::Terminated { attempt } | AttemptEvent::Concluded { attempt, .. }
8560                if *attempt == id
8561        )));
8562    }
8563
8564    #[tokio::test]
8565    async fn diagnostics_survive_cleanup_without_the_jit_or_a_token() {
8566        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8567        harness.ready().await;
8568        let attempt = harness.launch().await;
8569        harness
8570            .github
8571            .observe(GithubRunnerObservation::Registered { busy: false });
8572        harness.launcher.supervise(&harness.policy).await.unwrap();
8573        harness.clock.advance_secs(11);
8574        harness.processes.set_alive(false);
8575        harness
8576            .github
8577            .observe(GithubRunnerObservation::NotRegistered);
8578        harness.launcher.supervise(&harness.policy).await.unwrap();
8579        let diagnostic = fs::read_to_string(
8580            harness
8581                .launcher
8582                .diagnostics_root
8583                .join(format!("{}.log", attempt.id)),
8584        )
8585        .unwrap();
8586        assert!(diagnostic.contains("exited_idle_without_work"));
8587        assert!(!diagnostic.contains(JIT));
8588        assert!(!diagnostic.contains("ghp_"));
8589        assert!(!attempt.runtime_path().exists());
8590    }
8591
8592    #[test]
8593    fn native_process_listing_never_contains_jit_and_handoffs_never_survive() {
8594        let root = tempfile::tempdir().unwrap();
8595        let policy = fixtures::policy()
8596            .repository("octo/repo")
8597            .autoscale("home", 1)
8598            .active()
8599            .build();
8600        let runtime = root.path().join("successful");
8601        fs::create_dir_all(&runtime).unwrap();
8602        let processes = NativeProcesses::new();
8603        let config = EncodedJitConfig::new(JIT);
8604        let handoff =
8605            RestrictiveHandoff::create(&runtime, SecretString::from(config.expose().to_owned()))
8606                .unwrap();
8607        let mut child = native_inspection_spec()
8608            .spawn_runner_with_handoff(&handoff)
8609            .expect("native child starts");
8610        let pid = child.pid();
8611        handoff.delete().unwrap();
8612        let command_line = native_command_line(pid);
8613        assert!(
8614            !command_line.contains(JIT),
8615            "the encoded JIT configuration appeared in the native process listing"
8616        );
8617        assert_no_jit_file(&runtime);
8618        child
8619            .stop(Duration::from_secs(1))
8620            .expect("native child stops");
8621
8622        let failed_runtime = root.path().join("failed");
8623        fs::create_dir_all(&failed_runtime).unwrap();
8624        let failed = RunnerAttempt::allocate(
8625            AttemptId::new_random(),
8626            policy.id,
8627            &failed_runtime,
8628            FakeClock::default().now(),
8629        );
8630        assert!(
8631            processes
8632                .spawn(&failed, &EncodedJitConfig::new(JIT))
8633                .is_err(),
8634            "a runtime with no runner executable must fail"
8635        );
8636        assert_no_jit_file(&failed_runtime);
8637        processes
8638            .record_terminate_intent(&failed)
8639            .expect("the intent file and its directory entry are durably synced");
8640        assert_eq!(
8641            fs::read(NativeProcesses::intent_path(&failed)).unwrap(),
8642            b"registration-timeout\n"
8643        );
8644    }
8645
8646    #[test]
8647    fn post_spawn_boundaries_are_bounded_durable_and_never_retry_jit() {
8648        let root = tempfile::tempdir().unwrap();
8649        let policy = fixtures::policy()
8650            .repository("octo/repo")
8651            .autoscale("home", 1)
8652            .active()
8653            .build();
8654        let processes = NativeProcesses::new();
8655        processes.use_long_lived_test_listener();
8656        for (index, boundary) in [
8657            PostSpawnBoundary::HandoffDelete,
8658            PostSpawnBoundary::IdentitySerialize,
8659            PostSpawnBoundary::IdentityWrite,
8660            PostSpawnBoundary::ChildMapInsert,
8661        ]
8662        .into_iter()
8663        .enumerate()
8664        {
8665            let runtime = root.path().join(format!("post-spawn-{index}"));
8666            let bin = runtime.join("bin");
8667            fs::create_dir_all(&bin).unwrap();
8668            #[cfg(windows)]
8669            let listener = bin.join("Runner.Listener.exe");
8670            #[cfg(not(windows))]
8671            let listener = bin.join("Runner.Listener");
8672            fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
8673            let attempt = RunnerAttempt::allocate(
8674                AttemptId::new_random(),
8675                policy.id,
8676                &runtime,
8677                FakeClock::default().now(),
8678            );
8679            processes.fail_post_spawn_at(boundary);
8680            let failure = processes
8681                .spawn(&attempt, &EncodedJitConfig::new(JIT))
8682                .expect_err("fault must cross the post-spawn cleanup path");
8683            assert!(!failure.retryable, "{boundary:?} allowed duplicate retry");
8684            assert!(
8685                !processes.is_alive(&attempt).unwrap(),
8686                "{boundary:?} left a child"
8687            );
8688            assert!(!NativeProcesses::identity_path(&attempt).exists());
8689            assert_no_jit_file(&runtime);
8690        }
8691        assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
8692
8693        let runtime = root.path().join("identity-and-stop-fail");
8694        let bin = runtime.join("bin");
8695        fs::create_dir_all(&bin).unwrap();
8696        #[cfg(windows)]
8697        let listener = bin.join("Runner.Listener.exe");
8698        #[cfg(not(windows))]
8699        let listener = bin.join("Runner.Listener");
8700        fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
8701        let attempt = RunnerAttempt::allocate(
8702            AttemptId::new_random(),
8703            policy.id,
8704            &runtime,
8705            FakeClock::default().now(),
8706        );
8707        // The first fault rejects the normal identity write; the second rejects
8708        // its retry after the first stop fails. The fallback sidecar must make
8709        // the live-child result durable without an unbounded reap loop.
8710        processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
8711        processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
8712        processes.fail_next_post_spawn_stop();
8713        let failure = processes
8714            .spawn(&attempt, &EncodedJitConfig::new(JIT))
8715            .expect_err("the identity boundary must fail closed");
8716        assert!(failure.live_pid.is_some());
8717        assert_long_lived_listener_ready(&processes, &attempt);
8718        assert!(processes.is_alive(&attempt).unwrap());
8719        assert!(!NativeProcesses::identity_path(&attempt).exists());
8720        assert!(NativeProcesses::fallback_identity_path(&attempt).is_file());
8721        assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
8722        processes.terminate(&attempt).unwrap();
8723
8724        let runtime = root.path().join("persistent-stop-and-identity-failures");
8725        let bin = runtime.join("bin");
8726        fs::create_dir_all(&bin).unwrap();
8727        #[cfg(windows)]
8728        let listener = bin.join("Runner.Listener.exe");
8729        #[cfg(not(windows))]
8730        let listener = bin.join("Runner.Listener");
8731        fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
8732        let mut unresolved = RunnerAttempt::allocate(
8733            AttemptId::new_random(),
8734            policy.id,
8735            &runtime,
8736            FakeClock::default().now(),
8737        );
8738        for _ in 0..3 {
8739            processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
8740        }
8741        processes.fail_post_spawn_stops(MAX_POST_SPAWN_STOP_ATTEMPTS);
8742        let failure = processes
8743            .spawn(&unresolved, &EncodedJitConfig::new(JIT))
8744            .expect_err("bounded cleanup must return even when every stop errors");
8745        let pid = failure
8746            .live_pid
8747            .expect("the owned child remains supervised in this invocation");
8748        assert!(matches!(failure.reason, FailureReason::Other(_)));
8749        assert_long_lived_listener_ready(&processes, &unresolved);
8750        unresolved.jit_received(FakeClock::default().now()).unwrap();
8751        unresolved.started(pid, FakeClock::default().now()).unwrap();
8752        let journal = SqliteStore::open_in_memory().unwrap();
8753        journal.record_attempt(&unresolved).unwrap();
8754        let recovered = journal.attempt(unresolved.id).unwrap().unwrap();
8755        assert_eq!(recovered.process_id(), Some(pid));
8756        assert_eq!(recovered.state(), AttemptState::Starting);
8757        assert!(processes.is_alive(&unresolved).unwrap());
8758        assert!(!NativeProcesses::identity_path(&unresolved).exists());
8759        assert!(!NativeProcesses::fallback_identity_path(&unresolved).exists());
8760        assert_eq!(
8761            fs::read_to_string(NativeProcesses::unresolved_process_path(&unresolved)).unwrap(),
8762            pid.to_string(),
8763            "bounded cleanup must leave durable unresolved-process evidence before returning"
8764        );
8765        assert!(
8766            NativeProcesses::new().is_alive(&recovered).is_err(),
8767            "restart must fail closed on the durable starting/PID journal rather than trust a bare PID"
8768        );
8769        processes.terminate(&unresolved).unwrap();
8770
8771        let runtime = root.path().join("post-spawn-stop-failed");
8772        let bin = runtime.join("bin");
8773        fs::create_dir_all(&bin).unwrap();
8774        #[cfg(windows)]
8775        let listener = bin.join("Runner.Listener.exe");
8776        #[cfg(not(windows))]
8777        let listener = bin.join("Runner.Listener");
8778        fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
8779        let attempt = RunnerAttempt::allocate(
8780            AttemptId::new_random(),
8781            policy.id,
8782            &runtime,
8783            FakeClock::default().now(),
8784        );
8785        processes.fail_post_spawn_at(PostSpawnBoundary::ChildMapInsert);
8786        processes.fail_next_post_spawn_stop();
8787        let failure = processes
8788            .spawn(&attempt, &EncodedJitConfig::new(JIT))
8789            .expect_err("the injected stop failure must preserve supervision");
8790        let live_pid = failure
8791            .live_pid
8792            .expect("live PID is returned to the journal");
8793        assert!(!failure.retryable);
8794        assert_long_lived_listener_ready(&processes, &attempt);
8795        assert!(NativeProcesses::identity_path(&attempt).is_file());
8796        assert_eq!(
8797            NativeProcesses::read_identity(&attempt)
8798                .unwrap()
8799                .unwrap()
8800                .pid(),
8801            live_pid
8802        );
8803        assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
8804        processes.terminate(&attempt).unwrap();
8805    }
8806
8807    #[test]
8808    #[ignore = "spawned only as the platform-stable native listener fixture"]
8809    fn long_lived_native_listener_helper() {
8810        let ready = std::env::var_os("RUNNER_MANAGER_TEST_LISTENER_READY")
8811            .map(PathBuf::from)
8812            .expect("the parent supplies the readiness path");
8813        fs::write(ready, b"ready\n").expect("the listener publishes readiness");
8814        std::thread::sleep(Duration::from_secs(30));
8815    }
8816
8817    fn assert_long_lived_listener_ready(processes: &NativeProcesses, attempt: &RunnerAttempt) {
8818        let ready = attempt.runtime_path().join(TEST_LISTENER_READY);
8819        let deadline = std::time::Instant::now() + Duration::from_secs(5);
8820        loop {
8821            if ready.is_file() {
8822                assert_eq!(fs::read(&ready).unwrap(), b"ready\n");
8823                return;
8824            }
8825            assert!(
8826                processes.is_alive(attempt).unwrap(),
8827                "the native listener exited before publishing readiness"
8828            );
8829            assert!(
8830                std::time::Instant::now() < deadline,
8831                "the native listener stayed alive but never published readiness"
8832            );
8833            std::thread::sleep(Duration::from_millis(10));
8834        }
8835    }
8836
8837    #[tokio::test]
8838    async fn every_production_launch_prunes_under_the_same_allocation_guard() {
8839        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8840        harness.ready().await;
8841        assert_eq!(harness.packages.prunes.load(Ordering::SeqCst), 0);
8842        harness.launch().await;
8843        assert_eq!(harness.packages.prunes.load(Ordering::SeqCst), 1);
8844        assert_eq!(
8845            *harness.packages.prune_currents.lock().unwrap(),
8846            vec![harness.packages.version.clone()],
8847            "the leased current version is an exclusion, never the prune target"
8848        );
8849    }
8850
8851    fn assert_no_jit_file(runtime: &Path) {
8852        for entry in fs::read_dir(runtime).unwrap() {
8853            let path = entry.unwrap().path();
8854            if path.is_file() {
8855                let bytes = fs::read(&path).unwrap();
8856                assert!(
8857                    !bytes
8858                        .windows(JIT.len())
8859                        .any(|window| window == JIT.as_bytes()),
8860                    "a JIT payload survived in a runtime file"
8861                );
8862            }
8863        }
8864    }
8865
8866    #[test]
8867    fn production_listener_command_uses_the_supported_jit_contract() {
8868        let runtime = Path::new("runtime");
8869        let spec = runner_listener_spec(
8870            PathBuf::from("Runner.Listener"),
8871            runtime,
8872            Vec::new(),
8873            &RunnerEnv::default(),
8874        );
8875        let arguments: Vec<_> = spec
8876            .arguments()
8877            .iter()
8878            .map(|argument| argument.to_string_lossy().into_owned())
8879            .collect();
8880
8881        assert_eq!(arguments, ["run"]);
8882        assert!(
8883            !arguments
8884                .iter()
8885                .any(|argument| argument == "--jit-config-file"),
8886            "the obsolete file option would be rejected by Runner.Listener 2.336.0"
8887        );
8888    }
8889
8890    /// What a production runner starts with: the platform defaults, the host's
8891    /// `runner.env` over them, the attempt's own temporary directory, and
8892    /// normal scheduling.
8893    #[test]
8894    fn production_listener_layers_runner_env_over_the_platform_defaults() {
8895        let root = tempfile::tempdir().unwrap();
8896        let runtime = root.path().join("attempt");
8897        let host_env =
8898            RunnerEnv::parse("ELECTRON_CACHE=/cache/electron\nHOME=/operator/chose/this\n")
8899                .unwrap();
8900        let caches = vec![
8901            (
8902                "ELECTRON_CACHE",
8903                std::ffi::OsString::from("/rman/_cache/o/r/electron"),
8904            ),
8905            (
8906                "npm_config_cache",
8907                std::ffi::OsString::from("/rman/_cache/o/r/npm"),
8908            ),
8909        ];
8910        let spec = runner_listener_spec(
8911            PathBuf::from("Runner.Listener"),
8912            &runtime,
8913            caches,
8914            &host_env,
8915        );
8916        let env = |name: &str| spec.configured_env(name).map(PathBuf::from);
8917
8918        assert!(spec.expects_normal_scheduling());
8919        assert_eq!(
8920            env("ELECTRON_CACHE"),
8921            Some(PathBuf::from("/cache/electron")),
8922            "runner.env must win over a dependency cache of the same name"
8923        );
8924        assert_eq!(
8925            env("npm_config_cache"),
8926            Some(PathBuf::from("/rman/_cache/o/r/npm"))
8927        );
8928        assert_eq!(
8929            env("HOME"),
8930            Some(PathBuf::from("/operator/chose/this")),
8931            "runner.env must win over a platform default of the same name"
8932        );
8933        for tmp in ["TMPDIR", "TEMP", "TMP"] {
8934            assert_eq!(env(tmp), Some(runtime.join("tmp")), "{tmp}");
8935        }
8936
8937        let home = runtime.join(runner_env::RUNNER_HOME_DIR);
8938        if cfg!(windows) {
8939            // Each runner's own profile, created inside its attempt, so that
8940            // concurrent jobs stop sharing the service account's.
8941            assert_eq!(env("USERPROFILE"), Some(home.clone()));
8942            assert_eq!(env("APPDATA"), Some(home.join(r"AppData\Roaming")));
8943            assert_eq!(env("LOCALAPPDATA"), Some(home.join(r"AppData\Local")));
8944            assert!(home.join(r"AppData\Roaming").is_dir());
8945            assert!(home.join(r"AppData\Local").is_dir());
8946        } else {
8947            // Unix keeps the account's own profile.
8948            assert_eq!(env("USERPROFILE"), None);
8949            assert!(!home.exists());
8950        }
8951    }
8952
8953    /// Every step shell a runner starts inherits PowerShell's telemetry
8954    /// opt-out from the listener, unless the daemon or `runner.env` decided
8955    /// otherwise; see [`runner_env::POWERSHELL_TELEMETRY_OPTOUT`].
8956    #[test]
8957    fn production_listener_opts_powershell_out_of_telemetry() {
8958        let root = tempfile::tempdir().unwrap();
8959        let runtime = root.path().join("attempt");
8960        let listener = |host_env: &RunnerEnv| {
8961            runner_listener_spec(
8962                PathBuf::from("Runner.Listener"),
8963                &runtime,
8964                Vec::new(),
8965                host_env,
8966            )
8967        };
8968        let optout = |spec: &SpawnSpec| {
8969            spec.configured_env(runner_env::POWERSHELL_TELEMETRY_OPTOUT)
8970                .map(OsStr::to_os_string)
8971        };
8972
8973        let spec = listener(&RunnerEnv::default());
8974        if std::env::var_os(runner_env::POWERSHELL_TELEMETRY_OPTOUT)
8975            .is_some_and(|value| !value.is_empty())
8976        {
8977            // The daemon's own value is inherited as it is.
8978            assert_eq!(optout(&spec), None);
8979        } else {
8980            assert_eq!(
8981                optout(&spec),
8982                Some(runner_env::POWERSHELL_TELEMETRY_OPTOUT_VALUE.into())
8983            );
8984        }
8985
8986        let operator = RunnerEnv::parse("POWERSHELL_TELEMETRY_OPTOUT=0\n").unwrap();
8987        assert_eq!(
8988            optout(&listener(&operator)),
8989            Some("0".into()),
8990            "runner.env must win over the telemetry opt-out"
8991        );
8992    }
8993
8994    #[test]
8995    fn an_invalid_runner_env_fails_the_launch_without_echoing_a_value() {
8996        let root = tempfile::tempdir().unwrap();
8997        let path = runner_env::path_in(root.path());
8998        fs::write(&path, "GOOD=1\nghp_notarealtokenbutshapedlikeone\n").unwrap();
8999        let processes = NativeProcesses::new().with_runner_env_file(path.clone());
9000        let failure = processes.host_env().unwrap_err().to_string();
9001        assert!(
9002            failure.contains("runner.env") && failure.contains("line 2"),
9003            "{failure}"
9004        );
9005        assert!(
9006            !failure.contains("ghp_"),
9007            "the failure echoed a value: {failure}"
9008        );
9009
9010        // `prepare` runs before the JIT registration, so a broken file is
9011        // refused there, before GitHub is asked for anything.
9012        let policy = fixtures::policy()
9013            .repository("octo/repo")
9014            .autoscale("home", 1)
9015            .active()
9016            .build();
9017        let attempt = RunnerAttempt::allocate(
9018            AttemptId::new_random(),
9019            policy.id,
9020            root.path(),
9021            FakeClock::default().now(),
9022        );
9023        assert!(processes.prepare(&attempt, &policy).is_err());
9024
9025        fs::write(&path, "GOOD=1\n").unwrap();
9026        assert!(processes.prepare(&attempt, &policy).is_ok());
9027        assert_eq!(processes.host_env().unwrap().get("GOOD"), Some("1"));
9028        assert!(NativeProcesses::new().host_env().unwrap().is_empty());
9029    }
9030
9031    /// The wiring from `prepare` (which sees the policy) to `spawn` (which
9032    /// does not): the policy's repository decides the namespace, and a broken
9033    /// `caches.toml` is refused before GitHub is asked for anything.
9034    #[test]
9035    fn prepare_hands_the_policys_cache_namespace_to_the_launch() {
9036        let root = tempfile::tempdir().unwrap();
9037        let runner_root = root.path().join("rman");
9038        let runtime = runner_root.join("a1");
9039        fs::create_dir_all(runtime.join("bin")).unwrap();
9040        let config = runner_manager_platform::dependency_cache::config_path_in(root.path());
9041        let source_root = runner_root.clone();
9042        let processes = NativeProcesses::new().with_dependency_caches(DependencyCaches::new(
9043            config.clone(),
9044            Arc::new(move || Some(source_root.clone())),
9045            None,
9046        ));
9047        let policy = fixtures::policy()
9048            .repository("Octo/Repo")
9049            .autoscale("home", 1)
9050            .active()
9051            .build();
9052        let attempt = RunnerAttempt::allocate(
9053            AttemptId::new_random(),
9054            policy.id,
9055            &runtime,
9056            FakeClock::default().now(),
9057        );
9058        assert!(
9059            processes
9060                .cache_env(&attempt, None, &RunnerEnv::default())
9061                .is_empty(),
9062            "a launch with no prepared target, such as a bare `spawn`, has no cache"
9063        );
9064        let prepared = processes.prepare(&attempt, &policy).unwrap();
9065        let variables = processes.cache_env(
9066            &attempt,
9067            prepared.cache_target.as_ref(),
9068            &RunnerEnv::default(),
9069        );
9070        let npm = variables
9071            .iter()
9072            .find(|(name, _)| *name == "npm_config_cache")
9073            .map(|(_, value)| PathBuf::from(value));
9074        assert_eq!(
9075            npm,
9076            Some(
9077                runner_root
9078                    .join("_cache")
9079                    .join("octo")
9080                    .join("repo")
9081                    .join("npm")
9082            )
9083        );
9084
9085        fs::write(&config, "[tools]\nnot-a-tool = true\n").unwrap();
9086        let refused = processes
9087            .prepare(&attempt, &policy)
9088            .unwrap_err()
9089            .to_string();
9090        assert!(refused.contains("caches.toml"), "{refused}");
9091    }
9092
9093    #[cfg(windows)]
9094    fn native_inspection_spec() -> SpawnSpec {
9095        SpawnSpec::new("powershell.exe").args([
9096            "-NoProfile",
9097            "-NonInteractive",
9098            "-Command",
9099            "Start-Sleep -Seconds 30",
9100        ])
9101    }
9102
9103    #[cfg(unix)]
9104    fn native_inspection_spec() -> SpawnSpec {
9105        SpawnSpec::new("/bin/sh").args(["-c", "sleep 30"])
9106    }
9107
9108    #[cfg(windows)]
9109    fn native_command_line(pid: u32) -> String {
9110        let output = std::process::Command::new("powershell.exe")
9111            .args([
9112                "-NoProfile",
9113                "-NonInteractive",
9114                "-Command",
9115                &format!("(Get-CimInstance Win32_Process -Filter 'ProcessId = {pid}').CommandLine"),
9116            ])
9117            .output()
9118            .expect("PowerShell can inspect the native child");
9119        assert!(output.status.success(), "native process inspection failed");
9120        String::from_utf8(output.stdout).expect("Windows command lines are Unicode")
9121    }
9122
9123    #[cfg(target_os = "linux")]
9124    fn native_command_line(pid: u32) -> String {
9125        fs::read(format!("/proc/{pid}/cmdline"))
9126            .map(|bytes| String::from_utf8_lossy(&bytes).replace('\0', " "))
9127            .expect("/proc exposes the native child command line")
9128    }
9129
9130    #[cfg(target_os = "macos")]
9131    fn native_command_line(pid: u32) -> String {
9132        let output = std::process::Command::new("ps")
9133            .args(["-o", "command=", "-p", &pid.to_string()])
9134            .output()
9135            .expect("ps can inspect the native child");
9136        assert!(output.status.success(), "native process inspection failed");
9137        String::from_utf8(output.stdout).expect("the command line is UTF-8")
9138    }
9139
9140    // -- c2: persistent slot allocation -------------------------------------
9141
9142    #[tokio::test]
9143    async fn a_persistent_repository_leases_s1_and_journals_it_before_any_github_effect() {
9144        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9145            .with_persistent_workspace(2);
9146        harness.github.watch_journal(Arc::clone(&harness.store));
9147        harness.ready().await;
9148
9149        let attempt = harness.launch().await;
9150
9151        assert_eq!(
9152            attempt.workspace(),
9153            AttemptWorkspace::persistent_slot(nz(1)),
9154            "the lowest free slot is leased"
9155        );
9156        assert_eq!(attempt.runtime_path(), harness.slot_path(1));
9157        assert!(attempt.holds_slot_lease());
9158        // The exact runtime path is journalled, not re-derived later.
9159        assert_eq!(
9160            harness.attempt(attempt.id).runtime_path(),
9161            harness.slot_path(1)
9162        );
9163
9164        // Step 7 of "Slot allocation": the lease exists before GitHub is asked
9165        // for anything, and the runner's work folder stays the relative `_work`
9166        // the slot root is laid out around.
9167        let facts = harness.github.registration_facts();
9168        assert_eq!(facts.len(), 1);
9169        assert_eq!(
9170            facts[0].leased_slots,
9171            vec![1],
9172            "the lease was journalled first"
9173        );
9174        assert_eq!(facts[0].work_folder, DEFAULT_WORK_FOLDER);
9175    }
9176
9177    #[tokio::test]
9178    async fn a_terminal_but_uncleaned_attempt_keeps_its_slot_without_holding_capacity() {
9179        let harness = Harness::new(
9180            FakeGithubLifecycle::default().fail(true),
9181            Arc::new(PersistentDemand),
9182        )
9183        .with_persistent_workspace(2);
9184        harness.ready().await;
9185
9186        // A terminal JIT refusal concludes the attempt without cleaning it.
9187        harness.launch_result().await.unwrap_err();
9188        let first = harness.store.attempts().unwrap().remove(0);
9189        assert_eq!(first.state(), AttemptState::Failed);
9190        assert!(
9191            !first.state().counts_against_capacity(),
9192            "a concluded attempt is invisible to host capacity"
9193        );
9194        assert!(
9195            first.holds_slot_lease(),
9196            "and still owns its directory, so its slot is not free"
9197        );
9198
9199        let second = harness.launch().await;
9200        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
9201        assert_eq!(second.runtime_path(), harness.slot_path(2));
9202        assert_eq!(
9203            harness
9204                .store
9205                .slot_leases_for_policy(harness.policy.id)
9206                .unwrap()
9207                .len(),
9208            2
9209        );
9210    }
9211
9212    #[tokio::test]
9213    async fn two_sequential_allocations_at_capacity_one_reuse_s1_and_its_retained_work() {
9214        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9215            .with_persistent_workspace(1);
9216        harness.ready().await;
9217
9218        let first = harness.launch().await;
9219        assert_eq!(first.runtime_path(), harness.slot_path(1));
9220
9221        // What a job leaves behind, at the path the runner writes it to.
9222        let checkout = harness.slot_path(1).join(DEFAULT_WORK_FOLDER).join("repo");
9223        fs::create_dir_all(&checkout).unwrap();
9224        fs::write(checkout.join("checkout.txt"), b"from the first job").unwrap();
9225
9226        harness.cleanup_retaining_work(first.id).await;
9227
9228        let second = harness.launch().await;
9229        assert_ne!(second.id, first.id);
9230        assert_eq!(
9231            second.workspace(),
9232            AttemptWorkspace::persistent_slot(nz(1)),
9233            "a released slot is leased again rather than skipped"
9234        );
9235        assert_eq!(
9236            second.runtime_path(),
9237            first.runtime_path(),
9238            "the same slot is the same exact path"
9239        );
9240        assert_eq!(
9241            fs::read_to_string(checkout.join("checkout.txt")).unwrap(),
9242            "from the first job",
9243            "the retained job workspace survived the second allocation"
9244        );
9245        // The attempt's own runner material was recreated for this attempt.
9246        assert!(harness.slot_path(1).join("runner-package").exists());
9247    }
9248
9249    #[tokio::test]
9250    async fn lowering_capacity_leaves_higher_slots_alone_and_raising_it_permits_them_again() {
9251        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9252            .with_persistent_workspace(2);
9253        harness.ready().await;
9254
9255        let first = harness.launch().await;
9256        let second = harness.launch().await;
9257        assert_eq!(second.runtime_path(), harness.slot_path(2));
9258        let kept = harness
9259            .slot_path(2)
9260            .join(DEFAULT_WORK_FOLDER)
9261            .join("kept.txt");
9262        fs::create_dir_all(kept.parent().unwrap()).unwrap();
9263        fs::write(&kept, b"s2 was here").unwrap();
9264        harness.cleanup_retaining_work(second.id).await;
9265
9266        // The operator lowers the ceiling while s1 is still leased.
9267        harness.policy.set_max_capacity(nz(1)).unwrap();
9268        let refusal = harness.launch_result().await.unwrap_err().to_string();
9269        assert!(
9270            refusal.contains("s1 to s1"),
9271            "the refusal names the ceiling it reached: {refusal}"
9272        );
9273        assert!(
9274            harness.slot_path(2).exists() && kept.exists(),
9275            "lowering capacity deletes nothing; the higher slot is merely unusable"
9276        );
9277
9278        // Raising it again makes the free higher slot available.
9279        harness.policy.set_max_capacity(nz(2)).unwrap();
9280        let third = harness.launch().await;
9281        assert_eq!(third.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
9282        assert_eq!(third.runtime_path(), harness.slot_path(2));
9283        assert_eq!(fs::read_to_string(&kept).unwrap(), "s2 was here");
9284        assert!(first.holds_slot_lease(), "s1 was never disturbed");
9285    }
9286
9287    #[tokio::test]
9288    async fn organization_and_ephemeral_policies_never_enter_slot_allocation() {
9289        for policy in [
9290            fixtures::policy()
9291                .organization("octo")
9292                .autoscale("home", 2)
9293                .active()
9294                .build(),
9295            fixtures::policy()
9296                .repository("octo/repo")
9297                .autoscale("home", 2)
9298                .active()
9299                .build(),
9300        ] {
9301            let mut harness =
9302                Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9303                    .with_host_runner_root();
9304            assert_eq!(policy.workspace_policy(), &WorkspacePolicy::Ephemeral);
9305            harness.policy = policy;
9306            harness.ready().await;
9307
9308            let attempt = harness.launch().await;
9309            assert_eq!(attempt.workspace(), AttemptWorkspace::Ephemeral);
9310            assert_eq!(attempt.workspace().slot_number(), None);
9311            assert!(!attempt.holds_slot_lease());
9312            assert_eq!(
9313                attempt.runtime_path().parent().unwrap(),
9314                harness.host_root(),
9315                "a disposable attempt is a child of the host root, never of a slot"
9316            );
9317            assert!(
9318                harness
9319                    .store
9320                    .slot_leases_for_policy(harness.policy.id)
9321                    .unwrap()
9322                    .is_empty()
9323            );
9324        }
9325    }
9326
9327    #[tokio::test]
9328    async fn two_concurrent_allocations_never_share_a_slot() {
9329        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9330            .with_persistent_workspace(2);
9331        harness.github.watch_journal(Arc::clone(&harness.store));
9332        harness.ready().await;
9333
9334        // Both allocators race for the same host allocation lock, which is what
9335        // orders slot *selection*; each one then journals its lease before it
9336        // asks GitHub for anything.
9337        let (first, second) = tokio::join!(harness.launch_result(), harness.launch_result());
9338        let first = first.unwrap();
9339        let second = second.unwrap();
9340
9341        let slots: BTreeSet<u16> = [&first, &second]
9342            .iter()
9343            .map(|attempt| {
9344                attempt
9345                    .workspace()
9346                    .slot_number()
9347                    .expect("a persistent attempt leases a slot")
9348            })
9349            .collect();
9350        assert_eq!(slots, BTreeSet::from([1, 2]), "one slot each, never shared");
9351        assert_ne!(first.runtime_path(), second.runtime_path());
9352        assert_eq!(
9353            harness
9354                .store
9355                .slot_leases_for_policy(harness.policy.id)
9356                .unwrap()
9357                .len(),
9358            2
9359        );
9360
9361        // Every registration saw *its own* lease already in the journal. Reading
9362        // the whole journal and asking only that it be non-empty would pass on
9363        // the other allocator's lease, which is precisely the ordering bug this
9364        // test exists to exclude.
9365        let facts = harness.github.registration_facts();
9366        assert_eq!(facts.len(), 2);
9367        for fact in facts {
9368            let attempt = [&first, &second]
9369                .into_iter()
9370                .find(|attempt| runner_name(attempt.id) == fact.runner_name)
9371                .expect("every registration belongs to one of the two attempts");
9372            let slot = attempt
9373                .workspace()
9374                .slot_number()
9375                .expect("a persistent attempt leases a slot");
9376            assert!(
9377                fact.leased_slots.contains(&slot),
9378                "a JIT request never precedes its own lease: s{slot} not in {:?}",
9379                fact.leased_slots
9380            );
9381            assert_eq!(fact.work_folder, DEFAULT_WORK_FOLDER);
9382        }
9383    }
9384
9385    #[tokio::test]
9386    async fn the_database_is_the_final_fence_against_two_attempts_in_one_slot() {
9387        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9388            .with_persistent_workspace(2);
9389        harness.ready().await;
9390        let first = harness.launch().await;
9391
9392        // What a second allocator that lost the race would write: the lock
9393        // orders selection, and this index is what catches a writer the lock
9394        // could not see.
9395        let clash = RunnerAttempt::allocate_in(
9396            AttemptId::new_random(),
9397            harness.policy.id,
9398            first.runtime_path(),
9399            AttemptWorkspace::persistent_slot(nz(1)),
9400            harness.clock.now(),
9401        );
9402        assert!(matches!(
9403            harness.store.record_attempt(&clash).unwrap_err(),
9404            StoreError::SlotAlreadyLeased { slot: 1, .. }
9405        ));
9406
9407        // And the launcher reports it as itself rather than as a generic
9408        // journal failure, so the operator reads what actually happened.
9409        let error = harness.launcher.record_allocation(&clash).unwrap_err();
9410        let rendered = error.to_string();
9411        assert!(rendered.contains("slot s1"), "{rendered}");
9412        assert!(rendered.contains("nothing was written"), "{rendered}");
9413        assert_eq!(
9414            harness.store.attempts().unwrap().len(),
9415            1,
9416            "the losing allocator journalled nothing"
9417        );
9418    }
9419
9420    #[test]
9421    fn slot_selection_fills_the_lowest_gap_and_stops_at_the_ceiling() {
9422        let leased = |slots: &[u16]| -> Vec<RunnerAttempt> {
9423            slots
9424                .iter()
9425                .map(|slot| {
9426                    RunnerAttempt::allocate_in(
9427                        AttemptId::new_random(),
9428                        fixtures::POLICY_ID,
9429                        format!("/srv/rman/acme/s{slot}"),
9430                        AttemptWorkspace::persistent_slot(nz(*slot)),
9431                        fixtures::created_at(),
9432                    )
9433                })
9434                .collect()
9435        };
9436
9437        assert_eq!(lowest_free_slot(&[], nz(1)), Some(nz(1)));
9438        assert_eq!(lowest_free_slot(&leased(&[1]), nz(4)), Some(nz(2)));
9439        // The gap a released middle slot leaves is filled before the tail.
9440        assert_eq!(lowest_free_slot(&leased(&[1, 3]), nz(4)), Some(nz(2)));
9441        // The ceiling is a refusal, never a reason to allocate past it.
9442        assert_eq!(lowest_free_slot(&leased(&[1]), nz(1)), None);
9443        assert_eq!(lowest_free_slot(&leased(&[1, 2]), nz(2)), None);
9444        // An ephemeral attempt holds no slot and cannot block one.
9445        let ephemeral = vec![RunnerAttempt::allocate(
9446            AttemptId::new_random(),
9447            fixtures::POLICY_ID,
9448            "/srv/rman/host/abc",
9449            fixtures::created_at(),
9450        )];
9451        assert_eq!(lowest_free_slot(&ephemeral, nz(1)), Some(nz(1)));
9452    }
9453
9454    #[test]
9455    fn a_slot_is_reusable_only_when_it_is_empty_or_holds_one_real_work_directory() {
9456        let root = tempfile::tempdir().unwrap();
9457        let slot = root.path().join("s1");
9458        fs::create_dir(&slot).unwrap();
9459        accept_reusable_slot(&slot).expect("an empty slot is reusable");
9460
9461        fs::create_dir(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
9462        accept_reusable_slot(&slot).expect("a retained job workspace is reusable");
9463
9464        // Runner material a previous attempt left behind is refused rather than
9465        // reused or removed: deciding those bytes are safe is cleanup's job.
9466        fs::create_dir(slot.join("bin")).unwrap();
9467        fs::write(slot.join(".github-runner-id"), b"73").unwrap();
9468        let refusal = accept_reusable_slot(&slot).unwrap_err().to_string();
9469        assert!(refusal.contains("bin"), "{refusal}");
9470        assert!(refusal.contains(".github-runner-id"), "{refusal}");
9471
9472        // A `_work` that is not a real directory is not a job workspace.
9473        let file_work = root.path().join("s2");
9474        fs::create_dir(&file_work).unwrap();
9475        fs::write(file_work.join(DEFAULT_WORK_FOLDER), b"not a directory").unwrap();
9476        assert!(accept_reusable_slot(&file_work).is_err());
9477    }
9478
9479    #[cfg(unix)]
9480    #[test]
9481    fn a_link_shaped_work_directory_is_refused_rather_than_followed() {
9482        // Windows needs a privilege to create either kind of link, so the
9483        // link-shaped cases are asserted here; the rule itself is
9484        // platform-independent because it is `symlink_metadata`'s answer.
9485        let root = tempfile::tempdir().unwrap();
9486        let elsewhere = root.path().join("elsewhere");
9487        fs::create_dir(&elsewhere).unwrap();
9488
9489        let slot = root.path().join("s1");
9490        fs::create_dir(&slot).unwrap();
9491        std::os::unix::fs::symlink(&elsewhere, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
9492        assert!(accept_reusable_slot(&slot).is_err());
9493
9494        let linked_slot = root.path().join("s2");
9495        std::os::unix::fs::symlink(&elsewhere, &linked_slot).unwrap();
9496        assert!(create_or_validate_slot(&linked_slot).is_err());
9497    }
9498
9499    #[test]
9500    fn a_slot_standing_where_a_file_is_refuses_rather_than_replacing_it() {
9501        let root = tempfile::tempdir().unwrap();
9502        let occupied = root.path().join("s1");
9503        fs::write(&occupied, b"an operator's file").unwrap();
9504        let refusal = create_or_validate_slot(&occupied).unwrap_err().to_string();
9505        assert!(refusal.contains("is not a directory"), "{refusal}");
9506        assert_eq!(fs::read_to_string(&occupied).unwrap(), "an operator's file");
9507
9508        let fresh = root.path().join("s2");
9509        create_or_validate_slot(&fresh).expect("a missing slot is created");
9510        assert!(fresh.is_dir());
9511        create_or_validate_slot(&fresh).expect("an existing directory is accepted");
9512    }
9513
9514    #[test]
9515    fn the_retained_work_directory_is_matched_the_way_the_filesystem_matches_it() {
9516        assert!(is_work_folder(OsStr::new(DEFAULT_WORK_FOLDER)));
9517        assert!(!is_work_folder(OsStr::new("_work2")));
9518        // A Windows filesystem is case-insensitive, so `_Work` *is* the retained
9519        // job workspace there and must never be removed as a leftover; on a
9520        // case-sensitive filesystem it is a different directory entirely.
9521        assert_eq!(is_work_folder(OsStr::new("_Work")), cfg!(windows));
9522    }
9523
9524    #[test]
9525    fn package_materialization_never_overwrites_or_follows_a_retained_work_directory() {
9526        let root = tempfile::tempdir().unwrap();
9527        let package = root.path().join("package");
9528        fs::create_dir_all(package.join("bin")).unwrap();
9529        fs::write(package.join("bin").join("Runner.Listener"), b"binary").unwrap();
9530        // A nested `_work` inside the package's own tree is an ordinary name.
9531        fs::create_dir_all(package.join("externals").join(DEFAULT_WORK_FOLDER)).unwrap();
9532
9533        let slot = root.path().join("s1");
9534        let retained = slot.join(DEFAULT_WORK_FOLDER).join("repo");
9535        fs::create_dir_all(&retained).unwrap();
9536        fs::write(retained.join("checkout.txt"), b"from the first job").unwrap();
9537
9538        copy_package_tree(&package, &slot, &TrustedTrees::default())
9539            .expect("the package lays out around `_work`");
9540        assert!(slot.join("bin").join("Runner.Listener").exists());
9541        assert!(
9542            slot.join("externals").join(DEFAULT_WORK_FOLDER).is_dir(),
9543            "the guard is top-level only"
9544        );
9545        assert_eq!(
9546            fs::read_to_string(retained.join("checkout.txt")).unwrap(),
9547            "from the first job"
9548        );
9549
9550        // A package that ever grew a top-level `_work` is refused, not merged.
9551        fs::create_dir(package.join(DEFAULT_WORK_FOLDER)).unwrap();
9552        let error = copy_package_tree(&package, &slot, &TrustedTrees::default()).unwrap_err();
9553        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
9554        assert_eq!(
9555            fs::read_to_string(retained.join("checkout.txt")).unwrap(),
9556            "from the first job"
9557        );
9558    }
9559
9560    #[test]
9561    fn rolling_back_a_materialization_keeps_a_slot_but_removes_a_disposable_directory() {
9562        let root = tempfile::tempdir().unwrap();
9563
9564        let slot = root.path().join("s1");
9565        let retained = slot.join(DEFAULT_WORK_FOLDER);
9566        fs::create_dir_all(retained.join("repo")).unwrap();
9567        fs::write(retained.join("repo").join("checkout.txt"), b"kept").unwrap();
9568        fs::create_dir_all(slot.join("bin")).unwrap();
9569        fs::write(slot.join(".github-runner-id"), b"73").unwrap();
9570        let persistent = RunnerAttempt::allocate_in(
9571            AttemptId::new_random(),
9572            fixtures::POLICY_ID,
9573            &slot,
9574            AttemptWorkspace::persistent_slot(nz(1)),
9575            fixtures::created_at(),
9576        );
9577
9578        remove_materialized_package(&persistent).unwrap();
9579        assert!(slot.is_dir(), "the slot itself is not removed");
9580        assert!(!slot.join("bin").exists());
9581        assert!(!slot.join(".github-runner-id").exists());
9582        assert_eq!(
9583            fs::read_to_string(retained.join("repo").join("checkout.txt")).unwrap(),
9584            "kept"
9585        );
9586
9587        let disposable_path = root.path().join("abcdef012345");
9588        fs::create_dir_all(disposable_path.join(DEFAULT_WORK_FOLDER)).unwrap();
9589        let disposable = RunnerAttempt::allocate(
9590            AttemptId::new_random(),
9591            fixtures::POLICY_ID,
9592            &disposable_path,
9593            fixtures::created_at(),
9594        );
9595        remove_materialized_package(&disposable).unwrap();
9596        assert!(
9597            !disposable_path.exists(),
9598            "a disposable directory is still removed whole"
9599        );
9600    }
9601
9602    // -- c3: persistent cleanup and recovery --------------------------------
9603
9604    /// The runner state one attempt leaves at a slot root, as a real attempt
9605    /// leaves it: binaries, registration identity, a JIT handoff that outlived
9606    /// its process, and this agent's own lifecycle sidecars.
9607    ///
9608    /// Driven by [`SENSITIVE_SLOT_ENTRIES`] rather than by a second copy of it,
9609    /// so a name added to the thing cleanup must prove absent is a name every
9610    /// test here starts leaving behind.
9611    fn litter_the_slot(slot: &Path) {
9612        for directory in ["bin", "externals", "_diag"] {
9613            fs::create_dir_all(slot.join(directory)).unwrap();
9614        }
9615        fs::write(slot.join("bin").join("Runner.Listener"), b"binary").unwrap();
9616        for file in SENSITIVE_SLOT_ENTRIES
9617            .iter()
9618            .filter(|entry| !slot.join(entry).is_dir())
9619        {
9620            fs::write(slot.join(file), b"runner state").unwrap();
9621        }
9622        // A handoff whose owning process died before `Drop` could delete it.
9623        fs::write(
9624            slot.join(format!(
9625                "{}0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0.tmp",
9626                RestrictiveHandoff::NAME_PREFIX
9627            )),
9628            JIT.as_bytes(),
9629        )
9630        .unwrap();
9631    }
9632
9633    /// A marker under `_work` of the kind a job leaves for the next one.
9634    fn retain_under_work(slot: &Path) -> PathBuf {
9635        let checkout = slot.join(DEFAULT_WORK_FOLDER).join("repo").join("target");
9636        fs::create_dir_all(&checkout).unwrap();
9637        let marker = checkout.join("build-output.bin");
9638        fs::write(&marker, RETAINED).unwrap();
9639        marker
9640    }
9641
9642    /// What a job leaves under `_work` for the next job to reuse.
9643    const RETAINED: &str = "a Git-ignored build output the next job reuses";
9644
9645    /// Every direct entry of a directory, sorted, as plain strings.
9646    fn entries_of(directory: &Path) -> Vec<String> {
9647        let mut names: Vec<String> = fs::read_dir(directory)
9648            .unwrap()
9649            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
9650            .collect();
9651        names.sort();
9652        names
9653    }
9654
9655    /// The one entry a cleaned slot is allowed to hold.
9656    fn only_the_job_workspace() -> Vec<String> {
9657        vec![DEFAULT_WORK_FOLDER.to_owned()]
9658    }
9659
9660    #[cfg(unix)]
9661    #[test]
9662    fn disposable_tree_removal_does_not_open_a_dotnet_diagnostic_fifo() {
9663        use std::sync::mpsc;
9664
9665        let temporary = tempfile::tempdir().unwrap();
9666        let tree = temporary.path().join("attempt");
9667        let diagnostic = tree.join("tmp/clr-debug-pipe-runner-in");
9668        fs::create_dir_all(diagnostic.parent().unwrap()).unwrap();
9669        assert!(
9670            std::process::Command::new("mkfifo")
9671                .arg(&diagnostic)
9672                .status()
9673                .unwrap()
9674                .success()
9675        );
9676
9677        let (finished, result) = mpsc::channel();
9678        std::thread::spawn(move || {
9679            let removed = remove_runtime_tree(&tree);
9680            let _ = finished.send(removed);
9681        });
9682
9683        result
9684            .recv_timeout(Duration::from_secs(2))
9685            .expect("runtime deletion must not wait for a FIFO peer")
9686            .unwrap();
9687        assert!(!diagnostic.exists());
9688    }
9689
9690    /// The junction WinINet leaves in a job's profile, reproduced: its own DACL
9691    /// denies `Everyone` the right to list it.
9692    #[cfg(windows)]
9693    #[test]
9694    fn disposable_tree_removal_unlinks_a_junction_nobody_may_list() {
9695        let temporary = tempfile::tempdir().unwrap();
9696        let tree = temporary.path().join("attempt");
9697        let cache = tree.join(r"tmp\home\AppData\Local\Microsoft\Windows\INetCache");
9698        let outside = temporary.path().join("outside");
9699        fs::create_dir_all(&cache).unwrap();
9700        fs::create_dir_all(&outside).unwrap();
9701        fs::write(outside.join("keep.txt"), b"not the attempt's").unwrap();
9702        fs::write(tree.join("tmp").join("job.log"), b"job output").unwrap();
9703        let junction = cache.join("Content.IE5");
9704        let created = std::process::Command::new("cmd")
9705            .arg("/C")
9706            .arg("mklink")
9707            .arg("/J")
9708            .arg(&junction)
9709            .arg(&outside)
9710            .output()
9711            .unwrap();
9712        assert!(created.status.success(), "{created:?}");
9713        // `/L` puts the entry on the junction itself, as WinINet does, rather
9714        // than on the directory it points at. `*S-1-1-0` is `Everyone` in every
9715        // display language.
9716        let denied = std::process::Command::new("icacls")
9717            .arg(&junction)
9718            .args(["/L", "/deny", "*S-1-1-0:(RD)"])
9719            .output()
9720            .unwrap();
9721        assert!(denied.status.success(), "{denied:?}");
9722
9723        // The control: without the fix the tree cannot be removed at all.
9724        let unfixed = remove_dir_all::remove_dir_all(&tree)
9725            .expect_err("the fixture no longer reproduces the WinINet junction");
9726        assert_eq!(unfixed.kind(), std::io::ErrorKind::PermissionDenied);
9727        assert!(junction.symlink_metadata().is_ok());
9728
9729        remove_runtime_tree(&tree).expect("a tree holding a deny-list junction is removed");
9730        assert!(!tree.exists(), "the attempt tree survived");
9731        assert_eq!(
9732            fs::read(outside.join("keep.txt")).unwrap(),
9733            b"not the attempt's",
9734            "removing the junction followed it into the directory it points at"
9735        );
9736    }
9737
9738    /// One slot entry that refuses to be removed, and the undo that lets the
9739    /// temporary directory be torn down afterwards.
9740    ///
9741    /// The two operating systems refuse for different reasons and there is no
9742    /// portable third. Windows will not open a file for deletion while a handle
9743    /// with share mode zero is held on it; Unix will not unlink from a directory
9744    /// the caller cannot write. Both are states a real machine reaches -- a
9745    /// scanner holding a file open, a job that left a directory read-only -- so
9746    /// the injection is a filesystem fact rather than a seam cut into the
9747    /// product for a test to pull.
9748    ///
9749    /// The Unix half is a permission, and permissions do not apply to `root`.
9750    /// [`Self::inject`] proves the block on a throwaway directory before
9751    /// claiming it, so a suite running as `root` says it could not inject rather
9752    /// than asserting nothing and passing.
9753    struct BlockedDeletion {
9754        directory: PathBuf,
9755        #[cfg(windows)]
9756        _handle: fs::File,
9757    }
9758
9759    impl BlockedDeletion {
9760        const HELD: &'static str = "held-open";
9761
9762        /// Fill `directory` with a file that cannot be removed, or answer `None`
9763        /// when this account cannot be stopped from removing anything.
9764        fn inject(directory: &Path) -> Option<Self> {
9765            #[cfg(unix)]
9766            if !Self::refusal_is_possible() {
9767                return None;
9768            }
9769            fs::create_dir_all(directory).unwrap();
9770            fs::write(
9771                directory.join(Self::HELD),
9772                b"a file the scrub cannot remove",
9773            )
9774            .unwrap();
9775            #[cfg(windows)]
9776            let handle = {
9777                use std::os::windows::fs::OpenOptionsExt;
9778
9779                fs::OpenOptions::new()
9780                    .read(true)
9781                    .share_mode(0)
9782                    .open(directory.join(Self::HELD))
9783                    .expect("the blocking handle opens")
9784            };
9785            #[cfg(unix)]
9786            Self::set_mode(directory, 0o555);
9787            Some(Self {
9788                directory: directory.to_path_buf(),
9789                #[cfg(windows)]
9790                _handle: handle,
9791            })
9792        }
9793
9794        fn release(self) {
9795            drop(self);
9796        }
9797
9798        #[cfg(unix)]
9799        fn refusal_is_possible() -> bool {
9800            let probe = tempfile::tempdir().unwrap();
9801            let directory = probe.path().join("probe");
9802            fs::create_dir(&directory).unwrap();
9803            fs::write(directory.join("file"), b"probe").unwrap();
9804            Self::set_mode(&directory, 0o555);
9805            let refused = fs::remove_dir_all(&directory).is_err();
9806            Self::set_mode(&directory, 0o755);
9807            refused
9808        }
9809
9810        #[cfg(unix)]
9811        fn set_mode(directory: &Path, mode: u32) {
9812            use std::os::unix::fs::PermissionsExt;
9813
9814            let mut permissions = fs::metadata(directory).unwrap().permissions();
9815            permissions.set_mode(mode);
9816            fs::set_permissions(directory, permissions).unwrap();
9817        }
9818    }
9819
9820    impl Drop for BlockedDeletion {
9821        fn drop(&mut self) {
9822            #[cfg(unix)]
9823            Self::set_mode(&self.directory, 0o755);
9824            #[cfg(not(unix))]
9825            let _ = &self.directory;
9826        }
9827    }
9828
9829    #[tokio::test]
9830    async fn two_sequential_jobs_keep_the_checkout_and_start_without_the_earlier_runner_state() {
9831        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9832            .with_persistent_workspace(1);
9833        harness.ready().await;
9834
9835        let first = harness.launch().await;
9836        let slot = harness.slot_path(1);
9837        assert_eq!(first.runtime_path(), slot);
9838        assert_eq!(
9839            read_runner_id(&slot),
9840            Some(73),
9841            "the attempt registered, so its identity is on disk"
9842        );
9843        let marker = retain_under_work(&slot);
9844        litter_the_slot(&slot);
9845
9846        harness.cleanup_retaining_work(first.id).await;
9847
9848        // The allowlist is exactly one entry, so this assertion is the security
9849        // property in full: what is retained, and that nothing else is.
9850        assert_eq!(entries_of(&slot), only_the_job_workspace());
9851        assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
9852        assert_eq!(
9853            read_runner_id(&slot),
9854            None,
9855            "the first attempt's registration identity is gone before the second starts"
9856        );
9857        assert_eq!(harness.attempt(first.id).state(), AttemptState::Cleaned);
9858        assert!(!harness.attempt(first.id).holds_slot_lease());
9859
9860        let second = harness.launch().await;
9861        assert_ne!(second.id, first.id);
9862        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(1)));
9863        assert_eq!(
9864            second.runtime_path(),
9865            slot,
9866            "the same slot, so the same retained `_work`"
9867        );
9868        assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
9869    }
9870
9871    #[tokio::test]
9872    async fn cleaning_a_persistent_slot_needs_no_policy_and_scans_no_directory_for_ownership() {
9873        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9874            .with_persistent_workspace(1);
9875        harness.ready().await;
9876        let attempt = harness.launch().await;
9877        let slot = harness.slot_path(1);
9878        let marker = retain_under_work(&slot);
9879        litter_the_slot(&slot);
9880        harness.conclude(attempt.id);
9881
9882        // A repository removed from the product between the attempt concluding
9883        // and the sweep reaching it. The journalled runtime path and slot are
9884        // the only facts left, and `04-security-recovery.md` requires them to be
9885        // enough: the alternative is scanning a root to work out which
9886        // directories were ours, which invariant 6 forbids.
9887        harness
9888            .store
9889            .remove_policy(harness.policy.id, harness.policy.revision())
9890            .unwrap();
9891        assert!(harness.store.policy(harness.policy.id).unwrap().is_none());
9892
9893        harness
9894            .launcher
9895            .clean(attempt.id)
9896            .await
9897            .expect("journal facts alone are enough to clean the slot");
9898
9899        assert_eq!(entries_of(&slot), only_the_job_workspace());
9900        assert!(marker.exists());
9901        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
9902    }
9903
9904    #[tokio::test]
9905    async fn an_injected_partial_deletion_quarantines_the_slot_across_a_restart() {
9906        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9907            .with_persistent_workspace(2);
9908        harness.ready().await;
9909        let first = harness.launch().await;
9910        let slot = harness.slot_path(1);
9911        let marker = retain_under_work(&slot);
9912        litter_the_slot(&slot);
9913        harness.conclude(first.id);
9914
9915        let Some(block) = BlockedDeletion::inject(&slot.join("bin")) else {
9916            eprintln!(
9917                "skipped: this account cannot be refused a deletion, so no partial deletion can \
9918                 be injected"
9919            );
9920            return;
9921        };
9922
9923        let refusal = harness
9924            .launcher
9925            .clean(first.id)
9926            .await
9927            .expect_err("a deletion that failed may not report a cleaned slot");
9928        let rendered = refusal.reason.to_string();
9929        assert!(rendered.contains("could not be removed"), "{rendered}");
9930
9931        let held = harness.attempt(first.id);
9932        assert_eq!(held.state(), AttemptState::Failed, "still not cleaned");
9933        assert!(held.holds_slot_lease(), "so the slot is still leased");
9934        assert!(
9935            !held.state().counts_against_capacity(),
9936            "and a concluded attempt still costs the host no capacity"
9937        );
9938
9939        // The same journal and the same directories, under a launcher that
9940        // remembers nothing. Recovery must complete: a host that can launch
9941        // nothing at all because one slot is stuck is not what "does not count
9942        // as active host capacity" means.
9943        let restarted = harness.restart();
9944        restarted
9945            .recover_startup(std::slice::from_ref(&harness.policy))
9946            .await
9947            .expect("one quarantined slot does not stop the host recovering");
9948        assert_eq!(
9949            harness.attempt(first.id).state(),
9950            AttemptState::Failed,
9951            "the quarantine survived the restart"
9952        );
9953        assert!(
9954            harness
9955                .reconcile_events
9956                .events()
9957                .iter()
9958                .any(|event| matches!(
9959                    event,
9960                    LifecycleEvent::AttemptCleanFailed {
9961                        reason: "slot_entry_could_not_be_removed",
9962                        ..
9963                    }
9964                )),
9965            "the refusal is reported rather than retried in silence"
9966        );
9967
9968        // Capacity two, slot one quarantined: the next attempt goes to s2 and
9969        // never to the slot still holding runner state.
9970        let guard = harness.allocation_lock.acquire().await.unwrap();
9971        let second = restarted
9972            .launch(LaunchRequest {
9973                host: &harness.host,
9974                policy: &harness.policy,
9975                allocation_guard: &guard,
9976                lock_wait: Duration::ZERO,
9977            })
9978            .await
9979            .expect("the host can still launch");
9980        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
9981        drop(guard);
9982
9983        // And the same cleanup succeeds once the obstruction is gone, which is
9984        // what "retry through normal recovery" has to mean.
9985        block.release();
9986        restarted
9987            .clean(first.id)
9988            .await
9989            .expect("the retried cleanup completes");
9990        assert_eq!(entries_of(&slot), only_the_job_workspace());
9991        assert!(marker.exists());
9992        assert_eq!(harness.attempt(first.id).state(), AttemptState::Cleaned);
9993    }
9994
9995    /// The disposable half of the same injection, which had no test of its own.
9996    ///
9997    /// `scrub_workspace`'s ephemeral arm turns a failed `remove_dir_all` into
9998    /// `"attempt workspace could not be removed"`, and until now that branch was
9999    /// only reachable in theory: every injected-deletion test drove a persistent
10000    /// slot. The property is the same one and matters for the same reason --
10001    /// `04-security-recovery.md`'s "Cleanup partly fails and the slot is reused
10002    /// anyway" -- but the disposable guarantee is stronger, so a cleanup that
10003    /// reported success over a directory it had not removed would be the
10004    /// contamination gate failing silently rather than a slot being held.
10005    #[tokio::test]
10006    async fn an_injected_deletion_failure_leaves_a_disposable_attempt_uncleaned() {
10007        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
10008        harness.ready().await;
10009        let attempt = harness.launch().await;
10010        let runtime = attempt.runtime_path().to_path_buf();
10011        assert_eq!(attempt.workspace(), AttemptWorkspace::Ephemeral);
10012        harness.conclude(attempt.id);
10013
10014        let Some(block) = BlockedDeletion::inject(&runtime.join("held-open-subdirectory")) else {
10015            eprintln!(
10016                "skipped: this account cannot be refused a deletion, so no partial deletion can be injected"
10017            );
10018            return;
10019        };
10020
10021        let refusal = harness
10022            .launcher
10023            .clean(attempt.id)
10024            .await
10025            .expect_err("a deletion that failed may not report a removed workspace");
10026        let rendered = refusal.reason.to_string();
10027        assert!(
10028            rendered.contains("could not be removed"),
10029            "the refusal names what happened: {rendered}"
10030        );
10031        assert_ne!(
10032            harness.attempt(attempt.id).state(),
10033            AttemptState::Cleaned,
10034            "an attempt whose directory is still on disk is not cleaned"
10035        );
10036        assert!(
10037            runtime.is_dir(),
10038            "the directory the removal could not finish is still there, which is the fact the journal must keep agreeing with"
10039        );
10040
10041        let restarted = harness.restart();
10042        restarted
10043            .recover_startup(std::slice::from_ref(&harness.policy))
10044            .await
10045            .expect("one locked ephemeral workspace does not stop startup recovery");
10046        assert!(
10047            harness
10048                .reconcile_events
10049                .events()
10050                .iter()
10051                .any(|event| matches!(
10052                    event,
10053                    LifecycleEvent::AttemptCleanFailed {
10054                        attempt: failed_attempt,
10055                        reason: "ephemeral_workspace_could_not_be_removed",
10056                        ..
10057                    } if *failed_attempt == attempt.id
10058                )),
10059            "the deferred cleanup remains visible while the daemon keeps running"
10060        );
10061
10062        // And the ordinary retry -- the reconciler's next terminal sweep --
10063        // finishes it once the obstruction is gone.
10064        block.release();
10065        harness
10066            .launcher
10067            .clean(attempt.id)
10068            .await
10069            .expect("the retried cleanup completes");
10070        assert!(!runtime.exists(), "the whole attempt directory goes");
10071        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
10072    }
10073
10074    /// Supervision retries a workspace it cannot remove with per-attempt
10075    /// backoff, so a stuck workspace is reported once per delay rather than on
10076    /// every pass.
10077    #[tokio::test]
10078    async fn supervision_backs_off_a_workspace_it_cannot_remove() {
10079        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
10080        harness.ready().await;
10081        let attempt = harness.launch().await;
10082        let runtime = attempt.runtime_path().to_path_buf();
10083        harness.conclude(attempt.id);
10084        let Some(block) = BlockedDeletion::inject(&runtime.join("held-open-subdirectory")) else {
10085            eprintln!(
10086                "skipped: this account cannot be refused a deletion, so no partial deletion can be injected"
10087            );
10088            return;
10089        };
10090        let failures = || {
10091            harness
10092                .reconcile_events
10093                .events()
10094                .iter()
10095                .filter(|event| {
10096                    matches!(
10097                        event,
10098                        LifecycleEvent::AttemptCleanFailed { attempt: failed, .. }
10099                            if *failed == attempt.id
10100                    )
10101                })
10102                .count()
10103        };
10104        let supervise = async || {
10105            harness
10106                .launcher
10107                .supervise(&harness.policy)
10108                .await
10109                .expect("a stuck workspace does not fail supervision");
10110        };
10111
10112        supervise().await;
10113        assert_eq!(failures(), 1);
10114        supervise().await;
10115        assert_eq!(
10116            failures(),
10117            1,
10118            "the failed cleanup was retried on the very next pass"
10119        );
10120        harness.clock.advance_secs(31);
10121        supervise().await;
10122        assert_eq!(
10123            failures(),
10124            2,
10125            "the cleanup was not retried once its delay passed"
10126        );
10127
10128        block.release();
10129        harness.clock.advance_secs(61);
10130        supervise().await;
10131        assert!(
10132            !runtime.exists(),
10133            "the retry removes the workspace once it can"
10134        );
10135        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
10136    }
10137
10138    #[tokio::test]
10139    async fn changing_a_repository_back_to_ephemeral_leaves_every_old_slot_untouched() {
10140        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
10141            .with_persistent_workspace(1);
10142        harness.ready().await;
10143        let first = harness.launch().await;
10144        let slot = harness.slot_path(1);
10145        let marker = retain_under_work(&slot);
10146        harness.cleanup_retaining_work(first.id).await;
10147
10148        // Every attempt for this policy is cleaned, so the mutation is allowed
10149        // (`04-security-recovery.md`, "Recovery rules"). What it must not do is
10150        // move or delete anything the operator still owns.
10151        harness
10152            .policy
10153            .set_workspace_policy(WorkspacePolicy::Ephemeral)
10154            .unwrap();
10155
10156        let second = harness.launch().await;
10157        assert_eq!(second.workspace(), AttemptWorkspace::Ephemeral);
10158        assert_eq!(
10159            second.runtime_path().parent().unwrap(),
10160            harness.host_root(),
10161            "a disposable attempt is a child of the host root"
10162        );
10163        assert!(slot.is_dir(), "the old slot is left where it stands");
10164        assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
10165
10166        // And cleaning the disposable attempt removes its own directory whole
10167        // without reaching the retained slot beside it.
10168        harness.conclude(second.id);
10169        harness.launcher.clean(second.id).await.unwrap();
10170        assert!(!second.runtime_path().exists());
10171        assert!(marker.exists());
10172    }
10173
10174    #[tokio::test]
10175    async fn a_persistent_slot_is_scrubbed_only_after_the_process_is_signalled_and_gone() {
10176        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
10177            .with_persistent_workspace(1);
10178        harness.ready().await;
10179        let slot = harness.slot_path(1);
10180        fs::create_dir_all(&slot).unwrap();
10181        let marker = retain_under_work(&slot);
10182        litter_the_slot(&slot);
10183
10184        let id = AttemptId::new_random();
10185        let mut attempt = RunnerAttempt::allocate_in(
10186            id,
10187            harness.policy.id,
10188            &slot,
10189            AttemptWorkspace::persistent_slot(nz(1)),
10190            harness.clock.now(),
10191        );
10192        attempt.jit_received(harness.clock.now()).unwrap();
10193        attempt.started(4242, harness.clock.now()).unwrap();
10194        harness.store.record_attempt(&attempt).unwrap();
10195        harness.clock.advance_secs(11);
10196        harness.processes.set_alive(true);
10197        harness
10198            .github
10199            .observe(GithubRunnerObservation::NotRegistered);
10200
10201        harness.launcher.supervise(&harness.policy).await.unwrap();
10202
10203        // The identity and termination ordering `e3` established is unchanged by
10204        // the workspace kind: the intent is durable before the signal, and the
10205        // slot is scrubbed only once the process is gone.
10206        let actions = harness.processes.actions.lock().unwrap().clone();
10207        let intent = actions
10208            .iter()
10209            .position(|action| *action == "terminate_intent")
10210            .unwrap();
10211        let signal = actions
10212            .iter()
10213            .position(|action| *action == "terminate")
10214            .unwrap();
10215        assert!(intent < signal, "{actions:?}");
10216        assert!(!harness.processes.alive.load(Ordering::SeqCst));
10217
10218        let cleaned = harness.attempt(id);
10219        assert_eq!(cleaned.state(), AttemptState::Cleaned);
10220        assert!(matches!(
10221            cleaned.outcome(),
10222            Some(AttemptOutcome::Failed {
10223                reason: FailureReason::TerminatedAfterRegistrationTimeout
10224            })
10225        ));
10226        assert_eq!(entries_of(&slot), only_the_job_workspace());
10227        assert!(marker.exists());
10228    }
10229
10230    #[test]
10231    fn a_scrub_retains_one_real_work_directory_and_removes_every_other_entry() {
10232        let root = tempfile::tempdir().unwrap();
10233        let slot = root.path().join("s1");
10234        fs::create_dir(&slot).unwrap();
10235        let marker = retain_under_work(&slot);
10236        litter_the_slot(&slot);
10237        fs::write(slot.join("runner-package"), b"verified").unwrap();
10238
10239        scrub_slot_entries(&slot).expect("a slot of ordinary runner state scrubs");
10240        verify_slot_scrubbed(&slot).expect("and proves it afterwards");
10241
10242        assert_eq!(entries_of(&slot), only_the_job_workspace());
10243        assert!(marker.exists());
10244    }
10245
10246    #[test]
10247    fn a_residue_refusal_never_reports_the_under_count_as_the_fact() {
10248        let slot = Path::new("/runners/s1");
10249
10250        // The ordinary case: the listing counted, so the count is the fact and
10251        // the published names qualify it.
10252        let counted = residue_detail(slot, 2, &["`bin`".to_owned()]);
10253        assert!(counted.contains("2 entries other than"), "{counted}");
10254        assert!(counted.contains("including `bin`"), "{counted}");
10255        assert_eq!(
10256            residue_detail(slot, 1, &[]),
10257            format!(
10258                "1 entry other than `{DEFAULT_WORK_FOLDER}` survived cleanup of {}",
10259                slot.display()
10260            )
10261        );
10262
10263        // The race the second pass exists for: the listing saw nothing and the
10264        // filesystem answered otherwise. Saying "0 entries survived" here would
10265        // state the under-count as the fact and contradict the rest of the
10266        // sentence.
10267        let raced = residue_detail(slot, 0, &["`.credentials`".to_owned()]);
10268        assert!(!raced.contains('0'), "{raced}");
10269        assert!(raced.contains("reported nothing but"), "{raced}");
10270        assert!(raced.contains("`.credentials` survived cleanup"), "{raced}");
10271    }
10272
10273    #[test]
10274    fn verification_asks_the_filesystem_rather_than_the_listing_that_missed_an_entry() {
10275        let root = tempfile::tempdir().unwrap();
10276        let slot = root.path().join("s1");
10277        fs::create_dir(&slot).unwrap();
10278        fs::create_dir(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
10279        verify_slot_scrubbed(&slot).expect("only `_work` is a clean slot");
10280
10281        // Runner binaries, registration identity, process identity and this
10282        // agent's lifecycle marks, one at a time, so a scrub that skipped
10283        // exactly one is still caught.
10284        for survivor in ["bin", ".credentials", IDENTITY_FILE, RUNNER_ID_FILE] {
10285            fs::write(slot.join(survivor), b"left behind").unwrap();
10286            let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
10287            assert_eq!(quarantine.refusal, SlotRefusal::Residue);
10288            assert!(
10289                quarantine.detail.contains(&format!("`{survivor}`")),
10290                "{quarantine}"
10291            );
10292            fs::remove_file(slot.join(survivor)).unwrap();
10293        }
10294
10295        // A handoff is named by its published prefix, never by the UUID that
10296        // follows it, and never by the payload it holds.
10297        let handoff = slot.join(format!("{}whatever.tmp", RestrictiveHandoff::NAME_PREFIX));
10298        fs::write(&handoff, JIT.as_bytes()).unwrap();
10299        let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
10300        assert!(
10301            quarantine.detail.contains("an encoded JIT handoff"),
10302            "{quarantine}"
10303        );
10304        assert!(!quarantine.detail.contains(JIT), "{quarantine}");
10305        fs::remove_file(&handoff).unwrap();
10306
10307        // A name a workflow chose is counted and never echoed: a slot root is
10308        // writable by the job, so a file named after a secret would be published
10309        // by any message that repeated the listing.
10310        fs::write(slot.join("ghp_DO_NOT_LEAK"), b"named by the job").unwrap();
10311        let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
10312        assert!(
10313            quarantine.detail.contains("1 entry other than"),
10314            "{quarantine}"
10315        );
10316        assert!(
10317            !quarantine.detail.contains("ghp_DO_NOT_LEAK"),
10318            "{quarantine}"
10319        );
10320    }
10321
10322    #[test]
10323    fn a_slot_is_derived_from_the_journal_and_refused_when_it_disagrees() {
10324        let root = tempfile::tempdir().unwrap();
10325        let configured =
10326            LocalAbsolutePath::new(root.path().to_str().unwrap()).expect("a local absolute root");
10327        let slot = configured.as_path().join("s1");
10328        fs::create_dir(&slot).unwrap();
10329
10330        verify_journalled_slot(&slot, nz(1), Some(&configured))
10331            .expect("the journalled slot agrees");
10332        verify_journalled_slot(&slot, nz(1), None)
10333            .expect("and a policy that is gone removes a check, not the ability to clean");
10334
10335        // The journalled slot number is what names the directory. `s1` recorded
10336        // as slot two is corrupt state, not a slot to clean.
10337        assert_eq!(
10338            verify_journalled_slot(&slot, nz(2), None)
10339                .unwrap_err()
10340                .refusal,
10341            SlotRefusal::NotTheJournalledSlot
10342        );
10343        for stray in ["s1/nested", "not-a-slot", "s01"] {
10344            let path = configured.as_path().join(stray);
10345            assert_eq!(
10346                verify_journalled_slot(&path, nz(1), None)
10347                    .unwrap_err()
10348                    .refusal,
10349                SlotRefusal::NotTheJournalledSlot,
10350                "{}",
10351                path.display()
10352            );
10353        }
10354
10355        // A surviving policy that names a different root does not get to have
10356        // its disagreement resolved by deleting something.
10357        let elsewhere = tempfile::tempdir().unwrap();
10358        let other =
10359            LocalAbsolutePath::new(elsewhere.path().to_str().unwrap()).expect("a second root");
10360        assert_eq!(
10361            verify_journalled_slot(&slot, nz(1), Some(&other))
10362                .unwrap_err()
10363                .refusal,
10364            SlotRefusal::PolicyRootDisagrees
10365        );
10366    }
10367
10368    #[cfg(unix)]
10369    #[test]
10370    fn a_substituted_work_directory_quarantines_the_slot_and_deletes_nothing_outside_it() {
10371        // Windows needs a privilege to create a junction or a symlink, so the
10372        // substitution is made here; the rule is platform-independent because it
10373        // is `symlink_metadata`'s answer plus the reparse attribute.
10374        let root = tempfile::tempdir().unwrap();
10375        let outside = root.path().join("operator-data");
10376        fs::create_dir(&outside).unwrap();
10377        let sentinel = outside.join("do-not-delete.txt");
10378        fs::write(
10379            &sentinel,
10380            b"an operator's data, outside every approved root",
10381        )
10382        .unwrap();
10383
10384        let slot = root.path().join("s1");
10385        fs::create_dir(&slot).unwrap();
10386        fs::create_dir(slot.join("bin")).unwrap();
10387        std::os::unix::fs::symlink(&outside, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
10388
10389        let quarantine = scrub_slot_entries(&slot).unwrap_err();
10390        assert_eq!(quarantine.refusal, SlotRefusal::WorkNotADirectory);
10391        assert!(
10392            sentinel.exists(),
10393            "the deletion followed the link out of the slot"
10394        );
10395        assert!(outside.is_dir());
10396        assert!(
10397            slot.join(DEFAULT_WORK_FOLDER).symlink_metadata().is_ok(),
10398            "the substituted link is left for the operator, never unlinked as if it were ours"
10399        );
10400
10401        // A `_work` that is a plain file is the same refusal for the same
10402        // reason: it is not a job workspace, and this is not the code that
10403        // decides what to do about it.
10404        let file_work = root.path().join("s2");
10405        fs::create_dir(&file_work).unwrap();
10406        fs::write(file_work.join(DEFAULT_WORK_FOLDER), b"not a directory").unwrap();
10407        assert_eq!(
10408            scrub_slot_entries(&file_work).unwrap_err().refusal,
10409            SlotRefusal::WorkNotADirectory
10410        );
10411    }
10412
10413    #[cfg(unix)]
10414    #[test]
10415    fn a_slot_replaced_by_a_link_out_of_its_root_is_refused_before_anything_is_read() {
10416        let root = tempfile::tempdir().unwrap();
10417        let outside = root.path().join("operator-data");
10418        fs::create_dir(&outside).unwrap();
10419        let sentinel = outside.join("do-not-delete.txt");
10420        fs::write(
10421            &sentinel,
10422            b"an operator's data, outside every approved root",
10423        )
10424        .unwrap();
10425
10426        // The lexical half of containment passes -- the name is right and the
10427        // parent is right -- and canonical resolution is what catches it.
10428        let inside = root.path().join("inside");
10429        fs::create_dir(&inside).unwrap();
10430        let slot = inside.join("s1");
10431        std::os::unix::fs::symlink(&outside, &slot).unwrap();
10432
10433        assert_eq!(
10434            verify_journalled_slot(&slot, nz(1), None)
10435                .unwrap_err()
10436                .refusal,
10437            SlotRefusal::Containment
10438        );
10439        assert!(sentinel.exists());
10440        assert!(
10441            slot.symlink_metadata().is_ok(),
10442            "the link is left for the operator rather than removed as if it were ours"
10443        );
10444    }
10445
10446    /// The Windows half of the case above.
10447    ///
10448    /// Containment was proven only on Unix, and a symbolic link is the wrong
10449    /// instrument to prove it with on Windows: creating one needs a privilege an
10450    /// ordinary workflow does not have, so it is not the substitution an
10451    /// attacker would reach for. A **junction** needs none, which makes it both
10452    /// the realistic attack and the one this repository must refuse -- and
10453    /// `04-security-recovery.md` names it in the same breath as the symlink for
10454    /// exactly that reason.
10455    #[cfg(windows)]
10456    #[test]
10457    fn a_slot_root_replaced_by_a_junction_is_refused_before_anything_is_read() {
10458        let root = tempfile::tempdir().unwrap();
10459        let outside = root.path().join("operator-data");
10460        fs::create_dir(&outside).unwrap();
10461        let sentinel = outside.join("do-not-delete.txt");
10462        fs::write(
10463            &sentinel,
10464            b"an operator's data, outside every approved root",
10465        )
10466        .unwrap();
10467
10468        // The lexical half of containment passes -- `s1` under the root the
10469        // journal names -- and canonical resolution is what catches it.
10470        let inside = root.path().join("inside");
10471        fs::create_dir(&inside).unwrap();
10472        let slot = inside.join("s1");
10473        let Some(()) = plant_junction(&slot, &outside) else {
10474            eprintln!("skipped: this machine would not create a directory junction");
10475            return;
10476        };
10477
10478        assert_eq!(
10479            verify_journalled_slot(&slot, nz(1), None)
10480                .unwrap_err()
10481                .refusal,
10482            SlotRefusal::Containment
10483        );
10484        assert!(
10485            sentinel.exists(),
10486            "the refusal resolved the junction and reached the operator's data"
10487        );
10488        assert!(
10489            slot.symlink_metadata().is_ok(),
10490            "the junction is left for the operator rather than removed as if it were ours"
10491        );
10492    }
10493
10494    /// Plant a directory junction at `link` pointing at `target`.
10495    ///
10496    /// A junction is the Windows substitution this has to refuse, and unlike a
10497    /// symbolic link it needs no privilege — which is exactly why it is the one
10498    /// an unprivileged workflow would reach for. `mklink` is a `cmd` builtin, so
10499    /// there is no binary to find and nothing to install; `None` means this
10500    /// machine would not make one and the caller says so rather than asserting
10501    /// nothing.
10502    #[cfg(windows)]
10503    fn plant_junction(link: &Path, target: &Path) -> Option<()> {
10504        let made = std::process::Command::new("cmd")
10505            .arg("/C")
10506            .arg("mklink")
10507            .arg("/J")
10508            .arg(link)
10509            .arg(target)
10510            .output()
10511            .ok()?;
10512        (made.status.success() && link.symlink_metadata().is_ok()).then_some(())
10513    }
10514
10515    /// The dependency caches live beside attempts, under `<runner root>/_cache`,
10516    /// and jobs link into them (pnpm hard-links from its store; a workflow may
10517    /// symlink or junction a cache into its workspace). Removing an ephemeral
10518    /// attempt must take the links and never what they point at.
10519    #[test]
10520    fn removing_an_attempt_never_reaches_into_the_dependency_caches_it_linked() {
10521        let root = tempfile::tempdir().unwrap();
10522        let cache = root.path().join("_cache").join("o").join("r").join("npm");
10523        fs::create_dir_all(&cache).unwrap();
10524        let cached = cache.join("package.tgz");
10525        fs::write(&cached, b"kept between jobs").unwrap();
10526        let attempt = root.path().join("0123456789abcdef");
10527        let work = attempt.join("_work").join("repo");
10528        fs::create_dir_all(&work).unwrap();
10529        fs::hard_link(&cached, work.join("hard-linked.tgz")).unwrap();
10530        #[cfg(unix)]
10531        std::os::unix::fs::symlink(&cache, work.join("linked-cache")).unwrap();
10532        #[cfg(windows)]
10533        if plant_junction(&work.join("linked-cache"), &cache).is_none() {
10534            eprintln!("this machine would not create a junction; the hard link is still checked");
10535        }
10536
10537        remove_runtime_tree(&attempt).unwrap();
10538        assert!(!attempt.exists());
10539        assert_eq!(fs::read(&cached).unwrap(), b"kept between jobs");
10540    }
10541
10542    #[cfg(windows)]
10543    #[test]
10544    fn a_work_directory_replaced_by_a_junction_fails_closed_and_deletes_nothing_beyond_it() {
10545        let root = tempfile::tempdir().unwrap();
10546        let outside = root.path().join("operator-data");
10547        fs::create_dir(&outside).unwrap();
10548        let sentinel = outside.join("do-not-delete.txt");
10549        fs::write(
10550            &sentinel,
10551            b"an operator's data, outside every approved root",
10552        )
10553        .unwrap();
10554
10555        let slot = root.path().join("s1");
10556        fs::create_dir(&slot).unwrap();
10557        fs::create_dir(slot.join("bin")).unwrap();
10558        let Some(()) = plant_junction(&slot.join(DEFAULT_WORK_FOLDER), &outside) else {
10559            eprintln!("skipped: this machine would not create a directory junction");
10560            return;
10561        };
10562
10563        // The reparse point is what `is_link_like` answers on, so a junction is
10564        // refused for the same reason a symbolic link is and neither is
10565        // descended into.
10566        let work = fs::symlink_metadata(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
10567        assert!(is_link_like(&work), "a junction is a reparse point");
10568        let quarantine = scrub_slot_entries(&slot).unwrap_err();
10569        assert_eq!(quarantine.refusal, SlotRefusal::WorkNotADirectory);
10570        assert!(
10571            sentinel.exists(),
10572            "the deletion followed the junction out of the slot"
10573        );
10574        assert!(outside.is_dir());
10575
10576        // A junction standing where an ordinary entry was is unlinked rather
10577        // than followed, so the removal still cannot reach through it.
10578        let elsewhere = root.path().join("s2");
10579        fs::create_dir(&elsewhere).unwrap();
10580        fs::create_dir(elsewhere.join(DEFAULT_WORK_FOLDER)).unwrap();
10581        if plant_junction(&elsewhere.join("externals"), &outside).is_some() {
10582            scrub_slot_entries(&elsewhere).expect("an ordinary entry is removed, junction or not");
10583            verify_slot_scrubbed(&elsewhere).expect("and the slot verifies");
10584            assert!(sentinel.exists(), "the junction was followed, not unlinked");
10585            assert_eq!(entries_of(&elsewhere), only_the_job_workspace());
10586        }
10587    }
10588
10589    #[cfg(unix)]
10590    #[tokio::test]
10591    async fn a_substituted_work_directory_leaves_the_attempt_uncleaned_and_still_leased() {
10592        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
10593            .with_persistent_workspace(2);
10594        harness.ready().await;
10595        let first = harness.launch().await;
10596        let slot = harness.slot_path(1);
10597        harness.conclude(first.id);
10598
10599        let outside = harness._root.path().join("operator-data");
10600        fs::create_dir_all(&outside).unwrap();
10601        let sentinel = outside.join("do-not-delete.txt");
10602        fs::write(&sentinel, b"outside every approved root").unwrap();
10603        std::os::unix::fs::symlink(&outside, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
10604
10605        harness
10606            .launcher
10607            .clean(first.id)
10608            .await
10609            .expect_err("a slot whose `_work` was substituted is quarantined");
10610        assert!(sentinel.exists());
10611
10612        let held = harness.attempt(first.id);
10613        assert_eq!(held.state(), AttemptState::Failed);
10614        assert!(held.holds_slot_lease());
10615
10616        // The quarantined slot is not silently chosen again.
10617        let second = harness.launch().await;
10618        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
10619    }
10620
10621    #[test]
10622    fn a_slot_that_is_a_file_is_refused_and_a_slot_that_is_gone_is_not() {
10623        let root = tempfile::tempdir().unwrap();
10624        let occupied = root.path().join("s1");
10625        fs::write(&occupied, b"an operator's file").unwrap();
10626        // The journal check passes -- it is the right name under the right root
10627        // -- and the shape check is what refuses.
10628        verify_journalled_slot(&occupied, nz(1), None).expect("the path is the journalled slot");
10629        assert_eq!(
10630            slot_is_present(&occupied).unwrap_err().refusal,
10631            SlotRefusal::SlotNotADirectory
10632        );
10633        assert_eq!(fs::read_to_string(&occupied).unwrap(), "an operator's file");
10634
10635        // A directory that is simply not there leaves nothing to remove and
10636        // nothing to prove absent, so it is not a refusal.
10637        assert!(!slot_is_present(&root.path().join("s2")).unwrap());
10638        let present = root.path().join("s3");
10639        fs::create_dir(&present).unwrap();
10640        assert!(slot_is_present(&present).unwrap());
10641    }
10642
10643    #[test]
10644    fn cleanup_dispatches_on_the_journalled_kind_and_not_on_what_the_directory_holds() {
10645        let root = tempfile::tempdir().unwrap();
10646
10647        // A disposable directory that happens to contain a `_work` still goes
10648        // whole: the workspace kind is immutable so that the shape of a
10649        // directory a workflow can write to cannot choose its own algorithm.
10650        let disposable = root.path().join("abcdef012345");
10651        fs::create_dir_all(disposable.join(DEFAULT_WORK_FOLDER).join("repo")).unwrap();
10652        let ephemeral = RunnerAttempt::allocate(
10653            AttemptId::new_random(),
10654            fixtures::POLICY_ID,
10655            &disposable,
10656            fixtures::created_at(),
10657        );
10658        remove_materialized_package(&ephemeral).unwrap();
10659        assert!(!disposable.exists());
10660
10661        // And a slot keeps its `_work` with the same contents beneath it.
10662        let slot = root.path().join("s1");
10663        fs::create_dir_all(slot.join(DEFAULT_WORK_FOLDER).join("repo")).unwrap();
10664        fs::create_dir_all(slot.join("bin")).unwrap();
10665        let persistent = RunnerAttempt::allocate_in(
10666            AttemptId::new_random(),
10667            fixtures::POLICY_ID,
10668            &slot,
10669            AttemptWorkspace::persistent_slot(nz(1)),
10670            fixtures::created_at(),
10671        );
10672        remove_materialized_package(&persistent).unwrap();
10673        assert_eq!(entries_of(&slot), only_the_job_workspace());
10674        assert!(slot.join(DEFAULT_WORK_FOLDER).join("repo").is_dir());
10675    }
10676
10677    #[test]
10678    fn every_slot_refusal_names_a_distinct_event_class_and_keeps_the_lease() {
10679        let refusals = [
10680            SlotRefusal::NotTheJournalledSlot,
10681            SlotRefusal::PolicyRootDisagrees,
10682            SlotRefusal::Containment,
10683            SlotRefusal::SlotNotADirectory,
10684            SlotRefusal::Enumeration,
10685            SlotRefusal::WorkNotADirectory,
10686            SlotRefusal::Deletion,
10687            SlotRefusal::Residue,
10688        ];
10689        let classes: BTreeSet<&str> = refusals.iter().map(|refusal| refusal.class()).collect();
10690        assert_eq!(
10691            classes.len(),
10692            refusals.len(),
10693            "an event class shared by two refusals tells an operator less than it appears to"
10694        );
10695        for refusal in refusals {
10696            // The event field is a closed vocabulary, so it has to look like
10697            // one: `d1`'s sink allows the name verbatim.
10698            assert!(
10699                refusal
10700                    .class()
10701                    .chars()
10702                    .all(|c| c.is_ascii_lowercase() || c == '_'),
10703                "{}",
10704                refusal.class()
10705            );
10706            assert!(
10707                refusal.remediation().contains("slot lease"),
10708                "every refusal has to say the lease is still held: {}",
10709                refusal.class()
10710            );
10711        }
10712    }
10713
10714    #[test]
10715    fn copy_package_tree_copies_files_and_preserves_paths_with_spaces() {
10716        let root = tempfile::tempdir().unwrap();
10717        let source = root.path().join("source with spaces");
10718        let dest = root.path().join("dest with spaces");
10719
10720        fs::create_dir_all(&source).unwrap();
10721        fs::write(source.join("file1.txt"), b"hello").unwrap();
10722
10723        let nested = source.join("nested dir");
10724        fs::create_dir_all(&nested).unwrap();
10725        fs::write(nested.join("file2.txt"), b"world").unwrap();
10726
10727        // This is not a top-level `_work`, so it should be allowed
10728        let nested_work = nested.join(DEFAULT_WORK_FOLDER);
10729        fs::create_dir_all(&nested_work).unwrap();
10730        fs::write(nested_work.join("allowed.txt"), b"allowed").unwrap();
10731
10732        copy_package_tree(&source, &dest, &TrustedTrees::default()).unwrap();
10733
10734        assert_eq!(fs::read_to_string(dest.join("file1.txt")).unwrap(), "hello");
10735        assert_eq!(
10736            fs::read_to_string(dest.join("nested dir").join("file2.txt")).unwrap(),
10737            "world"
10738        );
10739        assert_eq!(
10740            fs::read_to_string(
10741                dest.join("nested dir")
10742                    .join(DEFAULT_WORK_FOLDER)
10743                    .join("allowed.txt")
10744            )
10745            .unwrap(),
10746            "allowed"
10747        );
10748    }
10749
10750    #[test]
10751    fn every_field_name_the_attempt_sink_emits_is_allowed() {
10752        use runner_manager_platform::logging::is_field_allowed;
10753
10754        // Kept beside the sink rather than derived from it, as in `reconcile`.
10755        for field in [
10756            "event",
10757            "attempt_id",
10758            "reason",
10759            "retry_in_ms",
10760            "duration_ms",
10761            "lock_wait_ms",
10762            "materialize_ms",
10763            "register_ms",
10764            "spawn_ms",
10765        ] {
10766            assert!(
10767                is_field_allowed(field),
10768                "`{field}` would be logged as `[redacted]`"
10769            );
10770        }
10771    }
10772
10773    #[cfg(unix)]
10774    fn package_entry(root: &Path, version: &str, manifest: &str) -> PathBuf {
10775        let entry = root.join("packages").join(version);
10776        fs::create_dir_all(entry.join("bin")).unwrap();
10777        fs::write(entry.join(crate::package::MANIFEST_FILE), manifest).unwrap();
10778        fs::write(entry.join("bin").join("Runner.Listener"), version).unwrap();
10779        entry
10780    }
10781
10782    /// The seed's binary's inode: a rebuilt seed holds a new file.
10783    #[cfg(unix)]
10784    fn listener_inode(seed: &Path) -> u64 {
10785        use std::os::unix::fs::MetadataExt as _;
10786        fs::metadata(seed.join("bin").join("Runner.Listener"))
10787            .unwrap()
10788            .ino()
10789    }
10790
10791    #[cfg(unix)]
10792    #[test]
10793    fn a_package_seed_is_built_once_and_reused_while_untouched() {
10794        let root = tempfile::tempdir().unwrap();
10795        let source = package_entry(root.path(), "2.336.0", "{\"digest\":\"a\"}");
10796        let seeds = root.path().join("runners").join(PACKAGE_SEED_DIR);
10797        let trusted = TrustedTrees::default();
10798
10799        let seed = refresh_package_seed(&source, &seeds, &trusted).unwrap();
10800        assert_eq!(seed, seeds.join("2.336.0"));
10801        assert_eq!(
10802            fs::read_to_string(seed.join("bin").join("Runner.Listener")).unwrap(),
10803            "2.336.0"
10804        );
10805
10806        let built = listener_inode(&seed);
10807        assert_eq!(
10808            refresh_package_seed(&source, &seeds, &trusted).unwrap(),
10809            seed
10810        );
10811        assert_eq!(listener_inode(&seed), built, "an untouched seed is reused");
10812    }
10813
10814    #[cfg(unix)]
10815    #[test]
10816    fn a_tampered_or_unrecorded_seed_is_rebuilt() {
10817        let root = tempfile::tempdir().unwrap();
10818        let source = package_entry(root.path(), "2.336.0", "{\"digest\":\"a\"}");
10819        let seeds = root.path().join("runners").join(PACKAGE_SEED_DIR);
10820        let trusted = TrustedTrees::default();
10821        let seed = refresh_package_seed(&source, &seeds, &trusted).unwrap();
10822
10823        // A job rewrites the binary in place and leaves the manifest alone.
10824        fs::write(seed.join("bin").join("Runner.Listener"), b"planted").unwrap();
10825        refresh_package_seed(&source, &seeds, &trusted).unwrap();
10826        assert_eq!(
10827            fs::read_to_string(seed.join("bin").join("Runner.Listener")).unwrap(),
10828            "2.336.0",
10829            "a seed whose print moved is rebuilt from the cache entry"
10830        );
10831
10832        // A restarted daemon has no print of a seed it did not build.
10833        // Keep the old inode allocated until the replacement is complete;
10834        // otherwise the filesystem may immediately reuse its number.
10835        let old_listener = fs::File::open(seed.join("bin").join("Runner.Listener")).unwrap();
10836        let built = listener_inode(&seed);
10837        refresh_package_seed(&source, &seeds, &TrustedTrees::default()).unwrap();
10838        assert_ne!(
10839            listener_inode(&seed),
10840            built,
10841            "an unrecorded seed is rebuilt"
10842        );
10843        drop(old_listener);
10844    }
10845
10846    #[cfg(unix)]
10847    #[test]
10848    fn a_package_seed_is_rebuilt_for_a_new_entry_and_drops_every_other() {
10849        let root = tempfile::tempdir().unwrap();
10850        let seeds = root.path().join("runners").join(PACKAGE_SEED_DIR);
10851        let trusted = TrustedTrees::default();
10852        let old = package_entry(root.path(), "2.335.0", "{\"digest\":\"old\"}");
10853        refresh_package_seed(&old, &seeds, &trusted).unwrap();
10854        fs::create_dir_all(seeds.join(".staging-interrupted")).unwrap();
10855        fs::write(seeds.join("stray"), b"").unwrap();
10856
10857        let new = package_entry(root.path(), "2.336.0", "{\"digest\":\"new\"}");
10858        let seed = refresh_package_seed(&new, &seeds, &trusted).unwrap();
10859
10860        let mut left: Vec<_> = fs::read_dir(&seeds)
10861            .unwrap()
10862            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
10863            .collect();
10864        left.sort();
10865        assert_eq!(left, ["2.336.0"]);
10866
10867        // A reinstalled entry of the same version has a different manifest.
10868        fs::write(
10869            new.join(crate::package::MANIFEST_FILE),
10870            "{\"digest\":\"again\"}",
10871        )
10872        .unwrap();
10873        refresh_package_seed(&new, &seeds, &trusted).unwrap();
10874        assert_eq!(
10875            fs::read_to_string(seed.join(crate::package::MANIFEST_FILE)).unwrap(),
10876            "{\"digest\":\"again\"}",
10877            "a stale seed is rebuilt from the changed entry"
10878        );
10879    }
10880
10881    #[cfg(unix)]
10882    #[test]
10883    fn a_package_on_the_runtime_volume_is_its_own_seed() {
10884        let root = tempfile::tempdir().unwrap();
10885        let source = package_entry(root.path(), "2.336.0", "{}");
10886        let runtime = root.path().join("runners").join("attempt");
10887        fs::create_dir_all(&runtime).unwrap();
10888
10889        let trusted = TrustedTrees::default();
10890        assert_eq!(package_seed(&source, &runtime, &trusted).unwrap(), source);
10891        copy_package_tree(&source, &runtime, &trusted).unwrap();
10892        assert!(runtime.join("bin").join("Runner.Listener").exists());
10893        assert!(!root.path().join("runners").join(PACKAGE_SEED_DIR).exists());
10894    }
10895
10896    #[test]
10897    fn copy_package_tree_refuses_top_level_work_folder() {
10898        let root = tempfile::tempdir().unwrap();
10899        let source = root.path().join("source");
10900        let dest = root.path().join("dest");
10901
10902        fs::create_dir_all(&source).unwrap();
10903        fs::write(source.join("file1.txt"), b"hello").unwrap();
10904
10905        // Top-level `_work` should be refused
10906        let top_work = source.join(DEFAULT_WORK_FOLDER);
10907        fs::create_dir_all(&top_work).unwrap();
10908
10909        let err = copy_package_tree(&source, &dest, &TrustedTrees::default()).unwrap_err();
10910        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
10911    }
10912}