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 host_capacity(
4738        &self,
4739        host: &runner_manager_domain::model::Host,
4740    ) -> Result<std::num::NonZeroU16, crate::reconcile::HostCapacityError> {
4741        self.ports
4742            .store
4743            .host(host.id)
4744            .map_err(|_| crate::reconcile::HostCapacityError::JournalUnreadable)?
4745            .map(|current| current.host_capacity)
4746            .ok_or(crate::reconcile::HostCapacityError::MissingHost)
4747    }
4748
4749    async fn supervise(
4750        &self,
4751        policy: &ScalePolicy,
4752    ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
4753        LifecycleLauncher::supervise(self, policy)
4754            .await
4755            .map_err(|error| LaunchFailure::new(error.reason()))
4756    }
4757
4758    async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
4759        self.ports.store.attempts().map_err(|_| {
4760            LaunchFailure::new(FailureReason::Other(
4761                "attempt journal could not be read".into(),
4762            ))
4763        })
4764    }
4765
4766    async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure> {
4767        self.launch_attempt(request.policy, request.allocation_guard, request.lock_wait)
4768            .await
4769            .map_err(|error| LaunchFailure::new(error.reason()))
4770    }
4771
4772    async fn clean(&self, id: AttemptId) -> Result<(), LaunchFailure> {
4773        let mut attempt = self
4774            .ports
4775            .store
4776            .attempt(id)
4777            .map_err(|_| {
4778                LaunchFailure::new(FailureReason::Other(
4779                    "attempt journal could not be read".into(),
4780                ))
4781            })?
4782            .ok_or_else(|| {
4783                LaunchFailure::new(FailureReason::Other(
4784                    "attempt disappeared from the journal".into(),
4785                ))
4786            })?;
4787        self.clean_attempt(&mut attempt)
4788            .map_err(|error| LaunchFailure::new(error.reason()))?;
4789        self.cleanup_retries().succeeded(id);
4790        Ok(())
4791    }
4792}
4793
4794fn runner_name(attempt: AttemptId) -> String {
4795    format!("runner-manager-{attempt}")
4796}
4797
4798/// How long reading a runner's diagnostics may take.
4799const EVIDENCE_DEADLINE: Duration = Duration::from_secs(2);
4800
4801/// What a native runner's own diagnostics say about whether it ran a job.
4802///
4803/// `Runner.Listener` writes `_diag/Runner_*.log` when it starts, and starts
4804/// `Runner.Worker` -- which writes `_diag/Worker_*.log` -- only for a job it has
4805/// acquired. So a worker log is proof a job ran, and a listener log without one
4806/// is proof none did. With neither, the directory is not where the listener
4807/// wrote, and nothing is concluded from it. `_diag` is scrubbed with the rest of
4808/// the runtime after every attempt, persistent slots included, so a log found
4809/// here belongs to this attempt.
4810#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4811enum JobEvidence {
4812    RanAJob,
4813    NoJob,
4814    Unknown,
4815}
4816
4817impl JobEvidence {
4818    fn of(runtime: &Path) -> Self {
4819        let diag = runtime.join("_diag");
4820        // Bounded: the daemon's loop runs on one thread, and a runtime on a
4821        // volume that does not answer (a hung disk, a pending macOS question)
4822        // must not stall it for longer than this.
4823        if runner_manager_platform::host_fitness::directory_responds(&diag, EVIDENCE_DEADLINE)
4824            != runner_manager_platform::host_fitness::Responsiveness::Responds
4825        {
4826            return Self::Unknown;
4827        }
4828        let Ok(entries) = fs::read_dir(diag) else {
4829            return Self::Unknown;
4830        };
4831        let mut listener = false;
4832        for entry in entries.flatten() {
4833            let name = entry.file_name();
4834            let name = name.to_string_lossy();
4835            if !name.ends_with(".log") {
4836                continue;
4837            }
4838            if name.starts_with("Worker_") {
4839                return Self::RanAJob;
4840            }
4841            listener |= name.starts_with("Runner_");
4842        }
4843        if listener { Self::NoJob } else { Self::Unknown }
4844    }
4845}
4846
4847/// The attempt's GitHub runner id: journalled, observed, or from the sidecar
4848/// written at registration.
4849fn known_runner_id(attempt: &RunnerAttempt, observed: Option<u64>) -> Option<u64> {
4850    attempt
4851        .github_runner_id()
4852        .or(observed)
4853        .or_else(|| read_runner_id(attempt.runtime_path()))
4854}
4855
4856fn read_runner_id(runtime: &Path) -> Option<u64> {
4857    fs::read_to_string(runtime.join(RUNNER_ID_FILE))
4858        .ok()?
4859        .trim()
4860        .parse()
4861        .ok()
4862}
4863
4864fn write_runner_id(runtime: &Path, runner_id: u64) -> Result<(), LifecycleError> {
4865    let target = runtime.join(RUNNER_ID_FILE);
4866    if let Some(existing) = read_runner_id(runtime) {
4867        return (existing == runner_id)
4868            .then_some(())
4869            .ok_or(LifecycleError::Journal);
4870    }
4871    let temporary = runtime.join(format!("{RUNNER_ID_FILE}.{}.tmp", uuid::Uuid::new_v4()));
4872    write_durable_file(&temporary, runner_id.to_string().as_bytes())
4873        .map_err(|_| LifecycleError::Journal)?;
4874    match fs::rename(&temporary, &target) {
4875        Ok(()) => sync_directory(runtime).map_err(|_| LifecycleError::Journal),
4876        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
4877            let _ = fs::remove_file(&temporary);
4878            (read_runner_id(runtime) == Some(runner_id))
4879                .then_some(())
4880                .ok_or(LifecycleError::Journal)
4881        }
4882        Err(_) => {
4883            let _ = fs::remove_file(&temporary);
4884            Err(LifecycleError::Journal)
4885        }
4886    }
4887}
4888
4889fn write_durable_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
4890    let mut file = fs::OpenOptions::new()
4891        .create(true)
4892        .truncate(true)
4893        .write(true)
4894        .open(path)?;
4895    file.write_all(bytes)?;
4896    file.sync_all()?;
4897    let parent = path.parent().ok_or_else(|| {
4898        std::io::Error::new(
4899            std::io::ErrorKind::InvalidInput,
4900            "file has no parent directory",
4901        )
4902    })?;
4903    sync_directory(parent)
4904}
4905
4906#[cfg(unix)]
4907fn sync_directory(path: &Path) -> std::io::Result<()> {
4908    fs::File::open(path)?.sync_all()
4909}
4910
4911#[cfg(windows)]
4912fn sync_directory(path: &Path) -> std::io::Result<()> {
4913    use std::os::windows::fs::OpenOptionsExt;
4914
4915    const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
4916    const FILE_SHARE_ALL: u32 = 0x0000_0007;
4917    const GENERIC_WRITE: u32 = 0x4000_0000;
4918    fs::OpenOptions::new()
4919        .access_mode(GENERIC_WRITE)
4920        .share_mode(FILE_SHARE_ALL)
4921        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
4922        .open(path)?
4923        .sync_all()
4924}
4925
4926#[cfg(test)]
4927mod tests {
4928    use super::*;
4929    use std::collections::BTreeSet;
4930    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
4931
4932    use crate::reconcile::{AllocationLock, InProcessAllocationLock};
4933    use runner_manager_domain::model::{Elapsed, TargetScope};
4934    use runner_manager_domain::store::SqliteStore;
4935    use runner_manager_github::jit::JitRunner;
4936    use runner_manager_testkit::clock::FakeClock;
4937    use runner_manager_testkit::fixtures;
4938
4939    #[test]
4940    fn production_provider_set_routes_every_implemented_isolated_backend() {
4941        let providers = PlatformExecutionProvider::new(HostId::from_u128(1));
4942        assert!(providers.isolated_provider(Backend::Auto).is_some());
4943        assert!(providers.isolated_provider(Backend::Oci).is_some());
4944        assert!(
4945            providers
4946                .isolated_provider(Backend::WindowsHyperVContainer)
4947                .is_some()
4948        );
4949        assert!(
4950            providers
4951                .isolated_provider(Backend::VirtualMachine)
4952                .is_none()
4953        );
4954    }
4955
4956    /// One event's fields, in the order they were recorded.
4957    type CapturedFields = Vec<(String, String)>;
4958
4959    /// Keeps the `(name, value)` fields of every `tracing` event emitted while
4960    /// it is installed.
4961    ///
4962    /// The names are kept and not just the rendered line, so a test can hold the
4963    /// event to `crate::logging`'s two rules -- the field allow-list and the
4964    /// value scrub -- instead of asserting that some string was passed to a
4965    /// macro.
4966    #[derive(Clone, Default)]
4967    struct CapturedEvents(std::sync::Arc<std::sync::Mutex<Vec<CapturedFields>>>);
4968
4969    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for CapturedEvents {
4970        fn on_event(
4971            &self,
4972            event: &tracing::Event<'_>,
4973            _context: tracing_subscriber::layer::Context<'_, S>,
4974        ) {
4975            struct Collect(Vec<(String, String)>);
4976            impl tracing::field::Visit for Collect {
4977                fn record_debug(
4978                    &mut self,
4979                    field: &tracing::field::Field,
4980                    value: &dyn std::fmt::Debug,
4981                ) {
4982                    // `{value:?}` on a `&str` field would keep the quotes, and
4983                    // the redaction rules are about the value, not its literal.
4984                    self.0.push((
4985                        field.name().to_owned(),
4986                        format!("{value:?}").trim_matches('"').to_owned(),
4987                    ));
4988                }
4989            }
4990            let mut collected = Collect(Vec::new());
4991            event.record(&mut collected);
4992            self.0
4993                .lock()
4994                .expect("the capture mutex is not poisoned")
4995                .push(collected.0);
4996        }
4997    }
4998
4999    /// The regression behind a three-hour outage that showed nothing an operator
5000    /// could act on.
5001    ///
5002    /// A root the daemon cannot use refuses the launch *before*
5003    /// `record_allocation`, so no attempt row is ever written: `b2` has nothing
5004    /// to carry the failure on and `g2` has nothing to show it from. The
5005    /// lifecycle event keeps only the variant -- `failure_reason_kind` allows no
5006    /// free text on an event -- so the whole failure read
5007    /// `runner_start_failed reason=other`, once per poll, for hours.
5008    ///
5009    /// The assertion is deliberately made against the **production redaction
5010    /// rules** and not merely against what was emitted. An earlier attempt at
5011    /// this fix logged the rendered error on a `detail` field and passed a test
5012    /// exactly like this one, while shipping `detail="[redacted]"`: the field
5013    /// was not allow-listed, and had it been, the value is mostly paths and
5014    /// would have been scrubbed to `[path]`. A test that does not ask
5015    /// `crate::logging` what survives is a test that proves nothing.
5016    #[test]
5017    fn a_launch_the_runner_root_refused_names_the_cause_in_the_log_that_ships() {
5018        use runner_manager_platform::logging;
5019        use tracing_subscriber::layer::SubscriberExt as _;
5020
5021        let captured = CapturedEvents::default();
5022        let error = RunnerRootError::DeniedByPrivacyPolicy {
5023            requested: PathBuf::from("/Volumes/NVME/runners"),
5024            refused: PathBuf::from("/Volumes/NVME"),
5025            remediation: RootOwner::Host.remediation(),
5026        };
5027        let kind = error.kind();
5028
5029        let failure = tracing::subscriber::with_default(
5030            tracing_subscriber::registry().with(captured.clone()),
5031            || root_failure(error),
5032        );
5033
5034        // The reason still carries the whole sentence. Nothing on *this* path
5035        // renders it -- there is no attempt row, and the event carries only the
5036        // variant -- so this is a guard against a refactor that drops the detail
5037        // before some future surface can show it, and not a claim that one does.
5038        assert!(
5039            matches!(
5040                &failure,
5041                LifecycleError::Failed(FailureReason::Other(detail))
5042                    if detail.contains("/Volumes/NVME/runners")
5043                        && detail.contains("Full Disk Access")
5044            ),
5045            "the reason must still carry the detail: {failure:?}"
5046        );
5047
5048        let events = captured
5049            .0
5050            .lock()
5051            .expect("the capture mutex is not poisoned")
5052            .clone();
5053        let event = events
5054            .iter()
5055            .find(|fields| fields.iter().any(|(_, value)| value.contains(kind)))
5056            .unwrap_or_else(|| panic!("the refusal did not name its cause: {events:?}"));
5057
5058        // Held to the rules the real sink applies, by name and by value. An
5059        // earlier fix put the rendered error on an unlisted `detail` field and
5060        // shipped `[redacted]`; asserting only that something was emitted would
5061        // have passed then too.
5062        for (name, value) in event {
5063            assert!(
5064                logging::is_field_allowed(name),
5065                "`{name}` is not allow-listed, so it ships as `{}`: {event:?}",
5066                logging::REDACTION
5067            );
5068            assert_eq!(
5069                &logging::redact(value),
5070                value,
5071                "`{name}` does not survive value-shape scrubbing: {event:?}"
5072            );
5073        }
5074    }
5075
5076    /// A slot number, for the tests that name one.
5077    fn nz(slot: u16) -> NonZeroU16 {
5078        NonZeroU16::new(slot).expect("a positive slot")
5079    }
5080
5081    const JIT: &str = "eyJzZWNyZXQiOiJnaHBfRE9fTk9UX0xFQUsifQ==";
5082
5083    #[derive(Debug, Default)]
5084    struct FakeGithubLifecycle {
5085        registration_failures: Mutex<VecDeque<bool>>,
5086        observations: Mutex<VecDeque<LifecycleGithubObservation>>,
5087        registrations: AtomicUsize,
5088        remaining_runners: AtomicUsize,
5089        /// Every runner id `deregister` was asked to remove, in order. A count
5090        /// would not do: the assertions worth making are that the *right*
5091        /// registration was deleted and that it was deleted once.
5092        deregistrations: Mutex<Vec<u64>>,
5093        /// Set to make `deregister` answer `false`, standing for a GitHub that
5094        /// could not be reached at the moment the attempt concluded.
5095        deregistration_fails: AtomicBool,
5096        /// The journal to read *during* a registration, for the ordering
5097        /// assertion `02-target-architecture.md` makes: the slot lease is
5098        /// written "before package or GitHub effects". Reading it afterwards
5099        /// would pass even if the write happened second.
5100        journal: Mutex<Option<Arc<SqliteStore>>>,
5101        /// One entry per registration, in order.
5102        registration_facts: Mutex<Vec<RegistrationFact>>,
5103    }
5104
5105    /// What one JIT registration saw of the world at the moment it was issued.
5106    ///
5107    /// `runner_name` is what ties the other two fields to *one* attempt: with
5108    /// two allocators racing, "some slot was journalled" is a much weaker claim
5109    /// than "the slot this very request belongs to was journalled", and only the
5110    /// name distinguishes them.
5111    #[derive(Debug, Clone)]
5112    struct RegistrationFact {
5113        /// The persistent slots the journal already held.
5114        leased_slots: Vec<u16>,
5115        /// The `work_folder` the request carried.
5116        work_folder: String,
5117        /// The runner name the request carried, i.e. [`runner_name`] of the
5118        /// registering attempt.
5119        runner_name: String,
5120        journal_states: Vec<AttemptState>,
5121    }
5122
5123    impl FakeGithubLifecycle {
5124        fn fail(mut self, terminal: bool) -> Self {
5125            self.registration_failures
5126                .get_mut()
5127                .expect("unpoisoned")
5128                .push_back(terminal);
5129            self
5130        }
5131
5132        fn watch_journal(&self, store: Arc<SqliteStore>) {
5133            *self.journal.lock().unwrap() = Some(store);
5134        }
5135
5136        fn registration_facts(&self) -> Vec<RegistrationFact> {
5137            self.registration_facts.lock().unwrap().clone()
5138        }
5139
5140        fn observe(&self, observation: GithubRunnerObservation) {
5141            let observation = match observation {
5142                GithubRunnerObservation::Unreachable => LifecycleGithubObservation::unreachable(),
5143                GithubRunnerObservation::NotRegistered => {
5144                    LifecycleGithubObservation::not_registered()
5145                }
5146                GithubRunnerObservation::Registered { busy } => {
5147                    LifecycleGithubObservation::registered(73, busy)
5148                }
5149            };
5150            self.observations.lock().unwrap().push_back(observation);
5151        }
5152    }
5153
5154    #[async_trait]
5155    impl LifecycleGithub for FakeGithubLifecycle {
5156        async fn register(
5157            &self,
5158            _target: &ScaleTarget,
5159            request: &JitRunnerRequest,
5160            _cancel: &CancelToken,
5161        ) -> Result<JitRegistration, JitRequestFailure> {
5162            self.registrations.fetch_add(1, Ordering::SeqCst);
5163            if let Some(store) = self.journal.lock().unwrap().as_ref() {
5164                let attempts = store.attempts().expect("the journal is readable");
5165                let slots = attempts
5166                    .iter()
5167                    .filter_map(|attempt| attempt.workspace().slot_number())
5168                    .collect();
5169                self.registration_facts
5170                    .lock()
5171                    .unwrap()
5172                    .push(RegistrationFact {
5173                        leased_slots: slots,
5174                        work_folder: request.work_folder().to_string(),
5175                        runner_name: request.name().to_string(),
5176                        journal_states: attempts.iter().map(RunnerAttempt::state).collect(),
5177                    });
5178            }
5179            if let Some(terminal) = self.registration_failures.lock().unwrap().pop_front() {
5180                return Err(JitRequestFailure {
5181                    terminal,
5182                    reason: if terminal {
5183                        FailureReason::Other("GitHub refused JIT registration with 403".into())
5184                    } else {
5185                        FailureReason::JitRequestFailed
5186                    },
5187                    retry_after: None,
5188                });
5189            }
5190            self.remaining_runners.store(1, Ordering::SeqCst);
5191            Ok(JitRegistration::new(
5192                EncodedJitConfig::new(JIT),
5193                JitRunner {
5194                    id: 73,
5195                    name: request.name().to_string(),
5196                    os: "windows".into(),
5197                    status: "offline".into(),
5198                    busy: false,
5199                    runner_group_id: Some(1),
5200                    labels: request.labels().to_vec(),
5201                },
5202            ))
5203        }
5204
5205        async fn observe(
5206            &self,
5207            _target: &ScaleTarget,
5208            _attempt: AttemptId,
5209            _cancel: &CancelToken,
5210        ) -> LifecycleGithubObservation {
5211            let observation = self
5212                .observations
5213                .lock()
5214                .unwrap()
5215                .pop_front()
5216                .unwrap_or(LifecycleGithubObservation::not_registered());
5217            if observation.status == GithubRunnerObservation::NotRegistered {
5218                self.remaining_runners.store(0, Ordering::SeqCst);
5219            }
5220            observation
5221        }
5222
5223        async fn deregister(
5224            &self,
5225            _target: &ScaleTarget,
5226            runner_id: u64,
5227            _cancel: &CancelToken,
5228        ) -> bool {
5229            self.deregistrations.lock().unwrap().push(runner_id);
5230            if self.deregistration_fails.load(Ordering::SeqCst) {
5231                return false;
5232            }
5233            self.remaining_runners.store(0, Ordering::SeqCst);
5234            true
5235        }
5236    }
5237
5238    #[derive(Debug)]
5239    struct FakePackages {
5240        version: RunnerVersion,
5241        leases: Mutex<BTreeSet<AttemptId>>,
5242        materializations: AtomicUsize,
5243        materialization_failures: AtomicUsize,
5244        release_failures: AtomicUsize,
5245        releases: AtomicUsize,
5246        prunes: AtomicUsize,
5247        prune_currents: Mutex<Vec<RunnerVersion>>,
5248    }
5249
5250    impl Default for FakePackages {
5251        fn default() -> Self {
5252            Self {
5253                version: RunnerVersion::parse("2.330.0").unwrap(),
5254                leases: Mutex::new(BTreeSet::new()),
5255                materializations: AtomicUsize::new(0),
5256                materialization_failures: AtomicUsize::new(0),
5257                release_failures: AtomicUsize::new(0),
5258                releases: AtomicUsize::new(0),
5259                prunes: AtomicUsize::new(0),
5260                prune_currents: Mutex::new(Vec::new()),
5261            }
5262        }
5263    }
5264
5265    impl FakePackages {
5266        fn fail_materializations(&self, count: usize) {
5267            self.materialization_failures.store(count, Ordering::SeqCst);
5268        }
5269
5270        fn fail_releases(&self, count: usize) {
5271            self.release_failures.store(count, Ordering::SeqCst);
5272        }
5273    }
5274
5275    #[async_trait]
5276    impl RuntimePackages for FakePackages {
5277        async fn materialize(
5278            &self,
5279            attempt: &RunnerAttempt,
5280        ) -> Result<RunnerVersion, FailureReason> {
5281            self.materializations.fetch_add(1, Ordering::SeqCst);
5282            if self
5283                .materialization_failures
5284                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
5285                    if left > 0 { Some(left - 1) } else { None }
5286                })
5287                .is_ok()
5288            {
5289                return Err(FailureReason::Other(
5290                    "runner package materialization failed transiently".into(),
5291                ));
5292            }
5293            fs::create_dir_all(attempt.runtime_path()).unwrap();
5294            fs::write(attempt.runtime_path().join("runner-package"), b"verified").unwrap();
5295            self.leases.lock().unwrap().insert(attempt.id);
5296            Ok(self.version.clone())
5297        }
5298
5299        fn release(&self, attempt: AttemptId) -> Result<(), FailureReason> {
5300            if self
5301                .release_failures
5302                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
5303                    if left > 0 { Some(left - 1) } else { None }
5304                })
5305                .is_ok()
5306            {
5307                return Err(FailureReason::Other(
5308                    "runner package lease could not be released".into(),
5309                ));
5310            }
5311            self.leases.lock().unwrap().remove(&attempt);
5312            self.releases.fetch_add(1, Ordering::SeqCst);
5313            Ok(())
5314        }
5315
5316        fn prune_obsolete_guarded(
5317            &self,
5318            _authority: PruneAuthority<'_>,
5319            current: &RunnerVersion,
5320            _attempts: &[RunnerAttempt],
5321        ) -> Result<(), FailureReason> {
5322            self.prunes.fetch_add(1, Ordering::SeqCst);
5323            self.prune_currents.lock().unwrap().push(current.clone());
5324            Ok(())
5325        }
5326    }
5327
5328    #[derive(Debug, Default)]
5329    struct FakeProcesses {
5330        alive: AtomicBool,
5331        completed_successfully: AtomicBool,
5332        spawns: AtomicUsize,
5333        spawn_failures: AtomicUsize,
5334        live_spawn_failure: AtomicBool,
5335        terminations: AtomicUsize,
5336        intent: AtomicBool,
5337        intent_failure: AtomicBool,
5338        actions: Mutex<Vec<&'static str>>,
5339        saw_secret: AtomicBool,
5340    }
5341
5342    impl FakeProcesses {
5343        fn fail_spawns(&self, count: usize) {
5344            self.spawn_failures.store(count, Ordering::SeqCst);
5345        }
5346
5347        fn fail_spawn_with_live_child(&self) {
5348            self.live_spawn_failure.store(true, Ordering::SeqCst);
5349        }
5350
5351        fn set_alive(&self, alive: bool) {
5352            self.alive.store(alive, Ordering::SeqCst);
5353        }
5354
5355        fn finish_successfully(&self) {
5356            self.completed_successfully.store(true, Ordering::SeqCst);
5357            self.alive.store(false, Ordering::SeqCst);
5358        }
5359
5360        fn fail_intent(&self) {
5361            self.intent_failure.store(true, Ordering::SeqCst);
5362        }
5363    }
5364
5365    impl ProcessSupervisor for FakeProcesses {
5366        fn spawn(
5367            &self,
5368            attempt: &RunnerAttempt,
5369            config: &EncodedJitConfig,
5370        ) -> Result<u32, ProcessStartFailure> {
5371            self.spawns.fetch_add(1, Ordering::SeqCst);
5372            // Model the production handoff on both paths: the sensitive file is
5373            // scoped to this call and absent when it returns.
5374            let handoff = RestrictiveHandoff::create(
5375                attempt.runtime_path(),
5376                SecretString::from(config.expose().to_owned()),
5377            )
5378            .unwrap();
5379            self.saw_secret
5380                .store(config.expose() == JIT, Ordering::SeqCst);
5381            let handoff_path = handoff.path().to_path_buf();
5382            let failing = self
5383                .spawn_failures
5384                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
5385                    if left > 0 { Some(left - 1) } else { None }
5386                })
5387                .is_ok();
5388            drop(handoff);
5389            assert!(!handoff_path.exists(), "handoff must be absent on return");
5390            if self.live_spawn_failure.swap(false, Ordering::SeqCst) {
5391                self.alive.store(true, Ordering::SeqCst);
5392                return Err(ProcessStartFailure::after_spawn_live(4242));
5393            }
5394            if failing {
5395                return Err(ProcessStartFailure::before_spawn(
5396                    FailureReason::ProcessStartFailed,
5397                ));
5398            }
5399            self.alive.store(true, Ordering::SeqCst);
5400            Ok(4242)
5401        }
5402
5403        fn is_alive(&self, _attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
5404            self.actions.lock().unwrap().push("observe_process");
5405            Ok(self.alive.load(Ordering::SeqCst))
5406        }
5407
5408        fn recovered_pid(&self, _attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
5409            Ok(self.alive.load(Ordering::SeqCst).then_some(4242))
5410        }
5411
5412        fn completed_successfully(&self, _attempt: &RunnerAttempt) -> bool {
5413            self.completed_successfully.load(Ordering::SeqCst)
5414        }
5415
5416        fn record_terminate_intent(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
5417            self.actions.lock().unwrap().push("terminate_intent");
5418            if self.intent_failure.load(Ordering::SeqCst) {
5419                return Err(FailureReason::Other(
5420                    "terminate intent directory sync failed".into(),
5421                ));
5422            }
5423            self.intent.store(true, Ordering::SeqCst);
5424            Ok(())
5425        }
5426
5427        fn has_terminate_intent(&self, _attempt: &RunnerAttempt) -> bool {
5428            self.intent.load(Ordering::SeqCst)
5429        }
5430
5431        fn terminate(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
5432            assert!(
5433                self.intent.load(Ordering::SeqCst),
5434                "the durable intent must exist before signalling"
5435            );
5436            self.actions.lock().unwrap().push("terminate");
5437            self.terminations.fetch_add(1, Ordering::SeqCst);
5438            self.alive.store(false, Ordering::SeqCst);
5439            Ok(())
5440        }
5441    }
5442
5443    #[derive(Debug, Default)]
5444    struct FakeIsolatedProvider {
5445        resources: Mutex<BTreeMap<AttemptId, (EnvironmentIdentity, EnvironmentState)>>,
5446        extra_resources: Mutex<Vec<EnvironmentIdentity>>,
5447        unsupported_host: AtomicBool,
5448        permission_denied: AtomicBool,
5449        incompatible_image: AtomicBool,
5450        prepare_failure: AtomicBool,
5451        recovery_unavailable: AtomicBool,
5452        destroy_deferred: AtomicBool,
5453        handoffs: AtomicUsize,
5454        completed_successfully: AtomicBool,
5455        native_calls: AtomicUsize,
5456        actions: Mutex<Vec<&'static str>>,
5457    }
5458
5459    impl FakeIsolatedProvider {
5460        fn identity(attempt: &RunnerAttempt, host: HostId) -> EnvironmentIdentity {
5461            let AttemptExecution::Isolated {
5462                provider_kind,
5463                resolved_image,
5464                generation,
5465                ..
5466            } = attempt.execution()
5467            else {
5468                panic!("isolated intent required")
5469            };
5470            EnvironmentIdentity::Isolated {
5471                host,
5472                attempt: attempt.id,
5473                provider_kind: *provider_kind,
5474                environment_id: format!("environment-{}", attempt.id),
5475                resolved_image: resolved_image.clone(),
5476                generation: generation.clone(),
5477            }
5478        }
5479
5480        fn resource_count(&self) -> usize {
5481            self.resources.lock().unwrap().len()
5482        }
5483    }
5484
5485    impl ExecutionProvider for FakeIsolatedProvider {
5486        fn probe(&self, policy: &ScalePolicy) -> ProviderCapability {
5487            if self.unsupported_host.load(Ordering::SeqCst) {
5488                ProviderCapability::Unsupported
5489            } else if self.permission_denied.load(Ordering::SeqCst) {
5490                ProviderCapability::PermissionDenied
5491            } else if policy.execution_policy().is_native() {
5492                ProviderCapability::Unsupported
5493            } else {
5494                ProviderCapability::Ready
5495            }
5496        }
5497
5498        fn resolve(
5499            &self,
5500            policy: &ScalePolicy,
5501        ) -> Result<Option<ResolvedEnvironment>, FailureReason> {
5502            let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
5503                policy.execution_policy()
5504            else {
5505                return Err(FailureReason::Other("isolated policy required".into()));
5506            };
5507            Ok(Some(ResolvedEnvironment {
5508                provider_kind: Backend::Oci,
5509                image: if self.incompatible_image.load(Ordering::SeqCst) {
5510                    ImageReference::new("vm-version:wrong-provider")
5511                        .expect("valid but incompatible")
5512                } else {
5513                    image.clone()
5514                },
5515            }))
5516        }
5517
5518        fn prepare(
5519            &self,
5520            attempt: &RunnerAttempt,
5521            policy: &ScalePolicy,
5522        ) -> Result<PreparedEnvironment, FailureReason> {
5523            assert_eq!(
5524                attempt.state(),
5525                AttemptState::Preparing,
5526                "intent must be durable before provider effect"
5527            );
5528            self.actions.lock().unwrap().push("prepare");
5529            let identity = Self::identity(attempt, policy.host_id);
5530            self.resources
5531                .lock()
5532                .unwrap()
5533                .insert(attempt.id, (identity.clone(), EnvironmentState::Starting));
5534            if self.prepare_failure.swap(false, Ordering::SeqCst) {
5535                return Err(FailureReason::Other("provider-secret-needle".into()));
5536            }
5537            Ok(PreparedEnvironment::isolated(attempt.id, identity))
5538        }
5539
5540        fn start(
5541            &self,
5542            prepared: PreparedEnvironment,
5543            attempt: &RunnerAttempt,
5544            handoff: OneTimeJitHandoff<'_>,
5545        ) -> Result<EnvironmentIdentity, ProcessStartFailure> {
5546            assert_eq!(prepared.attempt, attempt.id);
5547            assert_eq!(attempt.state(), AttemptState::JitReceived);
5548            assert_eq!(handoff.consume().expose(), JIT);
5549            self.handoffs.fetch_add(1, Ordering::SeqCst);
5550            self.actions.lock().unwrap().push("start");
5551            let mut resources = self.resources.lock().unwrap();
5552            let (identity, state) = resources.get_mut(&attempt.id).expect("prepared resource");
5553            *state = EnvironmentState::Running;
5554            Ok(identity.clone())
5555        }
5556
5557        fn inspect(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
5558            self.actions.lock().unwrap().push("inspect");
5559            Ok(self
5560                .resources
5561                .lock()
5562                .unwrap()
5563                .get(&attempt.id)
5564                .map_or(EnvironmentState::Missing, |(_, state)| *state))
5565        }
5566
5567        fn recover(&self, attempt: &RunnerAttempt) -> Result<EnvironmentState, FailureReason> {
5568            if self.recovery_unavailable.load(Ordering::SeqCst) {
5569                return Err(FailureReason::Other(
5570                    "provider discovery unavailable".into(),
5571                ));
5572            }
5573            self.inspect(attempt)
5574        }
5575
5576        fn owns(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
5577            Ok(self
5578                .resources
5579                .lock()
5580                .unwrap()
5581                .get(&attempt.id)
5582                .is_some_and(|(identity, _)| {
5583                    identity_matches_intent(attempt_host(identity), attempt, identity)
5584                }))
5585        }
5586
5587        fn stop(&self, attempt: &RunnerAttempt) -> Result<ProviderStop, FailureReason> {
5588            assert!(self.owns(attempt)?);
5589            self.actions.lock().unwrap().push("stop");
5590            if let Some((_, state)) = self.resources.lock().unwrap().get_mut(&attempt.id) {
5591                *state = EnvironmentState::Exited;
5592            }
5593            Ok(ProviderStop::Stopped)
5594        }
5595
5596        fn destroy(&self, attempt: &RunnerAttempt) -> Result<ProviderDestroy, FailureReason> {
5597            assert!(self.owns(attempt)?);
5598            self.actions.lock().unwrap().push("destroy");
5599            if self.destroy_deferred.load(Ordering::SeqCst) {
5600                return Ok(ProviderDestroy::Deferred("provider busy"));
5601            }
5602            self.resources.lock().unwrap().remove(&attempt.id);
5603            Ok(ProviderDestroy::Destroyed)
5604        }
5605
5606        fn enumerate_owned(&self, host: HostId) -> Vec<EnvironmentIdentity> {
5607            let mut owned = self
5608                .resources
5609                .lock()
5610                .unwrap()
5611                .values()
5612                .filter(|(identity, _)| attempt_host(identity) == host)
5613                .map(|(identity, _)| identity.clone())
5614                .collect::<Vec<_>>();
5615            owned.extend(
5616                self.extra_resources
5617                    .lock()
5618                    .unwrap()
5619                    .iter()
5620                    .filter(|identity| attempt_host(identity) == host)
5621                    .cloned(),
5622            );
5623            owned
5624        }
5625
5626        fn diagnostics(&self, _attempt: &RunnerAttempt) -> Vec<ProviderDiagnostic> {
5627            vec![ProviderDiagnostic::CleanupDeferred; 40]
5628        }
5629
5630        fn spawn(
5631            &self,
5632            _attempt: &RunnerAttempt,
5633            _config: &EncodedJitConfig,
5634        ) -> Result<u32, ProcessStartFailure> {
5635            self.native_calls.fetch_add(1, Ordering::SeqCst);
5636            panic!("isolated provider must never spawn natively")
5637        }
5638        fn is_alive(&self, _attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
5639            panic!("native fallback")
5640        }
5641        fn recovered_pid(&self, _attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
5642            panic!("native fallback")
5643        }
5644        fn completed_successfully(&self, _attempt: &RunnerAttempt) -> bool {
5645            self.completed_successfully.load(Ordering::SeqCst)
5646        }
5647        fn record_terminate_intent(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
5648            panic!("native fallback")
5649        }
5650        fn has_terminate_intent(&self, _attempt: &RunnerAttempt) -> bool {
5651            false
5652        }
5653        fn terminate(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
5654            panic!("native fallback")
5655        }
5656    }
5657
5658    fn attempt_host(identity: &EnvironmentIdentity) -> HostId {
5659        let EnvironmentIdentity::Isolated { host, .. } = identity else {
5660            panic!("isolated identity")
5661        };
5662        *host
5663    }
5664
5665    #[derive(Debug, Default)]
5666    struct FakeDemand {
5667        answers: Mutex<VecDeque<bool>>,
5668    }
5669
5670    impl FakeDemand {
5671        fn answering(answers: impl IntoIterator<Item = bool>) -> Self {
5672            Self {
5673                answers: Mutex::new(answers.into_iter().collect()),
5674            }
5675        }
5676    }
5677
5678    #[async_trait]
5679    impl DemandPersistence for FakeDemand {
5680        async fn persists(&self, _policy: PolicyId) -> bool {
5681            self.answers.lock().unwrap().pop_front().unwrap_or(true)
5682        }
5683    }
5684
5685    #[derive(Debug, Default)]
5686    struct FakeDelay(Mutex<Vec<Duration>>);
5687
5688    #[async_trait]
5689    impl RetryDelay for FakeDelay {
5690        async fn wait(&self, duration: Duration) {
5691            self.0.lock().unwrap().push(duration);
5692        }
5693    }
5694
5695    #[tokio::test]
5696    async fn live_capacity_reads_the_updated_sqlite_host_and_rejects_a_missing_host() {
5697        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
5698        let path = harness._root.path().join("live-capacity.sqlite3");
5699        harness.store = Arc::new(SqliteStore::open(&path).unwrap());
5700        harness.store.put_host(&harness.host).unwrap();
5701        harness.launcher = harness.restart();
5702        assert_eq!(
5703            harness.launcher.host_capacity(&harness.host).await.unwrap(),
5704            harness.host.host_capacity
5705        );
5706        // A separate CLI/TUI connection updates the journal while the existing
5707        // launcher keeps its original store connection and startup host.
5708        let writer = SqliteStore::open(&path).unwrap();
5709        let mut updated = harness.host.clone();
5710        updated.host_capacity = std::num::NonZeroU16::new(12).unwrap();
5711        writer.put_host(&updated).unwrap();
5712        assert_eq!(
5713            harness
5714                .launcher
5715                .host_capacity(&harness.host)
5716                .await
5717                .unwrap()
5718                .get(),
5719            12
5720        );
5721
5722        updated.host_capacity = std::num::NonZeroU16::new(2).unwrap();
5723        writer.put_host(&updated).unwrap();
5724        assert_eq!(
5725            harness
5726                .launcher
5727                .host_capacity(&harness.host)
5728                .await
5729                .unwrap()
5730                .get(),
5731            2
5732        );
5733
5734        let mut missing = harness.host.clone();
5735        missing.id = HostId::from_u128(999);
5736        assert_eq!(
5737            harness.launcher.host_capacity(&missing).await,
5738            Err(crate::reconcile::HostCapacityError::MissingHost)
5739        );
5740    }
5741
5742    struct Harness {
5743        _root: tempfile::TempDir,
5744        app_paths: runner_manager_platform::paths::AppPaths,
5745        launcher: LifecycleLauncher,
5746        demand: Arc<dyn DemandPersistence>,
5747        store: Arc<SqliteStore>,
5748        github: Arc<FakeGithubLifecycle>,
5749        packages: Arc<FakePackages>,
5750        processes: Arc<FakeProcesses>,
5751        clock: Arc<FakeClock>,
5752        events: Arc<AttemptEventLog>,
5753        reconcile_events: Arc<crate::reconcile::EventLog>,
5754        delay: Arc<FakeDelay>,
5755        host: runner_manager_domain::model::Host,
5756        policy: ScalePolicy,
5757        allocation_lock: InProcessAllocationLock,
5758        /// The repository persistent root, once one is configured.
5759        workspace_root: Option<LocalAbsolutePath>,
5760    }
5761
5762    impl Harness {
5763        fn new(github: FakeGithubLifecycle, demand: Arc<dyn DemandPersistence>) -> Self {
5764            let root = tempfile::tempdir().unwrap();
5765            let paths = runner_manager_platform::paths::AppPaths::rooted_at(root.path());
5766            paths.create_all().unwrap();
5767            let policy = fixtures::policy()
5768                .repository("octo/repo")
5769                .autoscale("home", 2)
5770                .active()
5771                .build();
5772            // A unit harness must never inspect or write the workstation's
5773            // production runner root. On Windows that is C:\rman, which is
5774            // intentionally inaccessible to an ordinary account after a boot
5775            // service is installed. Using it made the same suite pass on a
5776            // clean CI image and fail on a correctly secured developer host.
5777            let host_root = root.path().join("host-root");
5778            fs::create_dir_all(&host_root).unwrap();
5779            let mut host = fixtures::host().build();
5780            host.runner_root_override = Some(
5781                LocalAbsolutePath::new(host_root.to_str().expect("a UTF-8 temporary path"))
5782                    .expect("a local absolute host root"),
5783            );
5784            let store = Arc::new(SqliteStore::open_in_memory().unwrap());
5785            store.put_host(&host).unwrap();
5786            let github = Arc::new(github);
5787            let packages = Arc::new(FakePackages::default());
5788            let processes = Arc::new(FakeProcesses::default());
5789            let clock = Arc::new(FakeClock::default());
5790            let events = Arc::new(AttemptEventLog::default());
5791            let reconcile_events = Arc::new(crate::reconcile::EventLog::new());
5792            let delay = Arc::new(FakeDelay::default());
5793            let ports = LifecyclePorts {
5794                store: Arc::clone(&store) as Arc<dyn Store>,
5795                github: Arc::clone(&github) as Arc<dyn LifecycleGithub>,
5796                packages: Arc::clone(&packages) as Arc<dyn RuntimePackages>,
5797                processes: Arc::clone(&processes) as Arc<dyn ProcessSupervisor>,
5798                clock: Arc::clone(&clock) as Arc<dyn Clock>,
5799                demand: Arc::clone(&demand),
5800                delay: Arc::clone(&delay) as Arc<dyn RetryDelay>,
5801                events: Arc::clone(&events) as Arc<dyn AttemptEventSink>,
5802                reconcile_events: Arc::clone(&reconcile_events) as Arc<dyn EventSink>,
5803            };
5804            let launcher = Self::launcher_over(policy.host_id, &paths, ports);
5805            Self {
5806                _root: root,
5807                app_paths: paths,
5808                launcher,
5809                demand,
5810                store,
5811                github,
5812                packages,
5813                processes,
5814                clock,
5815                events,
5816                reconcile_events,
5817                delay,
5818                host,
5819                policy,
5820                allocation_lock: InProcessAllocationLock::new(),
5821                workspace_root: None,
5822            }
5823        }
5824
5825        /// Put disposable attempts under a host root of this harness's own.
5826        ///
5827        /// Without it the launcher resolves the *platform* default, which on
5828        /// Windows is `%SystemDrive%\rman` — a real directory on the machine
5829        /// running the suite. Every test added by `c2` places its files inside
5830        /// its own temporary directory instead.
5831        fn with_host_runner_root(mut self) -> Self {
5832            let host_root = self.host_root();
5833            fs::create_dir_all(&host_root).unwrap();
5834            self.host.runner_root_override = Some(
5835                LocalAbsolutePath::new(host_root.to_str().expect("a UTF-8 temporary path"))
5836                    .expect("a local absolute host root"),
5837            );
5838            self.store.put_host(&self.host).unwrap();
5839            self
5840        }
5841
5842        /// Opt this harness's repository into a persistent workspace (D4).
5843        fn with_persistent_workspace(mut self, capacity: u16) -> Self {
5844            self = self.with_host_runner_root();
5845            let root = self._root.path().join("persist");
5846            let root = LocalAbsolutePath::new(root.to_str().expect("a UTF-8 temporary path"))
5847                .expect("a local absolute workspace root");
5848            self.policy = fixtures::policy()
5849                .repository("octo/repo")
5850                .autoscale("home", capacity)
5851                .active()
5852                .build();
5853            self.policy
5854                .set_workspace_policy(
5855                    WorkspacePolicy::persistent(root.clone(), TargetScope::Repository)
5856                        .expect("a repository may be persistent"),
5857                )
5858                .expect("a repository may be persistent");
5859            self.workspace_root = Some(root);
5860            // The journal's copy, so that cleanup's cross-check against a
5861            // surviving policy is exercised rather than skipped.
5862            self.store.insert_policy(&self.policy).unwrap();
5863            self
5864        }
5865
5866        fn workspace_root(&self) -> &LocalAbsolutePath {
5867            self.workspace_root
5868                .as_ref()
5869                .expect("this harness configured a persistent workspace")
5870        }
5871
5872        fn slot_path(&self, slot: u16) -> PathBuf {
5873            self.workspace_root().as_path().join(format!("s{slot}"))
5874        }
5875
5876        fn host_root(&self) -> PathBuf {
5877            self._root.path().join("host-root")
5878        }
5879
5880        fn attempt(&self, id: AttemptId) -> RunnerAttempt {
5881            self.store
5882                .attempt(id)
5883                .unwrap()
5884                .expect("the attempt is journalled")
5885        }
5886
5887        /// Conclude an attempt and run the real cleanup over it.
5888        fn conclude(&self, id: AttemptId) -> RunnerAttempt {
5889            let mut attempt = self.attempt(id);
5890            attempt
5891                .conclude(
5892                    AttemptOutcome::failed(FailureReason::ProcessExitedUnexpectedly),
5893                    self.clock.now(),
5894                )
5895                .unwrap();
5896            self.store.record_attempt(&attempt).unwrap();
5897            attempt
5898        }
5899
5900        async fn cleanup_retaining_work(&self, id: AttemptId) {
5901            self.conclude(id);
5902            self.launcher
5903                .clean(id)
5904                .await
5905                .expect("the slot is scrubbed and the lease released");
5906        }
5907
5908        /// The launcher configuration every launcher in this harness shares, so
5909        /// that the one a restart mints cannot drift from the original.
5910        fn launcher_over(
5911            host: HostId,
5912            paths: &runner_manager_platform::paths::AppPaths,
5913            ports: LifecyclePorts,
5914        ) -> LifecycleLauncher {
5915            LifecycleLauncher::new(
5916                host,
5917                paths.clone(),
5918                paths.logs_dir(),
5919                1,
5920                RecoveryTimeouts::new(
5921                    Elapsed::seconds(10),
5922                    Elapsed::seconds(10),
5923                    Elapsed::seconds(10),
5924                ),
5925                RetryPolicy::bounded(3, Duration::from_millis(10), Duration::from_millis(25)),
5926                ports,
5927            )
5928        }
5929
5930        /// The same journal, the same directories, a launcher that remembers
5931        /// nothing — which is what a daemon restart is.
5932        fn restart(&self) -> LifecycleLauncher {
5933            Self::launcher_over(
5934                self.policy.host_id,
5935                &self.app_paths,
5936                LifecyclePorts {
5937                    store: Arc::clone(&self.store) as Arc<dyn Store>,
5938                    github: Arc::clone(&self.github) as Arc<dyn LifecycleGithub>,
5939                    packages: Arc::clone(&self.packages) as Arc<dyn RuntimePackages>,
5940                    processes: Arc::clone(&self.processes) as Arc<dyn ProcessSupervisor>,
5941                    clock: Arc::clone(&self.clock) as Arc<dyn Clock>,
5942                    demand: Arc::clone(&self.demand),
5943                    delay: Arc::clone(&self.delay) as Arc<dyn RetryDelay>,
5944                    events: Arc::clone(&self.events) as Arc<dyn AttemptEventSink>,
5945                    reconcile_events: Arc::clone(&self.reconcile_events) as Arc<dyn EventSink>,
5946                },
5947            )
5948        }
5949
5950        async fn ready(&self) {
5951            self.launcher
5952                .recover_startup(std::slice::from_ref(&self.policy))
5953                .await
5954                .unwrap();
5955        }
5956
5957        async fn launch(&self) -> RunnerAttempt {
5958            self.launch_result().await.unwrap()
5959        }
5960
5961        async fn launch_result(&self) -> Result<RunnerAttempt, LaunchFailure> {
5962            self.launch_after_waiting(Duration::ZERO).await
5963        }
5964
5965        async fn launch_after_waiting(
5966            &self,
5967            lock_wait: Duration,
5968        ) -> Result<RunnerAttempt, LaunchFailure> {
5969            let guard = self.allocation_lock.acquire().await.unwrap();
5970            self.launcher
5971                .launch(LaunchRequest {
5972                    host: &self.host,
5973                    policy: &self.policy,
5974                    allocation_guard: &guard,
5975                    lock_wait,
5976                })
5977                .await
5978        }
5979
5980        fn only_attempt(&self) -> RunnerAttempt {
5981            self.store.attempts().unwrap().into_iter().next().unwrap()
5982        }
5983    }
5984
5985    fn isolated_harness() -> Harness {
5986        use runner_manager_domain::execution::{ExecutionPolicy, ResourceLimits};
5987        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5988            .with_host_runner_root();
5989        let image =
5990            ImageReference::new(format!("registry.example/runner@sha256:{}", "a".repeat(64)))
5991                .expect("pinned image");
5992        harness
5993            .policy
5994            .set_execution_policy(ExecutionPolicy::Isolated {
5995                backend: Backend::Oci,
5996                image,
5997                resources: ResourceLimits {
5998                    cpu_millis: 1000,
5999                    memory_mib: 1024,
6000                    disk_mib: 4096,
6001                },
6002            })
6003            .expect("isolated policy");
6004        harness.github.watch_journal(Arc::clone(&harness.store));
6005        harness
6006    }
6007
6008    fn launcher_with_isolated(
6009        harness: &Harness,
6010        provider: Arc<FakeIsolatedProvider>,
6011    ) -> LifecycleLauncher {
6012        Harness::launcher_over(
6013            harness.policy.host_id,
6014            &harness.app_paths,
6015            LifecyclePorts {
6016                store: Arc::clone(&harness.store) as Arc<dyn Store>,
6017                github: Arc::clone(&harness.github) as Arc<dyn LifecycleGithub>,
6018                packages: Arc::clone(&harness.packages) as Arc<dyn RuntimePackages>,
6019                processes: provider as Arc<dyn ExecutionProvider>,
6020                clock: Arc::clone(&harness.clock) as Arc<dyn Clock>,
6021                demand: Arc::clone(&harness.demand),
6022                delay: Arc::clone(&harness.delay) as Arc<dyn RetryDelay>,
6023                events: Arc::clone(&harness.events) as Arc<dyn AttemptEventSink>,
6024                reconcile_events: Arc::clone(&harness.reconcile_events) as Arc<dyn EventSink>,
6025            },
6026        )
6027    }
6028
6029    #[tokio::test]
6030    async fn isolated_policy_and_journal_never_enter_native_provider_or_jit() {
6031        use runner_manager_domain::execution::{
6032            AttemptExecution, Backend, ExecutionPolicy, ImageReference, ResourceLimits,
6033        };
6034
6035        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
6036            .with_host_runner_root();
6037        let image =
6038            ImageReference::new(format!("registry.example/runner@sha256:{}", "a".repeat(64)))
6039                .expect("pinned image");
6040        harness
6041            .policy
6042            .set_execution_policy(ExecutionPolicy::Isolated {
6043                backend: Backend::Oci,
6044                image: image.clone(),
6045                resources: ResourceLimits {
6046                    cpu_millis: 1000,
6047                    memory_mib: 1024,
6048                    disk_mib: 4096,
6049                },
6050            })
6051            .expect("valid isolated profile");
6052
6053        harness.ready().await;
6054        assert_eq!(
6055            harness.processes.probe(&harness.policy),
6056            ProviderCapability::Unsupported
6057        );
6058        let failure = harness
6059            .launch_result()
6060            .await
6061            .expect_err("provider is unavailable");
6062        assert_eq!(
6063            failure.reason,
6064            FailureReason::IsolationProvider(IsolationProviderFailure::Unsupported)
6065        );
6066
6067        let runtime = harness.host_root().join("isolated-owned-environment");
6068        fs::create_dir_all(&runtime).expect("provider resource fixture");
6069        fs::write(runtime.join("owned-marker"), "non-secret").expect("fixture marker");
6070        let mut attempt = RunnerAttempt::allocate(
6071            AttemptId::from_u128(0x123),
6072            harness.policy.id,
6073            runtime.clone(),
6074            harness.clock.now(),
6075        );
6076        attempt
6077            .allocate_execution(AttemptExecution::Isolated {
6078                provider_kind: Backend::Oci,
6079                environment_id: None,
6080                resolved_image: image,
6081                generation: "generation-123".into(),
6082            })
6083            .expect("isolated intent");
6084        attempt
6085            .prepared_environment("environment-123".into())
6086            .expect("prepared identity");
6087        harness
6088            .store
6089            .record_attempt(&attempt)
6090            .expect("durable isolated journal");
6091
6092        harness
6093            .launcher
6094            .recover_startup(std::slice::from_ref(&harness.policy))
6095            .await
6096            .expect("unsupported isolated cleanup is profile-local");
6097        let failure = harness
6098            .launch_result()
6099            .await
6100            .expect_err("provider unavailable for this policy");
6101        assert_eq!(
6102            failure.reason,
6103            FailureReason::IsolationProvider(IsolationProviderFailure::Unsupported)
6104        );
6105        harness
6106            .launcher
6107            .supervise(&harness.policy)
6108            .await
6109            .expect("unavailable attempt is deferred");
6110        assert!(harness.launcher.clean(attempt.id).await.is_err());
6111        assert_eq!(
6112            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
6113            AttemptState::CleanupDeferred
6114        );
6115        assert!(matches!(
6116            harness.launcher.recover_startup(&[]).await,
6117            Err(LifecycleError::RecoveryIncomplete)
6118        ));
6119        assert!(
6120            runtime.join("owned-marker").is_file(),
6121            "native cleanup touched the isolated environment"
6122        );
6123        assert!(
6124            harness.processes.actions.lock().unwrap().is_empty(),
6125            "native recovery inspected an isolated identity"
6126        );
6127        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
6128        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
6129        assert_eq!(harness.packages.materializations.load(Ordering::SeqCst), 0);
6130    }
6131
6132    #[tokio::test]
6133    async fn isolated_prepare_is_durable_before_jit_and_start_uses_one_handoff() {
6134        let harness = isolated_harness();
6135        let provider = Arc::new(FakeIsolatedProvider::default());
6136        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6137        launcher
6138            .recover_startup(std::slice::from_ref(&harness.policy))
6139            .await
6140            .expect("ready");
6141        let guard = harness.allocation_lock.acquire().await.unwrap();
6142        let attempt = launcher
6143            .launch(LaunchRequest {
6144                host: &harness.host,
6145                policy: &harness.policy,
6146                allocation_guard: &guard,
6147                lock_wait: Duration::ZERO,
6148            })
6149            .await
6150            .expect("isolated launch");
6151        assert_eq!(attempt.state(), AttemptState::Starting);
6152        assert_eq!(provider.resource_count(), 1);
6153        assert_eq!(provider.handoffs.load(Ordering::SeqCst), 1);
6154        assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6155        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
6156        let fact = harness
6157            .github
6158            .registration_facts()
6159            .pop()
6160            .expect("JIT registration");
6161        assert_eq!(
6162            fact.journal_states,
6163            vec![AttemptState::Prepared],
6164            "provider readiness preceded GitHub JIT"
6165        );
6166        assert_eq!(
6167            harness
6168                .events
6169                .events()
6170                .into_iter()
6171                .filter_map(|event| match event {
6172                    AttemptEvent::State { state, .. } => Some(state),
6173                    _ => None,
6174                })
6175                .collect::<Vec<_>>(),
6176            vec![
6177                AttemptState::Allocated,
6178                AttemptState::Preparing,
6179                AttemptState::Prepared,
6180                AttemptState::JitReceived,
6181                AttemptState::Starting
6182            ]
6183        );
6184        let restarted = launcher_with_isolated(&harness, Arc::clone(&provider));
6185        restarted
6186            .recover_startup(std::slice::from_ref(&harness.policy))
6187            .await
6188            .expect("adopt live sandbox");
6189        assert_eq!(provider.resource_count(), 1);
6190        assert_eq!(
6191            harness.github.registrations.load(Ordering::SeqCst),
6192            1,
6193            "restart cannot issue duplicate JIT"
6194        );
6195        harness
6196            .github
6197            .observe(GithubRunnerObservation::Registered { busy: true });
6198        restarted
6199            .supervise(&harness.policy)
6200            .await
6201            .expect("job observed");
6202        assert_eq!(
6203            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
6204            AttemptState::Busy
6205        );
6206        provider
6207            .resources
6208            .lock()
6209            .unwrap()
6210            .get_mut(&attempt.id)
6211            .unwrap()
6212            .1 = EnvironmentState::Exited;
6213        harness
6214            .github
6215            .observe(GithubRunnerObservation::NotRegistered);
6216        restarted
6217            .supervise(&harness.policy)
6218            .await
6219            .expect("terminal cleanup");
6220        assert_eq!(provider.resource_count(), 0);
6221        assert_eq!(
6222            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
6223            AttemptState::Cleaned
6224        );
6225    }
6226
6227    #[tokio::test]
6228    async fn attached_isolated_job_exit_is_recorded_as_completed() {
6229        let harness = isolated_harness();
6230        let provider = Arc::new(FakeIsolatedProvider::default());
6231        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6232        launcher
6233            .recover_startup(std::slice::from_ref(&harness.policy))
6234            .await
6235            .unwrap();
6236        let guard = harness.allocation_lock.acquire().await.unwrap();
6237        let attempt = launcher
6238            .launch(LaunchRequest {
6239                host: &harness.host,
6240                policy: &harness.policy,
6241                allocation_guard: &guard,
6242                lock_wait: Duration::ZERO,
6243            })
6244            .await
6245            .unwrap();
6246        harness
6247            .github
6248            .observe(GithubRunnerObservation::Registered { busy: true });
6249        launcher.supervise(&harness.policy).await.unwrap();
6250        provider
6251            .resources
6252            .lock()
6253            .unwrap()
6254            .get_mut(&attempt.id)
6255            .unwrap()
6256            .1 = EnvironmentState::Exited;
6257        provider
6258            .completed_successfully
6259            .store(true, Ordering::SeqCst);
6260        harness
6261            .github
6262            .observe(GithubRunnerObservation::NotRegistered);
6263        launcher.supervise(&harness.policy).await.unwrap();
6264        let cleaned = harness.store.attempt(attempt.id).unwrap().unwrap();
6265        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
6266        assert_eq!(cleaned.state(), AttemptState::Cleaned);
6267    }
6268
6269    #[tokio::test]
6270    async fn isolated_prepare_failure_stays_local_and_crash_gap_recovers_owned_resource() {
6271        let harness = isolated_harness();
6272        let provider = Arc::new(FakeIsolatedProvider::default());
6273        provider.prepare_failure.store(true, Ordering::SeqCst);
6274        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6275        launcher
6276            .recover_startup(std::slice::from_ref(&harness.policy))
6277            .await
6278            .expect("ready");
6279        let guard = harness.allocation_lock.acquire().await.unwrap();
6280        let failure = launcher
6281            .launch(LaunchRequest {
6282                host: &harness.host,
6283                policy: &harness.policy,
6284                allocation_guard: &guard,
6285                lock_wait: Duration::ZERO,
6286            })
6287            .await
6288            .expect_err("prepare failed after creating resource");
6289        assert_eq!(
6290            failure.reason,
6291            FailureReason::IsolationProvider(IsolationProviderFailure::RuntimeOperationFailed)
6292        );
6293        assert_eq!(provider.resource_count(), 1);
6294        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
6295        assert!(
6296            !harness
6297                .store
6298                .dump_text()
6299                .unwrap()
6300                .contains("provider-secret-needle")
6301        );
6302        let id = harness.store.attempts().unwrap()[0].id;
6303        assert_eq!(
6304            harness.store.attempt(id).unwrap().unwrap().outcome(),
6305            Some(&AttemptOutcome::failed(FailureReason::IsolationProvider(
6306                IsolationProviderFailure::RuntimeOperationFailed
6307            )))
6308        );
6309        let restarted = launcher_with_isolated(&harness, Arc::clone(&provider));
6310        restarted
6311            .recover_startup(std::slice::from_ref(&harness.policy))
6312            .await
6313            .expect("profile-local recovery");
6314        assert_eq!(
6315            provider.resource_count(),
6316            0,
6317            "the exact owned resource was destroyed once"
6318        );
6319        assert_eq!(
6320            harness.store.attempt(id).unwrap().unwrap().state(),
6321            AttemptState::Cleaned
6322        );
6323        let diagnostic =
6324            fs::read_to_string(restarted.diagnostics_root.join(format!("{id}.log"))).unwrap();
6325        assert!(diagnostic.contains("reason=isolation_runtime_operation_failed"));
6326        assert!(!diagnostic.contains("provider-secret-needle"));
6327        assert_eq!(
6328            provider
6329                .actions
6330                .lock()
6331                .unwrap()
6332                .iter()
6333                .filter(|action| **action == "destroy")
6334                .count(),
6335            1
6336        );
6337        assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6338    }
6339
6340    #[test]
6341    fn isolation_capability_and_adapter_failures_keep_closed_categories() {
6342        let cases = [
6343            (
6344                ProviderCapability::NotInstalled,
6345                IsolationProviderFailure::NotInstalled,
6346            ),
6347            (
6348                ProviderCapability::PermissionDenied,
6349                IsolationProviderFailure::PermissionDenied,
6350            ),
6351            (
6352                ProviderCapability::ImageUnavailableOrIncompatible,
6353                IsolationProviderFailure::ImageUnavailableOrIncompatible,
6354            ),
6355            (
6356                ProviderCapability::DiskQuotaUnavailable,
6357                IsolationProviderFailure::DiskQuotaUnavailable,
6358            ),
6359            (
6360                ProviderCapability::Degraded,
6361                IsolationProviderFailure::Degraded,
6362            ),
6363        ];
6364        for (capability, category) in cases {
6365            assert_eq!(
6366                capability.refusal(),
6367                FailureReason::IsolationProvider(category)
6368            );
6369        }
6370        let raw = FailureReason::Other("ghp_secret_from_provider".into());
6371        let safe = safe_isolation_reason(raw, IsolationProviderFailure::RuntimeOperationFailed);
6372        assert_eq!(
6373            safe,
6374            FailureReason::IsolationProvider(IsolationProviderFailure::RuntimeOperationFailed)
6375        );
6376        assert!(!safe.to_string().contains("ghp_secret"));
6377        assert_eq!(
6378            safe_isolation_reason(
6379                FailureReason::IsolationProvider(IsolationProviderFailure::PermissionDenied),
6380                IsolationProviderFailure::RuntimeOperationFailed,
6381            ),
6382            FailureReason::IsolationProvider(IsolationProviderFailure::PermissionDenied)
6383        );
6384    }
6385
6386    #[tokio::test]
6387    async fn isolated_permission_and_image_failures_stop_before_jit_without_native_fallback() {
6388        for image_failure in [false, true] {
6389            let harness = isolated_harness();
6390            let provider = Arc::new(FakeIsolatedProvider::default());
6391            provider
6392                .permission_denied
6393                .store(!image_failure, Ordering::SeqCst);
6394            provider
6395                .incompatible_image
6396                .store(image_failure, Ordering::SeqCst);
6397            let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6398            launcher
6399                .recover_startup(std::slice::from_ref(&harness.policy))
6400                .await
6401                .unwrap();
6402            let guard = harness.allocation_lock.acquire().await.unwrap();
6403            let error = launcher
6404                .launch(LaunchRequest {
6405                    host: &harness.host,
6406                    policy: &harness.policy,
6407                    allocation_guard: &guard,
6408                    lock_wait: Duration::ZERO,
6409                })
6410                .await
6411                .expect_err("pre-JIT refusal");
6412            let expected = if image_failure {
6413                "resolved image is incompatible"
6414            } else {
6415                "permission denied"
6416            };
6417            assert!(error.reason.to_string().contains(expected));
6418            assert!(
6419                harness.store.attempts().unwrap().is_empty(),
6420                "no allocation was journalled"
6421            );
6422            assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
6423            assert_eq!(provider.handoffs.load(Ordering::SeqCst), 0);
6424            assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6425        }
6426    }
6427
6428    #[tokio::test]
6429    async fn unsupported_host_stops_before_jit_without_allocation_or_native_fallback() {
6430        let harness = isolated_harness();
6431        let provider = Arc::new(FakeIsolatedProvider::default());
6432        provider.unsupported_host.store(true, Ordering::SeqCst);
6433        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6434        launcher
6435            .recover_startup(std::slice::from_ref(&harness.policy))
6436            .await
6437            .unwrap();
6438        let guard = harness.allocation_lock.acquire().await.unwrap();
6439        let error = launcher
6440            .launch(LaunchRequest {
6441                host: &harness.host,
6442                policy: &harness.policy,
6443                allocation_guard: &guard,
6444                lock_wait: Duration::ZERO,
6445            })
6446            .await
6447            .expect_err("unsupported host must be refused before JIT");
6448
6449        assert_eq!(
6450            error.reason,
6451            FailureReason::IsolationProvider(IsolationProviderFailure::Unsupported)
6452        );
6453        assert!(harness.store.attempts().unwrap().is_empty());
6454        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
6455        assert_eq!(provider.handoffs.load(Ordering::SeqCst), 0);
6456        assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6457        assert!(provider.actions.lock().unwrap().is_empty());
6458    }
6459
6460    #[tokio::test]
6461    async fn no_journalled_environment_id_waits_for_provider_absence_proof() {
6462        let harness = isolated_harness();
6463        let provider = Arc::new(FakeIsolatedProvider::default());
6464        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6465        let runtime = harness.host_root().join("prepare-without-identity");
6466        fs::create_dir_all(&runtime).unwrap();
6467        let mut attempt = RunnerAttempt::allocate(
6468            AttemptId::from_u128(0x9191),
6469            harness.policy.id,
6470            runtime,
6471            harness.clock.now(),
6472        );
6473        let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6474            harness.policy.execution_policy()
6475        else {
6476            unreachable!()
6477        };
6478        attempt
6479            .allocate_execution(AttemptExecution::Isolated {
6480                provider_kind: Backend::Oci,
6481                environment_id: None,
6482                resolved_image: image.clone(),
6483                generation: "prepare-generation".into(),
6484            })
6485            .unwrap();
6486        attempt.begin_prepare(harness.clock.now()).unwrap();
6487        attempt
6488            .conclude(
6489                AttemptOutcome::failed(FailureReason::Other("prepare interrupted".into())),
6490                harness.clock.now(),
6491            )
6492            .unwrap();
6493        harness.store.record_attempt(&attempt).unwrap();
6494
6495        provider.recovery_unavailable.store(true, Ordering::SeqCst);
6496        launcher
6497            .clean(attempt.id)
6498            .await
6499            .expect_err("absence unproven");
6500        let deferred = harness.store.attempt(attempt.id).unwrap().unwrap();
6501        assert_eq!(deferred.state(), AttemptState::CleanupDeferred);
6502        assert!(deferred.counts_against_capacity());
6503
6504        provider.recovery_unavailable.store(false, Ordering::SeqCst);
6505        launcher.clean(attempt.id).await.expect("absence proven");
6506        assert_eq!(
6507            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
6508            AttemptState::Cleaned
6509        );
6510    }
6511
6512    #[tokio::test]
6513    async fn isolated_terminal_capacity_waits_for_confirmed_absence_and_generation_matches() {
6514        let harness = isolated_harness();
6515        let provider = Arc::new(FakeIsolatedProvider::default());
6516        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6517        launcher
6518            .recover_startup(std::slice::from_ref(&harness.policy))
6519            .await
6520            .expect("ready");
6521        let guard = harness.allocation_lock.acquire().await.unwrap();
6522        let mut attempt = launcher
6523            .launch(LaunchRequest {
6524                host: &harness.host,
6525                policy: &harness.policy,
6526                allocation_guard: &guard,
6527                lock_wait: Duration::ZERO,
6528            })
6529            .await
6530            .expect("launch");
6531        attempt
6532            .conclude(
6533                AttemptOutcome::failed(FailureReason::ProcessStartFailed),
6534                harness.clock.now(),
6535            )
6536            .unwrap();
6537        harness.store.record_attempt(&attempt).unwrap();
6538        provider.destroy_deferred.store(true, Ordering::SeqCst);
6539        launcher
6540            .clean(attempt.id)
6541            .await
6542            .expect_err("provider deferred destroy");
6543        let deferred = harness.store.attempt(attempt.id).unwrap().unwrap();
6544        assert_eq!(deferred.state(), AttemptState::CleanupDeferred);
6545        assert!(deferred.counts_against_capacity());
6546        assert_eq!(provider.resource_count(), 1);
6547        provider.destroy_deferred.store(false, Ordering::SeqCst);
6548        let restarted = launcher_with_isolated(&harness, Arc::clone(&provider));
6549        restarted
6550            .recover_startup(std::slice::from_ref(&harness.policy))
6551            .await
6552            .expect("retry cleanup");
6553        assert_eq!(provider.resource_count(), 0);
6554        assert!(
6555            !harness
6556                .store
6557                .attempt(attempt.id)
6558                .unwrap()
6559                .unwrap()
6560                .counts_against_capacity()
6561        );
6562
6563        // A reused runtime name with a different generation is not ours to delete.
6564        let second_id = AttemptId::from_u128(0x9999);
6565        let second_runtime = harness.host_root().join("generation-mismatch");
6566        fs::create_dir_all(&second_runtime).unwrap();
6567        let mut terminal = RunnerAttempt::allocate(
6568            second_id,
6569            harness.policy.id,
6570            second_runtime,
6571            harness.clock.now(),
6572        );
6573        let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6574            harness.policy.execution_policy()
6575        else {
6576            unreachable!()
6577        };
6578        terminal
6579            .allocate_execution(AttemptExecution::Isolated {
6580                provider_kind: Backend::Oci,
6581                environment_id: None,
6582                resolved_image: image.clone(),
6583                generation: "expected-generation".into(),
6584            })
6585            .unwrap();
6586        let mut stranger = FakeIsolatedProvider::identity(&terminal, harness.policy.host_id);
6587        let EnvironmentIdentity::Isolated { environment_id, .. } = &stranger else {
6588            unreachable!()
6589        };
6590        terminal.begin_prepare(harness.clock.now()).unwrap();
6591        terminal
6592            .prepared_environment(environment_id.clone())
6593            .unwrap();
6594        terminal.mark_prepared(harness.clock.now()).unwrap();
6595        terminal.jit_received(harness.clock.now()).unwrap();
6596        terminal.started_isolated(harness.clock.now()).unwrap();
6597        terminal
6598            .conclude(
6599                AttemptOutcome::failed(FailureReason::ProcessStartFailed),
6600                harness.clock.now(),
6601            )
6602            .unwrap();
6603        harness.store.record_attempt(&terminal).unwrap();
6604        let EnvironmentIdentity::Isolated { generation, .. } = &mut stranger else {
6605            unreachable!()
6606        };
6607        *generation = "another-generation".into();
6608        provider
6609            .resources
6610            .lock()
6611            .unwrap()
6612            .insert(second_id, (stranger, EnvironmentState::Running));
6613        restarted
6614            .clean(terminal.id)
6615            .await
6616            .expect_err("ownership mismatch quarantined");
6617        assert_eq!(provider.resource_count(), 1);
6618        assert_eq!(
6619            harness.store.attempt(terminal.id).unwrap().unwrap().state(),
6620            AttemptState::CleanupDeferred
6621        );
6622        assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6623    }
6624
6625    #[tokio::test]
6626    async fn isolated_restart_at_each_transition_adopts_or_destroys_one_resource() {
6627        for stage in [
6628            AttemptState::Allocated,
6629            AttemptState::Preparing,
6630            AttemptState::Prepared,
6631            AttemptState::JitReceived,
6632            AttemptState::Starting,
6633            AttemptState::Idle,
6634            AttemptState::Busy,
6635            AttemptState::Finished,
6636            AttemptState::Failed,
6637            AttemptState::Orphaned,
6638            AttemptState::Destroying,
6639            AttemptState::CleanupDeferred,
6640        ] {
6641            let harness = isolated_harness();
6642            let provider = Arc::new(FakeIsolatedProvider::default());
6643            let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6644            let id = AttemptId::from_u128(0x1000 + stage as u128);
6645            let runtime = harness.host_root().join(format!("phase-{stage}"));
6646            fs::create_dir_all(&runtime).unwrap();
6647            let mut attempt =
6648                RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
6649            let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6650                harness.policy.execution_policy()
6651            else {
6652                unreachable!()
6653            };
6654            attempt
6655                .allocate_execution(AttemptExecution::Isolated {
6656                    provider_kind: Backend::Oci,
6657                    environment_id: None,
6658                    resolved_image: image.clone(),
6659                    generation: format!("generation-{stage}"),
6660                })
6661                .unwrap();
6662            if stage != AttemptState::Allocated {
6663                attempt.begin_prepare(harness.clock.now()).unwrap();
6664            }
6665            let identity = FakeIsolatedProvider::identity(&attempt, harness.policy.host_id);
6666            if stage != AttemptState::Allocated {
6667                let resource_state = if matches!(
6668                    stage,
6669                    AttemptState::Finished
6670                        | AttemptState::Failed
6671                        | AttemptState::Orphaned
6672                        | AttemptState::Destroying
6673                        | AttemptState::CleanupDeferred
6674                ) {
6675                    EnvironmentState::Exited
6676                } else {
6677                    EnvironmentState::Running
6678                };
6679                provider
6680                    .resources
6681                    .lock()
6682                    .unwrap()
6683                    .insert(id, (identity.clone(), resource_state));
6684            }
6685            if !matches!(stage, AttemptState::Allocated | AttemptState::Preparing) {
6686                let EnvironmentIdentity::Isolated { environment_id, .. } = &identity else {
6687                    unreachable!()
6688                };
6689                attempt
6690                    .prepared_environment(environment_id.clone())
6691                    .unwrap();
6692                attempt.mark_prepared(harness.clock.now()).unwrap();
6693            }
6694            if matches!(
6695                stage,
6696                AttemptState::JitReceived
6697                    | AttemptState::Starting
6698                    | AttemptState::Idle
6699                    | AttemptState::Busy
6700                    | AttemptState::Finished
6701                    | AttemptState::Failed
6702                    | AttemptState::Orphaned
6703                    | AttemptState::Destroying
6704                    | AttemptState::CleanupDeferred
6705            ) {
6706                attempt.jit_received(harness.clock.now()).unwrap();
6707            }
6708            if matches!(
6709                stage,
6710                AttemptState::Starting
6711                    | AttemptState::Idle
6712                    | AttemptState::Busy
6713                    | AttemptState::Finished
6714                    | AttemptState::Failed
6715                    | AttemptState::Orphaned
6716                    | AttemptState::Destroying
6717                    | AttemptState::CleanupDeferred
6718            ) {
6719                attempt.started_isolated(harness.clock.now()).unwrap();
6720            }
6721            if matches!(
6722                stage,
6723                AttemptState::Idle | AttemptState::Busy | AttemptState::Finished
6724            ) {
6725                attempt.registered_idle(73, harness.clock.now()).unwrap();
6726            }
6727            if matches!(stage, AttemptState::Busy | AttemptState::Finished) {
6728                attempt.assigned_job(73, harness.clock.now()).unwrap();
6729            }
6730            if matches!(
6731                stage,
6732                AttemptState::Finished
6733                    | AttemptState::Failed
6734                    | AttemptState::Orphaned
6735                    | AttemptState::Destroying
6736                    | AttemptState::CleanupDeferred
6737            ) {
6738                let outcome = match stage {
6739                    AttemptState::Finished => AttemptOutcome::CompletedJob,
6740                    AttemptState::Orphaned => AttemptOutcome::Orphaned,
6741                    _ => AttemptOutcome::failed(FailureReason::ProcessStartFailed),
6742                };
6743                attempt.conclude(outcome, harness.clock.now()).unwrap();
6744            }
6745            if matches!(
6746                stage,
6747                AttemptState::Destroying | AttemptState::CleanupDeferred
6748            ) {
6749                attempt.begin_destroy(harness.clock.now()).unwrap();
6750            }
6751            if stage == AttemptState::CleanupDeferred {
6752                attempt.defer_cleanup(harness.clock.now()).unwrap();
6753            }
6754            harness.store.record_attempt(&attempt).unwrap();
6755            launcher
6756                .recover_startup(std::slice::from_ref(&harness.policy))
6757                .await
6758                .unwrap_or_else(|error| panic!("restart from {stage}: {error}"));
6759            let resumed = harness.store.attempt(id).unwrap().unwrap();
6760            if matches!(
6761                stage,
6762                AttemptState::Allocated
6763                    | AttemptState::Preparing
6764                    | AttemptState::Prepared
6765                    | AttemptState::Finished
6766                    | AttemptState::Failed
6767                    | AttemptState::Orphaned
6768                    | AttemptState::Destroying
6769                    | AttemptState::CleanupDeferred
6770            ) {
6771                assert_eq!(
6772                    resumed.state(),
6773                    AttemptState::Cleaned,
6774                    "{stage} must retire after restart"
6775                );
6776            } else {
6777                assert!(resumed.counts_against_capacity(), "live {stage} is adopted");
6778                assert_eq!(provider.resource_count(), 1);
6779                provider.resources.lock().unwrap().get_mut(&id).unwrap().1 =
6780                    EnvironmentState::Exited;
6781                launcher.supervise(&harness.policy).await.unwrap();
6782                assert_eq!(
6783                    harness.store.attempt(id).unwrap().unwrap().state(),
6784                    AttemptState::Cleaned
6785                );
6786            }
6787            assert_eq!(
6788                provider.resource_count(),
6789                0,
6790                "{stage} resource cleaned exactly once"
6791            );
6792            let destroyed = provider
6793                .actions
6794                .lock()
6795                .unwrap()
6796                .iter()
6797                .filter(|action| **action == "destroy")
6798                .count();
6799            assert_eq!(
6800                destroyed,
6801                usize::from(stage != AttemptState::Allocated),
6802                "{stage} destroy count"
6803            );
6804            assert_eq!(
6805                harness.github.registrations.load(Ordering::SeqCst),
6806                0,
6807                "restart from {stage} cannot duplicate JIT"
6808            );
6809            assert_eq!(provider.native_calls.load(Ordering::SeqCst), 0);
6810        }
6811    }
6812
6813    #[tokio::test]
6814    async fn duplicate_provider_ownership_is_quarantined_until_unambiguous() {
6815        let harness = isolated_harness();
6816        let provider = Arc::new(FakeIsolatedProvider::default());
6817        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6818        let id = AttemptId::from_u128(0x7777);
6819        let runtime = harness.host_root().join("duplicate-provider-ownership");
6820        fs::create_dir_all(&runtime).unwrap();
6821        let mut attempt =
6822            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
6823        let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6824            harness.policy.execution_policy()
6825        else {
6826            unreachable!()
6827        };
6828        attempt
6829            .allocate_execution(AttemptExecution::Isolated {
6830                provider_kind: Backend::Oci,
6831                environment_id: None,
6832                resolved_image: image.clone(),
6833                generation: "duplicate-generation".into(),
6834            })
6835            .unwrap();
6836        attempt.begin_prepare(harness.clock.now()).unwrap();
6837        harness.store.record_attempt(&attempt).unwrap();
6838        let first = FakeIsolatedProvider::identity(&attempt, harness.policy.host_id);
6839        let mut second = first.clone();
6840        let EnvironmentIdentity::Isolated { environment_id, .. } = &mut second else {
6841            unreachable!()
6842        };
6843        *environment_id = "another-environment".into();
6844        provider
6845            .resources
6846            .lock()
6847            .unwrap()
6848            .insert(id, (first, EnvironmentState::Running));
6849        provider.extra_resources.lock().unwrap().push(second);
6850        launcher
6851            .recover_startup(std::slice::from_ref(&harness.policy))
6852            .await
6853            .expect("duplicate is local");
6854        let deferred = harness.store.attempt(id).unwrap().unwrap();
6855        assert_eq!(deferred.state(), AttemptState::CleanupDeferred);
6856        assert!(deferred.counts_against_capacity());
6857        assert_eq!(provider.resource_count(), 1);
6858        assert_eq!(
6859            provider
6860                .actions
6861                .lock()
6862                .unwrap()
6863                .iter()
6864                .filter(|action| **action == "destroy")
6865                .count(),
6866            0
6867        );
6868        provider.extra_resources.lock().unwrap().clear();
6869        // A tolerated cleanup failure is retried after its backoff delay.
6870        harness.clock.advance_secs(31);
6871        launcher
6872            .recover_startup(std::slice::from_ref(&harness.policy))
6873            .await
6874            .expect("single identity recovered");
6875        assert_eq!(provider.resource_count(), 0);
6876        assert_eq!(
6877            harness.store.attempt(id).unwrap().unwrap().state(),
6878            AttemptState::Cleaned
6879        );
6880    }
6881
6882    #[tokio::test]
6883    async fn provider_resource_without_live_journal_is_surfaced_but_never_deleted() {
6884        let harness = isolated_harness();
6885        let provider = Arc::new(FakeIsolatedProvider::default());
6886        let launcher = launcher_with_isolated(&harness, Arc::clone(&provider));
6887        let id = AttemptId::from_u128(0x8888);
6888        let runtime = harness.host_root().join("orphan-provider-resource");
6889        fs::create_dir_all(&runtime).unwrap();
6890        let mut attempt =
6891            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
6892        let runner_manager_domain::execution::ExecutionPolicy::Isolated { image, .. } =
6893            harness.policy.execution_policy()
6894        else {
6895            unreachable!()
6896        };
6897        attempt
6898            .allocate_execution(AttemptExecution::Isolated {
6899                provider_kind: Backend::Oci,
6900                environment_id: None,
6901                resolved_image: image.clone(),
6902                generation: "orphan-generation".into(),
6903            })
6904            .unwrap();
6905        let identity = FakeIsolatedProvider::identity(&attempt, harness.policy.host_id);
6906        provider
6907            .resources
6908            .lock()
6909            .unwrap()
6910            .insert(id, (identity, EnvironmentState::Running));
6911        launcher
6912            .recover_startup(std::slice::from_ref(&harness.policy))
6913            .await
6914            .expect("orphan cannot block host");
6915        assert_eq!(provider.resource_count(), 1);
6916        assert!(
6917            harness
6918                .events
6919                .events()
6920                .contains(&AttemptEvent::QuarantinedOwnedResource { attempt: id })
6921        );
6922        assert_eq!(
6923            provider
6924                .actions
6925                .lock()
6926                .unwrap()
6927                .iter()
6928                .filter(|action| **action == "destroy")
6929                .count(),
6930            0
6931        );
6932
6933        let EnvironmentIdentity::Isolated { environment_id, .. } = provider
6934            .resources
6935            .lock()
6936            .unwrap()
6937            .get(&id)
6938            .unwrap()
6939            .0
6940            .clone()
6941        else {
6942            unreachable!()
6943        };
6944        attempt.begin_prepare(harness.clock.now()).unwrap();
6945        attempt.prepared_environment(environment_id).unwrap();
6946        attempt.mark_prepared(harness.clock.now()).unwrap();
6947        attempt.jit_received(harness.clock.now()).unwrap();
6948        attempt.started_isolated(harness.clock.now()).unwrap();
6949        attempt
6950            .conclude(
6951                AttemptOutcome::failed(FailureReason::ProcessStartFailed),
6952                harness.clock.now(),
6953            )
6954            .unwrap();
6955        attempt.begin_destroy(harness.clock.now()).unwrap();
6956        attempt.clean_isolated(harness.clock.now()).unwrap();
6957        harness.store.record_attempt(&attempt).unwrap();
6958        launcher
6959            .recover_startup(std::slice::from_ref(&harness.policy))
6960            .await
6961            .expect("cleaned row cannot authorize deletion");
6962        assert_eq!(provider.resource_count(), 1);
6963        assert_eq!(
6964            provider
6965                .actions
6966                .lock()
6967                .unwrap()
6968                .iter()
6969                .filter(|action| **action == "destroy")
6970                .count(),
6971            0
6972        );
6973    }
6974
6975    /// The wiring the three-hour outage needed and did not have.
6976    ///
6977    /// A root that refuses a launch does so before `record_allocation`, so no
6978    /// attempt row carries it, and the daemon's log scrubs the paths out of the
6979    /// sentence. The record this asserts is the only surface left, and
6980    /// `service status` reads it -- so if this wiring is ever dropped, the
6981    /// failure goes back to reading `runner_start_failed reason=other` once per
6982    /// poll and nothing else.
6983    #[tokio::test]
6984    async fn a_root_that_refuses_a_launch_is_recorded_and_cleared_when_one_succeeds() {
6985        use runner_manager_platform::service::{clear_runner_root_refusal, runner_root_refusals};
6986
6987        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
6988            .with_host_runner_root();
6989        harness.ready().await;
6990
6991        // A root under two directories that do not exist: refused by the
6992        // preflight, for a reason that has nothing to do with this platform, so
6993        // the assertion holds on all three.
6994        let unusable = harness
6995            ._root
6996            .path()
6997            .join("absent")
6998            .join("deeper")
6999            .join("runners");
7000        let mut host = harness.host.clone();
7001        host.runner_root_override = Some(
7002            LocalAbsolutePath::new(unusable.to_str().expect("a UTF-8 temporary path"))
7003                .expect("a local absolute host root"),
7004        );
7005        harness.store.put_host(&host).unwrap();
7006
7007        let failure = harness
7008            .launch_result()
7009            .await
7010            .expect_err("a root whose parents are missing cannot hold a runner");
7011        assert!(
7012            matches!(failure.reason, FailureReason::Other(_)),
7013            "{failure:?}"
7014        );
7015
7016        let refusals = runner_root_refusals(&harness.app_paths).expect("readable");
7017        let refusal = refusals
7018            .first()
7019            .expect("the refusal reached the one surface that can hold it");
7020        assert_eq!(refusal.policy, harness.policy.id.to_string());
7021        assert_eq!(refusal.kind, "missing_parents");
7022        assert!(
7023            refusal.root.contains("runners") && refusal.detail.contains("runners"),
7024            "the directory must be named in full: {refusal:?}"
7025        );
7026
7027        // And a root that works clears it, so a host that has been fixed stops
7028        // reporting a fault it no longer has.
7029        harness.store.put_host(&harness.host).unwrap();
7030        harness.launch().await;
7031        assert!(
7032            runner_root_refusals(&harness.app_paths)
7033                .expect("readable")
7034                .is_empty(),
7035            "a successful placement clears that policy's record"
7036        );
7037
7038        clear_runner_root_refusal(&harness.app_paths, &harness.policy.id.to_string())
7039            .expect("cleanup");
7040    }
7041
7042    #[tokio::test]
7043    async fn a_launch_reports_how_long_each_step_took() {
7044        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7045        harness.ready().await;
7046        let started = harness.launch().await;
7047        let events = harness.events.events();
7048        let launched = events
7049            .iter()
7050            .position(|event| matches!(event, AttemptEvent::Launched { attempt, .. } if *attempt == started.id))
7051            .expect("a successful launch reports its step timings");
7052        let starting = events
7053            .iter()
7054            .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Starting } if *attempt == started.id))
7055            .unwrap();
7056        assert!(starting < launched, "timings follow the start: {events:?}");
7057    }
7058
7059    #[tokio::test]
7060    async fn a_failed_launch_still_reports_its_step_timings() {
7061        let harness = Harness::new(
7062            FakeGithubLifecycle::default().fail(true),
7063            Arc::new(PersistentDemand),
7064        );
7065        harness.ready().await;
7066        let failed = harness.launch_after_waiting(Duration::from_secs(90)).await;
7067        assert!(failed.is_err());
7068
7069        let timings = harness
7070            .events
7071            .events()
7072            .into_iter()
7073            .find_map(|event| match event {
7074                AttemptEvent::Launched {
7075                    started: false,
7076                    timings,
7077                    ..
7078                } => Some(timings),
7079                _ => None,
7080            })
7081            .expect("a launch that failed at registration reports its timings");
7082        assert_eq!(timings.lock_wait, Duration::from_secs(90));
7083        assert_eq!(timings.spawn, Duration::ZERO, "spawn was never reached");
7084        assert!(timings.total() >= Duration::from_secs(90));
7085    }
7086
7087    #[cfg(target_os = "macos")]
7088    #[tokio::test]
7089    async fn a_launch_removes_the_seed_of_a_root_no_longer_in_use() {
7090        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7091        harness.ready().await;
7092
7093        // A runtime this host once placed under a root it no longer uses.
7094        let old_root = harness._root.path().join("old-root");
7095        let old_runtime = old_root.join("abandoned");
7096        fs::create_dir_all(old_root.join(PACKAGE_SEED_DIR).join("2.335.0")).unwrap();
7097        fs::create_dir_all(&old_runtime).unwrap();
7098        let old = RunnerAttempt::allocate(
7099            AttemptId::new_random(),
7100            harness.policy.id,
7101            &old_runtime,
7102            harness.clock.now(),
7103        );
7104        harness.store.record_attempt(&old).unwrap();
7105        let kept = harness.host_root().join(PACKAGE_SEED_DIR);
7106        fs::create_dir_all(kept.join("2.336.0")).unwrap();
7107
7108        harness.launch().await;
7109
7110        assert!(
7111            !old_root.join(PACKAGE_SEED_DIR).exists(),
7112            "the abandoned root's seed is removed"
7113        );
7114        assert!(old_runtime.exists(), "only the seed is touched");
7115        assert!(kept.exists(), "the host root's own seed is kept");
7116    }
7117
7118    #[tokio::test]
7119    async fn a_job_walks_every_state_and_cleans_every_artifact() {
7120        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7121        harness.ready().await;
7122        let started = harness.launch().await;
7123        assert_eq!(started.state(), AttemptState::Starting);
7124        assert_eq!(read_runner_id(started.runtime_path()), Some(73));
7125
7126        harness
7127            .github
7128            .observe(GithubRunnerObservation::Registered { busy: false });
7129        harness.launcher.supervise(&harness.policy).await.unwrap();
7130        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7131
7132        harness
7133            .github
7134            .observe(GithubRunnerObservation::Registered { busy: true });
7135        harness.launcher.supervise(&harness.policy).await.unwrap();
7136        assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
7137
7138        harness.processes.finish_successfully();
7139        harness
7140            .github
7141            .observe(GithubRunnerObservation::NotRegistered);
7142        harness.launcher.supervise(&harness.policy).await.unwrap();
7143        let cleaned = harness.only_attempt();
7144        assert_eq!(cleaned.state(), AttemptState::Cleaned);
7145        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
7146        assert!(!started.runtime_path().exists());
7147        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7148        assert_eq!(harness.github.remaining_runners.load(Ordering::SeqCst), 0);
7149
7150        let states: Vec<_> = harness
7151            .events
7152            .events()
7153            .into_iter()
7154            .filter_map(|event| match event {
7155                AttemptEvent::State { state, .. } => Some(state),
7156                _ => None,
7157            })
7158            .collect();
7159        assert_eq!(
7160            states,
7161            vec![
7162                AttemptState::Allocated,
7163                AttemptState::JitReceived,
7164                AttemptState::Starting,
7165                AttemptState::Idle,
7166                AttemptState::Busy,
7167                AttemptState::Finished,
7168                AttemptState::Cleaned,
7169            ]
7170        );
7171    }
7172
7173    #[tokio::test]
7174    async fn a_cleaned_ephemeral_attempt_reaps_a_directory_recreated_after_cleanup() {
7175        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7176        harness.ready().await;
7177        let started = harness.launch().await;
7178        let runtime = started.runtime_path().to_path_buf();
7179
7180        harness
7181            .github
7182            .observe(GithubRunnerObservation::Registered { busy: true });
7183        harness.launcher.supervise(&harness.policy).await.unwrap();
7184        harness.processes.finish_successfully();
7185        harness
7186            .github
7187            .observe(GithubRunnerObservation::NotRegistered);
7188        harness.launcher.supervise(&harness.policy).await.unwrap();
7189
7190        assert_eq!(harness.attempt(started.id).state(), AttemptState::Cleaned);
7191        assert!(!runtime.exists());
7192        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7193
7194        // Reproduce a late orphan creating output after the successful removal
7195        // and journal transition. The next ordinary policy supervision must
7196        // remove it without replaying package release or another state change.
7197        let residue = runtime.join("_work").join("late-node-process");
7198        fs::create_dir_all(&residue).unwrap();
7199        fs::write(residue.join("node_modules.lock"), b"late residue").unwrap();
7200
7201        harness.launcher.supervise(&harness.policy).await.unwrap();
7202
7203        assert!(!runtime.exists(), "late ephemeral residue is reaped");
7204        assert_eq!(harness.attempt(started.id).state(), AttemptState::Cleaned);
7205        assert_eq!(
7206            harness.packages.releases.load(Ordering::SeqCst),
7207            1,
7208            "reaping residue does not release the package lease twice"
7209        );
7210    }
7211
7212    #[tokio::test]
7213    async fn locked_late_residue_never_blocks_startup_recovery() {
7214        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7215        harness.ready().await;
7216        let started = harness.launch().await;
7217        let runtime = started.runtime_path().to_path_buf();
7218
7219        harness
7220            .github
7221            .observe(GithubRunnerObservation::Registered { busy: true });
7222        harness.launcher.supervise(&harness.policy).await.unwrap();
7223        harness.processes.finish_successfully();
7224        harness
7225            .github
7226            .observe(GithubRunnerObservation::NotRegistered);
7227        harness.launcher.supervise(&harness.policy).await.unwrap();
7228        assert_eq!(harness.attempt(started.id).state(), AttemptState::Cleaned);
7229
7230        let held = runtime.join("_work").join("late-node-process");
7231        fs::create_dir_all(&held).unwrap();
7232        fs::write(held.join("node_modules.lock"), b"late residue").unwrap();
7233        let Some(block) = BlockedDeletion::inject(&held) else {
7234            eprintln!(
7235                "skipped: this account cannot be refused a deletion, so locked late residue cannot be injected"
7236            );
7237            return;
7238        };
7239
7240        let restarted = harness.restart();
7241        restarted
7242            .recover_startup(std::slice::from_ref(&harness.policy))
7243            .await
7244            .expect("late residue cannot take the daemon offline");
7245        assert!(runtime.exists(), "the locked residue remains for a retry");
7246        assert!(
7247            harness
7248                .reconcile_events
7249                .events()
7250                .iter()
7251                .any(|event| matches!(
7252                    event,
7253                    LifecycleEvent::AttemptCleanFailed {
7254                        attempt,
7255                        reason: "late_ephemeral_workspace_could_not_be_removed",
7256                        ..
7257                    } if *attempt == started.id
7258                )),
7259            "the non-blocking cleanup failure remains visible"
7260        );
7261
7262        block.release();
7263        // A tolerated cleanup failure is retried after its backoff delay.
7264        harness.clock.advance_secs(31);
7265        restarted
7266            .supervise(&harness.policy)
7267            .await
7268            .expect("the ordinary retry succeeds after the lock is released");
7269        assert!(!runtime.exists(), "the retry removes the late residue");
7270        assert_eq!(harness.attempt(started.id).state(), AttemptState::Cleaned);
7271        assert_eq!(
7272            harness.packages.releases.load(Ordering::SeqCst),
7273            1,
7274            "retrying residue never releases the package lease twice"
7275        );
7276    }
7277
7278    #[tokio::test]
7279    async fn mixed_locked_cleanup_residue_isolated_from_the_whole_startup_pass() {
7280        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7281        harness.ready().await;
7282
7283        // The first attempt is terminal but its initial cleanup cannot finish.
7284        // This is the state left by the original failed job on the affected
7285        // workstation.
7286        let terminal = harness.launch().await;
7287        let terminal_runtime = terminal.runtime_path().to_path_buf();
7288        harness.conclude(terminal.id);
7289        let Some(terminal_block) = BlockedDeletion::inject(&terminal_runtime.join("late-child"))
7290        else {
7291            eprintln!("skipped: this account cannot inject the two independent deletion refusals");
7292            return;
7293        };
7294
7295        // The second attempt was cleaned successfully, then a child recreated
7296        // part of `_work`. Both real-world residue shapes existed together in
7297        // the incident, and neither may short-circuit recovery of the other.
7298        let cleaned = harness.launch().await;
7299        let cleaned_runtime = cleaned.runtime_path().to_path_buf();
7300        harness.conclude(cleaned.id);
7301        harness
7302            .launcher
7303            .clean(cleaned.id)
7304            .await
7305            .expect("the second attempt initially cleans");
7306        let Some(cleaned_block) =
7307            BlockedDeletion::inject(&cleaned_runtime.join("_work").join("late-child"))
7308        else {
7309            terminal_block.release();
7310            eprintln!("skipped: this account cannot inject the two independent deletion refusals");
7311            return;
7312        };
7313
7314        let restarted = harness.restart();
7315        for _ in 0..2 {
7316            restarted
7317                .recover_startup(std::slice::from_ref(&harness.policy))
7318                .await
7319                .expect("repeated recovery remains ready while both residues are locked");
7320        }
7321        assert_ne!(
7322            harness.attempt(terminal.id).state(),
7323            AttemptState::Cleaned,
7324            "the journal does not claim the terminal workspace was removed"
7325        );
7326        assert_eq!(
7327            harness.attempt(cleaned.id).state(),
7328            AttemptState::Cleaned,
7329            "late residue does not undo an already durable cleaned transition"
7330        );
7331        assert!(terminal_runtime.exists());
7332        assert!(cleaned_runtime.exists());
7333        assert_eq!(
7334            harness.packages.releases.load(Ordering::SeqCst),
7335            1,
7336            "repeated recovery neither loses nor duplicates package leases"
7337        );
7338
7339        terminal_block.release();
7340        cleaned_block.release();
7341        // A tolerated cleanup failure is retried after its backoff delay.
7342        harness.clock.advance_secs(31);
7343        restarted
7344            .supervise(&harness.policy)
7345            .await
7346            .expect("one ordinary pass clears both residues after their locks disappear");
7347        assert!(!terminal_runtime.exists());
7348        assert!(!cleaned_runtime.exists());
7349        assert_eq!(harness.attempt(terminal.id).state(), AttemptState::Cleaned);
7350        assert_eq!(harness.attempt(cleaned.id).state(), AttemptState::Cleaned);
7351        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 2);
7352    }
7353
7354    #[tokio::test]
7355    async fn a_terminal_attempt_whose_runtime_is_already_gone_recovers_cleanly() {
7356        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7357        harness.ready().await;
7358        let attempt = harness.launch().await;
7359        let runtime = attempt.runtime_path().to_path_buf();
7360        harness.conclude(attempt.id);
7361        fs::remove_dir_all(&runtime).unwrap();
7362
7363        harness
7364            .restart()
7365            .recover_startup(std::slice::from_ref(&harness.policy))
7366            .await
7367            .expect("an already absent disposable runtime is successful cleanup");
7368
7369        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
7370        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7371    }
7372
7373    #[tokio::test]
7374    async fn a_non_workspace_cleanup_failure_still_fails_closed_and_can_retry() {
7375        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7376        harness.ready().await;
7377        let attempt = harness.launch().await;
7378        let runtime = attempt.runtime_path().to_path_buf();
7379        harness.conclude(attempt.id);
7380        harness.packages.fail_releases(1);
7381
7382        let restarted = harness.restart();
7383        let failure = restarted
7384            .recover_startup(std::slice::from_ref(&harness.policy))
7385            .await
7386            .expect_err("a package-accounting failure is not safe to downgrade to residue");
7387        assert!(
7388            failure
7389                .reason()
7390                .to_string()
7391                .contains("package lease could not be released")
7392        );
7393        assert!(
7394            !runtime.exists(),
7395            "workspace removal completed before release failed"
7396        );
7397        assert_ne!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
7398
7399        restarted
7400            .recover_startup(std::slice::from_ref(&harness.policy))
7401            .await
7402            .expect("the same journal entry retries safely after the transient failure");
7403        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
7404        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7405    }
7406
7407    #[tokio::test]
7408    async fn startup_never_scrubs_a_cleaned_persistent_work_directory() {
7409        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
7410            .with_persistent_workspace(1);
7411        harness.ready().await;
7412        let attempt = harness.launch().await;
7413        let retained = attempt.runtime_path().join("_work").join("checkout-marker");
7414        fs::create_dir_all(retained.parent().unwrap()).unwrap();
7415        fs::write(&retained, b"persistent checkout").unwrap();
7416        harness.cleanup_retaining_work(attempt.id).await;
7417
7418        harness
7419            .restart()
7420            .recover_startup(std::slice::from_ref(&harness.policy))
7421            .await
7422            .expect("a cleaned persistent slot is already reconciled");
7423
7424        assert_eq!(fs::read(&retained).unwrap(), b"persistent checkout");
7425        assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
7426    }
7427
7428    #[tokio::test]
7429    async fn an_idle_exit_is_not_a_failure_in_the_journal_or_events() {
7430        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7431        harness.ready().await;
7432        let started = harness.launch().await;
7433        harness
7434            .github
7435            .observe(GithubRunnerObservation::Registered { busy: false });
7436        harness.launcher.supervise(&harness.policy).await.unwrap();
7437        harness.clock.advance_secs(11);
7438        harness.processes.set_alive(false);
7439        harness
7440            .github
7441            .observe(GithubRunnerObservation::NotRegistered);
7442        harness.launcher.supervise(&harness.policy).await.unwrap();
7443
7444        let cleaned = harness.only_attempt();
7445        assert!(cleaned.outcome().unwrap().is_idle_exit());
7446        assert!(!cleaned.outcome().unwrap().is_failure());
7447        assert!(!started.runtime_path().exists());
7448        assert!(
7449            harness
7450                .reconcile_events
7451                .events()
7452                .iter()
7453                .any(|event| matches!(
7454                    event,
7455                    LifecycleEvent::AttemptCleaned {
7456                        outcome: OutcomeKind::IdleExit,
7457                        ..
7458                    }
7459                ))
7460        );
7461        assert!(!harness.events.events().iter().any(|event| matches!(
7462            event,
7463            AttemptEvent::Concluded {
7464                outcome: OutcomeKind::Failed,
7465                ..
7466            }
7467        )));
7468    }
7469
7470    #[tokio::test]
7471    async fn handoff_is_absent_after_success_and_every_failed_spawn_retry() {
7472        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7473        harness.processes.fail_spawns(2);
7474        harness.ready().await;
7475        let attempt = harness.launch().await;
7476        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 3);
7477        assert!(harness.processes.saw_secret.load(Ordering::SeqCst));
7478        let names: Vec<_> = fs::read_dir(attempt.runtime_path())
7479            .unwrap()
7480            .map(|entry| entry.unwrap().file_name())
7481            .collect();
7482        assert!(
7483            names.iter().all(|name| {
7484                !name
7485                    .to_string_lossy()
7486                    .starts_with(RestrictiveHandoff::NAME_PREFIX)
7487            }),
7488            "JIT artifact survived: {names:?}"
7489        );
7490        assert_eq!(
7491            *harness.delay.0.lock().unwrap(),
7492            vec![Duration::from_millis(10), Duration::from_millis(20)]
7493        );
7494    }
7495
7496    #[tokio::test]
7497    async fn jit_retry_stops_with_demand_and_a_terminal_403_never_retries() {
7498        let gone = Harness::new(
7499            FakeGithubLifecycle::default().fail(false),
7500            Arc::new(FakeDemand::answering([false])),
7501        );
7502        gone.ready().await;
7503        assert!(gone.launch_result().await.is_err());
7504        assert_eq!(gone.github.registrations.load(Ordering::SeqCst), 1);
7505        assert!(gone.delay.0.lock().unwrap().is_empty());
7506
7507        let forbidden = Harness::new(
7508            FakeGithubLifecycle::default().fail(true),
7509            Arc::new(PersistentDemand),
7510        );
7511        forbidden.ready().await;
7512        assert!(forbidden.launch_result().await.is_err());
7513        assert_eq!(forbidden.github.registrations.load(Ordering::SeqCst), 1);
7514        assert!(forbidden.delay.0.lock().unwrap().is_empty());
7515        assert!(matches!(
7516            forbidden.only_attempt().outcome(),
7517            Some(AttemptOutcome::Failed {
7518                reason: FailureReason::Other(action)
7519            }) if action.contains("403")
7520        ));
7521
7522        let transient = Harness::new(
7523            FakeGithubLifecycle::default().fail(false).fail(false),
7524            Arc::new(PersistentDemand),
7525        );
7526        transient.ready().await;
7527        transient.launch().await;
7528        assert_eq!(transient.github.registrations.load(Ordering::SeqCst), 3);
7529        assert_eq!(
7530            *transient.delay.0.lock().unwrap(),
7531            vec![Duration::from_millis(10), Duration::from_millis(20)]
7532        );
7533    }
7534
7535    /// The layout has to leave room for what the runner writes underneath it.
7536    ///
7537    /// Windows refuses a path over `MAX_PATH`, and this product's own CI hit
7538    /// that: 264 characters against a limit of 260, failing three checkout
7539    /// retries with `Filename too long`. The two identifiers in the old layout
7540    /// cost 74 characters between them for no benefit -- an attempt id is
7541    /// unique on its own.
7542    #[test]
7543    fn a_workspace_leaves_room_for_the_deepest_path_a_checkout_writes() {
7544        const MAX_PATH: usize = 260;
7545        // The real root on the machine this was found on.
7546        let root = r"C:\Users\IvanD\AppData\Local\IvanMurzak\runner-manager\data\runtime";
7547        // What `actions/checkout` writes at its deepest: the work directory,
7548        // the repository named twice, and a pack keep-file with a 40-character
7549        // object name.
7550        let repo = "GitHub-Runner-Scaler-UI";
7551        let deepest = format!(
7552            r"_work\{repo}\{repo}\.git\objects\pack\pack-{}.keep",
7553            "0".repeat(40)
7554        );
7555
7556        let name = workspace_name(AttemptId::new_random());
7557        assert_eq!(name.len(), WORKSPACE_NAME_LEN, "{name}");
7558        assert!(
7559            name.chars().all(|c| c.is_ascii_hexdigit()),
7560            "a directory name must not carry the identifier's dashes: {name}"
7561        );
7562
7563        let full = format!(r"{root}\{name}\{deepest}");
7564        assert!(
7565            full.len() < MAX_PATH,
7566            "the deepest path a checkout writes must fit: {} characters, limit {MAX_PATH}",
7567            full.len()
7568        );
7569
7570        // The discriminator: the layout this replaced does not fit, so a test
7571        // that passed for both would be proving nothing.
7572        let old = format!(
7573            r"{root}\{}\{}\{deepest}",
7574            PolicyId::new_random(),
7575            AttemptId::new_random()
7576        );
7577        assert!(
7578            old.len() > MAX_PATH,
7579            "the old layout is supposed to be the thing that did not fit: {} characters",
7580            old.len()
7581        );
7582    }
7583
7584    #[tokio::test]
7585    async fn two_attempts_never_share_a_workspace_even_after_failure() {
7586        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7587        harness.ready().await;
7588        let first = harness.launch().await;
7589        fs::write(first.runtime_path().join("hostile-leftover"), b"first job").unwrap();
7590        harness
7591            .github
7592            .observe(GithubRunnerObservation::Registered { busy: false });
7593        harness.launcher.supervise(&harness.policy).await.unwrap();
7594        harness.clock.advance_secs(11);
7595        harness.processes.set_alive(false);
7596        harness
7597            .github
7598            .observe(GithubRunnerObservation::NotRegistered);
7599        harness.launcher.supervise(&harness.policy).await.unwrap();
7600        assert!(!first.runtime_path().exists());
7601
7602        let second = harness.launch().await;
7603        assert_ne!(first.runtime_path(), second.runtime_path());
7604        assert!(!second.runtime_path().join("hostile-leftover").exists());
7605
7606        fs::write(
7607            second.runtime_path().join("hostile-on-failure"),
7608            b"second job",
7609        )
7610        .unwrap();
7611        harness.processes.set_alive(false);
7612        harness
7613            .github
7614            .observe(GithubRunnerObservation::NotRegistered);
7615        harness.launcher.supervise(&harness.policy).await.unwrap();
7616        assert!(
7617            !second.runtime_path().exists(),
7618            "failed workspace was retained"
7619        );
7620    }
7621
7622    #[tokio::test]
7623    async fn a_runner_that_never_gets_a_job_is_stopped_deregistered_and_not_replaced() {
7624        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7625        harness.ready().await;
7626        let attempt = harness.launch().await;
7627
7628        // Registered and waiting, which is where it stays: the fake keeps
7629        // answering the same observation, exactly as GitHub does for a runner
7630        // nobody assigns work to.
7631        harness
7632            .github
7633            .observe(GithubRunnerObservation::Registered { busy: false });
7634        harness.launcher.supervise(&harness.policy).await.unwrap();
7635        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7636
7637        // One second inside the ten-second idle timeout nothing happens, which
7638        // is what keeps this from being a test that would pass on any clock.
7639        harness.clock.advance_secs(9);
7640        harness
7641            .github
7642            .observe(GithubRunnerObservation::Registered { busy: false });
7643        let none_yet = harness.launcher.supervise(&harness.policy).await.unwrap();
7644        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7645        assert!(none_yet.is_empty());
7646        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 0);
7647
7648        // Past it, the agent ends the runner itself.
7649        harness.clock.advance_secs(1);
7650        harness
7651            .github
7652            .observe(GithubRunnerObservation::Registered { busy: false });
7653        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
7654
7655        let concluded = harness.store.attempt(attempt.id).unwrap().unwrap();
7656        assert_eq!(
7657            concluded.outcome(),
7658            Some(&AttemptOutcome::ExitedIdleWithoutWork),
7659            "a surplus runner did not fail; recording one as a failure sends an operator \
7660             hunting a fault that does not exist"
7661        );
7662        assert_eq!(concluded.state(), AttemptState::Cleaned);
7663        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 1);
7664        assert!(!attempt.runtime_path().exists());
7665
7666        // The registration goes with it. Without this the runner stays listed
7667        // in the target's runner settings after the process it named is gone.
7668        assert_eq!(
7669            *harness.github.deregistrations.lock().unwrap(),
7670            vec![73],
7671            "the attempt's own runner id, deleted exactly once"
7672        );
7673
7674        // And nothing is started in its place: the work it was launched for went
7675        // elsewhere, so a replacement would rebuild it every idle timeout.
7676        assert!(
7677            replacements.is_empty(),
7678            "a surplus exit must not request a replacement"
7679        );
7680    }
7681
7682    #[tokio::test]
7683    async fn a_registration_github_will_not_delete_still_concludes_the_attempt() {
7684        // The delete is best-effort by construction: the process is gone and the
7685        // slot has to come back. Holding the conclusion until GitHub cooperates
7686        // would leak a capacity slot on every unreachable moment.
7687        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7688        harness.ready().await;
7689        let attempt = harness.launch().await;
7690        harness
7691            .github
7692            .observe(GithubRunnerObservation::Registered { busy: false });
7693        harness.launcher.supervise(&harness.policy).await.unwrap();
7694
7695        harness
7696            .github
7697            .deregistration_fails
7698            .store(true, Ordering::SeqCst);
7699        harness.clock.advance_secs(11);
7700        harness
7701            .github
7702            .observe(GithubRunnerObservation::Registered { busy: false });
7703        harness.launcher.supervise(&harness.policy).await.unwrap();
7704
7705        assert_eq!(
7706            *harness.github.deregistrations.lock().unwrap(),
7707            vec![73],
7708            "the delete was attempted"
7709        );
7710        let concluded = harness.store.attempt(attempt.id).unwrap().unwrap();
7711        assert_eq!(
7712            concluded.outcome(),
7713            Some(&AttemptOutcome::ExitedIdleWithoutWork),
7714            "the attempt concluded anyway"
7715        );
7716        assert_eq!(concluded.state(), AttemptState::Cleaned);
7717        assert!(!attempt.runtime_path().exists());
7718    }
7719
7720    #[tokio::test]
7721    async fn exit_before_acceptance_returns_replacement_intent_without_launching() {
7722        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7723        harness.ready().await;
7724        let first = harness.launch().await;
7725        harness.processes.set_alive(false);
7726        harness
7727            .github
7728            .observe(GithubRunnerObservation::NotRegistered);
7729        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
7730        let failed = harness.store.attempt(first.id).unwrap().unwrap();
7731        assert!(matches!(
7732            failed.outcome(),
7733            Some(AttemptOutcome::Failed {
7734                reason: FailureReason::ProcessExitedUnexpectedly
7735            })
7736        ));
7737        assert!(!first.runtime_path().exists());
7738
7739        assert_eq!(
7740            replacements,
7741            vec![ReplacementIntent {
7742                policy: harness.policy.id,
7743                previous_attempt: first.id,
7744                operation: "exit_before_acceptance_replacement",
7745            }]
7746        );
7747        assert_eq!(harness.store.attempts().unwrap().len(), 1);
7748        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
7749        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
7750        assert!(harness.delay.0.lock().unwrap().is_empty());
7751    }
7752
7753    /// Writes the runner's own diagnostics: always the listener's log, and the
7754    /// job worker's when `ran_a_job`. `Runner.Listener` starts `Runner.Worker`
7755    /// only for a job it has acquired.
7756    fn write_runner_diagnostics(runtime: &Path, ran_a_job: bool) {
7757        let diag = runtime.join("_diag");
7758        fs::create_dir_all(&diag).unwrap();
7759        fs::write(diag.join("Runner_20261007-211941-utc.log"), b"listener").unwrap();
7760        if ran_a_job {
7761            fs::write(diag.join("Worker_20261007-211950-utc.log"), b"worker").unwrap();
7762        }
7763    }
7764
7765    /// The macOS field case: a job of a few seconds starts and ends between two
7766    /// passes, so GitHub was never seen reporting the runner busy -- the attempt
7767    /// is still `starting` -- and the registration is already gone. It used to be
7768    /// recorded `process_exited_unexpectedly`, with a replacement runner.
7769    #[tokio::test]
7770    async fn a_job_too_short_to_be_seen_busy_is_recorded_as_completed() {
7771        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7772        harness.ready().await;
7773        let started = harness.launch().await;
7774        assert_eq!(started.state(), AttemptState::Starting);
7775        write_runner_diagnostics(started.runtime_path(), true);
7776        harness.processes.finish_successfully();
7777        harness
7778            .github
7779            .observe(GithubRunnerObservation::NotRegistered);
7780
7781        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
7782
7783        let cleaned = harness.only_attempt();
7784        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
7785        assert_eq!(cleaned.state(), AttemptState::Cleaned);
7786        assert_eq!(cleaned.github_runner_id(), Some(73));
7787        assert!(
7788            replacements.is_empty(),
7789            "a finished job needs no replacement"
7790        );
7791        let busy_seen = harness.events.events().into_iter().any(|event| {
7792            matches!(
7793                event,
7794                AttemptEvent::State {
7795                    state: AttemptState::Busy,
7796                    ..
7797                }
7798            )
7799        });
7800        assert!(busy_seen, "the journal walks the diagram to `busy` first");
7801    }
7802
7803    /// The same from `idle`: seen registered and waiting once, then gone.
7804    #[tokio::test]
7805    async fn a_job_taken_between_two_passes_after_idle_is_recorded_as_completed() {
7806        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7807        harness.ready().await;
7808        let started = harness.launch().await;
7809        harness
7810            .github
7811            .observe(GithubRunnerObservation::Registered { busy: false });
7812        harness.launcher.supervise(&harness.policy).await.unwrap();
7813        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7814
7815        write_runner_diagnostics(started.runtime_path(), true);
7816        harness.processes.finish_successfully();
7817        harness
7818            .github
7819            .observe(GithubRunnerObservation::NotRegistered);
7820        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
7821
7822        assert_eq!(
7823            harness.only_attempt().outcome(),
7824            Some(&AttemptOutcome::CompletedJob)
7825        );
7826        assert!(replacements.is_empty());
7827    }
7828
7829    /// The reverse error, from the same sampling: GitHub showed the runner
7830    /// assigned, the runner never started the job (no worker log), and it exited
7831    /// 0. That is not a completed job.
7832    #[tokio::test]
7833    async fn an_assignment_the_runner_never_took_up_is_not_a_completed_job() {
7834        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7835        harness.ready().await;
7836        let started = harness.launch().await;
7837        harness
7838            .github
7839            .observe(GithubRunnerObservation::Registered { busy: true });
7840        harness.launcher.supervise(&harness.policy).await.unwrap();
7841        assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
7842
7843        write_runner_diagnostics(started.runtime_path(), false);
7844        harness.processes.finish_successfully();
7845        harness
7846            .github
7847            .observe(GithubRunnerObservation::NotRegistered);
7848        harness.launcher.supervise(&harness.policy).await.unwrap();
7849
7850        let cleaned = harness.only_attempt();
7851        assert_eq!(
7852            cleaned.outcome(),
7853            Some(&AttemptOutcome::ExitedIdleWithoutWork)
7854        );
7855        assert_eq!(cleaned.state(), AttemptState::Cleaned);
7856    }
7857
7858    /// The mirror case: the runner really ran its job and exited 0 before GitHub
7859    /// took it off the list. It used to be recorded `orphaned`.
7860    #[tokio::test]
7861    async fn a_finished_job_still_listed_at_github_is_completed_and_deregistered() {
7862        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7863        harness.ready().await;
7864        let started = harness.launch().await;
7865        harness
7866            .github
7867            .observe(GithubRunnerObservation::Registered { busy: true });
7868        harness.launcher.supervise(&harness.policy).await.unwrap();
7869
7870        write_runner_diagnostics(started.runtime_path(), true);
7871        harness.processes.finish_successfully();
7872        harness
7873            .github
7874            .observe(GithubRunnerObservation::Registered { busy: true });
7875        harness.launcher.supervise(&harness.policy).await.unwrap();
7876
7877        assert_eq!(
7878            harness.only_attempt().outcome(),
7879            Some(&AttemptOutcome::CompletedJob)
7880        );
7881        assert_eq!(*harness.github.deregistrations.lock().unwrap(), vec![73]);
7882    }
7883
7884    /// A live runner journalled `busy` whose assignment GitHub withdrew goes
7885    /// back to `idle`, where the idle timeout holds it again.
7886    #[tokio::test]
7887    async fn a_live_runner_whose_assignment_was_withdrawn_goes_back_to_idle() {
7888        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7889        harness.ready().await;
7890        let started = harness.launch().await;
7891        harness
7892            .github
7893            .observe(GithubRunnerObservation::Registered { busy: true });
7894        harness.launcher.supervise(&harness.policy).await.unwrap();
7895        assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
7896
7897        write_runner_diagnostics(started.runtime_path(), false);
7898        harness
7899            .github
7900            .observe(GithubRunnerObservation::Registered { busy: false });
7901        harness.launcher.supervise(&harness.policy).await.unwrap();
7902        assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
7903
7904        // A runner that did start its job keeps `busy` whatever GitHub says.
7905        harness
7906            .github
7907            .observe(GithubRunnerObservation::Registered { busy: true });
7908        harness.launcher.supervise(&harness.policy).await.unwrap();
7909        write_runner_diagnostics(started.runtime_path(), true);
7910        harness
7911            .github
7912            .observe(GithubRunnerObservation::Registered { busy: false });
7913        harness.launcher.supervise(&harness.policy).await.unwrap();
7914        assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
7915    }
7916
7917    /// While GitHub cannot be reached nothing is concluded, so a registration
7918    /// still listed there is removed once it answers.
7919    #[tokio::test]
7920    async fn a_clean_exit_waits_for_github_to_answer() {
7921        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7922        harness.ready().await;
7923        let started = harness.launch().await;
7924        write_runner_diagnostics(started.runtime_path(), true);
7925        harness.processes.finish_successfully();
7926        harness.github.observe(GithubRunnerObservation::Unreachable);
7927        harness.launcher.supervise(&harness.policy).await.unwrap();
7928        assert_eq!(harness.only_attempt().state(), AttemptState::Starting);
7929
7930        harness
7931            .github
7932            .observe(GithubRunnerObservation::NotRegistered);
7933        harness.launcher.supervise(&harness.policy).await.unwrap();
7934        assert_eq!(
7935            harness.only_attempt().outcome(),
7936            Some(&AttemptOutcome::CompletedJob)
7937        );
7938    }
7939
7940    /// A runner id nobody can name is not a reason to stop supervising the
7941    /// policy: the attempt is concluded the way it was before, without one.
7942    #[tokio::test]
7943    async fn a_short_job_with_no_runner_id_still_concludes() {
7944        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7945        harness.ready().await;
7946        let started = harness.launch().await;
7947        fs::remove_file(started.runtime_path().join(RUNNER_ID_FILE)).unwrap();
7948        write_runner_diagnostics(started.runtime_path(), true);
7949        harness.processes.finish_successfully();
7950        harness
7951            .github
7952            .observe(GithubRunnerObservation::NotRegistered);
7953        harness
7954            .launcher
7955            .supervise(&harness.policy)
7956            .await
7957            .expect("supervision goes on");
7958        assert!(harness.only_attempt().is_terminal());
7959    }
7960
7961    /// Without the runner's diagnostics nothing changes: a clean exit seen only
7962    /// at `starting` is still a runner that exited before taking a job.
7963    #[tokio::test]
7964    async fn without_runner_diagnostics_an_early_exit_is_still_a_failure() {
7965        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
7966        harness.ready().await;
7967        harness.launch().await;
7968        harness.processes.finish_successfully();
7969        harness
7970            .github
7971            .observe(GithubRunnerObservation::NotRegistered);
7972        harness.launcher.supervise(&harness.policy).await.unwrap();
7973        assert!(matches!(
7974            harness.only_attempt().outcome(),
7975            Some(AttemptOutcome::Failed {
7976                reason: FailureReason::ProcessExitedUnexpectedly
7977            })
7978        ));
7979    }
7980
7981    #[tokio::test]
7982    async fn expired_jit_is_removed_and_does_not_reregister_after_demand_disappears() {
7983        let harness = Harness::new(
7984            FakeGithubLifecycle::default(),
7985            Arc::new(FakeDemand::answering([false])),
7986        );
7987        let id = AttemptId::new_random();
7988        let runtime = harness
7989            .launcher
7990            .app_paths
7991            .runtime_dir()
7992            .join(harness.policy.id.to_string())
7993            .join(id.to_string());
7994        fs::create_dir_all(&runtime).unwrap();
7995        let mut attempt =
7996            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
7997        attempt.jit_received(harness.clock.now()).unwrap();
7998        harness.store.record_attempt(&attempt).unwrap();
7999        harness.clock.advance_secs(11);
8000        let replacements = harness
8001            .launcher
8002            .recover_startup(std::slice::from_ref(&harness.policy))
8003            .await
8004            .unwrap();
8005        assert_eq!(
8006            replacements,
8007            vec![ReplacementIntent {
8008                policy: harness.policy.id,
8009                previous_attempt: id,
8010                operation: "jit_expired_replacement",
8011            }]
8012        );
8013
8014        let cleaned = harness.store.attempt(id).unwrap().unwrap();
8015        assert_eq!(cleaned.state(), AttemptState::Cleaned);
8016        assert!(matches!(
8017            cleaned.outcome(),
8018            Some(AttemptOutcome::Failed {
8019                reason: FailureReason::JitExpired
8020            })
8021        ));
8022        assert!(!runtime.exists());
8023        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
8024        assert!(harness.delay.0.lock().unwrap().is_empty());
8025    }
8026
8027    #[tokio::test]
8028    async fn expired_jit_returns_intent_but_never_launches_inside_lifecycle() {
8029        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8030        let id = AttemptId::new_random();
8031        let runtime = harness
8032            .launcher
8033            .app_paths
8034            .runtime_dir()
8035            .join("expired-with-demand");
8036        fs::create_dir_all(&runtime).unwrap();
8037        let mut attempt =
8038            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
8039        attempt.jit_received(harness.clock.now()).unwrap();
8040        harness.store.record_attempt(&attempt).unwrap();
8041        harness.clock.advance_secs(11);
8042        let replacements = harness
8043            .launcher
8044            .recover_startup(std::slice::from_ref(&harness.policy))
8045            .await
8046            .unwrap();
8047
8048        let attempts = harness.store.attempts().unwrap();
8049        assert_eq!(attempts.len(), 1);
8050        assert_eq!(
8051            attempts
8052                .iter()
8053                .find(|attempt| attempt.id == id)
8054                .unwrap()
8055                .state(),
8056            AttemptState::Cleaned
8057        );
8058        assert_eq!(
8059            replacements,
8060            vec![ReplacementIntent {
8061                policy: harness.policy.id,
8062                previous_attempt: id,
8063                operation: "jit_expired_replacement",
8064            }]
8065        );
8066        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
8067        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
8068        assert!(harness.delay.0.lock().unwrap().is_empty());
8069    }
8070
8071    #[tokio::test]
8072    async fn package_materialization_retries_are_bounded_and_demand_adjacent() {
8073        let persistent = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8074        persistent.packages.fail_materializations(2);
8075        persistent.ready().await;
8076        persistent.launch().await;
8077        assert_eq!(
8078            persistent.packages.materializations.load(Ordering::SeqCst),
8079            3
8080        );
8081        assert_eq!(
8082            *persistent.delay.0.lock().unwrap(),
8083            vec![Duration::from_millis(10), Duration::from_millis(20)]
8084        );
8085
8086        let gone_before_wait = Harness::new(
8087            FakeGithubLifecycle::default(),
8088            Arc::new(FakeDemand::answering([false])),
8089        );
8090        gone_before_wait.packages.fail_materializations(3);
8091        gone_before_wait.ready().await;
8092        assert!(gone_before_wait.launch_result().await.is_err());
8093        assert_eq!(
8094            gone_before_wait
8095                .packages
8096                .materializations
8097                .load(Ordering::SeqCst),
8098            1
8099        );
8100        assert!(gone_before_wait.delay.0.lock().unwrap().is_empty());
8101
8102        let gone_during_wait = Harness::new(
8103            FakeGithubLifecycle::default(),
8104            Arc::new(FakeDemand::answering([true, false])),
8105        );
8106        gone_during_wait.packages.fail_materializations(3);
8107        gone_during_wait.ready().await;
8108        assert!(gone_during_wait.launch_result().await.is_err());
8109        assert_eq!(
8110            gone_during_wait
8111                .packages
8112                .materializations
8113                .load(Ordering::SeqCst),
8114            1
8115        );
8116        assert_eq!(
8117            *gone_during_wait.delay.0.lock().unwrap(),
8118            vec![Duration::from_millis(10)]
8119        );
8120    }
8121
8122    #[tokio::test]
8123    async fn replacement_is_intent_only_and_never_launches_inside_lifecycle() {
8124        let harness = Harness::new(
8125            FakeGithubLifecycle::default(),
8126            Arc::new(FakeDemand::answering([true, false])),
8127        );
8128        harness.ready().await;
8129        let first = harness.launch().await;
8130        harness.processes.set_alive(false);
8131        harness
8132            .github
8133            .observe(GithubRunnerObservation::NotRegistered);
8134        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
8135
8136        assert_eq!(harness.store.attempts().unwrap().len(), 1);
8137        assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
8138        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
8139        assert!(harness.delay.0.lock().unwrap().is_empty());
8140        assert_eq!(
8141            replacements,
8142            vec![ReplacementIntent {
8143                policy: harness.policy.id,
8144                previous_attempt: first.id,
8145                operation: "exit_before_acceptance_replacement",
8146            }]
8147        );
8148        assert_eq!(
8149            harness.store.attempt(first.id).unwrap().unwrap().state(),
8150            AttemptState::Cleaned
8151        );
8152    }
8153
8154    #[tokio::test]
8155    async fn startup_adopts_a_live_process_and_refuses_launch_before_recovery() {
8156        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8157        let before = harness.launch_result().await;
8158        assert!(before.is_err());
8159        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
8160
8161        let id = AttemptId::new_random();
8162        let runtime = harness.launcher.app_paths.runtime_dir().join("adopt");
8163        fs::create_dir_all(&runtime).unwrap();
8164        let mut attempt =
8165            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
8166        attempt.jit_received(harness.clock.now()).unwrap();
8167        attempt.started(4242, harness.clock.now()).unwrap();
8168        harness.store.record_attempt(&attempt).unwrap();
8169        harness.processes.set_alive(true);
8170        harness
8171            .github
8172            .observe(GithubRunnerObservation::NotRegistered);
8173        let replacements = harness
8174            .launcher
8175            .recover_startup(std::slice::from_ref(&harness.policy))
8176            .await
8177            .unwrap();
8178        assert!(replacements.is_empty());
8179        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
8180        assert!(
8181            harness
8182                .events
8183                .events()
8184                .contains(&AttemptEvent::Adopted { attempt: id })
8185        );
8186    }
8187
8188    #[tokio::test]
8189    async fn spawn_before_starting_crash_recovers_pid_then_completes_and_cleans() {
8190        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8191        let id = AttemptId::new_random();
8192        let runtime = harness
8193            .launcher
8194            .app_paths
8195            .runtime_dir()
8196            .join("spawn-before-starting");
8197        fs::create_dir_all(&runtime).unwrap();
8198        let mut attempt =
8199            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
8200        attempt.jit_received(harness.clock.now()).unwrap();
8201        harness.store.record_attempt(&attempt).unwrap();
8202        harness.processes.set_alive(true);
8203        harness
8204            .github
8205            .observe(GithubRunnerObservation::Registered { busy: true });
8206
8207        let replacements = harness
8208            .launcher
8209            .recover_startup(std::slice::from_ref(&harness.policy))
8210            .await
8211            .unwrap();
8212        assert!(replacements.is_empty());
8213        let recovered = harness.store.attempt(id).unwrap().unwrap();
8214        assert_eq!(recovered.state(), AttemptState::Busy);
8215        assert_eq!(recovered.process_id(), Some(4242));
8216        assert_eq!(recovered.github_runner_id(), Some(73));
8217        let events = harness.events.events();
8218        let starting = events
8219            .iter()
8220            .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Starting } if *attempt == id))
8221            .unwrap();
8222        let busy = events
8223            .iter()
8224            .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Busy } if *attempt == id))
8225            .unwrap();
8226        assert!(starting < busy, "recovery skipped a legal edge: {events:?}");
8227
8228        harness.processes.finish_successfully();
8229        harness
8230            .github
8231            .observe(GithubRunnerObservation::NotRegistered);
8232        assert!(
8233            harness
8234                .launcher
8235                .supervise(&harness.policy)
8236                .await
8237                .unwrap()
8238                .is_empty()
8239        );
8240        let cleaned = harness.store.attempt(id).unwrap().unwrap();
8241        assert_eq!(cleaned.state(), AttemptState::Cleaned);
8242        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
8243        assert!(!runtime.exists());
8244    }
8245
8246    #[tokio::test]
8247    async fn failed_post_spawn_stop_keeps_capacity_until_supervision_proves_death() {
8248        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8249        harness.processes.fail_spawn_with_live_child();
8250        harness.ready().await;
8251        assert!(harness.launch_result().await.is_err());
8252
8253        let attempt = harness.only_attempt();
8254        assert_eq!(attempt.state(), AttemptState::Starting);
8255        assert_eq!(attempt.process_id(), Some(4242));
8256        assert!(attempt.outcome().is_none());
8257        assert!(attempt.state().counts_against_capacity());
8258        assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
8259        assert!(harness.delay.0.lock().unwrap().is_empty());
8260
8261        harness.processes.set_alive(false);
8262        harness
8263            .github
8264            .observe(GithubRunnerObservation::NotRegistered);
8265        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
8266        assert_eq!(replacements.len(), 1);
8267        assert_eq!(
8268            harness.store.attempt(attempt.id).unwrap().unwrap().state(),
8269            AttemptState::Cleaned
8270        );
8271    }
8272
8273    #[tokio::test]
8274    async fn remote_runner_identity_closes_both_sides_of_the_registration_crash_boundary() {
8275        for sidecar_already_present in [false, true] {
8276            let harness = Harness::new(
8277                FakeGithubLifecycle::default(),
8278                Arc::new(FakeDemand::answering([false])),
8279            );
8280            let id = AttemptId::new_random();
8281            let runtime =
8282                harness
8283                    .launcher
8284                    .app_paths
8285                    .runtime_dir()
8286                    .join(if sidecar_already_present {
8287                        "after-id-sidecar"
8288                    } else {
8289                        "before-id-sidecar"
8290                    });
8291            fs::create_dir_all(&runtime).unwrap();
8292            let mut attempt =
8293                RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
8294            if sidecar_already_present {
8295                write_runner_id(&runtime, 73).unwrap();
8296                attempt.jit_received(harness.clock.now()).unwrap();
8297            }
8298            harness.store.record_attempt(&attempt).unwrap();
8299            harness.processes.set_alive(true);
8300            harness
8301                .github
8302                .observe(GithubRunnerObservation::Registered { busy: false });
8303            harness
8304                .launcher
8305                .recover_startup(std::slice::from_ref(&harness.policy))
8306                .await
8307                .unwrap();
8308
8309            assert_eq!(read_runner_id(&runtime), Some(73));
8310            assert!(
8311                harness
8312                    .store
8313                    .attempt(id)
8314                    .unwrap()
8315                    .unwrap()
8316                    .outcome()
8317                    .is_none()
8318            );
8319            let events = harness.events.events();
8320            let recovered = events.iter().position(|event| {
8321                matches!(
8322                    event,
8323                    AttemptEvent::RemoteIdentityRecovered {
8324                        attempt,
8325                        runner_id: 73
8326                    } if *attempt == id
8327                )
8328            });
8329            assert_eq!(recovered.is_some(), !sidecar_already_present);
8330            if let Some(recovered) = recovered {
8331                let adopted = events
8332                    .iter()
8333                    .position(|event| matches!(event, AttemptEvent::Adopted { attempt } if *attempt == id))
8334                    .unwrap();
8335                assert!(
8336                    recovered < adopted,
8337                    "identity was not durable before adoption: {events:?}"
8338                );
8339            }
8340            assert!(runtime.exists());
8341        }
8342    }
8343
8344    #[tokio::test]
8345    async fn recovery_stays_closed_for_unknown_policy_and_unreachable_attempts() {
8346        let unknown = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8347        let unknown_attempt = RunnerAttempt::allocate(
8348            AttemptId::new_random(),
8349            PolicyId::from_u128(0xfeed),
8350            unknown
8351                .launcher
8352                .app_paths
8353                .runtime_dir()
8354                .join("unknown-policy"),
8355            unknown.clock.now(),
8356        );
8357        unknown.store.record_attempt(&unknown_attempt).unwrap();
8358        let expired_id = AttemptId::new_random();
8359        let expired_runtime = unknown
8360            .launcher
8361            .app_paths
8362            .runtime_dir()
8363            .join("expired-beside-unknown");
8364        fs::create_dir_all(&expired_runtime).unwrap();
8365        let mut expired = RunnerAttempt::allocate(
8366            expired_id,
8367            unknown.policy.id,
8368            expired_runtime,
8369            unknown.clock.now(),
8370        );
8371        expired.jit_received(unknown.clock.now()).unwrap();
8372        unknown.store.record_attempt(&expired).unwrap();
8373        unknown.clock.advance_secs(11);
8374        assert!(matches!(
8375            unknown
8376                .launcher
8377                .recover_startup(std::slice::from_ref(&unknown.policy))
8378                .await,
8379            Err(LifecycleError::RecoveryIncomplete)
8380        ));
8381        assert!(unknown.launch_result().await.is_err());
8382        assert_eq!(unknown.processes.spawns.load(Ordering::SeqCst), 0);
8383        let recovered_policy = fixtures::policy()
8384            .id(PolicyId::from_u128(0xfeed))
8385            .repository("octo/repo")
8386            .autoscale("home", 2)
8387            .active()
8388            .build();
8389        let pending = unknown
8390            .launcher
8391            .recover_startup(&[unknown.policy.clone(), recovered_policy])
8392            .await
8393            .unwrap();
8394        assert_eq!(
8395            pending,
8396            vec![ReplacementIntent {
8397                policy: unknown.policy.id,
8398                previous_attempt: expired_id,
8399                operation: "jit_expired_replacement",
8400            }]
8401        );
8402        assert_eq!(unknown.processes.spawns.load(Ordering::SeqCst), 0);
8403
8404        let unreachable = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8405        let id = AttemptId::new_random();
8406        let runtime = unreachable
8407            .launcher
8408            .app_paths
8409            .runtime_dir()
8410            .join("unreachable");
8411        fs::create_dir_all(&runtime).unwrap();
8412        unreachable
8413            .store
8414            .record_attempt(&RunnerAttempt::allocate(
8415                id,
8416                unreachable.policy.id,
8417                runtime,
8418                unreachable.clock.now(),
8419            ))
8420            .unwrap();
8421        unreachable
8422            .github
8423            .observe(GithubRunnerObservation::Unreachable);
8424        assert!(matches!(
8425            unreachable
8426                .launcher
8427                .recover_startup(std::slice::from_ref(&unreachable.policy))
8428                .await,
8429            Err(LifecycleError::RecoveryIncomplete)
8430        ));
8431        assert!(unreachable.launch_result().await.is_err());
8432        assert_eq!(unreachable.processes.spawns.load(Ordering::SeqCst), 0);
8433    }
8434
8435    #[tokio::test]
8436    async fn a_dead_busy_process_unknown_to_github_is_orphaned_and_cleaned() {
8437        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8438        let id = AttemptId::new_random();
8439        let runtime = harness.launcher.app_paths.runtime_dir().join("orphan");
8440        fs::create_dir_all(&runtime).unwrap();
8441        let mut attempt =
8442            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
8443        attempt.jit_received(harness.clock.now()).unwrap();
8444        attempt.started(4242, harness.clock.now()).unwrap();
8445        attempt.assigned_job(73, harness.clock.now()).unwrap();
8446        harness.store.record_attempt(&attempt).unwrap();
8447        harness.processes.set_alive(false);
8448        harness
8449            .github
8450            .observe(GithubRunnerObservation::NotRegistered);
8451        harness
8452            .launcher
8453            .recover_startup(std::slice::from_ref(&harness.policy))
8454            .await
8455            .unwrap();
8456        let cleaned = harness.store.attempt(id).unwrap().unwrap();
8457        assert_eq!(cleaned.state(), AttemptState::Cleaned);
8458        assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::Orphaned));
8459        assert!(!runtime.exists());
8460    }
8461
8462    #[tokio::test]
8463    async fn registration_timeout_journals_intent_stops_then_concludes_with_dead_reason() {
8464        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8465        harness.ready().await;
8466        let id = AttemptId::new_random();
8467        let runtime = harness.launcher.app_paths.runtime_dir().join("timeout");
8468        fs::create_dir_all(&runtime).unwrap();
8469        let mut attempt =
8470            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
8471        attempt.jit_received(harness.clock.now()).unwrap();
8472        attempt.started(4242, harness.clock.now()).unwrap();
8473        harness.store.record_attempt(&attempt).unwrap();
8474        harness.clock.advance_secs(11);
8475        harness.processes.set_alive(true);
8476        harness
8477            .github
8478            .observe(GithubRunnerObservation::NotRegistered);
8479        let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
8480        assert_eq!(
8481            replacements,
8482            vec![ReplacementIntent {
8483                policy: harness.policy.id,
8484                previous_attempt: id,
8485                operation: "registration_timeout_replacement",
8486            }]
8487        );
8488
8489        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 1);
8490        assert!(!harness.processes.alive.load(Ordering::SeqCst));
8491        let actions = harness.processes.actions.lock().unwrap().clone();
8492        let intent = actions
8493            .iter()
8494            .position(|action| *action == "terminate_intent")
8495            .unwrap();
8496        let signal = actions
8497            .iter()
8498            .position(|action| *action == "terminate")
8499            .unwrap();
8500        assert!(
8501            intent < signal,
8502            "intent was not durable before signal: {actions:?}"
8503        );
8504
8505        let cleaned = harness.store.attempt(id).unwrap().unwrap();
8506        assert!(matches!(
8507            cleaned.outcome(),
8508            Some(AttemptOutcome::Failed {
8509                reason: FailureReason::TerminatedAfterRegistrationTimeout
8510            })
8511        ));
8512        let events = harness.events.events();
8513        let intent = events
8514            .iter()
8515            .position(|event| matches!(event, AttemptEvent::TerminateIntent { .. }))
8516            .unwrap();
8517        let stopped = events
8518            .iter()
8519            .position(|event| matches!(event, AttemptEvent::Terminated { .. }))
8520            .unwrap();
8521        let concluded = events
8522            .iter()
8523            .position(|event| matches!(event, AttemptEvent::Concluded { .. }))
8524            .unwrap();
8525        assert!(intent < stopped && stopped < concluded, "{events:?}");
8526    }
8527
8528    #[tokio::test]
8529    async fn timeout_crash_recovery_returns_the_same_replacement_intent() {
8530        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8531        let id = AttemptId::new_random();
8532        let runtime = harness
8533            .launcher
8534            .app_paths
8535            .runtime_dir()
8536            .join("timeout-after-crash");
8537        fs::create_dir_all(&runtime).unwrap();
8538        let mut attempt =
8539            RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
8540        attempt.jit_received(harness.clock.now()).unwrap();
8541        attempt.started(4242, harness.clock.now()).unwrap();
8542        harness.store.record_attempt(&attempt).unwrap();
8543        harness.processes.intent.store(true, Ordering::SeqCst);
8544        harness.processes.set_alive(false);
8545        harness
8546            .github
8547            .observe(GithubRunnerObservation::NotRegistered);
8548
8549        let replacements = harness
8550            .launcher
8551            .recover_startup(std::slice::from_ref(&harness.policy))
8552            .await
8553            .unwrap();
8554        assert_eq!(
8555            replacements,
8556            vec![ReplacementIntent {
8557                policy: harness.policy.id,
8558                previous_attempt: id,
8559                operation: "registration_timeout_replacement",
8560            }]
8561        );
8562        let consumed = RunnerLauncher::supervise(&harness.launcher, &harness.policy)
8563            .await
8564            .unwrap();
8565        assert_eq!(consumed, replacements);
8566        assert!(
8567            RunnerLauncher::supervise(&harness.launcher, &harness.policy)
8568                .await
8569                .unwrap()
8570                .is_empty(),
8571            "startup replacement evidence must be consumed exactly once by e1"
8572        );
8573        assert!(matches!(
8574            harness.store.attempt(id).unwrap().unwrap().outcome(),
8575            Some(AttemptOutcome::Failed {
8576                reason: FailureReason::TerminatedAfterRegistrationTimeout
8577            })
8578        ));
8579    }
8580
8581    #[tokio::test]
8582    async fn terminate_intent_sync_failure_prevents_signal_and_conclusion() {
8583        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8584        let id = AttemptId::new_random();
8585        let runtime = harness
8586            .launcher
8587            .app_paths
8588            .runtime_dir()
8589            .join("timeout-sync-failure");
8590        fs::create_dir_all(&runtime).unwrap();
8591        let mut attempt =
8592            RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
8593        attempt.jit_received(harness.clock.now()).unwrap();
8594        attempt.started(4242, harness.clock.now()).unwrap();
8595        harness.store.record_attempt(&attempt).unwrap();
8596        harness.clock.advance_secs(11);
8597        harness.processes.set_alive(true);
8598        harness.processes.fail_intent();
8599        harness
8600            .github
8601            .observe(GithubRunnerObservation::NotRegistered);
8602
8603        assert!(
8604            harness
8605                .launcher
8606                .recover_startup(std::slice::from_ref(&harness.policy))
8607                .await
8608                .is_err()
8609        );
8610        assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 0);
8611        assert!(harness.processes.alive.load(Ordering::SeqCst));
8612        assert_eq!(
8613            harness.store.attempt(id).unwrap().unwrap().state(),
8614            AttemptState::Starting
8615        );
8616        assert!(!harness.events.events().iter().any(|event| matches!(
8617            event,
8618            AttemptEvent::Terminated { attempt } | AttemptEvent::Concluded { attempt, .. }
8619                if *attempt == id
8620        )));
8621    }
8622
8623    #[tokio::test]
8624    async fn diagnostics_survive_cleanup_without_the_jit_or_a_token() {
8625        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8626        harness.ready().await;
8627        let attempt = harness.launch().await;
8628        harness
8629            .github
8630            .observe(GithubRunnerObservation::Registered { busy: false });
8631        harness.launcher.supervise(&harness.policy).await.unwrap();
8632        harness.clock.advance_secs(11);
8633        harness.processes.set_alive(false);
8634        harness
8635            .github
8636            .observe(GithubRunnerObservation::NotRegistered);
8637        harness.launcher.supervise(&harness.policy).await.unwrap();
8638        let diagnostic = fs::read_to_string(
8639            harness
8640                .launcher
8641                .diagnostics_root
8642                .join(format!("{}.log", attempt.id)),
8643        )
8644        .unwrap();
8645        assert!(diagnostic.contains("exited_idle_without_work"));
8646        assert!(!diagnostic.contains(JIT));
8647        assert!(!diagnostic.contains("ghp_"));
8648        assert!(!attempt.runtime_path().exists());
8649    }
8650
8651    #[test]
8652    fn native_process_listing_never_contains_jit_and_handoffs_never_survive() {
8653        let root = tempfile::tempdir().unwrap();
8654        let policy = fixtures::policy()
8655            .repository("octo/repo")
8656            .autoscale("home", 1)
8657            .active()
8658            .build();
8659        let runtime = root.path().join("successful");
8660        fs::create_dir_all(&runtime).unwrap();
8661        let processes = NativeProcesses::new();
8662        let config = EncodedJitConfig::new(JIT);
8663        let handoff =
8664            RestrictiveHandoff::create(&runtime, SecretString::from(config.expose().to_owned()))
8665                .unwrap();
8666        let mut child = native_inspection_spec()
8667            .spawn_runner_with_handoff(&handoff)
8668            .expect("native child starts");
8669        let pid = child.pid();
8670        handoff.delete().unwrap();
8671        let command_line = native_command_line(pid);
8672        assert!(
8673            !command_line.contains(JIT),
8674            "the encoded JIT configuration appeared in the native process listing"
8675        );
8676        assert_no_jit_file(&runtime);
8677        child
8678            .stop(Duration::from_secs(1))
8679            .expect("native child stops");
8680
8681        let failed_runtime = root.path().join("failed");
8682        fs::create_dir_all(&failed_runtime).unwrap();
8683        let failed = RunnerAttempt::allocate(
8684            AttemptId::new_random(),
8685            policy.id,
8686            &failed_runtime,
8687            FakeClock::default().now(),
8688        );
8689        assert!(
8690            processes
8691                .spawn(&failed, &EncodedJitConfig::new(JIT))
8692                .is_err(),
8693            "a runtime with no runner executable must fail"
8694        );
8695        assert_no_jit_file(&failed_runtime);
8696        processes
8697            .record_terminate_intent(&failed)
8698            .expect("the intent file and its directory entry are durably synced");
8699        assert_eq!(
8700            fs::read(NativeProcesses::intent_path(&failed)).unwrap(),
8701            b"registration-timeout\n"
8702        );
8703    }
8704
8705    #[test]
8706    fn post_spawn_boundaries_are_bounded_durable_and_never_retry_jit() {
8707        let root = tempfile::tempdir().unwrap();
8708        let policy = fixtures::policy()
8709            .repository("octo/repo")
8710            .autoscale("home", 1)
8711            .active()
8712            .build();
8713        let processes = NativeProcesses::new();
8714        processes.use_long_lived_test_listener();
8715        for (index, boundary) in [
8716            PostSpawnBoundary::HandoffDelete,
8717            PostSpawnBoundary::IdentitySerialize,
8718            PostSpawnBoundary::IdentityWrite,
8719            PostSpawnBoundary::ChildMapInsert,
8720        ]
8721        .into_iter()
8722        .enumerate()
8723        {
8724            let runtime = root.path().join(format!("post-spawn-{index}"));
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 attempt = RunnerAttempt::allocate(
8733                AttemptId::new_random(),
8734                policy.id,
8735                &runtime,
8736                FakeClock::default().now(),
8737            );
8738            processes.fail_post_spawn_at(boundary);
8739            let failure = processes
8740                .spawn(&attempt, &EncodedJitConfig::new(JIT))
8741                .expect_err("fault must cross the post-spawn cleanup path");
8742            assert!(!failure.retryable, "{boundary:?} allowed duplicate retry");
8743            assert!(
8744                !processes.is_alive(&attempt).unwrap(),
8745                "{boundary:?} left a child"
8746            );
8747            assert!(!NativeProcesses::identity_path(&attempt).exists());
8748            assert_no_jit_file(&runtime);
8749        }
8750        assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
8751
8752        let runtime = root.path().join("identity-and-stop-fail");
8753        let bin = runtime.join("bin");
8754        fs::create_dir_all(&bin).unwrap();
8755        #[cfg(windows)]
8756        let listener = bin.join("Runner.Listener.exe");
8757        #[cfg(not(windows))]
8758        let listener = bin.join("Runner.Listener");
8759        fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
8760        let attempt = RunnerAttempt::allocate(
8761            AttemptId::new_random(),
8762            policy.id,
8763            &runtime,
8764            FakeClock::default().now(),
8765        );
8766        // The first fault rejects the normal identity write; the second rejects
8767        // its retry after the first stop fails. The fallback sidecar must make
8768        // the live-child result durable without an unbounded reap loop.
8769        processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
8770        processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
8771        processes.fail_next_post_spawn_stop();
8772        let failure = processes
8773            .spawn(&attempt, &EncodedJitConfig::new(JIT))
8774            .expect_err("the identity boundary must fail closed");
8775        assert!(failure.live_pid.is_some());
8776        assert_long_lived_listener_ready(&processes, &attempt);
8777        assert!(processes.is_alive(&attempt).unwrap());
8778        assert!(!NativeProcesses::identity_path(&attempt).exists());
8779        assert!(NativeProcesses::fallback_identity_path(&attempt).is_file());
8780        assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
8781        processes.terminate(&attempt).unwrap();
8782
8783        let runtime = root.path().join("persistent-stop-and-identity-failures");
8784        let bin = runtime.join("bin");
8785        fs::create_dir_all(&bin).unwrap();
8786        #[cfg(windows)]
8787        let listener = bin.join("Runner.Listener.exe");
8788        #[cfg(not(windows))]
8789        let listener = bin.join("Runner.Listener");
8790        fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
8791        let mut unresolved = RunnerAttempt::allocate(
8792            AttemptId::new_random(),
8793            policy.id,
8794            &runtime,
8795            FakeClock::default().now(),
8796        );
8797        for _ in 0..3 {
8798            processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
8799        }
8800        processes.fail_post_spawn_stops(MAX_POST_SPAWN_STOP_ATTEMPTS);
8801        let failure = processes
8802            .spawn(&unresolved, &EncodedJitConfig::new(JIT))
8803            .expect_err("bounded cleanup must return even when every stop errors");
8804        let pid = failure
8805            .live_pid
8806            .expect("the owned child remains supervised in this invocation");
8807        assert!(matches!(failure.reason, FailureReason::Other(_)));
8808        assert_long_lived_listener_ready(&processes, &unresolved);
8809        unresolved.jit_received(FakeClock::default().now()).unwrap();
8810        unresolved.started(pid, FakeClock::default().now()).unwrap();
8811        let journal = SqliteStore::open_in_memory().unwrap();
8812        journal.record_attempt(&unresolved).unwrap();
8813        let recovered = journal.attempt(unresolved.id).unwrap().unwrap();
8814        assert_eq!(recovered.process_id(), Some(pid));
8815        assert_eq!(recovered.state(), AttemptState::Starting);
8816        assert!(processes.is_alive(&unresolved).unwrap());
8817        assert!(!NativeProcesses::identity_path(&unresolved).exists());
8818        assert!(!NativeProcesses::fallback_identity_path(&unresolved).exists());
8819        assert_eq!(
8820            fs::read_to_string(NativeProcesses::unresolved_process_path(&unresolved)).unwrap(),
8821            pid.to_string(),
8822            "bounded cleanup must leave durable unresolved-process evidence before returning"
8823        );
8824        assert!(
8825            NativeProcesses::new().is_alive(&recovered).is_err(),
8826            "restart must fail closed on the durable starting/PID journal rather than trust a bare PID"
8827        );
8828        processes.terminate(&unresolved).unwrap();
8829
8830        let runtime = root.path().join("post-spawn-stop-failed");
8831        let bin = runtime.join("bin");
8832        fs::create_dir_all(&bin).unwrap();
8833        #[cfg(windows)]
8834        let listener = bin.join("Runner.Listener.exe");
8835        #[cfg(not(windows))]
8836        let listener = bin.join("Runner.Listener");
8837        fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
8838        let attempt = RunnerAttempt::allocate(
8839            AttemptId::new_random(),
8840            policy.id,
8841            &runtime,
8842            FakeClock::default().now(),
8843        );
8844        processes.fail_post_spawn_at(PostSpawnBoundary::ChildMapInsert);
8845        processes.fail_next_post_spawn_stop();
8846        let failure = processes
8847            .spawn(&attempt, &EncodedJitConfig::new(JIT))
8848            .expect_err("the injected stop failure must preserve supervision");
8849        let live_pid = failure
8850            .live_pid
8851            .expect("live PID is returned to the journal");
8852        assert!(!failure.retryable);
8853        assert_long_lived_listener_ready(&processes, &attempt);
8854        assert!(NativeProcesses::identity_path(&attempt).is_file());
8855        assert_eq!(
8856            NativeProcesses::read_identity(&attempt)
8857                .unwrap()
8858                .unwrap()
8859                .pid(),
8860            live_pid
8861        );
8862        assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
8863        processes.terminate(&attempt).unwrap();
8864    }
8865
8866    #[test]
8867    #[ignore = "spawned only as the platform-stable native listener fixture"]
8868    fn long_lived_native_listener_helper() {
8869        let ready = std::env::var_os("RUNNER_MANAGER_TEST_LISTENER_READY")
8870            .map(PathBuf::from)
8871            .expect("the parent supplies the readiness path");
8872        fs::write(ready, b"ready\n").expect("the listener publishes readiness");
8873        std::thread::sleep(Duration::from_secs(30));
8874    }
8875
8876    fn assert_long_lived_listener_ready(processes: &NativeProcesses, attempt: &RunnerAttempt) {
8877        let ready = attempt.runtime_path().join(TEST_LISTENER_READY);
8878        let deadline = std::time::Instant::now() + Duration::from_secs(5);
8879        loop {
8880            if ready.is_file() {
8881                assert_eq!(fs::read(&ready).unwrap(), b"ready\n");
8882                return;
8883            }
8884            assert!(
8885                processes.is_alive(attempt).unwrap(),
8886                "the native listener exited before publishing readiness"
8887            );
8888            assert!(
8889                std::time::Instant::now() < deadline,
8890                "the native listener stayed alive but never published readiness"
8891            );
8892            std::thread::sleep(Duration::from_millis(10));
8893        }
8894    }
8895
8896    #[tokio::test]
8897    async fn every_production_launch_prunes_under_the_same_allocation_guard() {
8898        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
8899        harness.ready().await;
8900        assert_eq!(harness.packages.prunes.load(Ordering::SeqCst), 0);
8901        harness.launch().await;
8902        assert_eq!(harness.packages.prunes.load(Ordering::SeqCst), 1);
8903        assert_eq!(
8904            *harness.packages.prune_currents.lock().unwrap(),
8905            vec![harness.packages.version.clone()],
8906            "the leased current version is an exclusion, never the prune target"
8907        );
8908    }
8909
8910    fn assert_no_jit_file(runtime: &Path) {
8911        for entry in fs::read_dir(runtime).unwrap() {
8912            let path = entry.unwrap().path();
8913            if path.is_file() {
8914                let bytes = fs::read(&path).unwrap();
8915                assert!(
8916                    !bytes
8917                        .windows(JIT.len())
8918                        .any(|window| window == JIT.as_bytes()),
8919                    "a JIT payload survived in a runtime file"
8920                );
8921            }
8922        }
8923    }
8924
8925    #[test]
8926    fn production_listener_command_uses_the_supported_jit_contract() {
8927        let runtime = Path::new("runtime");
8928        let spec = runner_listener_spec(
8929            PathBuf::from("Runner.Listener"),
8930            runtime,
8931            Vec::new(),
8932            &RunnerEnv::default(),
8933        );
8934        let arguments: Vec<_> = spec
8935            .arguments()
8936            .iter()
8937            .map(|argument| argument.to_string_lossy().into_owned())
8938            .collect();
8939
8940        assert_eq!(arguments, ["run"]);
8941        assert!(
8942            !arguments
8943                .iter()
8944                .any(|argument| argument == "--jit-config-file"),
8945            "the obsolete file option would be rejected by Runner.Listener 2.336.0"
8946        );
8947    }
8948
8949    /// What a production runner starts with: the platform defaults, the host's
8950    /// `runner.env` over them, the attempt's own temporary directory, and
8951    /// normal scheduling.
8952    #[test]
8953    fn production_listener_layers_runner_env_over_the_platform_defaults() {
8954        let root = tempfile::tempdir().unwrap();
8955        let runtime = root.path().join("attempt");
8956        let host_env =
8957            RunnerEnv::parse("ELECTRON_CACHE=/cache/electron\nHOME=/operator/chose/this\n")
8958                .unwrap();
8959        let caches = vec![
8960            (
8961                "ELECTRON_CACHE",
8962                std::ffi::OsString::from("/rman/_cache/o/r/electron"),
8963            ),
8964            (
8965                "npm_config_cache",
8966                std::ffi::OsString::from("/rman/_cache/o/r/npm"),
8967            ),
8968        ];
8969        let spec = runner_listener_spec(
8970            PathBuf::from("Runner.Listener"),
8971            &runtime,
8972            caches,
8973            &host_env,
8974        );
8975        let env = |name: &str| spec.configured_env(name).map(PathBuf::from);
8976
8977        assert!(spec.expects_normal_scheduling());
8978        assert_eq!(
8979            env("ELECTRON_CACHE"),
8980            Some(PathBuf::from("/cache/electron")),
8981            "runner.env must win over a dependency cache of the same name"
8982        );
8983        assert_eq!(
8984            env("npm_config_cache"),
8985            Some(PathBuf::from("/rman/_cache/o/r/npm"))
8986        );
8987        assert_eq!(
8988            env("HOME"),
8989            Some(PathBuf::from("/operator/chose/this")),
8990            "runner.env must win over a platform default of the same name"
8991        );
8992        for tmp in ["TMPDIR", "TEMP", "TMP"] {
8993            assert_eq!(env(tmp), Some(runtime.join("tmp")), "{tmp}");
8994        }
8995
8996        let home = runtime.join(runner_env::RUNNER_HOME_DIR);
8997        if cfg!(windows) {
8998            // Each runner's own profile, created inside its attempt, so that
8999            // concurrent jobs stop sharing the service account's.
9000            assert_eq!(env("USERPROFILE"), Some(home.clone()));
9001            assert_eq!(env("APPDATA"), Some(home.join(r"AppData\Roaming")));
9002            assert_eq!(env("LOCALAPPDATA"), Some(home.join(r"AppData\Local")));
9003            assert!(home.join(r"AppData\Roaming").is_dir());
9004            assert!(home.join(r"AppData\Local").is_dir());
9005        } else {
9006            // Unix keeps the account's own profile.
9007            assert_eq!(env("USERPROFILE"), None);
9008            assert!(!home.exists());
9009        }
9010    }
9011
9012    /// Every step shell a runner starts inherits PowerShell's telemetry
9013    /// opt-out from the listener, unless the daemon or `runner.env` decided
9014    /// otherwise; see [`runner_env::POWERSHELL_TELEMETRY_OPTOUT`].
9015    #[test]
9016    fn production_listener_opts_powershell_out_of_telemetry() {
9017        let root = tempfile::tempdir().unwrap();
9018        let runtime = root.path().join("attempt");
9019        let listener = |host_env: &RunnerEnv| {
9020            runner_listener_spec(
9021                PathBuf::from("Runner.Listener"),
9022                &runtime,
9023                Vec::new(),
9024                host_env,
9025            )
9026        };
9027        let optout = |spec: &SpawnSpec| {
9028            spec.configured_env(runner_env::POWERSHELL_TELEMETRY_OPTOUT)
9029                .map(OsStr::to_os_string)
9030        };
9031
9032        let spec = listener(&RunnerEnv::default());
9033        if std::env::var_os(runner_env::POWERSHELL_TELEMETRY_OPTOUT)
9034            .is_some_and(|value| !value.is_empty())
9035        {
9036            // The daemon's own value is inherited as it is.
9037            assert_eq!(optout(&spec), None);
9038        } else {
9039            assert_eq!(
9040                optout(&spec),
9041                Some(runner_env::POWERSHELL_TELEMETRY_OPTOUT_VALUE.into())
9042            );
9043        }
9044
9045        let operator = RunnerEnv::parse("POWERSHELL_TELEMETRY_OPTOUT=0\n").unwrap();
9046        assert_eq!(
9047            optout(&listener(&operator)),
9048            Some("0".into()),
9049            "runner.env must win over the telemetry opt-out"
9050        );
9051    }
9052
9053    #[test]
9054    fn an_invalid_runner_env_fails_the_launch_without_echoing_a_value() {
9055        let root = tempfile::tempdir().unwrap();
9056        let path = runner_env::path_in(root.path());
9057        fs::write(&path, "GOOD=1\nghp_notarealtokenbutshapedlikeone\n").unwrap();
9058        let processes = NativeProcesses::new().with_runner_env_file(path.clone());
9059        let failure = processes.host_env().unwrap_err().to_string();
9060        assert!(
9061            failure.contains("runner.env") && failure.contains("line 2"),
9062            "{failure}"
9063        );
9064        assert!(
9065            !failure.contains("ghp_"),
9066            "the failure echoed a value: {failure}"
9067        );
9068
9069        // `prepare` runs before the JIT registration, so a broken file is
9070        // refused there, before GitHub is asked for anything.
9071        let policy = fixtures::policy()
9072            .repository("octo/repo")
9073            .autoscale("home", 1)
9074            .active()
9075            .build();
9076        let attempt = RunnerAttempt::allocate(
9077            AttemptId::new_random(),
9078            policy.id,
9079            root.path(),
9080            FakeClock::default().now(),
9081        );
9082        assert!(processes.prepare(&attempt, &policy).is_err());
9083
9084        fs::write(&path, "GOOD=1\n").unwrap();
9085        assert!(processes.prepare(&attempt, &policy).is_ok());
9086        assert_eq!(processes.host_env().unwrap().get("GOOD"), Some("1"));
9087        assert!(NativeProcesses::new().host_env().unwrap().is_empty());
9088    }
9089
9090    /// The wiring from `prepare` (which sees the policy) to `spawn` (which
9091    /// does not): the policy's repository decides the namespace, and a broken
9092    /// `caches.toml` is refused before GitHub is asked for anything.
9093    #[test]
9094    fn prepare_hands_the_policys_cache_namespace_to_the_launch() {
9095        let root = tempfile::tempdir().unwrap();
9096        let runner_root = root.path().join("rman");
9097        let runtime = runner_root.join("a1");
9098        fs::create_dir_all(runtime.join("bin")).unwrap();
9099        let config = runner_manager_platform::dependency_cache::config_path_in(root.path());
9100        let source_root = runner_root.clone();
9101        let processes = NativeProcesses::new().with_dependency_caches(DependencyCaches::new(
9102            config.clone(),
9103            Arc::new(move || Some(source_root.clone())),
9104            None,
9105        ));
9106        let policy = fixtures::policy()
9107            .repository("Octo/Repo")
9108            .autoscale("home", 1)
9109            .active()
9110            .build();
9111        let attempt = RunnerAttempt::allocate(
9112            AttemptId::new_random(),
9113            policy.id,
9114            &runtime,
9115            FakeClock::default().now(),
9116        );
9117        assert!(
9118            processes
9119                .cache_env(&attempt, None, &RunnerEnv::default())
9120                .is_empty(),
9121            "a launch with no prepared target, such as a bare `spawn`, has no cache"
9122        );
9123        let prepared = processes.prepare(&attempt, &policy).unwrap();
9124        let variables = processes.cache_env(
9125            &attempt,
9126            prepared.cache_target.as_ref(),
9127            &RunnerEnv::default(),
9128        );
9129        let npm = variables
9130            .iter()
9131            .find(|(name, _)| *name == "npm_config_cache")
9132            .map(|(_, value)| PathBuf::from(value));
9133        assert_eq!(
9134            npm,
9135            Some(
9136                runner_root
9137                    .join("_cache")
9138                    .join("octo")
9139                    .join("repo")
9140                    .join("npm")
9141            )
9142        );
9143
9144        fs::write(&config, "[tools]\nnot-a-tool = true\n").unwrap();
9145        let refused = processes
9146            .prepare(&attempt, &policy)
9147            .unwrap_err()
9148            .to_string();
9149        assert!(refused.contains("caches.toml"), "{refused}");
9150    }
9151
9152    #[cfg(windows)]
9153    fn native_inspection_spec() -> SpawnSpec {
9154        SpawnSpec::new("powershell.exe").args([
9155            "-NoProfile",
9156            "-NonInteractive",
9157            "-Command",
9158            "Start-Sleep -Seconds 30",
9159        ])
9160    }
9161
9162    #[cfg(unix)]
9163    fn native_inspection_spec() -> SpawnSpec {
9164        SpawnSpec::new("/bin/sh").args(["-c", "sleep 30"])
9165    }
9166
9167    #[cfg(windows)]
9168    fn native_command_line(pid: u32) -> String {
9169        let output = std::process::Command::new("powershell.exe")
9170            .args([
9171                "-NoProfile",
9172                "-NonInteractive",
9173                "-Command",
9174                &format!("(Get-CimInstance Win32_Process -Filter 'ProcessId = {pid}').CommandLine"),
9175            ])
9176            .output()
9177            .expect("PowerShell can inspect the native child");
9178        assert!(output.status.success(), "native process inspection failed");
9179        String::from_utf8(output.stdout).expect("Windows command lines are Unicode")
9180    }
9181
9182    #[cfg(target_os = "linux")]
9183    fn native_command_line(pid: u32) -> String {
9184        fs::read(format!("/proc/{pid}/cmdline"))
9185            .map(|bytes| String::from_utf8_lossy(&bytes).replace('\0', " "))
9186            .expect("/proc exposes the native child command line")
9187    }
9188
9189    #[cfg(target_os = "macos")]
9190    fn native_command_line(pid: u32) -> String {
9191        let output = std::process::Command::new("ps")
9192            .args(["-o", "command=", "-p", &pid.to_string()])
9193            .output()
9194            .expect("ps can inspect the native child");
9195        assert!(output.status.success(), "native process inspection failed");
9196        String::from_utf8(output.stdout).expect("the command line is UTF-8")
9197    }
9198
9199    // -- c2: persistent slot allocation -------------------------------------
9200
9201    #[tokio::test]
9202    async fn a_persistent_repository_leases_s1_and_journals_it_before_any_github_effect() {
9203        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9204            .with_persistent_workspace(2);
9205        harness.github.watch_journal(Arc::clone(&harness.store));
9206        harness.ready().await;
9207
9208        let attempt = harness.launch().await;
9209
9210        assert_eq!(
9211            attempt.workspace(),
9212            AttemptWorkspace::persistent_slot(nz(1)),
9213            "the lowest free slot is leased"
9214        );
9215        assert_eq!(attempt.runtime_path(), harness.slot_path(1));
9216        assert!(attempt.holds_slot_lease());
9217        // The exact runtime path is journalled, not re-derived later.
9218        assert_eq!(
9219            harness.attempt(attempt.id).runtime_path(),
9220            harness.slot_path(1)
9221        );
9222
9223        // Step 7 of "Slot allocation": the lease exists before GitHub is asked
9224        // for anything, and the runner's work folder stays the relative `_work`
9225        // the slot root is laid out around.
9226        let facts = harness.github.registration_facts();
9227        assert_eq!(facts.len(), 1);
9228        assert_eq!(
9229            facts[0].leased_slots,
9230            vec![1],
9231            "the lease was journalled first"
9232        );
9233        assert_eq!(facts[0].work_folder, DEFAULT_WORK_FOLDER);
9234    }
9235
9236    #[tokio::test]
9237    async fn a_terminal_but_uncleaned_attempt_keeps_its_slot_without_holding_capacity() {
9238        let harness = Harness::new(
9239            FakeGithubLifecycle::default().fail(true),
9240            Arc::new(PersistentDemand),
9241        )
9242        .with_persistent_workspace(2);
9243        harness.ready().await;
9244
9245        // A terminal JIT refusal concludes the attempt without cleaning it.
9246        harness.launch_result().await.unwrap_err();
9247        let first = harness.store.attempts().unwrap().remove(0);
9248        assert_eq!(first.state(), AttemptState::Failed);
9249        assert!(
9250            !first.state().counts_against_capacity(),
9251            "a concluded attempt is invisible to host capacity"
9252        );
9253        assert!(
9254            first.holds_slot_lease(),
9255            "and still owns its directory, so its slot is not free"
9256        );
9257
9258        let second = harness.launch().await;
9259        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
9260        assert_eq!(second.runtime_path(), harness.slot_path(2));
9261        assert_eq!(
9262            harness
9263                .store
9264                .slot_leases_for_policy(harness.policy.id)
9265                .unwrap()
9266                .len(),
9267            2
9268        );
9269    }
9270
9271    #[tokio::test]
9272    async fn two_sequential_allocations_at_capacity_one_reuse_s1_and_its_retained_work() {
9273        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9274            .with_persistent_workspace(1);
9275        harness.ready().await;
9276
9277        let first = harness.launch().await;
9278        assert_eq!(first.runtime_path(), harness.slot_path(1));
9279
9280        // What a job leaves behind, at the path the runner writes it to.
9281        let checkout = harness.slot_path(1).join(DEFAULT_WORK_FOLDER).join("repo");
9282        fs::create_dir_all(&checkout).unwrap();
9283        fs::write(checkout.join("checkout.txt"), b"from the first job").unwrap();
9284
9285        harness.cleanup_retaining_work(first.id).await;
9286
9287        let second = harness.launch().await;
9288        assert_ne!(second.id, first.id);
9289        assert_eq!(
9290            second.workspace(),
9291            AttemptWorkspace::persistent_slot(nz(1)),
9292            "a released slot is leased again rather than skipped"
9293        );
9294        assert_eq!(
9295            second.runtime_path(),
9296            first.runtime_path(),
9297            "the same slot is the same exact path"
9298        );
9299        assert_eq!(
9300            fs::read_to_string(checkout.join("checkout.txt")).unwrap(),
9301            "from the first job",
9302            "the retained job workspace survived the second allocation"
9303        );
9304        // The attempt's own runner material was recreated for this attempt.
9305        assert!(harness.slot_path(1).join("runner-package").exists());
9306    }
9307
9308    #[tokio::test]
9309    async fn lowering_capacity_leaves_higher_slots_alone_and_raising_it_permits_them_again() {
9310        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9311            .with_persistent_workspace(2);
9312        harness.ready().await;
9313
9314        let first = harness.launch().await;
9315        let second = harness.launch().await;
9316        assert_eq!(second.runtime_path(), harness.slot_path(2));
9317        let kept = harness
9318            .slot_path(2)
9319            .join(DEFAULT_WORK_FOLDER)
9320            .join("kept.txt");
9321        fs::create_dir_all(kept.parent().unwrap()).unwrap();
9322        fs::write(&kept, b"s2 was here").unwrap();
9323        harness.cleanup_retaining_work(second.id).await;
9324
9325        // The operator lowers the ceiling while s1 is still leased.
9326        harness.policy.set_max_capacity(nz(1)).unwrap();
9327        let refusal = harness.launch_result().await.unwrap_err().to_string();
9328        assert!(
9329            refusal.contains("s1 to s1"),
9330            "the refusal names the ceiling it reached: {refusal}"
9331        );
9332        assert!(
9333            harness.slot_path(2).exists() && kept.exists(),
9334            "lowering capacity deletes nothing; the higher slot is merely unusable"
9335        );
9336
9337        // Raising it again makes the free higher slot available.
9338        harness.policy.set_max_capacity(nz(2)).unwrap();
9339        let third = harness.launch().await;
9340        assert_eq!(third.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
9341        assert_eq!(third.runtime_path(), harness.slot_path(2));
9342        assert_eq!(fs::read_to_string(&kept).unwrap(), "s2 was here");
9343        assert!(first.holds_slot_lease(), "s1 was never disturbed");
9344    }
9345
9346    #[tokio::test]
9347    async fn organization_and_ephemeral_policies_never_enter_slot_allocation() {
9348        for policy in [
9349            fixtures::policy()
9350                .organization("octo")
9351                .autoscale("home", 2)
9352                .active()
9353                .build(),
9354            fixtures::policy()
9355                .repository("octo/repo")
9356                .autoscale("home", 2)
9357                .active()
9358                .build(),
9359        ] {
9360            let mut harness =
9361                Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9362                    .with_host_runner_root();
9363            assert_eq!(policy.workspace_policy(), &WorkspacePolicy::Ephemeral);
9364            harness.policy = policy;
9365            harness.ready().await;
9366
9367            let attempt = harness.launch().await;
9368            assert_eq!(attempt.workspace(), AttemptWorkspace::Ephemeral);
9369            assert_eq!(attempt.workspace().slot_number(), None);
9370            assert!(!attempt.holds_slot_lease());
9371            assert_eq!(
9372                attempt.runtime_path().parent().unwrap(),
9373                harness.host_root(),
9374                "a disposable attempt is a child of the host root, never of a slot"
9375            );
9376            assert!(
9377                harness
9378                    .store
9379                    .slot_leases_for_policy(harness.policy.id)
9380                    .unwrap()
9381                    .is_empty()
9382            );
9383        }
9384    }
9385
9386    #[tokio::test]
9387    async fn two_concurrent_allocations_never_share_a_slot() {
9388        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9389            .with_persistent_workspace(2);
9390        harness.github.watch_journal(Arc::clone(&harness.store));
9391        harness.ready().await;
9392
9393        // Both allocators race for the same host allocation lock, which is what
9394        // orders slot *selection*; each one then journals its lease before it
9395        // asks GitHub for anything.
9396        let (first, second) = tokio::join!(harness.launch_result(), harness.launch_result());
9397        let first = first.unwrap();
9398        let second = second.unwrap();
9399
9400        let slots: BTreeSet<u16> = [&first, &second]
9401            .iter()
9402            .map(|attempt| {
9403                attempt
9404                    .workspace()
9405                    .slot_number()
9406                    .expect("a persistent attempt leases a slot")
9407            })
9408            .collect();
9409        assert_eq!(slots, BTreeSet::from([1, 2]), "one slot each, never shared");
9410        assert_ne!(first.runtime_path(), second.runtime_path());
9411        assert_eq!(
9412            harness
9413                .store
9414                .slot_leases_for_policy(harness.policy.id)
9415                .unwrap()
9416                .len(),
9417            2
9418        );
9419
9420        // Every registration saw *its own* lease already in the journal. Reading
9421        // the whole journal and asking only that it be non-empty would pass on
9422        // the other allocator's lease, which is precisely the ordering bug this
9423        // test exists to exclude.
9424        let facts = harness.github.registration_facts();
9425        assert_eq!(facts.len(), 2);
9426        for fact in facts {
9427            let attempt = [&first, &second]
9428                .into_iter()
9429                .find(|attempt| runner_name(attempt.id) == fact.runner_name)
9430                .expect("every registration belongs to one of the two attempts");
9431            let slot = attempt
9432                .workspace()
9433                .slot_number()
9434                .expect("a persistent attempt leases a slot");
9435            assert!(
9436                fact.leased_slots.contains(&slot),
9437                "a JIT request never precedes its own lease: s{slot} not in {:?}",
9438                fact.leased_slots
9439            );
9440            assert_eq!(fact.work_folder, DEFAULT_WORK_FOLDER);
9441        }
9442    }
9443
9444    #[tokio::test]
9445    async fn the_database_is_the_final_fence_against_two_attempts_in_one_slot() {
9446        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9447            .with_persistent_workspace(2);
9448        harness.ready().await;
9449        let first = harness.launch().await;
9450
9451        // What a second allocator that lost the race would write: the lock
9452        // orders selection, and this index is what catches a writer the lock
9453        // could not see.
9454        let clash = RunnerAttempt::allocate_in(
9455            AttemptId::new_random(),
9456            harness.policy.id,
9457            first.runtime_path(),
9458            AttemptWorkspace::persistent_slot(nz(1)),
9459            harness.clock.now(),
9460        );
9461        assert!(matches!(
9462            harness.store.record_attempt(&clash).unwrap_err(),
9463            StoreError::SlotAlreadyLeased { slot: 1, .. }
9464        ));
9465
9466        // And the launcher reports it as itself rather than as a generic
9467        // journal failure, so the operator reads what actually happened.
9468        let error = harness.launcher.record_allocation(&clash).unwrap_err();
9469        let rendered = error.to_string();
9470        assert!(rendered.contains("slot s1"), "{rendered}");
9471        assert!(rendered.contains("nothing was written"), "{rendered}");
9472        assert_eq!(
9473            harness.store.attempts().unwrap().len(),
9474            1,
9475            "the losing allocator journalled nothing"
9476        );
9477    }
9478
9479    #[test]
9480    fn slot_selection_fills_the_lowest_gap_and_stops_at_the_ceiling() {
9481        let leased = |slots: &[u16]| -> Vec<RunnerAttempt> {
9482            slots
9483                .iter()
9484                .map(|slot| {
9485                    RunnerAttempt::allocate_in(
9486                        AttemptId::new_random(),
9487                        fixtures::POLICY_ID,
9488                        format!("/srv/rman/acme/s{slot}"),
9489                        AttemptWorkspace::persistent_slot(nz(*slot)),
9490                        fixtures::created_at(),
9491                    )
9492                })
9493                .collect()
9494        };
9495
9496        assert_eq!(lowest_free_slot(&[], nz(1)), Some(nz(1)));
9497        assert_eq!(lowest_free_slot(&leased(&[1]), nz(4)), Some(nz(2)));
9498        // The gap a released middle slot leaves is filled before the tail.
9499        assert_eq!(lowest_free_slot(&leased(&[1, 3]), nz(4)), Some(nz(2)));
9500        // The ceiling is a refusal, never a reason to allocate past it.
9501        assert_eq!(lowest_free_slot(&leased(&[1]), nz(1)), None);
9502        assert_eq!(lowest_free_slot(&leased(&[1, 2]), nz(2)), None);
9503        // An ephemeral attempt holds no slot and cannot block one.
9504        let ephemeral = vec![RunnerAttempt::allocate(
9505            AttemptId::new_random(),
9506            fixtures::POLICY_ID,
9507            "/srv/rman/host/abc",
9508            fixtures::created_at(),
9509        )];
9510        assert_eq!(lowest_free_slot(&ephemeral, nz(1)), Some(nz(1)));
9511    }
9512
9513    #[test]
9514    fn a_slot_is_reusable_only_when_it_is_empty_or_holds_one_real_work_directory() {
9515        let root = tempfile::tempdir().unwrap();
9516        let slot = root.path().join("s1");
9517        fs::create_dir(&slot).unwrap();
9518        accept_reusable_slot(&slot).expect("an empty slot is reusable");
9519
9520        fs::create_dir(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
9521        accept_reusable_slot(&slot).expect("a retained job workspace is reusable");
9522
9523        // Runner material a previous attempt left behind is refused rather than
9524        // reused or removed: deciding those bytes are safe is cleanup's job.
9525        fs::create_dir(slot.join("bin")).unwrap();
9526        fs::write(slot.join(".github-runner-id"), b"73").unwrap();
9527        let refusal = accept_reusable_slot(&slot).unwrap_err().to_string();
9528        assert!(refusal.contains("bin"), "{refusal}");
9529        assert!(refusal.contains(".github-runner-id"), "{refusal}");
9530
9531        // A `_work` that is not a real directory is not a job workspace.
9532        let file_work = root.path().join("s2");
9533        fs::create_dir(&file_work).unwrap();
9534        fs::write(file_work.join(DEFAULT_WORK_FOLDER), b"not a directory").unwrap();
9535        assert!(accept_reusable_slot(&file_work).is_err());
9536    }
9537
9538    #[cfg(unix)]
9539    #[test]
9540    fn a_link_shaped_work_directory_is_refused_rather_than_followed() {
9541        // Windows needs a privilege to create either kind of link, so the
9542        // link-shaped cases are asserted here; the rule itself is
9543        // platform-independent because it is `symlink_metadata`'s answer.
9544        let root = tempfile::tempdir().unwrap();
9545        let elsewhere = root.path().join("elsewhere");
9546        fs::create_dir(&elsewhere).unwrap();
9547
9548        let slot = root.path().join("s1");
9549        fs::create_dir(&slot).unwrap();
9550        std::os::unix::fs::symlink(&elsewhere, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
9551        assert!(accept_reusable_slot(&slot).is_err());
9552
9553        let linked_slot = root.path().join("s2");
9554        std::os::unix::fs::symlink(&elsewhere, &linked_slot).unwrap();
9555        assert!(create_or_validate_slot(&linked_slot).is_err());
9556    }
9557
9558    #[test]
9559    fn a_slot_standing_where_a_file_is_refuses_rather_than_replacing_it() {
9560        let root = tempfile::tempdir().unwrap();
9561        let occupied = root.path().join("s1");
9562        fs::write(&occupied, b"an operator's file").unwrap();
9563        let refusal = create_or_validate_slot(&occupied).unwrap_err().to_string();
9564        assert!(refusal.contains("is not a directory"), "{refusal}");
9565        assert_eq!(fs::read_to_string(&occupied).unwrap(), "an operator's file");
9566
9567        let fresh = root.path().join("s2");
9568        create_or_validate_slot(&fresh).expect("a missing slot is created");
9569        assert!(fresh.is_dir());
9570        create_or_validate_slot(&fresh).expect("an existing directory is accepted");
9571    }
9572
9573    #[test]
9574    fn the_retained_work_directory_is_matched_the_way_the_filesystem_matches_it() {
9575        assert!(is_work_folder(OsStr::new(DEFAULT_WORK_FOLDER)));
9576        assert!(!is_work_folder(OsStr::new("_work2")));
9577        // A Windows filesystem is case-insensitive, so `_Work` *is* the retained
9578        // job workspace there and must never be removed as a leftover; on a
9579        // case-sensitive filesystem it is a different directory entirely.
9580        assert_eq!(is_work_folder(OsStr::new("_Work")), cfg!(windows));
9581    }
9582
9583    #[test]
9584    fn package_materialization_never_overwrites_or_follows_a_retained_work_directory() {
9585        let root = tempfile::tempdir().unwrap();
9586        let package = root.path().join("package");
9587        fs::create_dir_all(package.join("bin")).unwrap();
9588        fs::write(package.join("bin").join("Runner.Listener"), b"binary").unwrap();
9589        // A nested `_work` inside the package's own tree is an ordinary name.
9590        fs::create_dir_all(package.join("externals").join(DEFAULT_WORK_FOLDER)).unwrap();
9591
9592        let slot = root.path().join("s1");
9593        let retained = slot.join(DEFAULT_WORK_FOLDER).join("repo");
9594        fs::create_dir_all(&retained).unwrap();
9595        fs::write(retained.join("checkout.txt"), b"from the first job").unwrap();
9596
9597        copy_package_tree(&package, &slot, &TrustedTrees::default())
9598            .expect("the package lays out around `_work`");
9599        assert!(slot.join("bin").join("Runner.Listener").exists());
9600        assert!(
9601            slot.join("externals").join(DEFAULT_WORK_FOLDER).is_dir(),
9602            "the guard is top-level only"
9603        );
9604        assert_eq!(
9605            fs::read_to_string(retained.join("checkout.txt")).unwrap(),
9606            "from the first job"
9607        );
9608
9609        // A package that ever grew a top-level `_work` is refused, not merged.
9610        fs::create_dir(package.join(DEFAULT_WORK_FOLDER)).unwrap();
9611        let error = copy_package_tree(&package, &slot, &TrustedTrees::default()).unwrap_err();
9612        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
9613        assert_eq!(
9614            fs::read_to_string(retained.join("checkout.txt")).unwrap(),
9615            "from the first job"
9616        );
9617    }
9618
9619    #[test]
9620    fn rolling_back_a_materialization_keeps_a_slot_but_removes_a_disposable_directory() {
9621        let root = tempfile::tempdir().unwrap();
9622
9623        let slot = root.path().join("s1");
9624        let retained = slot.join(DEFAULT_WORK_FOLDER);
9625        fs::create_dir_all(retained.join("repo")).unwrap();
9626        fs::write(retained.join("repo").join("checkout.txt"), b"kept").unwrap();
9627        fs::create_dir_all(slot.join("bin")).unwrap();
9628        fs::write(slot.join(".github-runner-id"), b"73").unwrap();
9629        let persistent = RunnerAttempt::allocate_in(
9630            AttemptId::new_random(),
9631            fixtures::POLICY_ID,
9632            &slot,
9633            AttemptWorkspace::persistent_slot(nz(1)),
9634            fixtures::created_at(),
9635        );
9636
9637        remove_materialized_package(&persistent).unwrap();
9638        assert!(slot.is_dir(), "the slot itself is not removed");
9639        assert!(!slot.join("bin").exists());
9640        assert!(!slot.join(".github-runner-id").exists());
9641        assert_eq!(
9642            fs::read_to_string(retained.join("repo").join("checkout.txt")).unwrap(),
9643            "kept"
9644        );
9645
9646        let disposable_path = root.path().join("abcdef012345");
9647        fs::create_dir_all(disposable_path.join(DEFAULT_WORK_FOLDER)).unwrap();
9648        let disposable = RunnerAttempt::allocate(
9649            AttemptId::new_random(),
9650            fixtures::POLICY_ID,
9651            &disposable_path,
9652            fixtures::created_at(),
9653        );
9654        remove_materialized_package(&disposable).unwrap();
9655        assert!(
9656            !disposable_path.exists(),
9657            "a disposable directory is still removed whole"
9658        );
9659    }
9660
9661    // -- c3: persistent cleanup and recovery --------------------------------
9662
9663    /// The runner state one attempt leaves at a slot root, as a real attempt
9664    /// leaves it: binaries, registration identity, a JIT handoff that outlived
9665    /// its process, and this agent's own lifecycle sidecars.
9666    ///
9667    /// Driven by [`SENSITIVE_SLOT_ENTRIES`] rather than by a second copy of it,
9668    /// so a name added to the thing cleanup must prove absent is a name every
9669    /// test here starts leaving behind.
9670    fn litter_the_slot(slot: &Path) {
9671        for directory in ["bin", "externals", "_diag"] {
9672            fs::create_dir_all(slot.join(directory)).unwrap();
9673        }
9674        fs::write(slot.join("bin").join("Runner.Listener"), b"binary").unwrap();
9675        for file in SENSITIVE_SLOT_ENTRIES
9676            .iter()
9677            .filter(|entry| !slot.join(entry).is_dir())
9678        {
9679            fs::write(slot.join(file), b"runner state").unwrap();
9680        }
9681        // A handoff whose owning process died before `Drop` could delete it.
9682        fs::write(
9683            slot.join(format!(
9684                "{}0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0.tmp",
9685                RestrictiveHandoff::NAME_PREFIX
9686            )),
9687            JIT.as_bytes(),
9688        )
9689        .unwrap();
9690    }
9691
9692    /// A marker under `_work` of the kind a job leaves for the next one.
9693    fn retain_under_work(slot: &Path) -> PathBuf {
9694        let checkout = slot.join(DEFAULT_WORK_FOLDER).join("repo").join("target");
9695        fs::create_dir_all(&checkout).unwrap();
9696        let marker = checkout.join("build-output.bin");
9697        fs::write(&marker, RETAINED).unwrap();
9698        marker
9699    }
9700
9701    /// What a job leaves under `_work` for the next job to reuse.
9702    const RETAINED: &str = "a Git-ignored build output the next job reuses";
9703
9704    /// Every direct entry of a directory, sorted, as plain strings.
9705    fn entries_of(directory: &Path) -> Vec<String> {
9706        let mut names: Vec<String> = fs::read_dir(directory)
9707            .unwrap()
9708            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
9709            .collect();
9710        names.sort();
9711        names
9712    }
9713
9714    /// The one entry a cleaned slot is allowed to hold.
9715    fn only_the_job_workspace() -> Vec<String> {
9716        vec![DEFAULT_WORK_FOLDER.to_owned()]
9717    }
9718
9719    #[cfg(unix)]
9720    #[test]
9721    fn disposable_tree_removal_does_not_open_a_dotnet_diagnostic_fifo() {
9722        use std::sync::mpsc;
9723
9724        let temporary = tempfile::tempdir().unwrap();
9725        let tree = temporary.path().join("attempt");
9726        let diagnostic = tree.join("tmp/clr-debug-pipe-runner-in");
9727        fs::create_dir_all(diagnostic.parent().unwrap()).unwrap();
9728        assert!(
9729            std::process::Command::new("mkfifo")
9730                .arg(&diagnostic)
9731                .status()
9732                .unwrap()
9733                .success()
9734        );
9735
9736        let (finished, result) = mpsc::channel();
9737        std::thread::spawn(move || {
9738            let removed = remove_runtime_tree(&tree);
9739            let _ = finished.send(removed);
9740        });
9741
9742        result
9743            .recv_timeout(Duration::from_secs(2))
9744            .expect("runtime deletion must not wait for a FIFO peer")
9745            .unwrap();
9746        assert!(!diagnostic.exists());
9747    }
9748
9749    /// The junction WinINet leaves in a job's profile, reproduced: its own DACL
9750    /// denies `Everyone` the right to list it.
9751    #[cfg(windows)]
9752    #[test]
9753    fn disposable_tree_removal_unlinks_a_junction_nobody_may_list() {
9754        let temporary = tempfile::tempdir().unwrap();
9755        let tree = temporary.path().join("attempt");
9756        let cache = tree.join(r"tmp\home\AppData\Local\Microsoft\Windows\INetCache");
9757        let outside = temporary.path().join("outside");
9758        fs::create_dir_all(&cache).unwrap();
9759        fs::create_dir_all(&outside).unwrap();
9760        fs::write(outside.join("keep.txt"), b"not the attempt's").unwrap();
9761        fs::write(tree.join("tmp").join("job.log"), b"job output").unwrap();
9762        let junction = cache.join("Content.IE5");
9763        let created = std::process::Command::new("cmd")
9764            .arg("/C")
9765            .arg("mklink")
9766            .arg("/J")
9767            .arg(&junction)
9768            .arg(&outside)
9769            .output()
9770            .unwrap();
9771        assert!(created.status.success(), "{created:?}");
9772        // `/L` puts the entry on the junction itself, as WinINet does, rather
9773        // than on the directory it points at. `*S-1-1-0` is `Everyone` in every
9774        // display language.
9775        let denied = std::process::Command::new("icacls")
9776            .arg(&junction)
9777            .args(["/L", "/deny", "*S-1-1-0:(RD)"])
9778            .output()
9779            .unwrap();
9780        assert!(denied.status.success(), "{denied:?}");
9781
9782        // The control: without the fix the tree cannot be removed at all.
9783        let unfixed = remove_dir_all::remove_dir_all(&tree)
9784            .expect_err("the fixture no longer reproduces the WinINet junction");
9785        assert_eq!(unfixed.kind(), std::io::ErrorKind::PermissionDenied);
9786        assert!(junction.symlink_metadata().is_ok());
9787
9788        remove_runtime_tree(&tree).expect("a tree holding a deny-list junction is removed");
9789        assert!(!tree.exists(), "the attempt tree survived");
9790        assert_eq!(
9791            fs::read(outside.join("keep.txt")).unwrap(),
9792            b"not the attempt's",
9793            "removing the junction followed it into the directory it points at"
9794        );
9795    }
9796
9797    /// One slot entry that refuses to be removed, and the undo that lets the
9798    /// temporary directory be torn down afterwards.
9799    ///
9800    /// The two operating systems refuse for different reasons and there is no
9801    /// portable third. Windows will not open a file for deletion while a handle
9802    /// with share mode zero is held on it; Unix will not unlink from a directory
9803    /// the caller cannot write. Both are states a real machine reaches -- a
9804    /// scanner holding a file open, a job that left a directory read-only -- so
9805    /// the injection is a filesystem fact rather than a seam cut into the
9806    /// product for a test to pull.
9807    ///
9808    /// The Unix half is a permission, and permissions do not apply to `root`.
9809    /// [`Self::inject`] proves the block on a throwaway directory before
9810    /// claiming it, so a suite running as `root` says it could not inject rather
9811    /// than asserting nothing and passing.
9812    struct BlockedDeletion {
9813        directory: PathBuf,
9814        #[cfg(windows)]
9815        _handle: fs::File,
9816    }
9817
9818    impl BlockedDeletion {
9819        const HELD: &'static str = "held-open";
9820
9821        /// Fill `directory` with a file that cannot be removed, or answer `None`
9822        /// when this account cannot be stopped from removing anything.
9823        fn inject(directory: &Path) -> Option<Self> {
9824            #[cfg(unix)]
9825            if !Self::refusal_is_possible() {
9826                return None;
9827            }
9828            fs::create_dir_all(directory).unwrap();
9829            fs::write(
9830                directory.join(Self::HELD),
9831                b"a file the scrub cannot remove",
9832            )
9833            .unwrap();
9834            #[cfg(windows)]
9835            let handle = {
9836                use std::os::windows::fs::OpenOptionsExt;
9837
9838                fs::OpenOptions::new()
9839                    .read(true)
9840                    .share_mode(0)
9841                    .open(directory.join(Self::HELD))
9842                    .expect("the blocking handle opens")
9843            };
9844            #[cfg(unix)]
9845            Self::set_mode(directory, 0o555);
9846            Some(Self {
9847                directory: directory.to_path_buf(),
9848                #[cfg(windows)]
9849                _handle: handle,
9850            })
9851        }
9852
9853        fn release(self) {
9854            drop(self);
9855        }
9856
9857        #[cfg(unix)]
9858        fn refusal_is_possible() -> bool {
9859            let probe = tempfile::tempdir().unwrap();
9860            let directory = probe.path().join("probe");
9861            fs::create_dir(&directory).unwrap();
9862            fs::write(directory.join("file"), b"probe").unwrap();
9863            Self::set_mode(&directory, 0o555);
9864            let refused = fs::remove_dir_all(&directory).is_err();
9865            Self::set_mode(&directory, 0o755);
9866            refused
9867        }
9868
9869        #[cfg(unix)]
9870        fn set_mode(directory: &Path, mode: u32) {
9871            use std::os::unix::fs::PermissionsExt;
9872
9873            let mut permissions = fs::metadata(directory).unwrap().permissions();
9874            permissions.set_mode(mode);
9875            fs::set_permissions(directory, permissions).unwrap();
9876        }
9877    }
9878
9879    impl Drop for BlockedDeletion {
9880        fn drop(&mut self) {
9881            #[cfg(unix)]
9882            Self::set_mode(&self.directory, 0o755);
9883            #[cfg(not(unix))]
9884            let _ = &self.directory;
9885        }
9886    }
9887
9888    #[tokio::test]
9889    async fn two_sequential_jobs_keep_the_checkout_and_start_without_the_earlier_runner_state() {
9890        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9891            .with_persistent_workspace(1);
9892        harness.ready().await;
9893
9894        let first = harness.launch().await;
9895        let slot = harness.slot_path(1);
9896        assert_eq!(first.runtime_path(), slot);
9897        assert_eq!(
9898            read_runner_id(&slot),
9899            Some(73),
9900            "the attempt registered, so its identity is on disk"
9901        );
9902        let marker = retain_under_work(&slot);
9903        litter_the_slot(&slot);
9904
9905        harness.cleanup_retaining_work(first.id).await;
9906
9907        // The allowlist is exactly one entry, so this assertion is the security
9908        // property in full: what is retained, and that nothing else is.
9909        assert_eq!(entries_of(&slot), only_the_job_workspace());
9910        assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
9911        assert_eq!(
9912            read_runner_id(&slot),
9913            None,
9914            "the first attempt's registration identity is gone before the second starts"
9915        );
9916        assert_eq!(harness.attempt(first.id).state(), AttemptState::Cleaned);
9917        assert!(!harness.attempt(first.id).holds_slot_lease());
9918
9919        let second = harness.launch().await;
9920        assert_ne!(second.id, first.id);
9921        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(1)));
9922        assert_eq!(
9923            second.runtime_path(),
9924            slot,
9925            "the same slot, so the same retained `_work`"
9926        );
9927        assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
9928    }
9929
9930    #[tokio::test]
9931    async fn cleaning_a_persistent_slot_needs_no_policy_and_scans_no_directory_for_ownership() {
9932        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9933            .with_persistent_workspace(1);
9934        harness.ready().await;
9935        let attempt = harness.launch().await;
9936        let slot = harness.slot_path(1);
9937        let marker = retain_under_work(&slot);
9938        litter_the_slot(&slot);
9939        harness.conclude(attempt.id);
9940
9941        // A repository removed from the product between the attempt concluding
9942        // and the sweep reaching it. The journalled runtime path and slot are
9943        // the only facts left, and `04-security-recovery.md` requires them to be
9944        // enough: the alternative is scanning a root to work out which
9945        // directories were ours, which invariant 6 forbids.
9946        harness
9947            .store
9948            .remove_policy(harness.policy.id, harness.policy.revision())
9949            .unwrap();
9950        assert!(harness.store.policy(harness.policy.id).unwrap().is_none());
9951
9952        harness
9953            .launcher
9954            .clean(attempt.id)
9955            .await
9956            .expect("journal facts alone are enough to clean the slot");
9957
9958        assert_eq!(entries_of(&slot), only_the_job_workspace());
9959        assert!(marker.exists());
9960        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
9961    }
9962
9963    #[tokio::test]
9964    async fn an_injected_partial_deletion_quarantines_the_slot_across_a_restart() {
9965        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
9966            .with_persistent_workspace(2);
9967        harness.ready().await;
9968        let first = harness.launch().await;
9969        let slot = harness.slot_path(1);
9970        let marker = retain_under_work(&slot);
9971        litter_the_slot(&slot);
9972        harness.conclude(first.id);
9973
9974        let Some(block) = BlockedDeletion::inject(&slot.join("bin")) else {
9975            eprintln!(
9976                "skipped: this account cannot be refused a deletion, so no partial deletion can \
9977                 be injected"
9978            );
9979            return;
9980        };
9981
9982        let refusal = harness
9983            .launcher
9984            .clean(first.id)
9985            .await
9986            .expect_err("a deletion that failed may not report a cleaned slot");
9987        let rendered = refusal.reason.to_string();
9988        assert!(rendered.contains("could not be removed"), "{rendered}");
9989
9990        let held = harness.attempt(first.id);
9991        assert_eq!(held.state(), AttemptState::Failed, "still not cleaned");
9992        assert!(held.holds_slot_lease(), "so the slot is still leased");
9993        assert!(
9994            !held.state().counts_against_capacity(),
9995            "and a concluded attempt still costs the host no capacity"
9996        );
9997
9998        // The same journal and the same directories, under a launcher that
9999        // remembers nothing. Recovery must complete: a host that can launch
10000        // nothing at all because one slot is stuck is not what "does not count
10001        // as active host capacity" means.
10002        let restarted = harness.restart();
10003        restarted
10004            .recover_startup(std::slice::from_ref(&harness.policy))
10005            .await
10006            .expect("one quarantined slot does not stop the host recovering");
10007        assert_eq!(
10008            harness.attempt(first.id).state(),
10009            AttemptState::Failed,
10010            "the quarantine survived the restart"
10011        );
10012        assert!(
10013            harness
10014                .reconcile_events
10015                .events()
10016                .iter()
10017                .any(|event| matches!(
10018                    event,
10019                    LifecycleEvent::AttemptCleanFailed {
10020                        reason: "slot_entry_could_not_be_removed",
10021                        ..
10022                    }
10023                )),
10024            "the refusal is reported rather than retried in silence"
10025        );
10026
10027        // Capacity two, slot one quarantined: the next attempt goes to s2 and
10028        // never to the slot still holding runner state.
10029        let guard = harness.allocation_lock.acquire().await.unwrap();
10030        let second = restarted
10031            .launch(LaunchRequest {
10032                host: &harness.host,
10033                policy: &harness.policy,
10034                allocation_guard: &guard,
10035                lock_wait: Duration::ZERO,
10036            })
10037            .await
10038            .expect("the host can still launch");
10039        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
10040        drop(guard);
10041
10042        // And the same cleanup succeeds once the obstruction is gone, which is
10043        // what "retry through normal recovery" has to mean.
10044        block.release();
10045        restarted
10046            .clean(first.id)
10047            .await
10048            .expect("the retried cleanup completes");
10049        assert_eq!(entries_of(&slot), only_the_job_workspace());
10050        assert!(marker.exists());
10051        assert_eq!(harness.attempt(first.id).state(), AttemptState::Cleaned);
10052    }
10053
10054    /// The disposable half of the same injection, which had no test of its own.
10055    ///
10056    /// `scrub_workspace`'s ephemeral arm turns a failed `remove_dir_all` into
10057    /// `"attempt workspace could not be removed"`, and until now that branch was
10058    /// only reachable in theory: every injected-deletion test drove a persistent
10059    /// slot. The property is the same one and matters for the same reason --
10060    /// `04-security-recovery.md`'s "Cleanup partly fails and the slot is reused
10061    /// anyway" -- but the disposable guarantee is stronger, so a cleanup that
10062    /// reported success over a directory it had not removed would be the
10063    /// contamination gate failing silently rather than a slot being held.
10064    #[tokio::test]
10065    async fn an_injected_deletion_failure_leaves_a_disposable_attempt_uncleaned() {
10066        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
10067        harness.ready().await;
10068        let attempt = harness.launch().await;
10069        let runtime = attempt.runtime_path().to_path_buf();
10070        assert_eq!(attempt.workspace(), AttemptWorkspace::Ephemeral);
10071        harness.conclude(attempt.id);
10072
10073        let Some(block) = BlockedDeletion::inject(&runtime.join("held-open-subdirectory")) else {
10074            eprintln!(
10075                "skipped: this account cannot be refused a deletion, so no partial deletion can be injected"
10076            );
10077            return;
10078        };
10079
10080        let refusal = harness
10081            .launcher
10082            .clean(attempt.id)
10083            .await
10084            .expect_err("a deletion that failed may not report a removed workspace");
10085        let rendered = refusal.reason.to_string();
10086        assert!(
10087            rendered.contains("could not be removed"),
10088            "the refusal names what happened: {rendered}"
10089        );
10090        assert_ne!(
10091            harness.attempt(attempt.id).state(),
10092            AttemptState::Cleaned,
10093            "an attempt whose directory is still on disk is not cleaned"
10094        );
10095        assert!(
10096            runtime.is_dir(),
10097            "the directory the removal could not finish is still there, which is the fact the journal must keep agreeing with"
10098        );
10099
10100        let restarted = harness.restart();
10101        restarted
10102            .recover_startup(std::slice::from_ref(&harness.policy))
10103            .await
10104            .expect("one locked ephemeral workspace does not stop startup recovery");
10105        assert!(
10106            harness
10107                .reconcile_events
10108                .events()
10109                .iter()
10110                .any(|event| matches!(
10111                    event,
10112                    LifecycleEvent::AttemptCleanFailed {
10113                        attempt: failed_attempt,
10114                        reason: "ephemeral_workspace_could_not_be_removed",
10115                        ..
10116                    } if *failed_attempt == attempt.id
10117                )),
10118            "the deferred cleanup remains visible while the daemon keeps running"
10119        );
10120
10121        // And the ordinary retry -- the reconciler's next terminal sweep --
10122        // finishes it once the obstruction is gone.
10123        block.release();
10124        harness
10125            .launcher
10126            .clean(attempt.id)
10127            .await
10128            .expect("the retried cleanup completes");
10129        assert!(!runtime.exists(), "the whole attempt directory goes");
10130        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
10131    }
10132
10133    /// Supervision retries a workspace it cannot remove with per-attempt
10134    /// backoff, so a stuck workspace is reported once per delay rather than on
10135    /// every pass.
10136    #[tokio::test]
10137    async fn supervision_backs_off_a_workspace_it_cannot_remove() {
10138        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
10139        harness.ready().await;
10140        let attempt = harness.launch().await;
10141        let runtime = attempt.runtime_path().to_path_buf();
10142        harness.conclude(attempt.id);
10143        let Some(block) = BlockedDeletion::inject(&runtime.join("held-open-subdirectory")) else {
10144            eprintln!(
10145                "skipped: this account cannot be refused a deletion, so no partial deletion can be injected"
10146            );
10147            return;
10148        };
10149        let failures = || {
10150            harness
10151                .reconcile_events
10152                .events()
10153                .iter()
10154                .filter(|event| {
10155                    matches!(
10156                        event,
10157                        LifecycleEvent::AttemptCleanFailed { attempt: failed, .. }
10158                            if *failed == attempt.id
10159                    )
10160                })
10161                .count()
10162        };
10163        let supervise = async || {
10164            harness
10165                .launcher
10166                .supervise(&harness.policy)
10167                .await
10168                .expect("a stuck workspace does not fail supervision");
10169        };
10170
10171        supervise().await;
10172        assert_eq!(failures(), 1);
10173        supervise().await;
10174        assert_eq!(
10175            failures(),
10176            1,
10177            "the failed cleanup was retried on the very next pass"
10178        );
10179        harness.clock.advance_secs(31);
10180        supervise().await;
10181        assert_eq!(
10182            failures(),
10183            2,
10184            "the cleanup was not retried once its delay passed"
10185        );
10186
10187        block.release();
10188        harness.clock.advance_secs(61);
10189        supervise().await;
10190        assert!(
10191            !runtime.exists(),
10192            "the retry removes the workspace once it can"
10193        );
10194        assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
10195    }
10196
10197    #[tokio::test]
10198    async fn changing_a_repository_back_to_ephemeral_leaves_every_old_slot_untouched() {
10199        let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
10200            .with_persistent_workspace(1);
10201        harness.ready().await;
10202        let first = harness.launch().await;
10203        let slot = harness.slot_path(1);
10204        let marker = retain_under_work(&slot);
10205        harness.cleanup_retaining_work(first.id).await;
10206
10207        // Every attempt for this policy is cleaned, so the mutation is allowed
10208        // (`04-security-recovery.md`, "Recovery rules"). What it must not do is
10209        // move or delete anything the operator still owns.
10210        harness
10211            .policy
10212            .set_workspace_policy(WorkspacePolicy::Ephemeral)
10213            .unwrap();
10214
10215        let second = harness.launch().await;
10216        assert_eq!(second.workspace(), AttemptWorkspace::Ephemeral);
10217        assert_eq!(
10218            second.runtime_path().parent().unwrap(),
10219            harness.host_root(),
10220            "a disposable attempt is a child of the host root"
10221        );
10222        assert!(slot.is_dir(), "the old slot is left where it stands");
10223        assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
10224
10225        // And cleaning the disposable attempt removes its own directory whole
10226        // without reaching the retained slot beside it.
10227        harness.conclude(second.id);
10228        harness.launcher.clean(second.id).await.unwrap();
10229        assert!(!second.runtime_path().exists());
10230        assert!(marker.exists());
10231    }
10232
10233    #[tokio::test]
10234    async fn a_persistent_slot_is_scrubbed_only_after_the_process_is_signalled_and_gone() {
10235        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
10236            .with_persistent_workspace(1);
10237        harness.ready().await;
10238        let slot = harness.slot_path(1);
10239        fs::create_dir_all(&slot).unwrap();
10240        let marker = retain_under_work(&slot);
10241        litter_the_slot(&slot);
10242
10243        let id = AttemptId::new_random();
10244        let mut attempt = RunnerAttempt::allocate_in(
10245            id,
10246            harness.policy.id,
10247            &slot,
10248            AttemptWorkspace::persistent_slot(nz(1)),
10249            harness.clock.now(),
10250        );
10251        attempt.jit_received(harness.clock.now()).unwrap();
10252        attempt.started(4242, harness.clock.now()).unwrap();
10253        harness.store.record_attempt(&attempt).unwrap();
10254        harness.clock.advance_secs(11);
10255        harness.processes.set_alive(true);
10256        harness
10257            .github
10258            .observe(GithubRunnerObservation::NotRegistered);
10259
10260        harness.launcher.supervise(&harness.policy).await.unwrap();
10261
10262        // The identity and termination ordering `e3` established is unchanged by
10263        // the workspace kind: the intent is durable before the signal, and the
10264        // slot is scrubbed only once the process is gone.
10265        let actions = harness.processes.actions.lock().unwrap().clone();
10266        let intent = actions
10267            .iter()
10268            .position(|action| *action == "terminate_intent")
10269            .unwrap();
10270        let signal = actions
10271            .iter()
10272            .position(|action| *action == "terminate")
10273            .unwrap();
10274        assert!(intent < signal, "{actions:?}");
10275        assert!(!harness.processes.alive.load(Ordering::SeqCst));
10276
10277        let cleaned = harness.attempt(id);
10278        assert_eq!(cleaned.state(), AttemptState::Cleaned);
10279        assert!(matches!(
10280            cleaned.outcome(),
10281            Some(AttemptOutcome::Failed {
10282                reason: FailureReason::TerminatedAfterRegistrationTimeout
10283            })
10284        ));
10285        assert_eq!(entries_of(&slot), only_the_job_workspace());
10286        assert!(marker.exists());
10287    }
10288
10289    #[test]
10290    fn a_scrub_retains_one_real_work_directory_and_removes_every_other_entry() {
10291        let root = tempfile::tempdir().unwrap();
10292        let slot = root.path().join("s1");
10293        fs::create_dir(&slot).unwrap();
10294        let marker = retain_under_work(&slot);
10295        litter_the_slot(&slot);
10296        fs::write(slot.join("runner-package"), b"verified").unwrap();
10297
10298        scrub_slot_entries(&slot).expect("a slot of ordinary runner state scrubs");
10299        verify_slot_scrubbed(&slot).expect("and proves it afterwards");
10300
10301        assert_eq!(entries_of(&slot), only_the_job_workspace());
10302        assert!(marker.exists());
10303    }
10304
10305    #[test]
10306    fn a_residue_refusal_never_reports_the_under_count_as_the_fact() {
10307        let slot = Path::new("/runners/s1");
10308
10309        // The ordinary case: the listing counted, so the count is the fact and
10310        // the published names qualify it.
10311        let counted = residue_detail(slot, 2, &["`bin`".to_owned()]);
10312        assert!(counted.contains("2 entries other than"), "{counted}");
10313        assert!(counted.contains("including `bin`"), "{counted}");
10314        assert_eq!(
10315            residue_detail(slot, 1, &[]),
10316            format!(
10317                "1 entry other than `{DEFAULT_WORK_FOLDER}` survived cleanup of {}",
10318                slot.display()
10319            )
10320        );
10321
10322        // The race the second pass exists for: the listing saw nothing and the
10323        // filesystem answered otherwise. Saying "0 entries survived" here would
10324        // state the under-count as the fact and contradict the rest of the
10325        // sentence.
10326        let raced = residue_detail(slot, 0, &["`.credentials`".to_owned()]);
10327        assert!(!raced.contains('0'), "{raced}");
10328        assert!(raced.contains("reported nothing but"), "{raced}");
10329        assert!(raced.contains("`.credentials` survived cleanup"), "{raced}");
10330    }
10331
10332    #[test]
10333    fn verification_asks_the_filesystem_rather_than_the_listing_that_missed_an_entry() {
10334        let root = tempfile::tempdir().unwrap();
10335        let slot = root.path().join("s1");
10336        fs::create_dir(&slot).unwrap();
10337        fs::create_dir(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
10338        verify_slot_scrubbed(&slot).expect("only `_work` is a clean slot");
10339
10340        // Runner binaries, registration identity, process identity and this
10341        // agent's lifecycle marks, one at a time, so a scrub that skipped
10342        // exactly one is still caught.
10343        for survivor in ["bin", ".credentials", IDENTITY_FILE, RUNNER_ID_FILE] {
10344            fs::write(slot.join(survivor), b"left behind").unwrap();
10345            let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
10346            assert_eq!(quarantine.refusal, SlotRefusal::Residue);
10347            assert!(
10348                quarantine.detail.contains(&format!("`{survivor}`")),
10349                "{quarantine}"
10350            );
10351            fs::remove_file(slot.join(survivor)).unwrap();
10352        }
10353
10354        // A handoff is named by its published prefix, never by the UUID that
10355        // follows it, and never by the payload it holds.
10356        let handoff = slot.join(format!("{}whatever.tmp", RestrictiveHandoff::NAME_PREFIX));
10357        fs::write(&handoff, JIT.as_bytes()).unwrap();
10358        let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
10359        assert!(
10360            quarantine.detail.contains("an encoded JIT handoff"),
10361            "{quarantine}"
10362        );
10363        assert!(!quarantine.detail.contains(JIT), "{quarantine}");
10364        fs::remove_file(&handoff).unwrap();
10365
10366        // A name a workflow chose is counted and never echoed: a slot root is
10367        // writable by the job, so a file named after a secret would be published
10368        // by any message that repeated the listing.
10369        fs::write(slot.join("ghp_DO_NOT_LEAK"), b"named by the job").unwrap();
10370        let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
10371        assert!(
10372            quarantine.detail.contains("1 entry other than"),
10373            "{quarantine}"
10374        );
10375        assert!(
10376            !quarantine.detail.contains("ghp_DO_NOT_LEAK"),
10377            "{quarantine}"
10378        );
10379    }
10380
10381    #[test]
10382    fn a_slot_is_derived_from_the_journal_and_refused_when_it_disagrees() {
10383        let root = tempfile::tempdir().unwrap();
10384        let configured =
10385            LocalAbsolutePath::new(root.path().to_str().unwrap()).expect("a local absolute root");
10386        let slot = configured.as_path().join("s1");
10387        fs::create_dir(&slot).unwrap();
10388
10389        verify_journalled_slot(&slot, nz(1), Some(&configured))
10390            .expect("the journalled slot agrees");
10391        verify_journalled_slot(&slot, nz(1), None)
10392            .expect("and a policy that is gone removes a check, not the ability to clean");
10393
10394        // The journalled slot number is what names the directory. `s1` recorded
10395        // as slot two is corrupt state, not a slot to clean.
10396        assert_eq!(
10397            verify_journalled_slot(&slot, nz(2), None)
10398                .unwrap_err()
10399                .refusal,
10400            SlotRefusal::NotTheJournalledSlot
10401        );
10402        for stray in ["s1/nested", "not-a-slot", "s01"] {
10403            let path = configured.as_path().join(stray);
10404            assert_eq!(
10405                verify_journalled_slot(&path, nz(1), None)
10406                    .unwrap_err()
10407                    .refusal,
10408                SlotRefusal::NotTheJournalledSlot,
10409                "{}",
10410                path.display()
10411            );
10412        }
10413
10414        // A surviving policy that names a different root does not get to have
10415        // its disagreement resolved by deleting something.
10416        let elsewhere = tempfile::tempdir().unwrap();
10417        let other =
10418            LocalAbsolutePath::new(elsewhere.path().to_str().unwrap()).expect("a second root");
10419        assert_eq!(
10420            verify_journalled_slot(&slot, nz(1), Some(&other))
10421                .unwrap_err()
10422                .refusal,
10423            SlotRefusal::PolicyRootDisagrees
10424        );
10425    }
10426
10427    #[cfg(unix)]
10428    #[test]
10429    fn a_substituted_work_directory_quarantines_the_slot_and_deletes_nothing_outside_it() {
10430        // Windows needs a privilege to create a junction or a symlink, so the
10431        // substitution is made here; the rule is platform-independent because it
10432        // is `symlink_metadata`'s answer plus the reparse attribute.
10433        let root = tempfile::tempdir().unwrap();
10434        let outside = root.path().join("operator-data");
10435        fs::create_dir(&outside).unwrap();
10436        let sentinel = outside.join("do-not-delete.txt");
10437        fs::write(
10438            &sentinel,
10439            b"an operator's data, outside every approved root",
10440        )
10441        .unwrap();
10442
10443        let slot = root.path().join("s1");
10444        fs::create_dir(&slot).unwrap();
10445        fs::create_dir(slot.join("bin")).unwrap();
10446        std::os::unix::fs::symlink(&outside, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
10447
10448        let quarantine = scrub_slot_entries(&slot).unwrap_err();
10449        assert_eq!(quarantine.refusal, SlotRefusal::WorkNotADirectory);
10450        assert!(
10451            sentinel.exists(),
10452            "the deletion followed the link out of the slot"
10453        );
10454        assert!(outside.is_dir());
10455        assert!(
10456            slot.join(DEFAULT_WORK_FOLDER).symlink_metadata().is_ok(),
10457            "the substituted link is left for the operator, never unlinked as if it were ours"
10458        );
10459
10460        // A `_work` that is a plain file is the same refusal for the same
10461        // reason: it is not a job workspace, and this is not the code that
10462        // decides what to do about it.
10463        let file_work = root.path().join("s2");
10464        fs::create_dir(&file_work).unwrap();
10465        fs::write(file_work.join(DEFAULT_WORK_FOLDER), b"not a directory").unwrap();
10466        assert_eq!(
10467            scrub_slot_entries(&file_work).unwrap_err().refusal,
10468            SlotRefusal::WorkNotADirectory
10469        );
10470    }
10471
10472    #[cfg(unix)]
10473    #[test]
10474    fn a_slot_replaced_by_a_link_out_of_its_root_is_refused_before_anything_is_read() {
10475        let root = tempfile::tempdir().unwrap();
10476        let outside = root.path().join("operator-data");
10477        fs::create_dir(&outside).unwrap();
10478        let sentinel = outside.join("do-not-delete.txt");
10479        fs::write(
10480            &sentinel,
10481            b"an operator's data, outside every approved root",
10482        )
10483        .unwrap();
10484
10485        // The lexical half of containment passes -- the name is right and the
10486        // parent is right -- and canonical resolution is what catches it.
10487        let inside = root.path().join("inside");
10488        fs::create_dir(&inside).unwrap();
10489        let slot = inside.join("s1");
10490        std::os::unix::fs::symlink(&outside, &slot).unwrap();
10491
10492        assert_eq!(
10493            verify_journalled_slot(&slot, nz(1), None)
10494                .unwrap_err()
10495                .refusal,
10496            SlotRefusal::Containment
10497        );
10498        assert!(sentinel.exists());
10499        assert!(
10500            slot.symlink_metadata().is_ok(),
10501            "the link is left for the operator rather than removed as if it were ours"
10502        );
10503    }
10504
10505    /// The Windows half of the case above.
10506    ///
10507    /// Containment was proven only on Unix, and a symbolic link is the wrong
10508    /// instrument to prove it with on Windows: creating one needs a privilege an
10509    /// ordinary workflow does not have, so it is not the substitution an
10510    /// attacker would reach for. A **junction** needs none, which makes it both
10511    /// the realistic attack and the one this repository must refuse -- and
10512    /// `04-security-recovery.md` names it in the same breath as the symlink for
10513    /// exactly that reason.
10514    #[cfg(windows)]
10515    #[test]
10516    fn a_slot_root_replaced_by_a_junction_is_refused_before_anything_is_read() {
10517        let root = tempfile::tempdir().unwrap();
10518        let outside = root.path().join("operator-data");
10519        fs::create_dir(&outside).unwrap();
10520        let sentinel = outside.join("do-not-delete.txt");
10521        fs::write(
10522            &sentinel,
10523            b"an operator's data, outside every approved root",
10524        )
10525        .unwrap();
10526
10527        // The lexical half of containment passes -- `s1` under the root the
10528        // journal names -- and canonical resolution is what catches it.
10529        let inside = root.path().join("inside");
10530        fs::create_dir(&inside).unwrap();
10531        let slot = inside.join("s1");
10532        let Some(()) = plant_junction(&slot, &outside) else {
10533            eprintln!("skipped: this machine would not create a directory junction");
10534            return;
10535        };
10536
10537        assert_eq!(
10538            verify_journalled_slot(&slot, nz(1), None)
10539                .unwrap_err()
10540                .refusal,
10541            SlotRefusal::Containment
10542        );
10543        assert!(
10544            sentinel.exists(),
10545            "the refusal resolved the junction and reached the operator's data"
10546        );
10547        assert!(
10548            slot.symlink_metadata().is_ok(),
10549            "the junction is left for the operator rather than removed as if it were ours"
10550        );
10551    }
10552
10553    /// Plant a directory junction at `link` pointing at `target`.
10554    ///
10555    /// A junction is the Windows substitution this has to refuse, and unlike a
10556    /// symbolic link it needs no privilege — which is exactly why it is the one
10557    /// an unprivileged workflow would reach for. `mklink` is a `cmd` builtin, so
10558    /// there is no binary to find and nothing to install; `None` means this
10559    /// machine would not make one and the caller says so rather than asserting
10560    /// nothing.
10561    #[cfg(windows)]
10562    fn plant_junction(link: &Path, target: &Path) -> Option<()> {
10563        let made = std::process::Command::new("cmd")
10564            .arg("/C")
10565            .arg("mklink")
10566            .arg("/J")
10567            .arg(link)
10568            .arg(target)
10569            .output()
10570            .ok()?;
10571        (made.status.success() && link.symlink_metadata().is_ok()).then_some(())
10572    }
10573
10574    /// The dependency caches live beside attempts, under `<runner root>/_cache`,
10575    /// and jobs link into them (pnpm hard-links from its store; a workflow may
10576    /// symlink or junction a cache into its workspace). Removing an ephemeral
10577    /// attempt must take the links and never what they point at.
10578    #[test]
10579    fn removing_an_attempt_never_reaches_into_the_dependency_caches_it_linked() {
10580        let root = tempfile::tempdir().unwrap();
10581        let cache = root.path().join("_cache").join("o").join("r").join("npm");
10582        fs::create_dir_all(&cache).unwrap();
10583        let cached = cache.join("package.tgz");
10584        fs::write(&cached, b"kept between jobs").unwrap();
10585        let attempt = root.path().join("0123456789abcdef");
10586        let work = attempt.join("_work").join("repo");
10587        fs::create_dir_all(&work).unwrap();
10588        fs::hard_link(&cached, work.join("hard-linked.tgz")).unwrap();
10589        #[cfg(unix)]
10590        std::os::unix::fs::symlink(&cache, work.join("linked-cache")).unwrap();
10591        #[cfg(windows)]
10592        if plant_junction(&work.join("linked-cache"), &cache).is_none() {
10593            eprintln!("this machine would not create a junction; the hard link is still checked");
10594        }
10595
10596        remove_runtime_tree(&attempt).unwrap();
10597        assert!(!attempt.exists());
10598        assert_eq!(fs::read(&cached).unwrap(), b"kept between jobs");
10599    }
10600
10601    #[cfg(windows)]
10602    #[test]
10603    fn a_work_directory_replaced_by_a_junction_fails_closed_and_deletes_nothing_beyond_it() {
10604        let root = tempfile::tempdir().unwrap();
10605        let outside = root.path().join("operator-data");
10606        fs::create_dir(&outside).unwrap();
10607        let sentinel = outside.join("do-not-delete.txt");
10608        fs::write(
10609            &sentinel,
10610            b"an operator's data, outside every approved root",
10611        )
10612        .unwrap();
10613
10614        let slot = root.path().join("s1");
10615        fs::create_dir(&slot).unwrap();
10616        fs::create_dir(slot.join("bin")).unwrap();
10617        let Some(()) = plant_junction(&slot.join(DEFAULT_WORK_FOLDER), &outside) else {
10618            eprintln!("skipped: this machine would not create a directory junction");
10619            return;
10620        };
10621
10622        // The reparse point is what `is_link_like` answers on, so a junction is
10623        // refused for the same reason a symbolic link is and neither is
10624        // descended into.
10625        let work = fs::symlink_metadata(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
10626        assert!(is_link_like(&work), "a junction is a reparse point");
10627        let quarantine = scrub_slot_entries(&slot).unwrap_err();
10628        assert_eq!(quarantine.refusal, SlotRefusal::WorkNotADirectory);
10629        assert!(
10630            sentinel.exists(),
10631            "the deletion followed the junction out of the slot"
10632        );
10633        assert!(outside.is_dir());
10634
10635        // A junction standing where an ordinary entry was is unlinked rather
10636        // than followed, so the removal still cannot reach through it.
10637        let elsewhere = root.path().join("s2");
10638        fs::create_dir(&elsewhere).unwrap();
10639        fs::create_dir(elsewhere.join(DEFAULT_WORK_FOLDER)).unwrap();
10640        if plant_junction(&elsewhere.join("externals"), &outside).is_some() {
10641            scrub_slot_entries(&elsewhere).expect("an ordinary entry is removed, junction or not");
10642            verify_slot_scrubbed(&elsewhere).expect("and the slot verifies");
10643            assert!(sentinel.exists(), "the junction was followed, not unlinked");
10644            assert_eq!(entries_of(&elsewhere), only_the_job_workspace());
10645        }
10646    }
10647
10648    #[cfg(unix)]
10649    #[tokio::test]
10650    async fn a_substituted_work_directory_leaves_the_attempt_uncleaned_and_still_leased() {
10651        let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
10652            .with_persistent_workspace(2);
10653        harness.ready().await;
10654        let first = harness.launch().await;
10655        let slot = harness.slot_path(1);
10656        harness.conclude(first.id);
10657
10658        let outside = harness._root.path().join("operator-data");
10659        fs::create_dir_all(&outside).unwrap();
10660        let sentinel = outside.join("do-not-delete.txt");
10661        fs::write(&sentinel, b"outside every approved root").unwrap();
10662        std::os::unix::fs::symlink(&outside, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
10663
10664        harness
10665            .launcher
10666            .clean(first.id)
10667            .await
10668            .expect_err("a slot whose `_work` was substituted is quarantined");
10669        assert!(sentinel.exists());
10670
10671        let held = harness.attempt(first.id);
10672        assert_eq!(held.state(), AttemptState::Failed);
10673        assert!(held.holds_slot_lease());
10674
10675        // The quarantined slot is not silently chosen again.
10676        let second = harness.launch().await;
10677        assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
10678    }
10679
10680    #[test]
10681    fn a_slot_that_is_a_file_is_refused_and_a_slot_that_is_gone_is_not() {
10682        let root = tempfile::tempdir().unwrap();
10683        let occupied = root.path().join("s1");
10684        fs::write(&occupied, b"an operator's file").unwrap();
10685        // The journal check passes -- it is the right name under the right root
10686        // -- and the shape check is what refuses.
10687        verify_journalled_slot(&occupied, nz(1), None).expect("the path is the journalled slot");
10688        assert_eq!(
10689            slot_is_present(&occupied).unwrap_err().refusal,
10690            SlotRefusal::SlotNotADirectory
10691        );
10692        assert_eq!(fs::read_to_string(&occupied).unwrap(), "an operator's file");
10693
10694        // A directory that is simply not there leaves nothing to remove and
10695        // nothing to prove absent, so it is not a refusal.
10696        assert!(!slot_is_present(&root.path().join("s2")).unwrap());
10697        let present = root.path().join("s3");
10698        fs::create_dir(&present).unwrap();
10699        assert!(slot_is_present(&present).unwrap());
10700    }
10701
10702    #[test]
10703    fn cleanup_dispatches_on_the_journalled_kind_and_not_on_what_the_directory_holds() {
10704        let root = tempfile::tempdir().unwrap();
10705
10706        // A disposable directory that happens to contain a `_work` still goes
10707        // whole: the workspace kind is immutable so that the shape of a
10708        // directory a workflow can write to cannot choose its own algorithm.
10709        let disposable = root.path().join("abcdef012345");
10710        fs::create_dir_all(disposable.join(DEFAULT_WORK_FOLDER).join("repo")).unwrap();
10711        let ephemeral = RunnerAttempt::allocate(
10712            AttemptId::new_random(),
10713            fixtures::POLICY_ID,
10714            &disposable,
10715            fixtures::created_at(),
10716        );
10717        remove_materialized_package(&ephemeral).unwrap();
10718        assert!(!disposable.exists());
10719
10720        // And a slot keeps its `_work` with the same contents beneath it.
10721        let slot = root.path().join("s1");
10722        fs::create_dir_all(slot.join(DEFAULT_WORK_FOLDER).join("repo")).unwrap();
10723        fs::create_dir_all(slot.join("bin")).unwrap();
10724        let persistent = RunnerAttempt::allocate_in(
10725            AttemptId::new_random(),
10726            fixtures::POLICY_ID,
10727            &slot,
10728            AttemptWorkspace::persistent_slot(nz(1)),
10729            fixtures::created_at(),
10730        );
10731        remove_materialized_package(&persistent).unwrap();
10732        assert_eq!(entries_of(&slot), only_the_job_workspace());
10733        assert!(slot.join(DEFAULT_WORK_FOLDER).join("repo").is_dir());
10734    }
10735
10736    #[test]
10737    fn every_slot_refusal_names_a_distinct_event_class_and_keeps_the_lease() {
10738        let refusals = [
10739            SlotRefusal::NotTheJournalledSlot,
10740            SlotRefusal::PolicyRootDisagrees,
10741            SlotRefusal::Containment,
10742            SlotRefusal::SlotNotADirectory,
10743            SlotRefusal::Enumeration,
10744            SlotRefusal::WorkNotADirectory,
10745            SlotRefusal::Deletion,
10746            SlotRefusal::Residue,
10747        ];
10748        let classes: BTreeSet<&str> = refusals.iter().map(|refusal| refusal.class()).collect();
10749        assert_eq!(
10750            classes.len(),
10751            refusals.len(),
10752            "an event class shared by two refusals tells an operator less than it appears to"
10753        );
10754        for refusal in refusals {
10755            // The event field is a closed vocabulary, so it has to look like
10756            // one: `d1`'s sink allows the name verbatim.
10757            assert!(
10758                refusal
10759                    .class()
10760                    .chars()
10761                    .all(|c| c.is_ascii_lowercase() || c == '_'),
10762                "{}",
10763                refusal.class()
10764            );
10765            assert!(
10766                refusal.remediation().contains("slot lease"),
10767                "every refusal has to say the lease is still held: {}",
10768                refusal.class()
10769            );
10770        }
10771    }
10772
10773    #[test]
10774    fn copy_package_tree_copies_files_and_preserves_paths_with_spaces() {
10775        let root = tempfile::tempdir().unwrap();
10776        let source = root.path().join("source with spaces");
10777        let dest = root.path().join("dest with spaces");
10778
10779        fs::create_dir_all(&source).unwrap();
10780        fs::write(source.join("file1.txt"), b"hello").unwrap();
10781
10782        let nested = source.join("nested dir");
10783        fs::create_dir_all(&nested).unwrap();
10784        fs::write(nested.join("file2.txt"), b"world").unwrap();
10785
10786        // This is not a top-level `_work`, so it should be allowed
10787        let nested_work = nested.join(DEFAULT_WORK_FOLDER);
10788        fs::create_dir_all(&nested_work).unwrap();
10789        fs::write(nested_work.join("allowed.txt"), b"allowed").unwrap();
10790
10791        copy_package_tree(&source, &dest, &TrustedTrees::default()).unwrap();
10792
10793        assert_eq!(fs::read_to_string(dest.join("file1.txt")).unwrap(), "hello");
10794        assert_eq!(
10795            fs::read_to_string(dest.join("nested dir").join("file2.txt")).unwrap(),
10796            "world"
10797        );
10798        assert_eq!(
10799            fs::read_to_string(
10800                dest.join("nested dir")
10801                    .join(DEFAULT_WORK_FOLDER)
10802                    .join("allowed.txt")
10803            )
10804            .unwrap(),
10805            "allowed"
10806        );
10807    }
10808
10809    #[test]
10810    fn every_field_name_the_attempt_sink_emits_is_allowed() {
10811        use runner_manager_platform::logging::is_field_allowed;
10812
10813        // Kept beside the sink rather than derived from it, as in `reconcile`.
10814        for field in [
10815            "event",
10816            "attempt_id",
10817            "reason",
10818            "retry_in_ms",
10819            "duration_ms",
10820            "lock_wait_ms",
10821            "materialize_ms",
10822            "register_ms",
10823            "spawn_ms",
10824        ] {
10825            assert!(
10826                is_field_allowed(field),
10827                "`{field}` would be logged as `[redacted]`"
10828            );
10829        }
10830    }
10831
10832    #[cfg(unix)]
10833    fn package_entry(root: &Path, version: &str, manifest: &str) -> PathBuf {
10834        let entry = root.join("packages").join(version);
10835        fs::create_dir_all(entry.join("bin")).unwrap();
10836        fs::write(entry.join(crate::package::MANIFEST_FILE), manifest).unwrap();
10837        fs::write(entry.join("bin").join("Runner.Listener"), version).unwrap();
10838        entry
10839    }
10840
10841    /// The seed's binary's inode: a rebuilt seed holds a new file.
10842    #[cfg(unix)]
10843    fn listener_inode(seed: &Path) -> u64 {
10844        use std::os::unix::fs::MetadataExt as _;
10845        fs::metadata(seed.join("bin").join("Runner.Listener"))
10846            .unwrap()
10847            .ino()
10848    }
10849
10850    #[cfg(unix)]
10851    #[test]
10852    fn a_package_seed_is_built_once_and_reused_while_untouched() {
10853        let root = tempfile::tempdir().unwrap();
10854        let source = package_entry(root.path(), "2.336.0", "{\"digest\":\"a\"}");
10855        let seeds = root.path().join("runners").join(PACKAGE_SEED_DIR);
10856        let trusted = TrustedTrees::default();
10857
10858        let seed = refresh_package_seed(&source, &seeds, &trusted).unwrap();
10859        assert_eq!(seed, seeds.join("2.336.0"));
10860        assert_eq!(
10861            fs::read_to_string(seed.join("bin").join("Runner.Listener")).unwrap(),
10862            "2.336.0"
10863        );
10864
10865        let built = listener_inode(&seed);
10866        assert_eq!(
10867            refresh_package_seed(&source, &seeds, &trusted).unwrap(),
10868            seed
10869        );
10870        assert_eq!(listener_inode(&seed), built, "an untouched seed is reused");
10871    }
10872
10873    #[cfg(unix)]
10874    #[test]
10875    fn a_tampered_or_unrecorded_seed_is_rebuilt() {
10876        let root = tempfile::tempdir().unwrap();
10877        let source = package_entry(root.path(), "2.336.0", "{\"digest\":\"a\"}");
10878        let seeds = root.path().join("runners").join(PACKAGE_SEED_DIR);
10879        let trusted = TrustedTrees::default();
10880        let seed = refresh_package_seed(&source, &seeds, &trusted).unwrap();
10881
10882        // A job rewrites the binary in place and leaves the manifest alone.
10883        fs::write(seed.join("bin").join("Runner.Listener"), b"planted").unwrap();
10884        refresh_package_seed(&source, &seeds, &trusted).unwrap();
10885        assert_eq!(
10886            fs::read_to_string(seed.join("bin").join("Runner.Listener")).unwrap(),
10887            "2.336.0",
10888            "a seed whose print moved is rebuilt from the cache entry"
10889        );
10890
10891        // A restarted daemon has no print of a seed it did not build.
10892        // Keep the old inode allocated until the replacement is complete;
10893        // otherwise the filesystem may immediately reuse its number.
10894        let old_listener = fs::File::open(seed.join("bin").join("Runner.Listener")).unwrap();
10895        let built = listener_inode(&seed);
10896        refresh_package_seed(&source, &seeds, &TrustedTrees::default()).unwrap();
10897        assert_ne!(
10898            listener_inode(&seed),
10899            built,
10900            "an unrecorded seed is rebuilt"
10901        );
10902        drop(old_listener);
10903    }
10904
10905    #[cfg(unix)]
10906    #[test]
10907    fn a_package_seed_is_rebuilt_for_a_new_entry_and_drops_every_other() {
10908        let root = tempfile::tempdir().unwrap();
10909        let seeds = root.path().join("runners").join(PACKAGE_SEED_DIR);
10910        let trusted = TrustedTrees::default();
10911        let old = package_entry(root.path(), "2.335.0", "{\"digest\":\"old\"}");
10912        refresh_package_seed(&old, &seeds, &trusted).unwrap();
10913        fs::create_dir_all(seeds.join(".staging-interrupted")).unwrap();
10914        fs::write(seeds.join("stray"), b"").unwrap();
10915
10916        let new = package_entry(root.path(), "2.336.0", "{\"digest\":\"new\"}");
10917        let seed = refresh_package_seed(&new, &seeds, &trusted).unwrap();
10918
10919        let mut left: Vec<_> = fs::read_dir(&seeds)
10920            .unwrap()
10921            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
10922            .collect();
10923        left.sort();
10924        assert_eq!(left, ["2.336.0"]);
10925
10926        // A reinstalled entry of the same version has a different manifest.
10927        fs::write(
10928            new.join(crate::package::MANIFEST_FILE),
10929            "{\"digest\":\"again\"}",
10930        )
10931        .unwrap();
10932        refresh_package_seed(&new, &seeds, &trusted).unwrap();
10933        assert_eq!(
10934            fs::read_to_string(seed.join(crate::package::MANIFEST_FILE)).unwrap(),
10935            "{\"digest\":\"again\"}",
10936            "a stale seed is rebuilt from the changed entry"
10937        );
10938    }
10939
10940    #[cfg(unix)]
10941    #[test]
10942    fn a_package_on_the_runtime_volume_is_its_own_seed() {
10943        let root = tempfile::tempdir().unwrap();
10944        let source = package_entry(root.path(), "2.336.0", "{}");
10945        let runtime = root.path().join("runners").join("attempt");
10946        fs::create_dir_all(&runtime).unwrap();
10947
10948        let trusted = TrustedTrees::default();
10949        assert_eq!(package_seed(&source, &runtime, &trusted).unwrap(), source);
10950        copy_package_tree(&source, &runtime, &trusted).unwrap();
10951        assert!(runtime.join("bin").join("Runner.Listener").exists());
10952        assert!(!root.path().join("runners").join(PACKAGE_SEED_DIR).exists());
10953    }
10954
10955    #[test]
10956    fn copy_package_tree_refuses_top_level_work_folder() {
10957        let root = tempfile::tempdir().unwrap();
10958        let source = root.path().join("source");
10959        let dest = root.path().join("dest");
10960
10961        fs::create_dir_all(&source).unwrap();
10962        fs::write(source.join("file1.txt"), b"hello").unwrap();
10963
10964        // Top-level `_work` should be refused
10965        let top_work = source.join(DEFAULT_WORK_FOLDER);
10966        fs::create_dir_all(&top_work).unwrap();
10967
10968        let err = copy_package_tree(&source, &dest, &TrustedTrees::default()).unwrap_err();
10969        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
10970    }
10971}