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