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 => remove_runtime_tree(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
722fn remove_runtime_tree(path: &Path) -> std::io::Result<()> {
730 #[cfg(windows)]
731 {
732 remove_dir_all::remove_dir_all(path)
733 }
734 #[cfg(not(windows))]
735 {
736 fs::remove_dir_all(path)
737 }
738}
739
740#[derive(Debug, Clone, Copy, PartialEq, Eq)]
755enum SlotRefusal {
756 NotTheJournalledSlot,
758 PolicyRootDisagrees,
760 Containment,
762 SlotNotADirectory,
764 Enumeration,
766 WorkNotADirectory,
768 Deletion,
770 Residue,
772}
773
774impl SlotRefusal {
775 const fn class(self) -> &'static str {
777 match self {
778 Self::NotTheJournalledSlot => "slot_path_is_not_the_journalled_slot",
779 Self::PolicyRootDisagrees => "slot_root_disagrees_with_policy",
780 Self::Containment => "slot_escapes_its_root",
781 Self::SlotNotADirectory => "slot_is_not_a_directory",
782 Self::Enumeration => "slot_could_not_be_enumerated",
783 Self::WorkNotADirectory => "retained_work_is_not_a_directory",
784 Self::Deletion => "slot_entry_could_not_be_removed",
785 Self::Residue => "slot_still_holds_runner_state",
786 }
787 }
788
789 const fn remediation(self) -> &'static str {
791 match self {
792 Self::NotTheJournalledSlot | Self::PolicyRootDisagrees | Self::Containment => {
793 "the attempt keeps its slot lease and nothing was removed; correct the \
794 repository's persistent workspace path, or remove the slot directory by hand \
795 once you have confirmed what is in it"
796 }
797 Self::SlotNotADirectory | Self::WorkNotADirectory => {
798 "the attempt keeps its slot lease and nothing was removed; a job replaced the \
799 slot or its `_work` with a link, so inspect it before deleting anything and \
800 treat the retained workspace as untrusted"
801 }
802 Self::Enumeration | Self::Deletion | Self::Residue => {
803 "the attempt keeps its slot lease and will be cleaned again on the next pass; \
804 release whatever is holding the files open, or remove the slot's contents by \
805 hand leaving only `_work`"
806 }
807 }
808 }
809}
810
811#[derive(Debug, Clone, PartialEq, Eq)]
818struct SlotQuarantine {
819 refusal: SlotRefusal,
820 detail: String,
821}
822
823impl SlotQuarantine {
824 fn new(refusal: SlotRefusal, detail: impl Into<String>) -> Self {
825 Self {
826 refusal,
827 detail: detail.into(),
828 }
829 }
830}
831
832impl fmt::Display for SlotQuarantine {
833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834 write!(f, "{}; {}", self.detail, self.refusal.remediation())
835 }
836}
837
838fn verify_journalled_slot(
852 runtime: &Path,
853 slot: NonZeroU16,
854 configured: Option<&LocalAbsolutePath>,
855) -> Result<(), SlotQuarantine> {
856 let mislaid = || {
857 SlotQuarantine::new(
858 SlotRefusal::NotTheJournalledSlot,
859 format!(
860 "the journalled runtime {} is not the slot s{slot} this attempt was allocated as",
861 runtime.display()
862 ),
863 )
864 };
865 let local = |path: &Path| {
866 path.to_str()
867 .and_then(|raw| LocalAbsolutePath::new(raw).ok())
868 .ok_or_else(mislaid)
869 };
870
871 let runtime_path = local(runtime)?;
872 let root = local(runtime.parent().ok_or_else(mislaid)?)?;
873 let name = AttemptWorkspace::persistent_slot(slot)
880 .slot_directory_name()
881 .expect("a persistent workspace names its slot directory");
882 let derived = runner_root::derive_child(&root, &name).map_err(|_| mislaid())?;
883 if derived != runtime_path {
884 return Err(mislaid());
885 }
886 if let Some(configured) = configured
887 && configured != &root
888 {
889 return Err(SlotQuarantine::new(
890 SlotRefusal::PolicyRootDisagrees,
891 format!(
892 "the journalled slot {} is not under the repository's configured persistent root \
893 {}",
894 runtime.display(),
895 configured.as_str()
896 ),
897 ));
898 }
899 runner_root::verify_containment(&root, &derived).map_err(|source| {
902 SlotQuarantine::new(
903 SlotRefusal::Containment,
904 format!("the journalled slot is not inside the root it was allocated from: {source}"),
905 )
906 })
907}
908
909fn slot_is_present(slot: &Path) -> Result<bool, SlotQuarantine> {
920 match fs::symlink_metadata(slot) {
921 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
922 Err(source) => Err(SlotQuarantine::new(
923 SlotRefusal::SlotNotADirectory,
924 format!(
925 "the slot {} could not be inspected: {:?}",
926 slot.display(),
927 source.kind()
928 ),
929 )),
930 Ok(metadata) if !metadata.is_dir() || is_link_like(&metadata) => Err(SlotQuarantine::new(
931 SlotRefusal::SlotNotADirectory,
932 format!(
933 "the slot {} is a link or a file rather than a real directory",
934 slot.display()
935 ),
936 )),
937 Ok(_) => Ok(true),
938 }
939}
940
941fn scrub_slot_entries(slot: &Path) -> Result<(), SlotQuarantine> {
956 let unreadable = |source: std::io::Error| {
957 SlotQuarantine::new(
958 SlotRefusal::Enumeration,
959 format!(
960 "the entries of {} could not be listed: {:?}",
961 slot.display(),
962 source.kind()
963 ),
964 )
965 };
966 for entry in fs::read_dir(slot).map_err(unreadable)? {
967 let name = entry.map_err(unreadable)?.file_name();
968 let path = slot.join(&name);
969 let Some(metadata) = listed_entry_metadata(&path).map_err(unreadable)? else {
972 continue;
973 };
974 if is_work_folder(&name) {
975 if is_retainable_work_folder(&name, &metadata) {
976 continue;
977 }
978 return Err(SlotQuarantine::new(
979 SlotRefusal::WorkNotADirectory,
980 format!(
981 "the retained `{DEFAULT_WORK_FOLDER}` in {} is a link or a file rather than a \
982 real directory",
983 slot.display()
984 ),
985 ));
986 }
987 remove_slot_entry(&path, &metadata).map_err(|source| {
988 SlotQuarantine::new(
989 SlotRefusal::Deletion,
990 format!(
991 "an entry of {} could not be removed: {:?}",
992 slot.display(),
993 source.kind()
994 ),
995 )
996 })?;
997 }
998 Ok(())
999}
1000
1001fn listed_entry_metadata(path: &Path) -> std::io::Result<Option<fs::Metadata>> {
1007 match fs::symlink_metadata(path) {
1008 Ok(metadata) => Ok(Some(metadata)),
1009 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
1010 Err(source) => Err(source),
1011 }
1012}
1013
1014fn remove_slot_entry(path: &Path, metadata: &fs::Metadata) -> std::io::Result<()> {
1019 let removed = if is_link_like(metadata) {
1020 fs::remove_file(path).or_else(|_| fs::remove_dir(path))
1023 } else if metadata.is_dir() {
1024 remove_runtime_tree(path)
1025 } else {
1026 fs::remove_file(path)
1027 };
1028 match removed {
1029 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1030 other => other,
1031 }
1032}
1033
1034fn verify_slot_scrubbed(slot: &Path) -> Result<(), SlotQuarantine> {
1051 let unreadable = |source: std::io::Error| {
1052 SlotQuarantine::new(
1053 SlotRefusal::Enumeration,
1054 format!(
1055 "the entries of {} could not be listed to verify the scrub: {:?}",
1056 slot.display(),
1057 source.kind()
1058 ),
1059 )
1060 };
1061 let mut residue = 0_usize;
1062 let mut named: Vec<String> = Vec::new();
1063 for entry in fs::read_dir(slot).map_err(unreadable)? {
1064 let name = entry.map_err(unreadable)?.file_name();
1065 let Some(metadata) = listed_entry_metadata(&slot.join(&name)).map_err(unreadable)? else {
1069 continue;
1070 };
1071 if is_retainable_work_folder(&name, &metadata) {
1072 continue;
1073 }
1074 residue = residue.saturating_add(1);
1075 if name
1076 .to_string_lossy()
1077 .starts_with(RestrictiveHandoff::NAME_PREFIX)
1078 {
1079 named.push("an encoded JIT handoff".to_owned());
1080 }
1081 }
1082 named.extend(
1083 SENSITIVE_SLOT_ENTRIES
1084 .iter()
1085 .filter(|entry| fs::symlink_metadata(slot.join(entry)).is_ok())
1086 .map(|entry| format!("`{entry}`")),
1087 );
1088 if residue == 0 && named.is_empty() {
1089 return Ok(());
1090 }
1091 named.sort_unstable();
1092 named.dedup();
1093 Err(SlotQuarantine::new(
1094 SlotRefusal::Residue,
1095 residue_detail(slot, residue, &named),
1096 ))
1097}
1098
1099fn residue_detail(slot: &Path, residue: usize, named: &[String]) -> String {
1109 if residue == 0 {
1110 format!(
1114 "the listing of {} reported nothing but `{DEFAULT_WORK_FOLDER}`, yet {} survived \
1115 cleanup",
1116 slot.display(),
1117 named.join(", ")
1118 )
1119 } else {
1120 format!(
1121 "{residue} entr{} other than `{DEFAULT_WORK_FOLDER}` survived cleanup of {}{}",
1122 if residue == 1 { "y" } else { "ies" },
1123 slot.display(),
1124 if named.is_empty() {
1125 String::new()
1126 } else {
1127 format!(", including {}", named.join(", "))
1128 }
1129 )
1130 }
1131}
1132
1133fn replacement_operation(outcome: &AttemptOutcome) -> Option<&'static str> {
1134 match outcome {
1135 AttemptOutcome::Failed {
1136 reason: FailureReason::JitExpired,
1137 } => Some("jit_expired_replacement"),
1138 AttemptOutcome::Failed {
1139 reason: FailureReason::ProcessExitedUnexpectedly,
1140 } => Some("exit_before_acceptance_replacement"),
1141 _ => None,
1142 }
1143}
1144
1145fn copy_package_tree(source: &Path, destination: &Path) -> std::io::Result<()> {
1160 if source.join(DEFAULT_WORK_FOLDER).exists() {
1161 return Err(std::io::Error::new(
1162 std::io::ErrorKind::InvalidData,
1163 "a cached runner package contains a _work folder, which means it was used \
1164 to run a job before it was archived; the cache must only contain clean \
1165 extracts to prevent data leakage",
1166 ));
1167 }
1168
1169 #[cfg(unix)]
1170 {
1171 let status = std::process::Command::new("cp")
1172 .arg("-a")
1173 .arg(format!("{}/.", source.display()))
1174 .arg(destination)
1175 .status()?;
1176 if status.success() {
1177 Ok(())
1178 } else {
1179 Err(std::io::Error::other("cp failed"))
1180 }
1181 }
1182 #[cfg(not(unix))]
1183 copy_package_entries(source, destination, true)
1184}
1185
1186#[cfg(not(unix))]
1187fn copy_package_entries(source: &Path, destination: &Path, top_level: bool) -> std::io::Result<()> {
1188 fs::create_dir_all(destination)?;
1189 for entry in fs::read_dir(source)? {
1190 let entry = entry?;
1191 if top_level && is_work_folder(&entry.file_name()) {
1192 return Err(std::io::Error::new(
1193 std::io::ErrorKind::InvalidData,
1194 format!(
1195 "the runner package holds a top-level `{DEFAULT_WORK_FOLDER}`; copying \
1196 it would overwrite the job workspace a persistent slot retains"
1197 ),
1198 ));
1199 }
1200 let target = destination.join(entry.file_name());
1201 if entry.file_type()?.is_dir() {
1202 copy_package_entries(&entry.path(), &target, false)?;
1203 } else {
1204 fs::copy(entry.path(), target)?;
1205 }
1206 }
1207 Ok(())
1208}
1209
1210#[derive(Debug, Clone, PartialEq, Eq)]
1213pub struct ProcessStartFailure {
1214 pub reason: FailureReason,
1215 pub retryable: bool,
1218 pub live_pid: Option<u32>,
1221}
1222
1223impl ProcessStartFailure {
1224 fn before_spawn(reason: FailureReason) -> Self {
1225 Self {
1226 reason,
1227 retryable: true,
1228 live_pid: None,
1229 }
1230 }
1231
1232 fn after_spawn_stopped() -> Self {
1233 Self {
1234 reason: FailureReason::ProcessStartFailed,
1235 retryable: false,
1236 live_pid: None,
1237 }
1238 }
1239
1240 fn after_spawn_live(pid: u32) -> Self {
1241 Self::after_spawn_live_with_reason(pid, FailureReason::ProcessStartFailed)
1242 }
1243
1244 fn after_spawn_live_with_reason(pid: u32, reason: FailureReason) -> Self {
1245 Self {
1246 reason,
1247 retryable: false,
1248 live_pid: Some(pid),
1249 }
1250 }
1251}
1252
1253pub trait ProcessSupervisor: fmt::Debug + Send + Sync {
1254 fn spawn(
1255 &self,
1256 attempt: &RunnerAttempt,
1257 config: &EncodedJitConfig,
1258 ) -> Result<u32, ProcessStartFailure>;
1259 fn is_alive(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason>;
1260 fn recovered_pid(&self, attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason>;
1263 fn completed_successfully(&self, attempt: &RunnerAttempt) -> bool;
1266 fn record_terminate_intent(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason>;
1267 fn has_terminate_intent(&self, attempt: &RunnerAttempt) -> bool;
1268 fn terminate(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason>;
1269}
1270
1271#[derive(Debug, Default)]
1274pub struct NativeProcesses {
1275 children: Mutex<BTreeMap<AttemptId, ChildProcess>>,
1276 successful_exits: Mutex<BTreeMap<AttemptId, bool>>,
1277 #[cfg(test)]
1278 post_spawn_faults: Mutex<VecDeque<PostSpawnBoundary>>,
1279 #[cfg(test)]
1280 post_spawn_reaps: std::sync::atomic::AtomicUsize,
1281 #[cfg(test)]
1282 post_spawn_stop_failures: std::sync::atomic::AtomicUsize,
1283 #[cfg(test)]
1284 use_long_lived_test_listener: std::sync::atomic::AtomicBool,
1285}
1286
1287#[cfg(test)]
1288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1289enum PostSpawnBoundary {
1290 HandoffDelete,
1291 IdentitySerialize,
1292 IdentityWrite,
1293 ChildMapInsert,
1294}
1295
1296impl NativeProcesses {
1297 #[must_use]
1298 pub fn new() -> Self {
1299 Self::default()
1300 }
1301
1302 #[cfg(test)]
1303 fn fail_post_spawn_at(&self, boundary: PostSpawnBoundary) {
1304 self.post_spawn_faults.lock().unwrap().push_back(boundary);
1305 }
1306
1307 #[cfg(test)]
1308 fn faults_at(&self, boundary: PostSpawnBoundary) -> bool {
1309 let mut faults = self.post_spawn_faults.lock().unwrap();
1310 if faults.front() == Some(&boundary) {
1311 faults.pop_front();
1312 true
1313 } else {
1314 false
1315 }
1316 }
1317
1318 #[cfg(test)]
1319 fn fail_post_spawn_stops(&self, count: usize) {
1320 self.post_spawn_stop_failures
1321 .fetch_add(count, std::sync::atomic::Ordering::SeqCst);
1322 }
1323
1324 #[cfg(test)]
1325 fn fail_next_post_spawn_stop(&self) {
1326 self.fail_post_spawn_stops(1);
1327 }
1328
1329 #[cfg(test)]
1330 fn use_long_lived_test_listener(&self) {
1331 self.use_long_lived_test_listener
1332 .store(true, std::sync::atomic::Ordering::SeqCst);
1333 }
1334
1335 fn stop_spawned_child(&self, child: &mut ChildProcess) -> Result<(), FailureReason> {
1336 #[cfg(test)]
1337 if self
1338 .post_spawn_stop_failures
1339 .fetch_update(
1340 std::sync::atomic::Ordering::SeqCst,
1341 std::sync::atomic::Ordering::SeqCst,
1342 |left| if left > 0 { Some(left - 1) } else { None },
1343 )
1344 .is_ok()
1345 {
1346 return Err(FailureReason::Other("injected runner stop failure".into()));
1347 }
1348 child
1349 .stop(Duration::from_secs(1))
1350 .map(|_| ())
1351 .map_err(|_| FailureReason::Other("spawned runner process could not be stopped".into()))
1352 }
1353
1354 fn abort_spawned_child(
1355 &self,
1356 mut child: ChildProcess,
1357 attempt: &RunnerAttempt,
1358 remove_identity: bool,
1359 ) -> ProcessStartFailure {
1360 let mut reaped = self.stop_spawned_child(&mut child).is_ok();
1361 if reaped {
1362 if remove_identity {
1363 Self::remove_identity_files(attempt);
1364 }
1365 } else {
1366 let identity_durable =
1369 serde_json::to_vec(child.identity())
1370 .ok()
1371 .is_some_and(|identity| {
1372 self.persist_identity(attempt, &identity).is_ok()
1373 || self.persist_fallback_identity(attempt, &identity).is_ok()
1374 });
1375 if !identity_durable {
1376 for _ in 1..MAX_POST_SPAWN_STOP_ATTEMPTS {
1381 if self.stop_spawned_child(&mut child).is_ok() {
1382 reaped = true;
1383 break;
1384 }
1385 }
1386 if !reaped {
1387 let pid = child.pid();
1392 let marker = write_durable_file(
1393 &Self::unresolved_process_path(attempt),
1394 pid.to_string().as_bytes(),
1395 );
1396 self.children
1397 .lock()
1398 .unwrap_or_else(std::sync::PoisonError::into_inner)
1399 .insert(attempt.id, child);
1400 let reason = if marker.is_ok() {
1401 FailureReason::Other(
1402 "spawn cleanup exhausted its bounded stop attempts; the live process remains under durable unresolved supervision"
1403 .into(),
1404 )
1405 } else {
1406 FailureReason::Other(
1407 "spawn cleanup exhausted its bounded stop attempts and the unresolved-process marker could not be journalled"
1408 .into(),
1409 )
1410 };
1411 return ProcessStartFailure::after_spawn_live_with_reason(pid, reason);
1412 }
1413 } else {
1414 let pid = child.pid();
1415 self.children
1416 .lock()
1417 .unwrap_or_else(std::sync::PoisonError::into_inner)
1418 .insert(attempt.id, child);
1419 return ProcessStartFailure::after_spawn_live(pid);
1420 }
1421 }
1422 #[cfg(test)]
1423 if reaped {
1424 self.post_spawn_reaps
1425 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1426 }
1427 #[cfg(not(test))]
1428 let _ = reaped;
1429 ProcessStartFailure::after_spawn_stopped()
1430 }
1431
1432 fn identity_path(attempt: &RunnerAttempt) -> PathBuf {
1433 attempt.runtime_path().join(IDENTITY_FILE)
1434 }
1435
1436 fn fallback_identity_path(attempt: &RunnerAttempt) -> PathBuf {
1437 attempt.runtime_path().join(FALLBACK_IDENTITY_FILE)
1438 }
1439
1440 fn unresolved_process_path(attempt: &RunnerAttempt) -> PathBuf {
1441 attempt.runtime_path().join(UNRESOLVED_PROCESS_FILE)
1442 }
1443
1444 fn remove_identity_files(attempt: &RunnerAttempt) {
1445 let _ = fs::remove_file(Self::identity_path(attempt));
1446 let _ = fs::remove_file(Self::fallback_identity_path(attempt));
1447 let _ = fs::remove_file(Self::unresolved_process_path(attempt));
1448 }
1449
1450 fn persist_identity(&self, attempt: &RunnerAttempt, bytes: &[u8]) -> std::io::Result<()> {
1451 self.persist_identity_at(&Self::identity_path(attempt), bytes)
1452 }
1453
1454 fn persist_fallback_identity(
1455 &self,
1456 attempt: &RunnerAttempt,
1457 bytes: &[u8],
1458 ) -> std::io::Result<()> {
1459 self.persist_identity_at(&Self::fallback_identity_path(attempt), bytes)
1460 }
1461
1462 fn persist_identity_at(&self, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
1463 #[cfg(test)]
1464 if self.faults_at(PostSpawnBoundary::IdentityWrite) {
1465 return Err(std::io::Error::other("injected identity write failure"));
1466 }
1467 write_durable_file(path, bytes)
1468 }
1469
1470 fn intent_path(attempt: &RunnerAttempt) -> PathBuf {
1471 attempt.runtime_path().join(TERMINATE_INTENT_FILE)
1472 }
1473
1474 fn read_identity(attempt: &RunnerAttempt) -> Result<Option<ProcessIdentity>, FailureReason> {
1475 match Self::read_identity_at(&Self::identity_path(attempt))? {
1476 Some(identity) => Ok(Some(identity)),
1477 None => Self::read_identity_at(&Self::fallback_identity_path(attempt)),
1478 }
1479 }
1480
1481 fn read_identity_at(path: &Path) -> Result<Option<ProcessIdentity>, FailureReason> {
1482 match fs::read(path) {
1483 Ok(bytes) => serde_json::from_slice(&bytes)
1484 .map(Some)
1485 .map_err(|_| FailureReason::Other("process identity journal is unreadable".into())),
1486 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
1487 Err(_) => Err(FailureReason::Other(
1488 "process identity journal could not be read".into(),
1489 )),
1490 }
1491 }
1492}
1493
1494impl ProcessSupervisor for NativeProcesses {
1495 fn spawn(
1496 &self,
1497 attempt: &RunnerAttempt,
1498 config: &EncodedJitConfig,
1499 ) -> Result<u32, ProcessStartFailure> {
1500 let handoff = RestrictiveHandoff::create(
1501 attempt.runtime_path(),
1502 SecretString::from(config.expose().to_owned()),
1503 )
1504 .map_err(|_| ProcessStartFailure::before_spawn(FailureReason::ProcessStartFailed))?;
1505 #[cfg(windows)]
1506 let program = attempt
1507 .runtime_path()
1508 .join("bin")
1509 .join("Runner.Listener.exe");
1510 #[cfg(not(windows))]
1511 let program = attempt.runtime_path().join("bin").join("Runner.Listener");
1512 if !program.is_file() {
1515 return Err(ProcessStartFailure::before_spawn(
1516 FailureReason::ProcessStartFailed,
1517 ));
1518 }
1519 #[cfg(test)]
1520 let spec = if self
1521 .use_long_lived_test_listener
1522 .load(std::sync::atomic::Ordering::SeqCst)
1523 {
1524 SpawnSpec::new(program)
1525 .args([
1526 "--ignored",
1527 "--exact",
1528 "lifecycle::tests::long_lived_native_listener_helper",
1529 "--nocapture",
1530 ])
1531 .env(
1532 "RUNNER_MANAGER_TEST_LISTENER_READY",
1533 attempt.runtime_path().join(TEST_LISTENER_READY),
1534 )
1535 .working_dir(attempt.runtime_path())
1536 } else {
1537 runner_listener_spec(program, attempt.runtime_path())
1538 };
1539 #[cfg(not(test))]
1540 let spec = runner_listener_spec(program, attempt.runtime_path());
1541 let child = spec
1542 .spawn_runner_with_handoff(&handoff)
1543 .map_err(|_| ProcessStartFailure::before_spawn(FailureReason::ProcessStartFailed))?;
1544 #[cfg(test)]
1546 if self.faults_at(PostSpawnBoundary::HandoffDelete) {
1547 drop(handoff);
1548 return Err(self.abort_spawned_child(child, attempt, false));
1549 }
1550 if handoff.delete().is_err() {
1551 return Err(self.abort_spawned_child(child, attempt, false));
1552 }
1553 #[cfg(test)]
1554 if self.faults_at(PostSpawnBoundary::IdentitySerialize) {
1555 return Err(self.abort_spawned_child(child, attempt, false));
1556 }
1557 let identity = match serde_json::to_vec(child.identity()) {
1558 Ok(identity) => identity,
1559 Err(_) => {
1560 return Err(self.abort_spawned_child(child, attempt, false));
1561 }
1562 };
1563 if self.persist_identity(attempt, &identity).is_err() {
1564 return Err(self.abort_spawned_child(child, attempt, true));
1565 }
1566 let pid = child.pid();
1567 #[cfg(test)]
1568 if self.faults_at(PostSpawnBoundary::ChildMapInsert) {
1569 return Err(self.abort_spawned_child(child, attempt, true));
1570 }
1571 let mut children = self
1572 .children
1573 .lock()
1574 .unwrap_or_else(std::sync::PoisonError::into_inner);
1575 children.insert(attempt.id, child);
1576 Ok(pid)
1577 }
1578
1579 fn is_alive(&self, attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
1580 let mut children = self
1581 .children
1582 .lock()
1583 .unwrap_or_else(std::sync::PoisonError::into_inner);
1584 if let Some(child) = children.get_mut(&attempt.id) {
1585 return match child
1586 .try_exit_status()
1587 .map_err(|_| FailureReason::Other("runner process could not be observed".into()))?
1588 {
1589 None => Ok(true),
1590 Some(status) => {
1591 if let Ok(mut exits) = self.successful_exits.lock() {
1592 exits.insert(attempt.id, status.success());
1593 }
1594 Ok(false)
1595 }
1596 };
1597 }
1598 let Some(identity) = Self::read_identity(attempt)? else {
1599 if attempt.process_id().is_some() || Self::unresolved_process_path(attempt).is_file() {
1600 return Err(FailureReason::Other(
1601 "runner process identity is missing; refusing recovery until the process is resolved"
1602 .into(),
1603 ));
1604 }
1605 return Ok(false);
1606 };
1607 match identity.recheck() {
1608 Ok(Adoption::Live) => Ok(true),
1609 Ok(Adoption::Gone | Adoption::PidRecycled { .. }) => Ok(false),
1610 Err(_) => Ok(false),
1611 }
1612 }
1613
1614 fn recovered_pid(&self, attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
1615 Ok(Self::read_identity(attempt)?.map(|identity| identity.pid()))
1616 }
1617
1618 fn completed_successfully(&self, attempt: &RunnerAttempt) -> bool {
1619 self.successful_exits
1620 .lock()
1621 .ok()
1622 .and_then(|exits| exits.get(&attempt.id).copied())
1623 .unwrap_or(false)
1624 }
1625
1626 fn record_terminate_intent(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
1627 let path = Self::intent_path(attempt);
1628 write_durable_file(&path, b"registration-timeout\n")
1629 .map_err(|_| FailureReason::Other("terminate intent could not be journalled".into()))
1630 }
1631
1632 fn has_terminate_intent(&self, attempt: &RunnerAttempt) -> bool {
1633 Self::intent_path(attempt).is_file()
1634 }
1635
1636 fn terminate(&self, attempt: &RunnerAttempt) -> Result<(), FailureReason> {
1637 let mut children = self
1638 .children
1639 .lock()
1640 .unwrap_or_else(std::sync::PoisonError::into_inner);
1641 if let Some(child) = children.get_mut(&attempt.id) {
1642 child
1643 .stop(Duration::from_secs(10))
1644 .map_err(|_| FailureReason::Other("runner process could not be stopped".into()))?;
1645 return Ok(());
1646 }
1647 let Some(identity) = Self::read_identity(attempt)? else {
1648 return Ok(());
1649 };
1650 match identity
1651 .terminate(Duration::from_secs(10))
1652 .map_err(|_| FailureReason::Other("runner process could not be stopped".into()))?
1653 {
1654 Termination::Terminated | Termination::AlreadyGone => Ok(()),
1655 Termination::RefusedPidRecycled { .. } => Err(FailureReason::Other(
1656 "runner PID was recycled; refusing to signal it".into(),
1657 )),
1658 }
1659 }
1660}
1661
1662pub struct LifecyclePorts {
1663 pub store: Arc<dyn Store>,
1664 pub github: Arc<dyn LifecycleGithub>,
1665 pub packages: Arc<dyn RuntimePackages>,
1666 pub processes: Arc<dyn ProcessSupervisor>,
1667 pub clock: Arc<dyn Clock>,
1668 pub demand: Arc<dyn DemandPersistence>,
1669 pub delay: Arc<dyn RetryDelay>,
1670 pub events: Arc<dyn AttemptEventSink>,
1671 pub reconcile_events: Arc<dyn EventSink>,
1672}
1673
1674impl fmt::Debug for LifecyclePorts {
1675 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1676 f.debug_struct("LifecyclePorts")
1677 .field("store", &self.store)
1678 .field("github", &self.github)
1679 .field("packages", &self.packages)
1680 .field("processes", &self.processes)
1681 .finish_non_exhaustive()
1682 }
1683}
1684
1685#[derive(Debug, thiserror::Error)]
1686pub enum LifecycleError {
1687 #[error("attempt journal operation failed")]
1688 Journal,
1689 #[error("attempt {0} is not in the journal")]
1690 Missing(AttemptId),
1691 #[error("attempt lifecycle transition was refused")]
1692 Transition,
1693 #[error("startup recovery has not completed")]
1694 RecoveryIncomplete,
1695 #[error("the persistent slot was not cleaned: {detail}")]
1705 SlotQuarantined {
1706 class: &'static str,
1708 detail: String,
1709 },
1710 #[error("runner lifecycle failed: {0}")]
1711 Failed(FailureReason),
1712}
1713
1714impl LifecycleError {
1715 fn reason(&self) -> FailureReason {
1716 match self {
1717 Self::Failed(reason) => reason.clone(),
1718 Self::RecoveryIncomplete => FailureReason::Other("startup recovery incomplete".into()),
1719 Self::Journal => FailureReason::Other("attempt journal operation failed".into()),
1720 Self::Missing(_) => FailureReason::Other("attempt disappeared from the journal".into()),
1721 Self::Transition => FailureReason::Other("attempt transition was refused".into()),
1722 Self::SlotQuarantined { .. } => FailureReason::Other(self.to_string()),
1725 }
1726 }
1727}
1728
1729#[derive(Debug)]
1731pub struct LifecycleLauncher {
1732 host_id: HostId,
1733 app_paths: runner_manager_platform::paths::AppPaths,
1734 diagnostics_root: PathBuf,
1735 runner_group_id: u64,
1736 timeouts: RecoveryTimeouts,
1737 retry: RetryPolicy,
1738 cancel: CancelToken,
1739 ports: LifecyclePorts,
1740 recovery_complete: Mutex<bool>,
1741 versions: Mutex<BTreeMap<AttemptId, RunnerVersion>>,
1742 pending_replacements: Mutex<BTreeMap<AttemptId, ReplacementIntent>>,
1743}
1744
1745#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1746enum ReconcileProgress {
1747 Reconciled,
1748 Deferred,
1749 Replacement {
1750 attempt: AttemptId,
1751 operation: &'static str,
1752 },
1753}
1754
1755impl LifecycleLauncher {
1756 #[must_use]
1757 pub fn new(
1758 host_id: HostId,
1759 app_paths: runner_manager_platform::paths::AppPaths,
1760 diagnostics_root: impl Into<PathBuf>,
1761 runner_group_id: u64,
1762 timeouts: RecoveryTimeouts,
1763 retry: RetryPolicy,
1764 ports: LifecyclePorts,
1765 ) -> Self {
1766 Self {
1767 host_id,
1768 app_paths,
1769 diagnostics_root: diagnostics_root.into(),
1770 runner_group_id,
1771 timeouts,
1772 retry,
1773 cancel: CancelToken::new(),
1774 ports,
1775 recovery_complete: Mutex::new(false),
1776 versions: Mutex::new(BTreeMap::new()),
1777 pending_replacements: Mutex::new(BTreeMap::new()),
1778 }
1779 }
1780
1781 pub async fn recover_startup(
1785 &self,
1786 policies: &[ScalePolicy],
1787 ) -> Result<Vec<ReplacementIntent>, LifecycleError> {
1788 let by_id: BTreeMap<_, _> = policies.iter().map(|policy| (policy.id, policy)).collect();
1789 let attempts = self
1790 .ports
1791 .store
1792 .attempts()
1793 .map_err(|_| LifecycleError::Journal)?;
1794 let mut unresolved = false;
1795 for attempt in attempts {
1796 let Some(policy) = by_id.get(&attempt.policy_id) else {
1797 if !attempt.is_terminal() && attempt.state() != AttemptState::Cleaned {
1798 unresolved = true;
1799 }
1800 continue;
1801 };
1802 authorize(self.host_id, policy, &attempt).map_err(|_| LifecycleError::Journal)?;
1803 match self.reconcile_one(policy, attempt).await? {
1804 ReconcileProgress::Deferred => unresolved = true,
1805 ReconcileProgress::Replacement { attempt, operation } => {
1806 self.pending_replacements
1807 .lock()
1808 .map_err(|_| LifecycleError::Journal)?
1809 .insert(
1810 attempt,
1811 ReplacementIntent {
1812 policy: policy.id,
1813 previous_attempt: attempt,
1814 operation,
1815 },
1816 );
1817 }
1818 ReconcileProgress::Reconciled => {}
1819 }
1820 }
1821 if unresolved {
1822 return Err(LifecycleError::RecoveryIncomplete);
1823 }
1824 *self
1825 .recovery_complete
1826 .lock()
1827 .map_err(|_| LifecycleError::Journal)? = true;
1828 Ok(self
1829 .pending_replacements
1830 .lock()
1831 .map_err(|_| LifecycleError::Journal)?
1832 .values()
1833 .copied()
1834 .collect())
1835 }
1836
1837 pub async fn supervise(
1839 &self,
1840 policy: &ScalePolicy,
1841 ) -> Result<Vec<ReplacementIntent>, LifecycleError> {
1842 let mut replacements = Vec::new();
1843 self.pending_replacements
1844 .lock()
1845 .map_err(|_| LifecycleError::Journal)?
1846 .retain(|_, intent| {
1847 if intent.policy == policy.id {
1848 replacements.push(*intent);
1849 false
1850 } else {
1851 true
1852 }
1853 });
1854 let attempts = self
1855 .ports
1856 .store
1857 .attempts_for_policy(policy.id)
1858 .map_err(|_| LifecycleError::Journal)?;
1859 for attempt in attempts {
1860 authorize(self.host_id, policy, &attempt).map_err(|_| LifecycleError::Journal)?;
1861 if let ReconcileProgress::Replacement { attempt, operation } =
1862 self.reconcile_one(policy, attempt).await?
1863 {
1864 replacements.push(ReplacementIntent {
1865 policy: policy.id,
1866 previous_attempt: attempt,
1867 operation,
1868 });
1869 }
1870 }
1871 Ok(replacements)
1872 }
1873
1874 async fn reconcile_one(
1875 &self,
1876 policy: &ScalePolicy,
1877 mut attempt: RunnerAttempt,
1878 ) -> Result<ReconcileProgress, LifecycleError> {
1879 if attempt.state() == AttemptState::Cleaned {
1880 return Ok(ReconcileProgress::Reconciled);
1881 }
1882 if attempt.is_terminal() {
1883 self.clean_or_quarantine(&mut attempt)?;
1884 return Ok(ReconcileProgress::Reconciled);
1885 }
1886 let process_alive = self
1887 .ports
1888 .processes
1889 .is_alive(&attempt)
1890 .map_err(LifecycleError::Failed)?;
1891 let github = self
1892 .ports
1893 .github
1894 .observe(&policy.target, attempt.id, &self.cancel)
1895 .await;
1896
1897 if let Some(runner_id) = github.runner_id
1902 && read_runner_id(attempt.runtime_path()).is_none()
1903 {
1904 write_runner_id(attempt.runtime_path(), runner_id)?;
1905 self.ports
1906 .events
1907 .emit(AttemptEvent::RemoteIdentityRecovered {
1908 attempt: attempt.id,
1909 runner_id,
1910 });
1911 }
1912
1913 if attempt.state() == AttemptState::JitReceived
1918 && process_alive
1919 && let Some(pid) = self
1920 .ports
1921 .processes
1922 .recovered_pid(&attempt)
1923 .map_err(LifecycleError::Failed)?
1924 {
1925 attempt
1926 .started(pid, self.ports.clock.now())
1927 .map_err(|_| LifecycleError::Transition)?;
1928 self.record(&attempt)?;
1929 }
1930
1931 if attempt.state() == AttemptState::Busy
1936 && !process_alive
1937 && github.status == GithubRunnerObservation::NotRegistered
1938 && self.ports.processes.completed_successfully(&attempt)
1939 {
1940 self.conclude(&mut attempt, AttemptOutcome::CompletedJob)?;
1941 self.clean_or_quarantine(&mut attempt)?;
1942 return Ok(ReconcileProgress::Reconciled);
1943 }
1944
1945 if self.ports.processes.has_terminate_intent(&attempt) && !process_alive {
1948 self.deregister_runner(policy, &attempt).await;
1949 self.conclude(
1950 &mut attempt,
1951 AttemptOutcome::failed(FailureReason::TerminatedAfterRegistrationTimeout),
1952 )?;
1953 self.clean_or_quarantine(&mut attempt)?;
1954 return Ok(ReconcileProgress::Replacement {
1955 attempt: attempt.id,
1956 operation: "registration_timeout_replacement",
1957 });
1958 }
1959
1960 if matches!(
1966 attempt.state(),
1967 AttemptState::Allocated | AttemptState::JitReceived
1968 ) && !process_alive
1969 && matches!(github.status, GithubRunnerObservation::Registered { .. })
1970 {
1971 if attempt.state() == AttemptState::Allocated {
1972 attempt
1973 .jit_received(self.ports.clock.now())
1974 .map_err(|_| LifecycleError::Transition)?;
1975 self.record(&attempt)?;
1976 }
1977 self.deregister_runner(policy, &attempt).await;
1978 self.conclude(
1979 &mut attempt,
1980 AttemptOutcome::failed(FailureReason::JitExpired),
1981 )?;
1982 self.clean_or_quarantine(&mut attempt)?;
1983 return Ok(ReconcileProgress::Replacement {
1984 attempt: attempt.id,
1985 operation: "jit_expired_replacement",
1986 });
1987 }
1988
1989 match recovery_decision(
1990 &attempt,
1991 RecoveryObservation {
1992 process_alive,
1993 github: github.status,
1994 },
1995 self.timeouts,
1996 self.ports.clock.as_ref(),
1997 ) {
1998 RecoveryDecision::Nothing | RecoveryDecision::Wait => Ok(ReconcileProgress::Reconciled),
1999 RecoveryDecision::Defer => Ok(ReconcileProgress::Deferred),
2000 RecoveryDecision::Adopt => {
2001 self.ports.events.emit(AttemptEvent::Adopted {
2002 attempt: attempt.id,
2003 });
2004 Ok(ReconcileProgress::Reconciled)
2005 }
2006 RecoveryDecision::Clean => {
2007 self.clean_or_quarantine(&mut attempt)?;
2008 Ok(ReconcileProgress::Reconciled)
2009 }
2010 RecoveryDecision::Observe(state) => {
2011 let runner_id = attempt
2012 .github_runner_id()
2013 .or(github.runner_id)
2014 .or_else(|| read_runner_id(attempt.runtime_path()))
2015 .ok_or(LifecycleError::Transition)?;
2016 match state {
2017 AttemptState::JitReceived => attempt
2018 .jit_received(self.ports.clock.now())
2019 .map_err(|_| LifecycleError::Transition)?,
2020 AttemptState::Starting => {
2021 let pid = attempt.process_id().ok_or(LifecycleError::Transition)?;
2022 attempt
2023 .started(pid, self.ports.clock.now())
2024 .map_err(|_| LifecycleError::Transition)?;
2025 }
2026 AttemptState::Idle => attempt
2027 .registered_idle(runner_id, self.ports.clock.now())
2028 .map_err(|_| LifecycleError::Transition)?,
2029 AttemptState::Busy => attempt
2030 .assigned_job(runner_id, self.ports.clock.now())
2031 .map_err(|_| LifecycleError::Transition)?,
2032 _ => return Err(LifecycleError::Transition),
2033 }
2034 self.record(&attempt)?;
2035 Ok(ReconcileProgress::Reconciled)
2036 }
2037 RecoveryDecision::Conclude(outcome) => {
2038 let replacement = replacement_operation(&outcome);
2039 if matches!(github.status, GithubRunnerObservation::Registered { .. }) {
2044 self.deregister_runner(policy, &attempt).await;
2045 }
2046 self.conclude(&mut attempt, outcome)?;
2047 self.clean_or_quarantine(&mut attempt)?;
2048 Ok(
2049 replacement.map_or(ReconcileProgress::Reconciled, |operation| {
2050 ReconcileProgress::Replacement {
2051 attempt: attempt.id,
2052 operation,
2053 }
2054 }),
2055 )
2056 }
2057 RecoveryDecision::Terminate(payload) => {
2058 let idle_exit = payload.is_idle_exit();
2068 self.ports
2069 .processes
2070 .record_terminate_intent(&attempt)
2071 .map_err(LifecycleError::Failed)?;
2072 self.ports.events.emit(AttemptEvent::TerminateIntent {
2073 attempt: attempt.id,
2074 });
2075 self.ports
2076 .processes
2077 .terminate(&attempt)
2078 .map_err(LifecycleError::Failed)?;
2079 if self
2080 .ports
2081 .processes
2082 .is_alive(&attempt)
2083 .map_err(LifecycleError::Failed)?
2084 {
2085 return Ok(ReconcileProgress::Deferred);
2086 }
2087 self.ports.events.emit(AttemptEvent::Terminated {
2088 attempt: attempt.id,
2089 });
2090 let outcome = if idle_exit {
2096 AttemptOutcome::ExitedIdleWithoutWork
2097 } else {
2098 AttemptOutcome::failed(FailureReason::TerminatedAfterRegistrationTimeout)
2099 };
2100 self.deregister_runner(policy, &attempt).await;
2101 self.conclude(&mut attempt, outcome)?;
2102 self.clean_or_quarantine(&mut attempt)?;
2103 if idle_exit {
2107 Ok(ReconcileProgress::Reconciled)
2108 } else {
2109 Ok(ReconcileProgress::Replacement {
2110 attempt: attempt.id,
2111 operation: "registration_timeout_replacement",
2112 })
2113 }
2114 }
2115 }
2116 }
2117
2118 fn record(&self, attempt: &RunnerAttempt) -> Result<(), LifecycleError> {
2119 self.ports
2120 .store
2121 .record_attempt(attempt)
2122 .map_err(|_| LifecycleError::Journal)?;
2123 self.ports.events.emit(AttemptEvent::State {
2124 attempt: attempt.id,
2125 state: attempt.state(),
2126 });
2127 Ok(())
2128 }
2129
2130 async fn deregister_runner(&self, policy: &ScalePolicy, attempt: &RunnerAttempt) {
2151 let Some(runner_id) = attempt
2152 .github_runner_id()
2153 .or_else(|| read_runner_id(attempt.runtime_path()))
2154 else {
2155 return;
2156 };
2157 if self
2158 .ports
2159 .github
2160 .deregister(&policy.target, runner_id, &self.cancel)
2161 .await
2162 {
2163 self.ports.events.emit(AttemptEvent::Deregistered {
2164 attempt: attempt.id,
2165 runner_id,
2166 });
2167 } else {
2168 tracing::warn!(
2169 attempt = %attempt.id,
2170 runner_id,
2171 "the runner registration could not be removed from GitHub; it will show in the \
2172 target's runner settings until GitHub retires it or a later pass removes it"
2173 );
2174 }
2175 }
2176
2177 fn conclude(
2178 &self,
2179 attempt: &mut RunnerAttempt,
2180 outcome: AttemptOutcome,
2181 ) -> Result<(), LifecycleError> {
2182 attempt
2183 .conclude(outcome.clone(), self.ports.clock.now())
2184 .map_err(|_| LifecycleError::Transition)?;
2185 self.record(attempt)?;
2186 self.ports.events.emit(AttemptEvent::Concluded {
2187 attempt: attempt.id,
2188 outcome: OutcomeKind::of(&outcome),
2189 });
2190 Ok(())
2191 }
2192
2193 fn clean_or_quarantine(&self, attempt: &mut RunnerAttempt) -> Result<(), LifecycleError> {
2208 match self.clean_attempt(attempt) {
2209 Err(LifecycleError::SlotQuarantined { class, .. }) => {
2210 self.ports
2211 .reconcile_events
2212 .emit(LifecycleEvent::AttemptCleanFailed {
2213 policy: attempt.policy_id,
2214 attempt: attempt.id,
2215 reason: class,
2216 });
2217 Ok(())
2218 }
2219 other => other,
2220 }
2221 }
2222
2223 fn clean_attempt(&self, attempt: &mut RunnerAttempt) -> Result<(), LifecycleError> {
2224 let outcome = attempt
2225 .outcome()
2226 .cloned()
2227 .ok_or(LifecycleError::Transition)?;
2228 self.preserve_diagnostics(attempt, &outcome)?;
2229 self.scrub_workspace(attempt)?;
2230 self.ports
2231 .packages
2232 .release(attempt.id)
2233 .map_err(LifecycleError::Failed)?;
2234 attempt
2235 .clean(self.ports.clock.now())
2236 .map_err(|_| LifecycleError::Transition)?;
2237 self.record(attempt)?;
2238 let kind = OutcomeKind::of(&outcome);
2239 self.ports.events.emit(AttemptEvent::Cleaned {
2240 attempt: attempt.id,
2241 outcome: kind,
2242 });
2243 self.ports
2244 .reconcile_events
2245 .emit(LifecycleEvent::AttemptCleaned {
2246 policy: attempt.policy_id,
2247 attempt: attempt.id,
2248 outcome: kind,
2249 });
2250 Ok(())
2251 }
2252
2253 fn scrub_workspace(&self, attempt: &RunnerAttempt) -> Result<(), LifecycleError> {
2263 #[cfg(test)]
2264 {
2265 if matches!(
2269 std::env::var("RUNNER_MANAGER_TEST_MUTANT").as_deref(),
2270 Ok("skip_workspace_cleanup" | "reuse_job_workspace")
2271 ) {
2272 return Ok(());
2273 }
2274 }
2275 match attempt.workspace() {
2276 AttemptWorkspace::Ephemeral => match remove_runtime_tree(attempt.runtime_path()) {
2277 Ok(()) => Ok(()),
2278 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
2279 Err(_) => Err(LifecycleError::Failed(FailureReason::Other(
2280 "attempt workspace could not be removed".into(),
2281 ))),
2282 },
2283 AttemptWorkspace::PersistentSlot { slot } => self.scrub_persistent_slot(attempt, slot),
2284 }
2285 }
2286
2287 fn scrub_persistent_slot(
2300 &self,
2301 attempt: &RunnerAttempt,
2302 slot: NonZeroU16,
2303 ) -> Result<(), LifecycleError> {
2304 let configured = self
2309 .ports
2310 .store
2311 .policy(attempt.policy_id)
2312 .map_err(|_| LifecycleError::Journal)?
2313 .and_then(|policy| match policy.workspace_policy() {
2314 WorkspacePolicy::Persistent { root } => Some(root.clone()),
2315 WorkspacePolicy::Ephemeral => None,
2316 });
2317 let runtime = attempt.runtime_path();
2318 self.quarantine_on_refusal(
2319 attempt,
2320 verify_journalled_slot(runtime, slot, configured.as_ref())
2321 .and_then(|()| slot_is_present(runtime))
2322 .and_then(|present| {
2323 if present {
2324 scrub_slot_entries(runtime).and_then(|()| verify_slot_scrubbed(runtime))
2325 } else {
2326 Ok(())
2327 }
2328 }),
2329 )
2330 }
2331
2332 fn quarantine_on_refusal(
2341 &self,
2342 attempt: &RunnerAttempt,
2343 outcome: Result<(), SlotQuarantine>,
2344 ) -> Result<(), LifecycleError> {
2345 let Err(quarantine) = outcome else {
2346 return Ok(());
2347 };
2348 let detail = quarantine.to_string();
2349 tracing::warn!(
2350 attempt = %attempt.id,
2351 policy = %attempt.policy_id,
2352 slot = attempt.workspace().slot_number(),
2353 refusal = quarantine.refusal.class(),
2354 "{detail}"
2355 );
2356 Err(LifecycleError::SlotQuarantined {
2357 class: quarantine.refusal.class(),
2358 detail,
2359 })
2360 }
2361
2362 fn preserve_diagnostics(
2363 &self,
2364 attempt: &RunnerAttempt,
2365 outcome: &AttemptOutcome,
2366 ) -> Result<(), LifecycleError> {
2367 fs::create_dir_all(&self.diagnostics_root).map_err(|_| {
2368 LifecycleError::Failed(FailureReason::Other(
2369 "diagnostics directory could not be created".into(),
2370 ))
2371 })?;
2372 let diagnostic = format!(
2375 "attempt_id={}\npolicy_id={}\noutcome={}\n",
2376 attempt.id,
2377 attempt.policy_id,
2378 OutcomeKind::of(outcome).as_str()
2379 );
2380 fs::write(
2381 self.diagnostics_root.join(format!("{}.log", attempt.id)),
2382 diagnostic,
2383 )
2384 .map_err(|_| {
2385 LifecycleError::Failed(FailureReason::Other(
2386 "redacted diagnostics could not be preserved".into(),
2387 ))
2388 })
2389 }
2390
2391 async fn materialize_with_retry(
2392 &self,
2393 policy: &ScalePolicy,
2394 attempt: &RunnerAttempt,
2395 ) -> Result<RunnerVersion, FailureReason> {
2396 let mut issued = 0_u32;
2397 loop {
2398 issued = issued.saturating_add(1);
2399 match self.ports.packages.materialize(attempt).await {
2400 Ok(version) => return Ok(version),
2401 Err(reason)
2402 if package_failure_is_terminal(&reason)
2403 || issued >= self.retry.max_attempts.max(1) =>
2404 {
2405 return Err(reason);
2406 }
2407 Err(reason) => {
2408 if !self.ports.demand.persists(policy.id).await {
2409 return Err(reason);
2410 }
2411 let delay = self.retry.delay(issued);
2412 self.ports.events.emit(AttemptEvent::Retry {
2413 attempt: attempt.id,
2414 operation: "package_materialization",
2415 delay,
2416 });
2417 self.ports.delay.wait(delay).await;
2418 if !self.ports.demand.persists(policy.id).await {
2419 return Err(reason);
2420 }
2421 }
2422 }
2423 }
2424 }
2425
2426 async fn register_with_retry(
2427 &self,
2428 policy: &ScalePolicy,
2429 attempt: AttemptId,
2430 request: &JitRunnerRequest,
2431 ) -> Result<JitRegistration, LifecycleError> {
2432 let mut issued = 0_u32;
2433 loop {
2434 issued = issued.saturating_add(1);
2435 match self
2436 .ports
2437 .github
2438 .register(&policy.target, request, &self.cancel)
2439 .await
2440 {
2441 Ok(registration) => return Ok(registration),
2442 Err(error) if error.terminal => {
2443 return Err(LifecycleError::Failed(error.reason));
2444 }
2445 Err(error) => {
2446 if issued >= self.retry.max_attempts.max(1)
2447 || !self.ports.demand.persists(policy.id).await
2448 {
2449 return Err(LifecycleError::Failed(error.reason));
2450 }
2451 let delay = error
2452 .retry_after
2453 .unwrap_or_else(|| self.retry.delay(issued));
2454 self.ports.events.emit(AttemptEvent::Retry {
2455 attempt,
2456 operation: "jit_request",
2457 delay,
2458 });
2459 self.ports.delay.wait(delay).await;
2460 if !self.ports.demand.persists(policy.id).await {
2461 return Err(LifecycleError::Failed(error.reason));
2462 }
2463 }
2464 }
2465 }
2466 }
2467
2468 fn allocate_workspace(
2478 &self,
2479 policy: &ScalePolicy,
2480 id: AttemptId,
2481 ) -> Result<Placement, LifecycleError> {
2482 let placement = match policy.workspace_policy() {
2483 WorkspacePolicy::Persistent { root } => self.allocate_persistent_slot(policy, root),
2488 WorkspacePolicy::Ephemeral => self.allocate_disposable(policy, id),
2489 };
2490 if placement.is_ok() {
2493 self.root_accepted(policy.id);
2494 }
2495 placement
2496 }
2497
2498 fn configured_host_root(&self) -> Result<Option<LocalAbsolutePath>, LifecycleError> {
2505 let host = self
2506 .ports
2507 .store
2508 .host(self.host_id)
2509 .map_err(|_| LifecycleError::Journal)?
2510 .ok_or_else(|| LifecycleError::Failed(FailureReason::Other("host not found".into())))?;
2511 Ok(host.runner_root_override.clone())
2512 }
2513
2514 fn effective_host_root(
2519 &self,
2520 policy: &ScalePolicy,
2521 ) -> Result<LocalAbsolutePath, LifecycleError> {
2522 match self.configured_host_root()? {
2523 Some(configured) => Ok(configured),
2524 None => default_runner_root(&self.app_paths).map_err(|error| {
2525 self.root_refused(policy.id, "the platform default runner root", error)
2528 }),
2529 }
2530 }
2531
2532 fn root_refused(&self, policy: PolicyId, root: &str, error: RunnerRootError) -> LifecycleError {
2545 let _ = runner_manager_platform::service::record_runner_root_refusal(
2546 &self.app_paths,
2547 &policy.to_string(),
2548 self.ports.clock.now(),
2549 error.kind(),
2550 root,
2551 &error.to_string(),
2552 );
2553 root_failure(error)
2554 }
2555
2556 fn root_accepted(&self, policy: PolicyId) {
2563 let _ = runner_manager_platform::service::clear_runner_root_refusal(
2564 &self.app_paths,
2565 &policy.to_string(),
2566 );
2567 }
2568
2569 fn allocate_disposable(
2572 &self,
2573 policy: &ScalePolicy,
2574 id: AttemptId,
2575 ) -> Result<Placement, LifecycleError> {
2576 let effective_root = self.effective_host_root(policy)?;
2577 RootPreflight::new(&self.app_paths)
2578 .check(&RootOwner::Host, &effective_root)
2579 .map_err(|error| self.root_refused(policy.id, effective_root.as_str(), error))?;
2580 let runtime = effective_root.as_path().join({
2581 #[cfg(test)]
2582 {
2583 if std::env::var("RUNNER_MANAGER_TEST_MUTANT").as_deref()
2584 == Ok("reuse_job_workspace")
2585 {
2586 "mutant-shared-workspace".to_owned()
2587 } else {
2588 workspace_name(id)
2589 }
2590 }
2591 #[cfg(not(test))]
2592 {
2593 workspace_name(id)
2594 }
2595 });
2596 fs::create_dir_all(&runtime)
2597 .map_err(|_| LifecycleError::Failed(FailureReason::ProcessStartFailed))?;
2598 Ok(Placement {
2599 runtime,
2600 workspace: AttemptWorkspace::Ephemeral,
2601 })
2602 }
2603
2604 fn allocate_persistent_slot(
2616 &self,
2617 policy: &ScalePolicy,
2618 root: &LocalAbsolutePath,
2619 ) -> Result<Placement, LifecycleError> {
2620 let ceiling = policy.max_capacity().ok_or_else(|| {
2623 LifecycleError::Failed(FailureReason::Other(
2624 "a persistent workspace needs the policy's max_capacity to bound its slots"
2625 .to_string(),
2626 ))
2627 })?;
2628 let leases = self
2629 .ports
2630 .store
2631 .slot_leases_for_policy(policy.id)
2632 .map_err(|_| LifecycleError::Journal)?;
2633 let slot = lowest_free_slot(&leases, ceiling).ok_or_else(|| {
2634 LifecycleError::Failed(FailureReason::Other(format!(
2635 "every persistent slot s1 to s{ceiling} for {} is leased by an attempt that has \
2636 not been cleaned, so no slot is free; raise the repository's max capacity, or \
2637 finish cleaning a concluded attempt",
2638 policy.target
2639 )))
2640 })?;
2641 let workspace = AttemptWorkspace::persistent_slot(slot);
2642 let name = workspace
2643 .slot_directory_name()
2644 .expect("a persistent allocation names its slot directory");
2645
2646 let host_root = self
2658 .configured_host_root()?
2659 .or_else(|| default_runner_root(&self.app_paths).ok());
2660 let mut preflight = RootPreflight::new(&self.app_paths);
2661 if let Some(host_root) = host_root {
2662 preflight = preflight.against(RootOwner::Host, host_root);
2663 }
2664 let checked = preflight
2665 .check(&RootOwner::Repository(policy.target.to_string()), root)
2666 .map_err(|error| self.root_refused(policy.id, root.as_str(), error))?;
2667 if let Some(leaf) = checked.leaf_to_create() {
2668 fs::create_dir(leaf).map_err(|source| {
2669 LifecycleError::Failed(FailureReason::Other(format!(
2670 "the persistent workspace root {} could not be created: {source}",
2671 leaf.display()
2672 )))
2673 })?;
2674 }
2675
2676 let slot_path = runner_root::derive_child(root, &name)
2680 .map_err(|error| self.root_refused(policy.id, root.as_str(), error))?;
2681 create_or_validate_slot(slot_path.as_path())?;
2682 runner_root::verify_containment(root, &slot_path)
2683 .map_err(|error| self.root_refused(policy.id, root.as_str(), error))?;
2684 accept_reusable_slot(slot_path.as_path())?;
2685 Ok(Placement {
2686 runtime: slot_path.as_path().to_path_buf(),
2687 workspace,
2688 })
2689 }
2690
2691 fn record_allocation(&self, attempt: &RunnerAttempt) -> Result<(), LifecycleError> {
2703 match self.ports.store.record_attempt(attempt) {
2704 Ok(()) => {
2705 self.ports.events.emit(AttemptEvent::State {
2706 attempt: attempt.id,
2707 state: attempt.state(),
2708 });
2709 Ok(())
2710 }
2711 Err(error @ StoreError::SlotAlreadyLeased { .. }) => Err(LifecycleError::Failed(
2712 FailureReason::Other(error.to_string()),
2713 )),
2714 Err(_) => Err(LifecycleError::Journal),
2715 }
2716 }
2717
2718 async fn launch_attempt(
2719 &self,
2720 policy: &ScalePolicy,
2721 allocation_guard: &AllocationGuard,
2722 ) -> Result<RunnerAttempt, LifecycleError> {
2723 if !*self
2724 .recovery_complete
2725 .lock()
2726 .map_err(|_| LifecycleError::Journal)?
2727 {
2728 return Err(LifecycleError::RecoveryIncomplete);
2729 }
2730 let labels = policy
2731 .routing_labels()
2732 .ok_or(LifecycleError::Failed(FailureReason::JitRequestFailed))?;
2733 let id = AttemptId::new_random();
2734 let placement = self.allocate_workspace(policy, id)?;
2735 let mut attempt = RunnerAttempt::allocate_in(
2736 id,
2737 policy.id,
2738 placement.runtime,
2739 placement.workspace,
2740 self.ports.clock.now(),
2741 );
2742 self.record_allocation(&attempt)?;
2747
2748 let version = match self.materialize_with_retry(policy, &attempt).await {
2749 Ok(version) => version,
2750 Err(reason) => return self.fail_launch(&mut attempt, reason),
2751 };
2752 self.prune_under_allocation_lock(allocation_guard, &version)?;
2753 self.versions
2754 .lock()
2755 .map_err(|_| LifecycleError::Journal)?
2756 .insert(id, version);
2757
2758 let jit_request =
2759 JitRunnerRequest::for_policy(runner_name(id), self.runner_group_id, labels);
2760 let registration = match self.register_with_retry(policy, id, &jit_request).await {
2761 Ok(registration) => registration,
2762 Err(error) => return self.fail_launch(&mut attempt, error.reason()),
2763 };
2764 let runner_id = registration.runner().id;
2765 write_runner_id(attempt.runtime_path(), runner_id)?;
2766 attempt
2767 .jit_received(self.ports.clock.now())
2768 .map_err(|_| LifecycleError::Transition)?;
2769 self.record(&attempt)?;
2770 let config = registration.into_config();
2771 let mut issued = 0_u32;
2772 let pid = loop {
2773 issued = issued.saturating_add(1);
2774 match self.ports.processes.spawn(&attempt, &config) {
2775 Ok(pid) => break pid,
2776 Err(error) => {
2777 if let Some(pid) = error.live_pid {
2778 attempt
2779 .started(pid, self.ports.clock.now())
2780 .map_err(|_| LifecycleError::Transition)?;
2781 self.record(&attempt)?;
2782 return Err(LifecycleError::Failed(error.reason));
2783 }
2784 if !error.retryable
2785 || issued >= self.retry.max_attempts.max(1)
2786 || !self.ports.demand.persists(policy.id).await
2787 {
2788 return self.fail_launch(&mut attempt, error.reason);
2789 }
2790 let delay = self.retry.delay(issued);
2791 self.ports.events.emit(AttemptEvent::Retry {
2792 attempt: attempt.id,
2793 operation: "process_start",
2794 delay,
2795 });
2796 self.ports.delay.wait(delay).await;
2797 if !self.ports.demand.persists(policy.id).await {
2798 return self.fail_launch(&mut attempt, error.reason);
2799 }
2800 }
2801 }
2802 };
2803 attempt
2804 .started(pid, self.ports.clock.now())
2805 .map_err(|_| LifecycleError::Transition)?;
2806 self.record(&attempt)?;
2807 Ok(attempt)
2808 }
2809
2810 fn fail_launch<T>(
2811 &self,
2812 attempt: &mut RunnerAttempt,
2813 reason: FailureReason,
2814 ) -> Result<T, LifecycleError> {
2815 self.conclude(attempt, AttemptOutcome::failed(reason.clone()))?;
2816 Err(LifecycleError::Failed(reason))
2817 }
2818
2819 fn prune_under_allocation_lock(
2822 &self,
2823 guard: &AllocationGuard,
2824 version: &RunnerVersion,
2825 ) -> Result<(), LifecycleError> {
2826 let attempts = self
2827 .ports
2828 .store
2829 .attempts()
2830 .map_err(|_| LifecycleError::Journal)?;
2831 self.ports
2832 .packages
2833 .prune_obsolete_guarded(
2834 PruneAuthority::from_launch_request(guard),
2835 version,
2836 &attempts,
2837 )
2838 .map_err(LifecycleError::Failed)
2839 }
2840}
2841
2842#[async_trait]
2843impl RunnerLauncher for LifecycleLauncher {
2844 async fn supervise(
2845 &self,
2846 policy: &ScalePolicy,
2847 ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
2848 LifecycleLauncher::supervise(self, policy)
2849 .await
2850 .map_err(|error| LaunchFailure::new(error.reason()))
2851 }
2852
2853 async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
2854 self.ports.store.attempts().map_err(|_| {
2855 LaunchFailure::new(FailureReason::Other(
2856 "attempt journal could not be read".into(),
2857 ))
2858 })
2859 }
2860
2861 async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure> {
2862 self.launch_attempt(request.policy, request.allocation_guard)
2863 .await
2864 .map_err(|error| LaunchFailure::new(error.reason()))
2865 }
2866
2867 async fn clean(&self, id: AttemptId) -> Result<(), LaunchFailure> {
2868 let mut attempt = self
2869 .ports
2870 .store
2871 .attempt(id)
2872 .map_err(|_| {
2873 LaunchFailure::new(FailureReason::Other(
2874 "attempt journal could not be read".into(),
2875 ))
2876 })?
2877 .ok_or_else(|| {
2878 LaunchFailure::new(FailureReason::Other(
2879 "attempt disappeared from the journal".into(),
2880 ))
2881 })?;
2882 self.clean_attempt(&mut attempt)
2883 .map_err(|error| LaunchFailure::new(error.reason()))
2884 }
2885}
2886
2887fn runner_name(attempt: AttemptId) -> String {
2888 format!("runner-manager-{attempt}")
2889}
2890
2891fn read_runner_id(runtime: &Path) -> Option<u64> {
2892 fs::read_to_string(runtime.join(RUNNER_ID_FILE))
2893 .ok()?
2894 .trim()
2895 .parse()
2896 .ok()
2897}
2898
2899fn write_runner_id(runtime: &Path, runner_id: u64) -> Result<(), LifecycleError> {
2900 let target = runtime.join(RUNNER_ID_FILE);
2901 if let Some(existing) = read_runner_id(runtime) {
2902 return (existing == runner_id)
2903 .then_some(())
2904 .ok_or(LifecycleError::Journal);
2905 }
2906 let temporary = runtime.join(format!("{RUNNER_ID_FILE}.{}.tmp", uuid::Uuid::new_v4()));
2907 write_durable_file(&temporary, runner_id.to_string().as_bytes())
2908 .map_err(|_| LifecycleError::Journal)?;
2909 match fs::rename(&temporary, &target) {
2910 Ok(()) => sync_directory(runtime).map_err(|_| LifecycleError::Journal),
2911 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
2912 let _ = fs::remove_file(&temporary);
2913 (read_runner_id(runtime) == Some(runner_id))
2914 .then_some(())
2915 .ok_or(LifecycleError::Journal)
2916 }
2917 Err(_) => {
2918 let _ = fs::remove_file(&temporary);
2919 Err(LifecycleError::Journal)
2920 }
2921 }
2922}
2923
2924fn write_durable_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
2925 let mut file = fs::OpenOptions::new()
2926 .create(true)
2927 .truncate(true)
2928 .write(true)
2929 .open(path)?;
2930 file.write_all(bytes)?;
2931 file.sync_all()?;
2932 let parent = path.parent().ok_or_else(|| {
2933 std::io::Error::new(
2934 std::io::ErrorKind::InvalidInput,
2935 "file has no parent directory",
2936 )
2937 })?;
2938 sync_directory(parent)
2939}
2940
2941#[cfg(unix)]
2942fn sync_directory(path: &Path) -> std::io::Result<()> {
2943 fs::File::open(path)?.sync_all()
2944}
2945
2946#[cfg(windows)]
2947fn sync_directory(path: &Path) -> std::io::Result<()> {
2948 use std::os::windows::fs::OpenOptionsExt;
2949
2950 const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
2951 const FILE_SHARE_ALL: u32 = 0x0000_0007;
2952 const GENERIC_WRITE: u32 = 0x4000_0000;
2953 fs::OpenOptions::new()
2954 .access_mode(GENERIC_WRITE)
2955 .share_mode(FILE_SHARE_ALL)
2956 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
2957 .open(path)?
2958 .sync_all()
2959}
2960
2961#[cfg(test)]
2962mod tests {
2963 use super::*;
2964 use std::collections::BTreeSet;
2965 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
2966
2967 use crate::reconcile::{AllocationLock, InProcessAllocationLock};
2968 use runner_manager_domain::model::{Elapsed, TargetScope};
2969 use runner_manager_domain::store::SqliteStore;
2970 use runner_manager_github::jit::JitRunner;
2971 use runner_manager_testkit::clock::FakeClock;
2972 use runner_manager_testkit::fixtures;
2973
2974 type CapturedFields = Vec<(String, String)>;
2976
2977 #[derive(Clone, Default)]
2985 struct CapturedEvents(std::sync::Arc<std::sync::Mutex<Vec<CapturedFields>>>);
2986
2987 impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for CapturedEvents {
2988 fn on_event(
2989 &self,
2990 event: &tracing::Event<'_>,
2991 _context: tracing_subscriber::layer::Context<'_, S>,
2992 ) {
2993 struct Collect(Vec<(String, String)>);
2994 impl tracing::field::Visit for Collect {
2995 fn record_debug(
2996 &mut self,
2997 field: &tracing::field::Field,
2998 value: &dyn std::fmt::Debug,
2999 ) {
3000 self.0.push((
3003 field.name().to_owned(),
3004 format!("{value:?}").trim_matches('"').to_owned(),
3005 ));
3006 }
3007 }
3008 let mut collected = Collect(Vec::new());
3009 event.record(&mut collected);
3010 self.0
3011 .lock()
3012 .expect("the capture mutex is not poisoned")
3013 .push(collected.0);
3014 }
3015 }
3016
3017 #[test]
3035 fn a_launch_the_runner_root_refused_names_the_cause_in_the_log_that_ships() {
3036 use runner_manager_platform::logging;
3037 use tracing_subscriber::layer::SubscriberExt as _;
3038
3039 let captured = CapturedEvents::default();
3040 let error = RunnerRootError::DeniedByPrivacyPolicy {
3041 requested: PathBuf::from("/Volumes/NVME/runners"),
3042 refused: PathBuf::from("/Volumes/NVME"),
3043 remediation: RootOwner::Host.remediation(),
3044 };
3045 let kind = error.kind();
3046
3047 let failure = tracing::subscriber::with_default(
3048 tracing_subscriber::registry().with(captured.clone()),
3049 || root_failure(error),
3050 );
3051
3052 assert!(
3057 matches!(
3058 &failure,
3059 LifecycleError::Failed(FailureReason::Other(detail))
3060 if detail.contains("/Volumes/NVME/runners")
3061 && detail.contains("Full Disk Access")
3062 ),
3063 "the reason must still carry the detail: {failure:?}"
3064 );
3065
3066 let events = captured
3067 .0
3068 .lock()
3069 .expect("the capture mutex is not poisoned")
3070 .clone();
3071 let event = events
3072 .iter()
3073 .find(|fields| fields.iter().any(|(_, value)| value.contains(kind)))
3074 .unwrap_or_else(|| panic!("the refusal did not name its cause: {events:?}"));
3075
3076 for (name, value) in event {
3081 assert!(
3082 logging::is_field_allowed(name),
3083 "`{name}` is not allow-listed, so it ships as `{}`: {event:?}",
3084 logging::REDACTION
3085 );
3086 assert_eq!(
3087 &logging::redact(value),
3088 value,
3089 "`{name}` does not survive value-shape scrubbing: {event:?}"
3090 );
3091 }
3092 }
3093
3094 fn nz(slot: u16) -> NonZeroU16 {
3096 NonZeroU16::new(slot).expect("a positive slot")
3097 }
3098
3099 const JIT: &str = "eyJzZWNyZXQiOiJnaHBfRE9fTk9UX0xFQUsifQ==";
3100
3101 #[derive(Debug, Default)]
3102 struct FakeGithubLifecycle {
3103 registration_failures: Mutex<VecDeque<bool>>,
3104 observations: Mutex<VecDeque<LifecycleGithubObservation>>,
3105 registrations: AtomicUsize,
3106 remaining_runners: AtomicUsize,
3107 deregistrations: Mutex<Vec<u64>>,
3111 deregistration_fails: AtomicBool,
3114 journal: Mutex<Option<Arc<SqliteStore>>>,
3119 registration_facts: Mutex<Vec<RegistrationFact>>,
3121 }
3122
3123 #[derive(Debug, Clone)]
3130 struct RegistrationFact {
3131 leased_slots: Vec<u16>,
3133 work_folder: String,
3135 runner_name: String,
3138 }
3139
3140 impl FakeGithubLifecycle {
3141 fn fail(mut self, terminal: bool) -> Self {
3142 self.registration_failures
3143 .get_mut()
3144 .expect("unpoisoned")
3145 .push_back(terminal);
3146 self
3147 }
3148
3149 fn watch_journal(&self, store: Arc<SqliteStore>) {
3150 *self.journal.lock().unwrap() = Some(store);
3151 }
3152
3153 fn registration_facts(&self) -> Vec<RegistrationFact> {
3154 self.registration_facts.lock().unwrap().clone()
3155 }
3156
3157 fn observe(&self, observation: GithubRunnerObservation) {
3158 let observation = match observation {
3159 GithubRunnerObservation::Unreachable => LifecycleGithubObservation::unreachable(),
3160 GithubRunnerObservation::NotRegistered => {
3161 LifecycleGithubObservation::not_registered()
3162 }
3163 GithubRunnerObservation::Registered { busy } => {
3164 LifecycleGithubObservation::registered(73, busy)
3165 }
3166 };
3167 self.observations.lock().unwrap().push_back(observation);
3168 }
3169 }
3170
3171 #[async_trait]
3172 impl LifecycleGithub for FakeGithubLifecycle {
3173 async fn register(
3174 &self,
3175 _target: &ScaleTarget,
3176 request: &JitRunnerRequest,
3177 _cancel: &CancelToken,
3178 ) -> Result<JitRegistration, JitRequestFailure> {
3179 self.registrations.fetch_add(1, Ordering::SeqCst);
3180 if let Some(store) = self.journal.lock().unwrap().as_ref() {
3181 let slots = store
3182 .attempts()
3183 .expect("the journal is readable")
3184 .iter()
3185 .filter_map(|attempt| attempt.workspace().slot_number())
3186 .collect();
3187 self.registration_facts
3188 .lock()
3189 .unwrap()
3190 .push(RegistrationFact {
3191 leased_slots: slots,
3192 work_folder: request.work_folder().to_string(),
3193 runner_name: request.name().to_string(),
3194 });
3195 }
3196 if let Some(terminal) = self.registration_failures.lock().unwrap().pop_front() {
3197 return Err(JitRequestFailure {
3198 terminal,
3199 reason: if terminal {
3200 FailureReason::Other("GitHub refused JIT registration with 403".into())
3201 } else {
3202 FailureReason::JitRequestFailed
3203 },
3204 retry_after: None,
3205 });
3206 }
3207 self.remaining_runners.store(1, Ordering::SeqCst);
3208 Ok(JitRegistration::new(
3209 EncodedJitConfig::new(JIT),
3210 JitRunner {
3211 id: 73,
3212 name: request.name().to_string(),
3213 os: "windows".into(),
3214 status: "offline".into(),
3215 busy: false,
3216 runner_group_id: Some(1),
3217 labels: request.labels().to_vec(),
3218 },
3219 ))
3220 }
3221
3222 async fn observe(
3223 &self,
3224 _target: &ScaleTarget,
3225 _attempt: AttemptId,
3226 _cancel: &CancelToken,
3227 ) -> LifecycleGithubObservation {
3228 let observation = self
3229 .observations
3230 .lock()
3231 .unwrap()
3232 .pop_front()
3233 .unwrap_or(LifecycleGithubObservation::not_registered());
3234 if observation.status == GithubRunnerObservation::NotRegistered {
3235 self.remaining_runners.store(0, Ordering::SeqCst);
3236 }
3237 observation
3238 }
3239
3240 async fn deregister(
3241 &self,
3242 _target: &ScaleTarget,
3243 runner_id: u64,
3244 _cancel: &CancelToken,
3245 ) -> bool {
3246 self.deregistrations.lock().unwrap().push(runner_id);
3247 if self.deregistration_fails.load(Ordering::SeqCst) {
3248 return false;
3249 }
3250 self.remaining_runners.store(0, Ordering::SeqCst);
3251 true
3252 }
3253 }
3254
3255 #[derive(Debug)]
3256 struct FakePackages {
3257 version: RunnerVersion,
3258 leases: Mutex<BTreeSet<AttemptId>>,
3259 materializations: AtomicUsize,
3260 materialization_failures: AtomicUsize,
3261 releases: AtomicUsize,
3262 prunes: AtomicUsize,
3263 prune_currents: Mutex<Vec<RunnerVersion>>,
3264 }
3265
3266 impl Default for FakePackages {
3267 fn default() -> Self {
3268 Self {
3269 version: RunnerVersion::parse("2.330.0").unwrap(),
3270 leases: Mutex::new(BTreeSet::new()),
3271 materializations: AtomicUsize::new(0),
3272 materialization_failures: AtomicUsize::new(0),
3273 releases: AtomicUsize::new(0),
3274 prunes: AtomicUsize::new(0),
3275 prune_currents: Mutex::new(Vec::new()),
3276 }
3277 }
3278 }
3279
3280 impl FakePackages {
3281 fn fail_materializations(&self, count: usize) {
3282 self.materialization_failures.store(count, Ordering::SeqCst);
3283 }
3284 }
3285
3286 #[async_trait]
3287 impl RuntimePackages for FakePackages {
3288 async fn materialize(
3289 &self,
3290 attempt: &RunnerAttempt,
3291 ) -> Result<RunnerVersion, FailureReason> {
3292 self.materializations.fetch_add(1, Ordering::SeqCst);
3293 if self
3294 .materialization_failures
3295 .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
3296 if left > 0 { Some(left - 1) } else { None }
3297 })
3298 .is_ok()
3299 {
3300 return Err(FailureReason::Other(
3301 "runner package materialization failed transiently".into(),
3302 ));
3303 }
3304 fs::create_dir_all(attempt.runtime_path()).unwrap();
3305 fs::write(attempt.runtime_path().join("runner-package"), b"verified").unwrap();
3306 self.leases.lock().unwrap().insert(attempt.id);
3307 Ok(self.version.clone())
3308 }
3309
3310 fn release(&self, attempt: AttemptId) -> Result<(), FailureReason> {
3311 self.leases.lock().unwrap().remove(&attempt);
3312 self.releases.fetch_add(1, Ordering::SeqCst);
3313 Ok(())
3314 }
3315
3316 fn prune_obsolete_guarded(
3317 &self,
3318 _authority: PruneAuthority<'_>,
3319 current: &RunnerVersion,
3320 _attempts: &[RunnerAttempt],
3321 ) -> Result<(), FailureReason> {
3322 self.prunes.fetch_add(1, Ordering::SeqCst);
3323 self.prune_currents.lock().unwrap().push(current.clone());
3324 Ok(())
3325 }
3326 }
3327
3328 #[derive(Debug, Default)]
3329 struct FakeProcesses {
3330 alive: AtomicBool,
3331 completed_successfully: AtomicBool,
3332 spawns: AtomicUsize,
3333 spawn_failures: AtomicUsize,
3334 live_spawn_failure: AtomicBool,
3335 terminations: AtomicUsize,
3336 intent: AtomicBool,
3337 intent_failure: AtomicBool,
3338 actions: Mutex<Vec<&'static str>>,
3339 saw_secret: AtomicBool,
3340 }
3341
3342 impl FakeProcesses {
3343 fn fail_spawns(&self, count: usize) {
3344 self.spawn_failures.store(count, Ordering::SeqCst);
3345 }
3346
3347 fn fail_spawn_with_live_child(&self) {
3348 self.live_spawn_failure.store(true, Ordering::SeqCst);
3349 }
3350
3351 fn set_alive(&self, alive: bool) {
3352 self.alive.store(alive, Ordering::SeqCst);
3353 }
3354
3355 fn finish_successfully(&self) {
3356 self.completed_successfully.store(true, Ordering::SeqCst);
3357 self.alive.store(false, Ordering::SeqCst);
3358 }
3359
3360 fn fail_intent(&self) {
3361 self.intent_failure.store(true, Ordering::SeqCst);
3362 }
3363 }
3364
3365 impl ProcessSupervisor for FakeProcesses {
3366 fn spawn(
3367 &self,
3368 attempt: &RunnerAttempt,
3369 config: &EncodedJitConfig,
3370 ) -> Result<u32, ProcessStartFailure> {
3371 self.spawns.fetch_add(1, Ordering::SeqCst);
3372 let handoff = RestrictiveHandoff::create(
3375 attempt.runtime_path(),
3376 SecretString::from(config.expose().to_owned()),
3377 )
3378 .unwrap();
3379 self.saw_secret
3380 .store(config.expose() == JIT, Ordering::SeqCst);
3381 let handoff_path = handoff.path().to_path_buf();
3382 let failing = self
3383 .spawn_failures
3384 .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
3385 if left > 0 { Some(left - 1) } else { None }
3386 })
3387 .is_ok();
3388 drop(handoff);
3389 assert!(!handoff_path.exists(), "handoff must be absent on return");
3390 if self.live_spawn_failure.swap(false, Ordering::SeqCst) {
3391 self.alive.store(true, Ordering::SeqCst);
3392 return Err(ProcessStartFailure::after_spawn_live(4242));
3393 }
3394 if failing {
3395 return Err(ProcessStartFailure::before_spawn(
3396 FailureReason::ProcessStartFailed,
3397 ));
3398 }
3399 self.alive.store(true, Ordering::SeqCst);
3400 Ok(4242)
3401 }
3402
3403 fn is_alive(&self, _attempt: &RunnerAttempt) -> Result<bool, FailureReason> {
3404 self.actions.lock().unwrap().push("observe_process");
3405 Ok(self.alive.load(Ordering::SeqCst))
3406 }
3407
3408 fn recovered_pid(&self, _attempt: &RunnerAttempt) -> Result<Option<u32>, FailureReason> {
3409 Ok(self.alive.load(Ordering::SeqCst).then_some(4242))
3410 }
3411
3412 fn completed_successfully(&self, _attempt: &RunnerAttempt) -> bool {
3413 self.completed_successfully.load(Ordering::SeqCst)
3414 }
3415
3416 fn record_terminate_intent(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
3417 self.actions.lock().unwrap().push("terminate_intent");
3418 if self.intent_failure.load(Ordering::SeqCst) {
3419 return Err(FailureReason::Other(
3420 "terminate intent directory sync failed".into(),
3421 ));
3422 }
3423 self.intent.store(true, Ordering::SeqCst);
3424 Ok(())
3425 }
3426
3427 fn has_terminate_intent(&self, _attempt: &RunnerAttempt) -> bool {
3428 self.intent.load(Ordering::SeqCst)
3429 }
3430
3431 fn terminate(&self, _attempt: &RunnerAttempt) -> Result<(), FailureReason> {
3432 assert!(
3433 self.intent.load(Ordering::SeqCst),
3434 "the durable intent must exist before signalling"
3435 );
3436 self.actions.lock().unwrap().push("terminate");
3437 self.terminations.fetch_add(1, Ordering::SeqCst);
3438 self.alive.store(false, Ordering::SeqCst);
3439 Ok(())
3440 }
3441 }
3442
3443 #[derive(Debug, Default)]
3444 struct FakeDemand {
3445 answers: Mutex<VecDeque<bool>>,
3446 }
3447
3448 impl FakeDemand {
3449 fn answering(answers: impl IntoIterator<Item = bool>) -> Self {
3450 Self {
3451 answers: Mutex::new(answers.into_iter().collect()),
3452 }
3453 }
3454 }
3455
3456 #[async_trait]
3457 impl DemandPersistence for FakeDemand {
3458 async fn persists(&self, _policy: PolicyId) -> bool {
3459 self.answers.lock().unwrap().pop_front().unwrap_or(true)
3460 }
3461 }
3462
3463 #[derive(Debug, Default)]
3464 struct FakeDelay(Mutex<Vec<Duration>>);
3465
3466 #[async_trait]
3467 impl RetryDelay for FakeDelay {
3468 async fn wait(&self, duration: Duration) {
3469 self.0.lock().unwrap().push(duration);
3470 }
3471 }
3472
3473 struct Harness {
3474 _root: tempfile::TempDir,
3475 app_paths: runner_manager_platform::paths::AppPaths,
3476 launcher: LifecycleLauncher,
3477 demand: Arc<dyn DemandPersistence>,
3478 store: Arc<SqliteStore>,
3479 github: Arc<FakeGithubLifecycle>,
3480 packages: Arc<FakePackages>,
3481 processes: Arc<FakeProcesses>,
3482 clock: Arc<FakeClock>,
3483 events: Arc<AttemptEventLog>,
3484 reconcile_events: Arc<crate::reconcile::EventLog>,
3485 delay: Arc<FakeDelay>,
3486 host: runner_manager_domain::model::Host,
3487 policy: ScalePolicy,
3488 allocation_lock: InProcessAllocationLock,
3489 workspace_root: Option<LocalAbsolutePath>,
3491 }
3492
3493 impl Harness {
3494 fn new(github: FakeGithubLifecycle, demand: Arc<dyn DemandPersistence>) -> Self {
3495 let root = tempfile::tempdir().unwrap();
3496 let paths = runner_manager_platform::paths::AppPaths::rooted_at(root.path());
3497 paths.create_all().unwrap();
3498 let policy = fixtures::policy()
3499 .repository("octo/repo")
3500 .autoscale("home", 2)
3501 .active()
3502 .build();
3503 let host = fixtures::host().build();
3504 let store = Arc::new(SqliteStore::open_in_memory().unwrap());
3505 store.put_host(&host).unwrap();
3506 let github = Arc::new(github);
3507 let packages = Arc::new(FakePackages::default());
3508 let processes = Arc::new(FakeProcesses::default());
3509 let clock = Arc::new(FakeClock::default());
3510 let events = Arc::new(AttemptEventLog::default());
3511 let reconcile_events = Arc::new(crate::reconcile::EventLog::new());
3512 let delay = Arc::new(FakeDelay::default());
3513 let ports = LifecyclePorts {
3514 store: Arc::clone(&store) as Arc<dyn Store>,
3515 github: Arc::clone(&github) as Arc<dyn LifecycleGithub>,
3516 packages: Arc::clone(&packages) as Arc<dyn RuntimePackages>,
3517 processes: Arc::clone(&processes) as Arc<dyn ProcessSupervisor>,
3518 clock: Arc::clone(&clock) as Arc<dyn Clock>,
3519 demand: Arc::clone(&demand),
3520 delay: Arc::clone(&delay) as Arc<dyn RetryDelay>,
3521 events: Arc::clone(&events) as Arc<dyn AttemptEventSink>,
3522 reconcile_events: Arc::clone(&reconcile_events) as Arc<dyn EventSink>,
3523 };
3524 let launcher = Self::launcher_over(policy.host_id, &paths, ports);
3525 Self {
3526 _root: root,
3527 app_paths: paths,
3528 launcher,
3529 demand,
3530 store,
3531 github,
3532 packages,
3533 processes,
3534 clock,
3535 events,
3536 reconcile_events,
3537 delay,
3538 host,
3539 policy,
3540 allocation_lock: InProcessAllocationLock::new(),
3541 workspace_root: None,
3542 }
3543 }
3544
3545 fn with_host_runner_root(mut self) -> Self {
3552 let host_root = self.host_root();
3553 fs::create_dir_all(&host_root).unwrap();
3554 self.host.runner_root_override = Some(
3555 LocalAbsolutePath::new(host_root.to_str().expect("a UTF-8 temporary path"))
3556 .expect("a local absolute host root"),
3557 );
3558 self.store.put_host(&self.host).unwrap();
3559 self
3560 }
3561
3562 fn with_persistent_workspace(mut self, capacity: u16) -> Self {
3564 self = self.with_host_runner_root();
3565 let root = self._root.path().join("persist");
3566 let root = LocalAbsolutePath::new(root.to_str().expect("a UTF-8 temporary path"))
3567 .expect("a local absolute workspace root");
3568 self.policy = fixtures::policy()
3569 .repository("octo/repo")
3570 .autoscale("home", capacity)
3571 .active()
3572 .build();
3573 self.policy
3574 .set_workspace_policy(
3575 WorkspacePolicy::persistent(root.clone(), TargetScope::Repository)
3576 .expect("a repository may be persistent"),
3577 )
3578 .expect("a repository may be persistent");
3579 self.workspace_root = Some(root);
3580 self.store.insert_policy(&self.policy).unwrap();
3583 self
3584 }
3585
3586 fn workspace_root(&self) -> &LocalAbsolutePath {
3587 self.workspace_root
3588 .as_ref()
3589 .expect("this harness configured a persistent workspace")
3590 }
3591
3592 fn slot_path(&self, slot: u16) -> PathBuf {
3593 self.workspace_root().as_path().join(format!("s{slot}"))
3594 }
3595
3596 fn host_root(&self) -> PathBuf {
3597 self._root.path().join("host-root")
3598 }
3599
3600 fn attempt(&self, id: AttemptId) -> RunnerAttempt {
3601 self.store
3602 .attempt(id)
3603 .unwrap()
3604 .expect("the attempt is journalled")
3605 }
3606
3607 fn conclude(&self, id: AttemptId) -> RunnerAttempt {
3609 let mut attempt = self.attempt(id);
3610 attempt
3611 .conclude(
3612 AttemptOutcome::failed(FailureReason::ProcessExitedUnexpectedly),
3613 self.clock.now(),
3614 )
3615 .unwrap();
3616 self.store.record_attempt(&attempt).unwrap();
3617 attempt
3618 }
3619
3620 async fn cleanup_retaining_work(&self, id: AttemptId) {
3621 self.conclude(id);
3622 self.launcher
3623 .clean(id)
3624 .await
3625 .expect("the slot is scrubbed and the lease released");
3626 }
3627
3628 fn launcher_over(
3631 host: HostId,
3632 paths: &runner_manager_platform::paths::AppPaths,
3633 ports: LifecyclePorts,
3634 ) -> LifecycleLauncher {
3635 LifecycleLauncher::new(
3636 host,
3637 paths.clone(),
3638 paths.logs_dir(),
3639 1,
3640 RecoveryTimeouts::new(
3641 Elapsed::seconds(10),
3642 Elapsed::seconds(10),
3643 Elapsed::seconds(10),
3644 ),
3645 RetryPolicy::bounded(3, Duration::from_millis(10), Duration::from_millis(25)),
3646 ports,
3647 )
3648 }
3649
3650 fn restart(&self) -> LifecycleLauncher {
3653 Self::launcher_over(
3654 self.policy.host_id,
3655 &self.app_paths,
3656 LifecyclePorts {
3657 store: Arc::clone(&self.store) as Arc<dyn Store>,
3658 github: Arc::clone(&self.github) as Arc<dyn LifecycleGithub>,
3659 packages: Arc::clone(&self.packages) as Arc<dyn RuntimePackages>,
3660 processes: Arc::clone(&self.processes) as Arc<dyn ProcessSupervisor>,
3661 clock: Arc::clone(&self.clock) as Arc<dyn Clock>,
3662 demand: Arc::clone(&self.demand),
3663 delay: Arc::clone(&self.delay) as Arc<dyn RetryDelay>,
3664 events: Arc::clone(&self.events) as Arc<dyn AttemptEventSink>,
3665 reconcile_events: Arc::clone(&self.reconcile_events) as Arc<dyn EventSink>,
3666 },
3667 )
3668 }
3669
3670 async fn ready(&self) {
3671 self.launcher
3672 .recover_startup(std::slice::from_ref(&self.policy))
3673 .await
3674 .unwrap();
3675 }
3676
3677 async fn launch(&self) -> RunnerAttempt {
3678 self.launch_result().await.unwrap()
3679 }
3680
3681 async fn launch_result(&self) -> Result<RunnerAttempt, LaunchFailure> {
3682 let guard = self.allocation_lock.acquire().await.unwrap();
3683 self.launcher
3684 .launch(LaunchRequest {
3685 host: &self.host,
3686 policy: &self.policy,
3687 allocation_guard: &guard,
3688 })
3689 .await
3690 }
3691
3692 fn only_attempt(&self) -> RunnerAttempt {
3693 self.store.attempts().unwrap().into_iter().next().unwrap()
3694 }
3695 }
3696
3697 #[tokio::test]
3706 async fn a_root_that_refuses_a_launch_is_recorded_and_cleared_when_one_succeeds() {
3707 use runner_manager_platform::service::{clear_runner_root_refusal, runner_root_refusals};
3708
3709 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
3710 .with_host_runner_root();
3711 harness.ready().await;
3712
3713 let unusable = harness
3717 ._root
3718 .path()
3719 .join("absent")
3720 .join("deeper")
3721 .join("runners");
3722 let mut host = harness.host.clone();
3723 host.runner_root_override = Some(
3724 LocalAbsolutePath::new(unusable.to_str().expect("a UTF-8 temporary path"))
3725 .expect("a local absolute host root"),
3726 );
3727 harness.store.put_host(&host).unwrap();
3728
3729 let failure = harness
3730 .launch_result()
3731 .await
3732 .expect_err("a root whose parents are missing cannot hold a runner");
3733 assert!(
3734 matches!(failure.reason, FailureReason::Other(_)),
3735 "{failure:?}"
3736 );
3737
3738 let refusals = runner_root_refusals(&harness.app_paths).expect("readable");
3739 let refusal = refusals
3740 .first()
3741 .expect("the refusal reached the one surface that can hold it");
3742 assert_eq!(refusal.policy, harness.policy.id.to_string());
3743 assert_eq!(refusal.kind, "missing_parents");
3744 assert!(
3745 refusal.root.contains("runners") && refusal.detail.contains("runners"),
3746 "the directory must be named in full: {refusal:?}"
3747 );
3748
3749 harness.store.put_host(&harness.host).unwrap();
3752 harness.launch().await;
3753 assert!(
3754 runner_root_refusals(&harness.app_paths)
3755 .expect("readable")
3756 .is_empty(),
3757 "a successful placement clears that policy's record"
3758 );
3759
3760 clear_runner_root_refusal(&harness.app_paths, &harness.policy.id.to_string())
3761 .expect("cleanup");
3762 }
3763
3764 #[tokio::test]
3765 async fn a_job_walks_every_state_and_cleans_every_artifact() {
3766 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
3767 harness.ready().await;
3768 let started = harness.launch().await;
3769 assert_eq!(started.state(), AttemptState::Starting);
3770 assert_eq!(read_runner_id(started.runtime_path()), Some(73));
3771
3772 harness
3773 .github
3774 .observe(GithubRunnerObservation::Registered { busy: false });
3775 harness.launcher.supervise(&harness.policy).await.unwrap();
3776 assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
3777
3778 harness
3779 .github
3780 .observe(GithubRunnerObservation::Registered { busy: true });
3781 harness.launcher.supervise(&harness.policy).await.unwrap();
3782 assert_eq!(harness.only_attempt().state(), AttemptState::Busy);
3783
3784 harness.processes.finish_successfully();
3785 harness
3786 .github
3787 .observe(GithubRunnerObservation::NotRegistered);
3788 harness.launcher.supervise(&harness.policy).await.unwrap();
3789 let cleaned = harness.only_attempt();
3790 assert_eq!(cleaned.state(), AttemptState::Cleaned);
3791 assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
3792 assert!(!started.runtime_path().exists());
3793 assert_eq!(harness.packages.releases.load(Ordering::SeqCst), 1);
3794 assert_eq!(harness.github.remaining_runners.load(Ordering::SeqCst), 0);
3795
3796 let states: Vec<_> = harness
3797 .events
3798 .events()
3799 .into_iter()
3800 .filter_map(|event| match event {
3801 AttemptEvent::State { state, .. } => Some(state),
3802 _ => None,
3803 })
3804 .collect();
3805 assert_eq!(
3806 states,
3807 vec![
3808 AttemptState::Allocated,
3809 AttemptState::JitReceived,
3810 AttemptState::Starting,
3811 AttemptState::Idle,
3812 AttemptState::Busy,
3813 AttemptState::Finished,
3814 AttemptState::Cleaned,
3815 ]
3816 );
3817 }
3818
3819 #[tokio::test]
3820 async fn an_idle_exit_is_not_a_failure_in_the_journal_or_events() {
3821 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
3822 harness.ready().await;
3823 let started = harness.launch().await;
3824 harness
3825 .github
3826 .observe(GithubRunnerObservation::Registered { busy: false });
3827 harness.launcher.supervise(&harness.policy).await.unwrap();
3828 harness.clock.advance_secs(11);
3829 harness.processes.set_alive(false);
3830 harness
3831 .github
3832 .observe(GithubRunnerObservation::NotRegistered);
3833 harness.launcher.supervise(&harness.policy).await.unwrap();
3834
3835 let cleaned = harness.only_attempt();
3836 assert!(cleaned.outcome().unwrap().is_idle_exit());
3837 assert!(!cleaned.outcome().unwrap().is_failure());
3838 assert!(!started.runtime_path().exists());
3839 assert!(
3840 harness
3841 .reconcile_events
3842 .events()
3843 .iter()
3844 .any(|event| matches!(
3845 event,
3846 LifecycleEvent::AttemptCleaned {
3847 outcome: OutcomeKind::IdleExit,
3848 ..
3849 }
3850 ))
3851 );
3852 assert!(!harness.events.events().iter().any(|event| matches!(
3853 event,
3854 AttemptEvent::Concluded {
3855 outcome: OutcomeKind::Failed,
3856 ..
3857 }
3858 )));
3859 }
3860
3861 #[tokio::test]
3862 async fn handoff_is_absent_after_success_and_every_failed_spawn_retry() {
3863 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
3864 harness.processes.fail_spawns(2);
3865 harness.ready().await;
3866 let attempt = harness.launch().await;
3867 assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 3);
3868 assert!(harness.processes.saw_secret.load(Ordering::SeqCst));
3869 let names: Vec<_> = fs::read_dir(attempt.runtime_path())
3870 .unwrap()
3871 .map(|entry| entry.unwrap().file_name())
3872 .collect();
3873 assert!(
3874 names.iter().all(|name| {
3875 !name
3876 .to_string_lossy()
3877 .starts_with(RestrictiveHandoff::NAME_PREFIX)
3878 }),
3879 "JIT artifact survived: {names:?}"
3880 );
3881 assert_eq!(
3882 *harness.delay.0.lock().unwrap(),
3883 vec![Duration::from_millis(10), Duration::from_millis(20)]
3884 );
3885 }
3886
3887 #[tokio::test]
3888 async fn jit_retry_stops_with_demand_and_a_terminal_403_never_retries() {
3889 let gone = Harness::new(
3890 FakeGithubLifecycle::default().fail(false),
3891 Arc::new(FakeDemand::answering([false])),
3892 );
3893 gone.ready().await;
3894 assert!(gone.launch_result().await.is_err());
3895 assert_eq!(gone.github.registrations.load(Ordering::SeqCst), 1);
3896 assert!(gone.delay.0.lock().unwrap().is_empty());
3897
3898 let forbidden = Harness::new(
3899 FakeGithubLifecycle::default().fail(true),
3900 Arc::new(PersistentDemand),
3901 );
3902 forbidden.ready().await;
3903 assert!(forbidden.launch_result().await.is_err());
3904 assert_eq!(forbidden.github.registrations.load(Ordering::SeqCst), 1);
3905 assert!(forbidden.delay.0.lock().unwrap().is_empty());
3906 assert!(matches!(
3907 forbidden.only_attempt().outcome(),
3908 Some(AttemptOutcome::Failed {
3909 reason: FailureReason::Other(action)
3910 }) if action.contains("403")
3911 ));
3912
3913 let transient = Harness::new(
3914 FakeGithubLifecycle::default().fail(false).fail(false),
3915 Arc::new(PersistentDemand),
3916 );
3917 transient.ready().await;
3918 transient.launch().await;
3919 assert_eq!(transient.github.registrations.load(Ordering::SeqCst), 3);
3920 assert_eq!(
3921 *transient.delay.0.lock().unwrap(),
3922 vec![Duration::from_millis(10), Duration::from_millis(20)]
3923 );
3924 }
3925
3926 #[test]
3934 fn a_workspace_leaves_room_for_the_deepest_path_a_checkout_writes() {
3935 const MAX_PATH: usize = 260;
3936 let root = r"C:\Users\IvanD\AppData\Local\IvanMurzak\runner-manager\data\runtime";
3938 let repo = "GitHub-Runner-Scaler-UI";
3942 let deepest = format!(
3943 r"_work\{repo}\{repo}\.git\objects\pack\pack-{}.keep",
3944 "0".repeat(40)
3945 );
3946
3947 let name = workspace_name(AttemptId::new_random());
3948 assert_eq!(name.len(), WORKSPACE_NAME_LEN, "{name}");
3949 assert!(
3950 name.chars().all(|c| c.is_ascii_hexdigit()),
3951 "a directory name must not carry the identifier's dashes: {name}"
3952 );
3953
3954 let full = format!(r"{root}\{name}\{deepest}");
3955 assert!(
3956 full.len() < MAX_PATH,
3957 "the deepest path a checkout writes must fit: {} characters, limit {MAX_PATH}",
3958 full.len()
3959 );
3960
3961 let old = format!(
3964 r"{root}\{}\{}\{deepest}",
3965 PolicyId::new_random(),
3966 AttemptId::new_random()
3967 );
3968 assert!(
3969 old.len() > MAX_PATH,
3970 "the old layout is supposed to be the thing that did not fit: {} characters",
3971 old.len()
3972 );
3973 }
3974
3975 #[tokio::test]
3976 async fn two_attempts_never_share_a_workspace_even_after_failure() {
3977 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
3978 harness.ready().await;
3979 let first = harness.launch().await;
3980 fs::write(first.runtime_path().join("hostile-leftover"), b"first job").unwrap();
3981 harness
3982 .github
3983 .observe(GithubRunnerObservation::Registered { busy: false });
3984 harness.launcher.supervise(&harness.policy).await.unwrap();
3985 harness.clock.advance_secs(11);
3986 harness.processes.set_alive(false);
3987 harness
3988 .github
3989 .observe(GithubRunnerObservation::NotRegistered);
3990 harness.launcher.supervise(&harness.policy).await.unwrap();
3991 assert!(!first.runtime_path().exists());
3992
3993 let second = harness.launch().await;
3994 assert_ne!(first.runtime_path(), second.runtime_path());
3995 assert!(!second.runtime_path().join("hostile-leftover").exists());
3996
3997 fs::write(
3998 second.runtime_path().join("hostile-on-failure"),
3999 b"second job",
4000 )
4001 .unwrap();
4002 harness.processes.set_alive(false);
4003 harness
4004 .github
4005 .observe(GithubRunnerObservation::NotRegistered);
4006 harness.launcher.supervise(&harness.policy).await.unwrap();
4007 assert!(
4008 !second.runtime_path().exists(),
4009 "failed workspace was retained"
4010 );
4011 }
4012
4013 #[tokio::test]
4014 async fn a_runner_that_never_gets_a_job_is_stopped_deregistered_and_not_replaced() {
4015 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4016 harness.ready().await;
4017 let attempt = harness.launch().await;
4018
4019 harness
4023 .github
4024 .observe(GithubRunnerObservation::Registered { busy: false });
4025 harness.launcher.supervise(&harness.policy).await.unwrap();
4026 assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
4027
4028 harness.clock.advance_secs(9);
4031 harness
4032 .github
4033 .observe(GithubRunnerObservation::Registered { busy: false });
4034 let none_yet = harness.launcher.supervise(&harness.policy).await.unwrap();
4035 assert_eq!(harness.only_attempt().state(), AttemptState::Idle);
4036 assert!(none_yet.is_empty());
4037 assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 0);
4038
4039 harness.clock.advance_secs(1);
4041 harness
4042 .github
4043 .observe(GithubRunnerObservation::Registered { busy: false });
4044 let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4045
4046 let concluded = harness.store.attempt(attempt.id).unwrap().unwrap();
4047 assert_eq!(
4048 concluded.outcome(),
4049 Some(&AttemptOutcome::ExitedIdleWithoutWork),
4050 "a surplus runner did not fail; recording one as a failure sends an operator \
4051 hunting a fault that does not exist"
4052 );
4053 assert_eq!(concluded.state(), AttemptState::Cleaned);
4054 assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 1);
4055 assert!(!attempt.runtime_path().exists());
4056
4057 assert_eq!(
4060 *harness.github.deregistrations.lock().unwrap(),
4061 vec![73],
4062 "the attempt's own runner id, deleted exactly once"
4063 );
4064
4065 assert!(
4068 replacements.is_empty(),
4069 "a surplus exit must not request a replacement"
4070 );
4071 }
4072
4073 #[tokio::test]
4074 async fn a_registration_github_will_not_delete_still_concludes_the_attempt() {
4075 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4079 harness.ready().await;
4080 let attempt = harness.launch().await;
4081 harness
4082 .github
4083 .observe(GithubRunnerObservation::Registered { busy: false });
4084 harness.launcher.supervise(&harness.policy).await.unwrap();
4085
4086 harness
4087 .github
4088 .deregistration_fails
4089 .store(true, Ordering::SeqCst);
4090 harness.clock.advance_secs(11);
4091 harness
4092 .github
4093 .observe(GithubRunnerObservation::Registered { busy: false });
4094 harness.launcher.supervise(&harness.policy).await.unwrap();
4095
4096 assert_eq!(
4097 *harness.github.deregistrations.lock().unwrap(),
4098 vec![73],
4099 "the delete was attempted"
4100 );
4101 let concluded = harness.store.attempt(attempt.id).unwrap().unwrap();
4102 assert_eq!(
4103 concluded.outcome(),
4104 Some(&AttemptOutcome::ExitedIdleWithoutWork),
4105 "the attempt concluded anyway"
4106 );
4107 assert_eq!(concluded.state(), AttemptState::Cleaned);
4108 assert!(!attempt.runtime_path().exists());
4109 }
4110
4111 #[tokio::test]
4112 async fn exit_before_acceptance_returns_replacement_intent_without_launching() {
4113 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4114 harness.ready().await;
4115 let first = harness.launch().await;
4116 harness.processes.set_alive(false);
4117 harness
4118 .github
4119 .observe(GithubRunnerObservation::NotRegistered);
4120 let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4121 let failed = harness.store.attempt(first.id).unwrap().unwrap();
4122 assert!(matches!(
4123 failed.outcome(),
4124 Some(AttemptOutcome::Failed {
4125 reason: FailureReason::ProcessExitedUnexpectedly
4126 })
4127 ));
4128 assert!(!first.runtime_path().exists());
4129
4130 assert_eq!(
4131 replacements,
4132 vec![ReplacementIntent {
4133 policy: harness.policy.id,
4134 previous_attempt: first.id,
4135 operation: "exit_before_acceptance_replacement",
4136 }]
4137 );
4138 assert_eq!(harness.store.attempts().unwrap().len(), 1);
4139 assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
4140 assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
4141 assert!(harness.delay.0.lock().unwrap().is_empty());
4142 }
4143
4144 #[tokio::test]
4145 async fn expired_jit_is_removed_and_does_not_reregister_after_demand_disappears() {
4146 let harness = Harness::new(
4147 FakeGithubLifecycle::default(),
4148 Arc::new(FakeDemand::answering([false])),
4149 );
4150 let id = AttemptId::new_random();
4151 let runtime = harness
4152 .launcher
4153 .app_paths
4154 .runtime_dir()
4155 .join(harness.policy.id.to_string())
4156 .join(id.to_string());
4157 fs::create_dir_all(&runtime).unwrap();
4158 let mut attempt =
4159 RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4160 attempt.jit_received(harness.clock.now()).unwrap();
4161 harness.store.record_attempt(&attempt).unwrap();
4162 harness.clock.advance_secs(11);
4163 let replacements = harness
4164 .launcher
4165 .recover_startup(std::slice::from_ref(&harness.policy))
4166 .await
4167 .unwrap();
4168 assert_eq!(
4169 replacements,
4170 vec![ReplacementIntent {
4171 policy: harness.policy.id,
4172 previous_attempt: id,
4173 operation: "jit_expired_replacement",
4174 }]
4175 );
4176
4177 let cleaned = harness.store.attempt(id).unwrap().unwrap();
4178 assert_eq!(cleaned.state(), AttemptState::Cleaned);
4179 assert!(matches!(
4180 cleaned.outcome(),
4181 Some(AttemptOutcome::Failed {
4182 reason: FailureReason::JitExpired
4183 })
4184 ));
4185 assert!(!runtime.exists());
4186 assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
4187 assert!(harness.delay.0.lock().unwrap().is_empty());
4188 }
4189
4190 #[tokio::test]
4191 async fn expired_jit_returns_intent_but_never_launches_inside_lifecycle() {
4192 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4193 let id = AttemptId::new_random();
4194 let runtime = harness
4195 .launcher
4196 .app_paths
4197 .runtime_dir()
4198 .join("expired-with-demand");
4199 fs::create_dir_all(&runtime).unwrap();
4200 let mut attempt =
4201 RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4202 attempt.jit_received(harness.clock.now()).unwrap();
4203 harness.store.record_attempt(&attempt).unwrap();
4204 harness.clock.advance_secs(11);
4205 let replacements = harness
4206 .launcher
4207 .recover_startup(std::slice::from_ref(&harness.policy))
4208 .await
4209 .unwrap();
4210
4211 let attempts = harness.store.attempts().unwrap();
4212 assert_eq!(attempts.len(), 1);
4213 assert_eq!(
4214 attempts
4215 .iter()
4216 .find(|attempt| attempt.id == id)
4217 .unwrap()
4218 .state(),
4219 AttemptState::Cleaned
4220 );
4221 assert_eq!(
4222 replacements,
4223 vec![ReplacementIntent {
4224 policy: harness.policy.id,
4225 previous_attempt: id,
4226 operation: "jit_expired_replacement",
4227 }]
4228 );
4229 assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 0);
4230 assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
4231 assert!(harness.delay.0.lock().unwrap().is_empty());
4232 }
4233
4234 #[tokio::test]
4235 async fn package_materialization_retries_are_bounded_and_demand_adjacent() {
4236 let persistent = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4237 persistent.packages.fail_materializations(2);
4238 persistent.ready().await;
4239 persistent.launch().await;
4240 assert_eq!(
4241 persistent.packages.materializations.load(Ordering::SeqCst),
4242 3
4243 );
4244 assert_eq!(
4245 *persistent.delay.0.lock().unwrap(),
4246 vec![Duration::from_millis(10), Duration::from_millis(20)]
4247 );
4248
4249 let gone_before_wait = Harness::new(
4250 FakeGithubLifecycle::default(),
4251 Arc::new(FakeDemand::answering([false])),
4252 );
4253 gone_before_wait.packages.fail_materializations(3);
4254 gone_before_wait.ready().await;
4255 assert!(gone_before_wait.launch_result().await.is_err());
4256 assert_eq!(
4257 gone_before_wait
4258 .packages
4259 .materializations
4260 .load(Ordering::SeqCst),
4261 1
4262 );
4263 assert!(gone_before_wait.delay.0.lock().unwrap().is_empty());
4264
4265 let gone_during_wait = Harness::new(
4266 FakeGithubLifecycle::default(),
4267 Arc::new(FakeDemand::answering([true, false])),
4268 );
4269 gone_during_wait.packages.fail_materializations(3);
4270 gone_during_wait.ready().await;
4271 assert!(gone_during_wait.launch_result().await.is_err());
4272 assert_eq!(
4273 gone_during_wait
4274 .packages
4275 .materializations
4276 .load(Ordering::SeqCst),
4277 1
4278 );
4279 assert_eq!(
4280 *gone_during_wait.delay.0.lock().unwrap(),
4281 vec![Duration::from_millis(10)]
4282 );
4283 }
4284
4285 #[tokio::test]
4286 async fn replacement_is_intent_only_and_never_launches_inside_lifecycle() {
4287 let harness = Harness::new(
4288 FakeGithubLifecycle::default(),
4289 Arc::new(FakeDemand::answering([true, false])),
4290 );
4291 harness.ready().await;
4292 let first = harness.launch().await;
4293 harness.processes.set_alive(false);
4294 harness
4295 .github
4296 .observe(GithubRunnerObservation::NotRegistered);
4297 let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4298
4299 assert_eq!(harness.store.attempts().unwrap().len(), 1);
4300 assert_eq!(harness.github.registrations.load(Ordering::SeqCst), 1);
4301 assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
4302 assert!(harness.delay.0.lock().unwrap().is_empty());
4303 assert_eq!(
4304 replacements,
4305 vec![ReplacementIntent {
4306 policy: harness.policy.id,
4307 previous_attempt: first.id,
4308 operation: "exit_before_acceptance_replacement",
4309 }]
4310 );
4311 assert_eq!(
4312 harness.store.attempt(first.id).unwrap().unwrap().state(),
4313 AttemptState::Cleaned
4314 );
4315 }
4316
4317 #[tokio::test]
4318 async fn startup_adopts_a_live_process_and_refuses_launch_before_recovery() {
4319 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4320 let before = harness.launch_result().await;
4321 assert!(before.is_err());
4322 assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
4323
4324 let id = AttemptId::new_random();
4325 let runtime = harness.launcher.app_paths.runtime_dir().join("adopt");
4326 fs::create_dir_all(&runtime).unwrap();
4327 let mut attempt =
4328 RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
4329 attempt.jit_received(harness.clock.now()).unwrap();
4330 attempt.started(4242, harness.clock.now()).unwrap();
4331 harness.store.record_attempt(&attempt).unwrap();
4332 harness.processes.set_alive(true);
4333 harness
4334 .github
4335 .observe(GithubRunnerObservation::NotRegistered);
4336 let replacements = harness
4337 .launcher
4338 .recover_startup(std::slice::from_ref(&harness.policy))
4339 .await
4340 .unwrap();
4341 assert!(replacements.is_empty());
4342 assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 0);
4343 assert!(
4344 harness
4345 .events
4346 .events()
4347 .contains(&AttemptEvent::Adopted { attempt: id })
4348 );
4349 }
4350
4351 #[tokio::test]
4352 async fn spawn_before_starting_crash_recovers_pid_then_completes_and_cleans() {
4353 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4354 let id = AttemptId::new_random();
4355 let runtime = harness
4356 .launcher
4357 .app_paths
4358 .runtime_dir()
4359 .join("spawn-before-starting");
4360 fs::create_dir_all(&runtime).unwrap();
4361 let mut attempt =
4362 RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4363 attempt.jit_received(harness.clock.now()).unwrap();
4364 harness.store.record_attempt(&attempt).unwrap();
4365 harness.processes.set_alive(true);
4366 harness
4367 .github
4368 .observe(GithubRunnerObservation::Registered { busy: true });
4369
4370 let replacements = harness
4371 .launcher
4372 .recover_startup(std::slice::from_ref(&harness.policy))
4373 .await
4374 .unwrap();
4375 assert!(replacements.is_empty());
4376 let recovered = harness.store.attempt(id).unwrap().unwrap();
4377 assert_eq!(recovered.state(), AttemptState::Busy);
4378 assert_eq!(recovered.process_id(), Some(4242));
4379 assert_eq!(recovered.github_runner_id(), Some(73));
4380 let events = harness.events.events();
4381 let starting = events
4382 .iter()
4383 .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Starting } if *attempt == id))
4384 .unwrap();
4385 let busy = events
4386 .iter()
4387 .position(|event| matches!(event, AttemptEvent::State { attempt, state: AttemptState::Busy } if *attempt == id))
4388 .unwrap();
4389 assert!(starting < busy, "recovery skipped a legal edge: {events:?}");
4390
4391 harness.processes.finish_successfully();
4392 harness
4393 .github
4394 .observe(GithubRunnerObservation::NotRegistered);
4395 assert!(
4396 harness
4397 .launcher
4398 .supervise(&harness.policy)
4399 .await
4400 .unwrap()
4401 .is_empty()
4402 );
4403 let cleaned = harness.store.attempt(id).unwrap().unwrap();
4404 assert_eq!(cleaned.state(), AttemptState::Cleaned);
4405 assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::CompletedJob));
4406 assert!(!runtime.exists());
4407 }
4408
4409 #[tokio::test]
4410 async fn failed_post_spawn_stop_keeps_capacity_until_supervision_proves_death() {
4411 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4412 harness.processes.fail_spawn_with_live_child();
4413 harness.ready().await;
4414 assert!(harness.launch_result().await.is_err());
4415
4416 let attempt = harness.only_attempt();
4417 assert_eq!(attempt.state(), AttemptState::Starting);
4418 assert_eq!(attempt.process_id(), Some(4242));
4419 assert!(attempt.outcome().is_none());
4420 assert!(attempt.state().counts_against_capacity());
4421 assert_eq!(harness.processes.spawns.load(Ordering::SeqCst), 1);
4422 assert!(harness.delay.0.lock().unwrap().is_empty());
4423
4424 harness.processes.set_alive(false);
4425 harness
4426 .github
4427 .observe(GithubRunnerObservation::NotRegistered);
4428 let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4429 assert_eq!(replacements.len(), 1);
4430 assert_eq!(
4431 harness.store.attempt(attempt.id).unwrap().unwrap().state(),
4432 AttemptState::Cleaned
4433 );
4434 }
4435
4436 #[tokio::test]
4437 async fn remote_runner_identity_closes_both_sides_of_the_registration_crash_boundary() {
4438 for sidecar_already_present in [false, true] {
4439 let harness = Harness::new(
4440 FakeGithubLifecycle::default(),
4441 Arc::new(FakeDemand::answering([false])),
4442 );
4443 let id = AttemptId::new_random();
4444 let runtime =
4445 harness
4446 .launcher
4447 .app_paths
4448 .runtime_dir()
4449 .join(if sidecar_already_present {
4450 "after-id-sidecar"
4451 } else {
4452 "before-id-sidecar"
4453 });
4454 fs::create_dir_all(&runtime).unwrap();
4455 let mut attempt =
4456 RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4457 if sidecar_already_present {
4458 write_runner_id(&runtime, 73).unwrap();
4459 attempt.jit_received(harness.clock.now()).unwrap();
4460 }
4461 harness.store.record_attempt(&attempt).unwrap();
4462 harness.processes.set_alive(true);
4463 harness
4464 .github
4465 .observe(GithubRunnerObservation::Registered { busy: false });
4466 harness
4467 .launcher
4468 .recover_startup(std::slice::from_ref(&harness.policy))
4469 .await
4470 .unwrap();
4471
4472 assert_eq!(read_runner_id(&runtime), Some(73));
4473 assert!(
4474 harness
4475 .store
4476 .attempt(id)
4477 .unwrap()
4478 .unwrap()
4479 .outcome()
4480 .is_none()
4481 );
4482 let events = harness.events.events();
4483 let recovered = events.iter().position(|event| {
4484 matches!(
4485 event,
4486 AttemptEvent::RemoteIdentityRecovered {
4487 attempt,
4488 runner_id: 73
4489 } if *attempt == id
4490 )
4491 });
4492 assert_eq!(recovered.is_some(), !sidecar_already_present);
4493 if let Some(recovered) = recovered {
4494 let adopted = events
4495 .iter()
4496 .position(|event| matches!(event, AttemptEvent::Adopted { attempt } if *attempt == id))
4497 .unwrap();
4498 assert!(
4499 recovered < adopted,
4500 "identity was not durable before adoption: {events:?}"
4501 );
4502 }
4503 assert!(runtime.exists());
4504 }
4505 }
4506
4507 #[tokio::test]
4508 async fn recovery_stays_closed_for_unknown_policy_and_unreachable_attempts() {
4509 let unknown = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4510 let unknown_attempt = RunnerAttempt::allocate(
4511 AttemptId::new_random(),
4512 PolicyId::from_u128(0xfeed),
4513 unknown
4514 .launcher
4515 .app_paths
4516 .runtime_dir()
4517 .join("unknown-policy"),
4518 unknown.clock.now(),
4519 );
4520 unknown.store.record_attempt(&unknown_attempt).unwrap();
4521 let expired_id = AttemptId::new_random();
4522 let expired_runtime = unknown
4523 .launcher
4524 .app_paths
4525 .runtime_dir()
4526 .join("expired-beside-unknown");
4527 fs::create_dir_all(&expired_runtime).unwrap();
4528 let mut expired = RunnerAttempt::allocate(
4529 expired_id,
4530 unknown.policy.id,
4531 expired_runtime,
4532 unknown.clock.now(),
4533 );
4534 expired.jit_received(unknown.clock.now()).unwrap();
4535 unknown.store.record_attempt(&expired).unwrap();
4536 unknown.clock.advance_secs(11);
4537 assert!(matches!(
4538 unknown
4539 .launcher
4540 .recover_startup(std::slice::from_ref(&unknown.policy))
4541 .await,
4542 Err(LifecycleError::RecoveryIncomplete)
4543 ));
4544 assert!(unknown.launch_result().await.is_err());
4545 assert_eq!(unknown.processes.spawns.load(Ordering::SeqCst), 0);
4546 let recovered_policy = fixtures::policy()
4547 .id(PolicyId::from_u128(0xfeed))
4548 .repository("octo/repo")
4549 .autoscale("home", 2)
4550 .active()
4551 .build();
4552 let pending = unknown
4553 .launcher
4554 .recover_startup(&[unknown.policy.clone(), recovered_policy])
4555 .await
4556 .unwrap();
4557 assert_eq!(
4558 pending,
4559 vec![ReplacementIntent {
4560 policy: unknown.policy.id,
4561 previous_attempt: expired_id,
4562 operation: "jit_expired_replacement",
4563 }]
4564 );
4565 assert_eq!(unknown.processes.spawns.load(Ordering::SeqCst), 0);
4566
4567 let unreachable = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4568 let id = AttemptId::new_random();
4569 let runtime = unreachable
4570 .launcher
4571 .app_paths
4572 .runtime_dir()
4573 .join("unreachable");
4574 fs::create_dir_all(&runtime).unwrap();
4575 unreachable
4576 .store
4577 .record_attempt(&RunnerAttempt::allocate(
4578 id,
4579 unreachable.policy.id,
4580 runtime,
4581 unreachable.clock.now(),
4582 ))
4583 .unwrap();
4584 unreachable
4585 .github
4586 .observe(GithubRunnerObservation::Unreachable);
4587 assert!(matches!(
4588 unreachable
4589 .launcher
4590 .recover_startup(std::slice::from_ref(&unreachable.policy))
4591 .await,
4592 Err(LifecycleError::RecoveryIncomplete)
4593 ));
4594 assert!(unreachable.launch_result().await.is_err());
4595 assert_eq!(unreachable.processes.spawns.load(Ordering::SeqCst), 0);
4596 }
4597
4598 #[tokio::test]
4599 async fn a_dead_busy_process_unknown_to_github_is_orphaned_and_cleaned() {
4600 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4601 let id = AttemptId::new_random();
4602 let runtime = harness.launcher.app_paths.runtime_dir().join("orphan");
4603 fs::create_dir_all(&runtime).unwrap();
4604 let mut attempt =
4605 RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4606 attempt.jit_received(harness.clock.now()).unwrap();
4607 attempt.started(4242, harness.clock.now()).unwrap();
4608 attempt.assigned_job(73, harness.clock.now()).unwrap();
4609 harness.store.record_attempt(&attempt).unwrap();
4610 harness.processes.set_alive(false);
4611 harness
4612 .github
4613 .observe(GithubRunnerObservation::NotRegistered);
4614 harness
4615 .launcher
4616 .recover_startup(std::slice::from_ref(&harness.policy))
4617 .await
4618 .unwrap();
4619 let cleaned = harness.store.attempt(id).unwrap().unwrap();
4620 assert_eq!(cleaned.state(), AttemptState::Cleaned);
4621 assert_eq!(cleaned.outcome(), Some(&AttemptOutcome::Orphaned));
4622 assert!(!runtime.exists());
4623 }
4624
4625 #[tokio::test]
4626 async fn registration_timeout_journals_intent_stops_then_concludes_with_dead_reason() {
4627 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4628 harness.ready().await;
4629 let id = AttemptId::new_random();
4630 let runtime = harness.launcher.app_paths.runtime_dir().join("timeout");
4631 fs::create_dir_all(&runtime).unwrap();
4632 let mut attempt =
4633 RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
4634 attempt.jit_received(harness.clock.now()).unwrap();
4635 attempt.started(4242, harness.clock.now()).unwrap();
4636 harness.store.record_attempt(&attempt).unwrap();
4637 harness.clock.advance_secs(11);
4638 harness.processes.set_alive(true);
4639 harness
4640 .github
4641 .observe(GithubRunnerObservation::NotRegistered);
4642 let replacements = harness.launcher.supervise(&harness.policy).await.unwrap();
4643 assert_eq!(
4644 replacements,
4645 vec![ReplacementIntent {
4646 policy: harness.policy.id,
4647 previous_attempt: id,
4648 operation: "registration_timeout_replacement",
4649 }]
4650 );
4651
4652 assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 1);
4653 assert!(!harness.processes.alive.load(Ordering::SeqCst));
4654 let actions = harness.processes.actions.lock().unwrap().clone();
4655 let intent = actions
4656 .iter()
4657 .position(|action| *action == "terminate_intent")
4658 .unwrap();
4659 let signal = actions
4660 .iter()
4661 .position(|action| *action == "terminate")
4662 .unwrap();
4663 assert!(
4664 intent < signal,
4665 "intent was not durable before signal: {actions:?}"
4666 );
4667
4668 let cleaned = harness.store.attempt(id).unwrap().unwrap();
4669 assert!(matches!(
4670 cleaned.outcome(),
4671 Some(AttemptOutcome::Failed {
4672 reason: FailureReason::TerminatedAfterRegistrationTimeout
4673 })
4674 ));
4675 let events = harness.events.events();
4676 let intent = events
4677 .iter()
4678 .position(|event| matches!(event, AttemptEvent::TerminateIntent { .. }))
4679 .unwrap();
4680 let stopped = events
4681 .iter()
4682 .position(|event| matches!(event, AttemptEvent::Terminated { .. }))
4683 .unwrap();
4684 let concluded = events
4685 .iter()
4686 .position(|event| matches!(event, AttemptEvent::Concluded { .. }))
4687 .unwrap();
4688 assert!(intent < stopped && stopped < concluded, "{events:?}");
4689 }
4690
4691 #[tokio::test]
4692 async fn timeout_crash_recovery_returns_the_same_replacement_intent() {
4693 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4694 let id = AttemptId::new_random();
4695 let runtime = harness
4696 .launcher
4697 .app_paths
4698 .runtime_dir()
4699 .join("timeout-after-crash");
4700 fs::create_dir_all(&runtime).unwrap();
4701 let mut attempt =
4702 RunnerAttempt::allocate(id, harness.policy.id, runtime, harness.clock.now());
4703 attempt.jit_received(harness.clock.now()).unwrap();
4704 attempt.started(4242, harness.clock.now()).unwrap();
4705 harness.store.record_attempt(&attempt).unwrap();
4706 harness.processes.intent.store(true, Ordering::SeqCst);
4707 harness.processes.set_alive(false);
4708 harness
4709 .github
4710 .observe(GithubRunnerObservation::NotRegistered);
4711
4712 let replacements = harness
4713 .launcher
4714 .recover_startup(std::slice::from_ref(&harness.policy))
4715 .await
4716 .unwrap();
4717 assert_eq!(
4718 replacements,
4719 vec![ReplacementIntent {
4720 policy: harness.policy.id,
4721 previous_attempt: id,
4722 operation: "registration_timeout_replacement",
4723 }]
4724 );
4725 let consumed = RunnerLauncher::supervise(&harness.launcher, &harness.policy)
4726 .await
4727 .unwrap();
4728 assert_eq!(consumed, replacements);
4729 assert!(
4730 RunnerLauncher::supervise(&harness.launcher, &harness.policy)
4731 .await
4732 .unwrap()
4733 .is_empty(),
4734 "startup replacement evidence must be consumed exactly once by e1"
4735 );
4736 assert!(matches!(
4737 harness.store.attempt(id).unwrap().unwrap().outcome(),
4738 Some(AttemptOutcome::Failed {
4739 reason: FailureReason::TerminatedAfterRegistrationTimeout
4740 })
4741 ));
4742 }
4743
4744 #[tokio::test]
4745 async fn terminate_intent_sync_failure_prevents_signal_and_conclusion() {
4746 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4747 let id = AttemptId::new_random();
4748 let runtime = harness
4749 .launcher
4750 .app_paths
4751 .runtime_dir()
4752 .join("timeout-sync-failure");
4753 fs::create_dir_all(&runtime).unwrap();
4754 let mut attempt =
4755 RunnerAttempt::allocate(id, harness.policy.id, &runtime, harness.clock.now());
4756 attempt.jit_received(harness.clock.now()).unwrap();
4757 attempt.started(4242, harness.clock.now()).unwrap();
4758 harness.store.record_attempt(&attempt).unwrap();
4759 harness.clock.advance_secs(11);
4760 harness.processes.set_alive(true);
4761 harness.processes.fail_intent();
4762 harness
4763 .github
4764 .observe(GithubRunnerObservation::NotRegistered);
4765
4766 assert!(
4767 harness
4768 .launcher
4769 .recover_startup(std::slice::from_ref(&harness.policy))
4770 .await
4771 .is_err()
4772 );
4773 assert_eq!(harness.processes.terminations.load(Ordering::SeqCst), 0);
4774 assert!(harness.processes.alive.load(Ordering::SeqCst));
4775 assert_eq!(
4776 harness.store.attempt(id).unwrap().unwrap().state(),
4777 AttemptState::Starting
4778 );
4779 assert!(!harness.events.events().iter().any(|event| matches!(
4780 event,
4781 AttemptEvent::Terminated { attempt } | AttemptEvent::Concluded { attempt, .. }
4782 if *attempt == id
4783 )));
4784 }
4785
4786 #[tokio::test]
4787 async fn diagnostics_survive_cleanup_without_the_jit_or_a_token() {
4788 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
4789 harness.ready().await;
4790 let attempt = harness.launch().await;
4791 harness
4792 .github
4793 .observe(GithubRunnerObservation::Registered { busy: false });
4794 harness.launcher.supervise(&harness.policy).await.unwrap();
4795 harness.clock.advance_secs(11);
4796 harness.processes.set_alive(false);
4797 harness
4798 .github
4799 .observe(GithubRunnerObservation::NotRegistered);
4800 harness.launcher.supervise(&harness.policy).await.unwrap();
4801 let diagnostic = fs::read_to_string(
4802 harness
4803 .launcher
4804 .diagnostics_root
4805 .join(format!("{}.log", attempt.id)),
4806 )
4807 .unwrap();
4808 assert!(diagnostic.contains("exited_idle_without_work"));
4809 assert!(!diagnostic.contains(JIT));
4810 assert!(!diagnostic.contains("ghp_"));
4811 assert!(!attempt.runtime_path().exists());
4812 }
4813
4814 #[test]
4815 fn native_process_listing_never_contains_jit_and_handoffs_never_survive() {
4816 let root = tempfile::tempdir().unwrap();
4817 let policy = fixtures::policy()
4818 .repository("octo/repo")
4819 .autoscale("home", 1)
4820 .active()
4821 .build();
4822 let runtime = root.path().join("successful");
4823 fs::create_dir_all(&runtime).unwrap();
4824 let processes = NativeProcesses::new();
4825 let config = EncodedJitConfig::new(JIT);
4826 let handoff =
4827 RestrictiveHandoff::create(&runtime, SecretString::from(config.expose().to_owned()))
4828 .unwrap();
4829 let mut child = native_inspection_spec()
4830 .spawn_runner_with_handoff(&handoff)
4831 .expect("native child starts");
4832 let pid = child.pid();
4833 handoff.delete().unwrap();
4834 let command_line = native_command_line(pid);
4835 assert!(
4836 !command_line.contains(JIT),
4837 "the encoded JIT configuration appeared in the native process listing"
4838 );
4839 assert_no_jit_file(&runtime);
4840 child
4841 .stop(Duration::from_secs(1))
4842 .expect("native child stops");
4843
4844 let failed_runtime = root.path().join("failed");
4845 fs::create_dir_all(&failed_runtime).unwrap();
4846 let failed = RunnerAttempt::allocate(
4847 AttemptId::new_random(),
4848 policy.id,
4849 &failed_runtime,
4850 FakeClock::default().now(),
4851 );
4852 assert!(
4853 processes
4854 .spawn(&failed, &EncodedJitConfig::new(JIT))
4855 .is_err(),
4856 "a runtime with no runner executable must fail"
4857 );
4858 assert_no_jit_file(&failed_runtime);
4859 processes
4860 .record_terminate_intent(&failed)
4861 .expect("the intent file and its directory entry are durably synced");
4862 assert_eq!(
4863 fs::read(NativeProcesses::intent_path(&failed)).unwrap(),
4864 b"registration-timeout\n"
4865 );
4866 }
4867
4868 #[test]
4869 fn post_spawn_boundaries_are_bounded_durable_and_never_retry_jit() {
4870 let root = tempfile::tempdir().unwrap();
4871 let policy = fixtures::policy()
4872 .repository("octo/repo")
4873 .autoscale("home", 1)
4874 .active()
4875 .build();
4876 let processes = NativeProcesses::new();
4877 processes.use_long_lived_test_listener();
4878 for (index, boundary) in [
4879 PostSpawnBoundary::HandoffDelete,
4880 PostSpawnBoundary::IdentitySerialize,
4881 PostSpawnBoundary::IdentityWrite,
4882 PostSpawnBoundary::ChildMapInsert,
4883 ]
4884 .into_iter()
4885 .enumerate()
4886 {
4887 let runtime = root.path().join(format!("post-spawn-{index}"));
4888 let bin = runtime.join("bin");
4889 fs::create_dir_all(&bin).unwrap();
4890 #[cfg(windows)]
4891 let listener = bin.join("Runner.Listener.exe");
4892 #[cfg(not(windows))]
4893 let listener = bin.join("Runner.Listener");
4894 fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
4895 let attempt = RunnerAttempt::allocate(
4896 AttemptId::new_random(),
4897 policy.id,
4898 &runtime,
4899 FakeClock::default().now(),
4900 );
4901 processes.fail_post_spawn_at(boundary);
4902 let failure = processes
4903 .spawn(&attempt, &EncodedJitConfig::new(JIT))
4904 .expect_err("fault must cross the post-spawn cleanup path");
4905 assert!(!failure.retryable, "{boundary:?} allowed duplicate retry");
4906 assert!(
4907 !processes.is_alive(&attempt).unwrap(),
4908 "{boundary:?} left a child"
4909 );
4910 assert!(!NativeProcesses::identity_path(&attempt).exists());
4911 assert_no_jit_file(&runtime);
4912 }
4913 assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
4914
4915 let runtime = root.path().join("identity-and-stop-fail");
4916 let bin = runtime.join("bin");
4917 fs::create_dir_all(&bin).unwrap();
4918 #[cfg(windows)]
4919 let listener = bin.join("Runner.Listener.exe");
4920 #[cfg(not(windows))]
4921 let listener = bin.join("Runner.Listener");
4922 fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
4923 let attempt = RunnerAttempt::allocate(
4924 AttemptId::new_random(),
4925 policy.id,
4926 &runtime,
4927 FakeClock::default().now(),
4928 );
4929 processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
4933 processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
4934 processes.fail_next_post_spawn_stop();
4935 let failure = processes
4936 .spawn(&attempt, &EncodedJitConfig::new(JIT))
4937 .expect_err("the identity boundary must fail closed");
4938 assert!(failure.live_pid.is_some());
4939 assert_long_lived_listener_ready(&processes, &attempt);
4940 assert!(processes.is_alive(&attempt).unwrap());
4941 assert!(!NativeProcesses::identity_path(&attempt).exists());
4942 assert!(NativeProcesses::fallback_identity_path(&attempt).is_file());
4943 assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
4944 processes.terminate(&attempt).unwrap();
4945
4946 let runtime = root.path().join("persistent-stop-and-identity-failures");
4947 let bin = runtime.join("bin");
4948 fs::create_dir_all(&bin).unwrap();
4949 #[cfg(windows)]
4950 let listener = bin.join("Runner.Listener.exe");
4951 #[cfg(not(windows))]
4952 let listener = bin.join("Runner.Listener");
4953 fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
4954 let mut unresolved = RunnerAttempt::allocate(
4955 AttemptId::new_random(),
4956 policy.id,
4957 &runtime,
4958 FakeClock::default().now(),
4959 );
4960 for _ in 0..3 {
4961 processes.fail_post_spawn_at(PostSpawnBoundary::IdentityWrite);
4962 }
4963 processes.fail_post_spawn_stops(MAX_POST_SPAWN_STOP_ATTEMPTS);
4964 let failure = processes
4965 .spawn(&unresolved, &EncodedJitConfig::new(JIT))
4966 .expect_err("bounded cleanup must return even when every stop errors");
4967 let pid = failure
4968 .live_pid
4969 .expect("the owned child remains supervised in this invocation");
4970 assert!(matches!(failure.reason, FailureReason::Other(_)));
4971 assert_long_lived_listener_ready(&processes, &unresolved);
4972 unresolved.jit_received(FakeClock::default().now()).unwrap();
4973 unresolved.started(pid, FakeClock::default().now()).unwrap();
4974 let journal = SqliteStore::open_in_memory().unwrap();
4975 journal.record_attempt(&unresolved).unwrap();
4976 let recovered = journal.attempt(unresolved.id).unwrap().unwrap();
4977 assert_eq!(recovered.process_id(), Some(pid));
4978 assert_eq!(recovered.state(), AttemptState::Starting);
4979 assert!(processes.is_alive(&unresolved).unwrap());
4980 assert!(!NativeProcesses::identity_path(&unresolved).exists());
4981 assert!(!NativeProcesses::fallback_identity_path(&unresolved).exists());
4982 assert_eq!(
4983 fs::read_to_string(NativeProcesses::unresolved_process_path(&unresolved)).unwrap(),
4984 pid.to_string(),
4985 "bounded cleanup must leave durable unresolved-process evidence before returning"
4986 );
4987 assert!(
4988 NativeProcesses::new().is_alive(&recovered).is_err(),
4989 "restart must fail closed on the durable starting/PID journal rather than trust a bare PID"
4990 );
4991 processes.terminate(&unresolved).unwrap();
4992
4993 let runtime = root.path().join("post-spawn-stop-failed");
4994 let bin = runtime.join("bin");
4995 fs::create_dir_all(&bin).unwrap();
4996 #[cfg(windows)]
4997 let listener = bin.join("Runner.Listener.exe");
4998 #[cfg(not(windows))]
4999 let listener = bin.join("Runner.Listener");
5000 fs::copy(std::env::current_exe().unwrap(), &listener).unwrap();
5001 let attempt = RunnerAttempt::allocate(
5002 AttemptId::new_random(),
5003 policy.id,
5004 &runtime,
5005 FakeClock::default().now(),
5006 );
5007 processes.fail_post_spawn_at(PostSpawnBoundary::ChildMapInsert);
5008 processes.fail_next_post_spawn_stop();
5009 let failure = processes
5010 .spawn(&attempt, &EncodedJitConfig::new(JIT))
5011 .expect_err("the injected stop failure must preserve supervision");
5012 let live_pid = failure
5013 .live_pid
5014 .expect("live PID is returned to the journal");
5015 assert!(!failure.retryable);
5016 assert_long_lived_listener_ready(&processes, &attempt);
5017 assert!(NativeProcesses::identity_path(&attempt).is_file());
5018 assert_eq!(
5019 NativeProcesses::read_identity(&attempt)
5020 .unwrap()
5021 .unwrap()
5022 .pid(),
5023 live_pid
5024 );
5025 assert_eq!(processes.post_spawn_reaps.load(Ordering::SeqCst), 4);
5026 processes.terminate(&attempt).unwrap();
5027 }
5028
5029 #[test]
5030 #[ignore = "spawned only as the platform-stable native listener fixture"]
5031 fn long_lived_native_listener_helper() {
5032 let ready = std::env::var_os("RUNNER_MANAGER_TEST_LISTENER_READY")
5033 .map(PathBuf::from)
5034 .expect("the parent supplies the readiness path");
5035 fs::write(ready, b"ready\n").expect("the listener publishes readiness");
5036 std::thread::sleep(Duration::from_secs(30));
5037 }
5038
5039 fn assert_long_lived_listener_ready(processes: &NativeProcesses, attempt: &RunnerAttempt) {
5040 let ready = attempt.runtime_path().join(TEST_LISTENER_READY);
5041 let deadline = std::time::Instant::now() + Duration::from_secs(5);
5042 loop {
5043 if ready.is_file() {
5044 assert_eq!(fs::read(&ready).unwrap(), b"ready\n");
5045 return;
5046 }
5047 assert!(
5048 processes.is_alive(attempt).unwrap(),
5049 "the native listener exited before publishing readiness"
5050 );
5051 assert!(
5052 std::time::Instant::now() < deadline,
5053 "the native listener stayed alive but never published readiness"
5054 );
5055 std::thread::sleep(Duration::from_millis(10));
5056 }
5057 }
5058
5059 #[tokio::test]
5060 async fn every_production_launch_prunes_under_the_same_allocation_guard() {
5061 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
5062 harness.ready().await;
5063 assert_eq!(harness.packages.prunes.load(Ordering::SeqCst), 0);
5064 harness.launch().await;
5065 assert_eq!(harness.packages.prunes.load(Ordering::SeqCst), 1);
5066 assert_eq!(
5067 *harness.packages.prune_currents.lock().unwrap(),
5068 vec![harness.packages.version.clone()],
5069 "the leased current version is an exclusion, never the prune target"
5070 );
5071 }
5072
5073 fn assert_no_jit_file(runtime: &Path) {
5074 for entry in fs::read_dir(runtime).unwrap() {
5075 let path = entry.unwrap().path();
5076 if path.is_file() {
5077 let bytes = fs::read(&path).unwrap();
5078 assert!(
5079 !bytes
5080 .windows(JIT.len())
5081 .any(|window| window == JIT.as_bytes()),
5082 "a JIT payload survived in a runtime file"
5083 );
5084 }
5085 }
5086 }
5087
5088 #[test]
5089 fn production_listener_command_uses_the_supported_jit_contract() {
5090 let runtime = Path::new("runtime");
5091 let spec = runner_listener_spec(PathBuf::from("Runner.Listener"), runtime);
5092 let arguments: Vec<_> = spec
5093 .arguments()
5094 .iter()
5095 .map(|argument| argument.to_string_lossy().into_owned())
5096 .collect();
5097
5098 assert_eq!(arguments, ["run"]);
5099 assert!(
5100 !arguments
5101 .iter()
5102 .any(|argument| argument == "--jit-config-file"),
5103 "the obsolete file option would be rejected by Runner.Listener 2.336.0"
5104 );
5105 }
5106
5107 #[cfg(windows)]
5108 fn native_inspection_spec() -> SpawnSpec {
5109 SpawnSpec::new("powershell.exe").args([
5110 "-NoProfile",
5111 "-NonInteractive",
5112 "-Command",
5113 "Start-Sleep -Seconds 30",
5114 ])
5115 }
5116
5117 #[cfg(unix)]
5118 fn native_inspection_spec() -> SpawnSpec {
5119 SpawnSpec::new("/bin/sh").args(["-c", "sleep 30"])
5120 }
5121
5122 #[cfg(windows)]
5123 fn native_command_line(pid: u32) -> String {
5124 let output = std::process::Command::new("powershell.exe")
5125 .args([
5126 "-NoProfile",
5127 "-NonInteractive",
5128 "-Command",
5129 &format!("(Get-CimInstance Win32_Process -Filter 'ProcessId = {pid}').CommandLine"),
5130 ])
5131 .output()
5132 .expect("PowerShell can inspect the native child");
5133 assert!(output.status.success(), "native process inspection failed");
5134 String::from_utf8(output.stdout).expect("Windows command lines are Unicode")
5135 }
5136
5137 #[cfg(target_os = "linux")]
5138 fn native_command_line(pid: u32) -> String {
5139 fs::read(format!("/proc/{pid}/cmdline"))
5140 .map(|bytes| String::from_utf8_lossy(&bytes).replace('\0', " "))
5141 .expect("/proc exposes the native child command line")
5142 }
5143
5144 #[cfg(target_os = "macos")]
5145 fn native_command_line(pid: u32) -> String {
5146 let output = std::process::Command::new("ps")
5147 .args(["-o", "command=", "-p", &pid.to_string()])
5148 .output()
5149 .expect("ps can inspect the native child");
5150 assert!(output.status.success(), "native process inspection failed");
5151 String::from_utf8(output.stdout).expect("the command line is UTF-8")
5152 }
5153
5154 #[tokio::test]
5157 async fn a_persistent_repository_leases_s1_and_journals_it_before_any_github_effect() {
5158 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5159 .with_persistent_workspace(2);
5160 harness.github.watch_journal(Arc::clone(&harness.store));
5161 harness.ready().await;
5162
5163 let attempt = harness.launch().await;
5164
5165 assert_eq!(
5166 attempt.workspace(),
5167 AttemptWorkspace::persistent_slot(nz(1)),
5168 "the lowest free slot is leased"
5169 );
5170 assert_eq!(attempt.runtime_path(), harness.slot_path(1));
5171 assert!(attempt.holds_slot_lease());
5172 assert_eq!(
5174 harness.attempt(attempt.id).runtime_path(),
5175 harness.slot_path(1)
5176 );
5177
5178 let facts = harness.github.registration_facts();
5182 assert_eq!(facts.len(), 1);
5183 assert_eq!(
5184 facts[0].leased_slots,
5185 vec![1],
5186 "the lease was journalled first"
5187 );
5188 assert_eq!(facts[0].work_folder, DEFAULT_WORK_FOLDER);
5189 }
5190
5191 #[tokio::test]
5192 async fn a_terminal_but_uncleaned_attempt_keeps_its_slot_without_holding_capacity() {
5193 let harness = Harness::new(
5194 FakeGithubLifecycle::default().fail(true),
5195 Arc::new(PersistentDemand),
5196 )
5197 .with_persistent_workspace(2);
5198 harness.ready().await;
5199
5200 harness.launch_result().await.unwrap_err();
5202 let first = harness.store.attempts().unwrap().remove(0);
5203 assert_eq!(first.state(), AttemptState::Failed);
5204 assert!(
5205 !first.state().counts_against_capacity(),
5206 "a concluded attempt is invisible to host capacity"
5207 );
5208 assert!(
5209 first.holds_slot_lease(),
5210 "and still owns its directory, so its slot is not free"
5211 );
5212
5213 let second = harness.launch().await;
5214 assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
5215 assert_eq!(second.runtime_path(), harness.slot_path(2));
5216 assert_eq!(
5217 harness
5218 .store
5219 .slot_leases_for_policy(harness.policy.id)
5220 .unwrap()
5221 .len(),
5222 2
5223 );
5224 }
5225
5226 #[tokio::test]
5227 async fn two_sequential_allocations_at_capacity_one_reuse_s1_and_its_retained_work() {
5228 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5229 .with_persistent_workspace(1);
5230 harness.ready().await;
5231
5232 let first = harness.launch().await;
5233 assert_eq!(first.runtime_path(), harness.slot_path(1));
5234
5235 let checkout = harness.slot_path(1).join(DEFAULT_WORK_FOLDER).join("repo");
5237 fs::create_dir_all(&checkout).unwrap();
5238 fs::write(checkout.join("checkout.txt"), b"from the first job").unwrap();
5239
5240 harness.cleanup_retaining_work(first.id).await;
5241
5242 let second = harness.launch().await;
5243 assert_ne!(second.id, first.id);
5244 assert_eq!(
5245 second.workspace(),
5246 AttemptWorkspace::persistent_slot(nz(1)),
5247 "a released slot is leased again rather than skipped"
5248 );
5249 assert_eq!(
5250 second.runtime_path(),
5251 first.runtime_path(),
5252 "the same slot is the same exact path"
5253 );
5254 assert_eq!(
5255 fs::read_to_string(checkout.join("checkout.txt")).unwrap(),
5256 "from the first job",
5257 "the retained job workspace survived the second allocation"
5258 );
5259 assert!(harness.slot_path(1).join("runner-package").exists());
5261 }
5262
5263 #[tokio::test]
5264 async fn lowering_capacity_leaves_higher_slots_alone_and_raising_it_permits_them_again() {
5265 let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5266 .with_persistent_workspace(2);
5267 harness.ready().await;
5268
5269 let first = harness.launch().await;
5270 let second = harness.launch().await;
5271 assert_eq!(second.runtime_path(), harness.slot_path(2));
5272 let kept = harness
5273 .slot_path(2)
5274 .join(DEFAULT_WORK_FOLDER)
5275 .join("kept.txt");
5276 fs::create_dir_all(kept.parent().unwrap()).unwrap();
5277 fs::write(&kept, b"s2 was here").unwrap();
5278 harness.cleanup_retaining_work(second.id).await;
5279
5280 harness.policy.set_max_capacity(nz(1)).unwrap();
5282 let refusal = harness.launch_result().await.unwrap_err().to_string();
5283 assert!(
5284 refusal.contains("s1 to s1"),
5285 "the refusal names the ceiling it reached: {refusal}"
5286 );
5287 assert!(
5288 harness.slot_path(2).exists() && kept.exists(),
5289 "lowering capacity deletes nothing; the higher slot is merely unusable"
5290 );
5291
5292 harness.policy.set_max_capacity(nz(2)).unwrap();
5294 let third = harness.launch().await;
5295 assert_eq!(third.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
5296 assert_eq!(third.runtime_path(), harness.slot_path(2));
5297 assert_eq!(fs::read_to_string(&kept).unwrap(), "s2 was here");
5298 assert!(first.holds_slot_lease(), "s1 was never disturbed");
5299 }
5300
5301 #[tokio::test]
5302 async fn organization_and_ephemeral_policies_never_enter_slot_allocation() {
5303 for policy in [
5304 fixtures::policy()
5305 .organization("octo")
5306 .autoscale("home", 2)
5307 .active()
5308 .build(),
5309 fixtures::policy()
5310 .repository("octo/repo")
5311 .autoscale("home", 2)
5312 .active()
5313 .build(),
5314 ] {
5315 let mut harness =
5316 Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5317 .with_host_runner_root();
5318 assert_eq!(policy.workspace_policy(), &WorkspacePolicy::Ephemeral);
5319 harness.policy = policy;
5320 harness.ready().await;
5321
5322 let attempt = harness.launch().await;
5323 assert_eq!(attempt.workspace(), AttemptWorkspace::Ephemeral);
5324 assert_eq!(attempt.workspace().slot_number(), None);
5325 assert!(!attempt.holds_slot_lease());
5326 assert_eq!(
5327 attempt.runtime_path().parent().unwrap(),
5328 harness.host_root(),
5329 "a disposable attempt is a child of the host root, never of a slot"
5330 );
5331 assert!(
5332 harness
5333 .store
5334 .slot_leases_for_policy(harness.policy.id)
5335 .unwrap()
5336 .is_empty()
5337 );
5338 }
5339 }
5340
5341 #[tokio::test]
5342 async fn two_concurrent_allocations_never_share_a_slot() {
5343 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5344 .with_persistent_workspace(2);
5345 harness.github.watch_journal(Arc::clone(&harness.store));
5346 harness.ready().await;
5347
5348 let (first, second) = tokio::join!(harness.launch_result(), harness.launch_result());
5352 let first = first.unwrap();
5353 let second = second.unwrap();
5354
5355 let slots: BTreeSet<u16> = [&first, &second]
5356 .iter()
5357 .map(|attempt| {
5358 attempt
5359 .workspace()
5360 .slot_number()
5361 .expect("a persistent attempt leases a slot")
5362 })
5363 .collect();
5364 assert_eq!(slots, BTreeSet::from([1, 2]), "one slot each, never shared");
5365 assert_ne!(first.runtime_path(), second.runtime_path());
5366 assert_eq!(
5367 harness
5368 .store
5369 .slot_leases_for_policy(harness.policy.id)
5370 .unwrap()
5371 .len(),
5372 2
5373 );
5374
5375 let facts = harness.github.registration_facts();
5380 assert_eq!(facts.len(), 2);
5381 for fact in facts {
5382 let attempt = [&first, &second]
5383 .into_iter()
5384 .find(|attempt| runner_name(attempt.id) == fact.runner_name)
5385 .expect("every registration belongs to one of the two attempts");
5386 let slot = attempt
5387 .workspace()
5388 .slot_number()
5389 .expect("a persistent attempt leases a slot");
5390 assert!(
5391 fact.leased_slots.contains(&slot),
5392 "a JIT request never precedes its own lease: s{slot} not in {:?}",
5393 fact.leased_slots
5394 );
5395 assert_eq!(fact.work_folder, DEFAULT_WORK_FOLDER);
5396 }
5397 }
5398
5399 #[tokio::test]
5400 async fn the_database_is_the_final_fence_against_two_attempts_in_one_slot() {
5401 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5402 .with_persistent_workspace(2);
5403 harness.ready().await;
5404 let first = harness.launch().await;
5405
5406 let clash = RunnerAttempt::allocate_in(
5410 AttemptId::new_random(),
5411 harness.policy.id,
5412 first.runtime_path(),
5413 AttemptWorkspace::persistent_slot(nz(1)),
5414 harness.clock.now(),
5415 );
5416 assert!(matches!(
5417 harness.store.record_attempt(&clash).unwrap_err(),
5418 StoreError::SlotAlreadyLeased { slot: 1, .. }
5419 ));
5420
5421 let error = harness.launcher.record_allocation(&clash).unwrap_err();
5424 let rendered = error.to_string();
5425 assert!(rendered.contains("slot s1"), "{rendered}");
5426 assert!(rendered.contains("nothing was written"), "{rendered}");
5427 assert_eq!(
5428 harness.store.attempts().unwrap().len(),
5429 1,
5430 "the losing allocator journalled nothing"
5431 );
5432 }
5433
5434 #[test]
5435 fn slot_selection_fills_the_lowest_gap_and_stops_at_the_ceiling() {
5436 let leased = |slots: &[u16]| -> Vec<RunnerAttempt> {
5437 slots
5438 .iter()
5439 .map(|slot| {
5440 RunnerAttempt::allocate_in(
5441 AttemptId::new_random(),
5442 fixtures::POLICY_ID,
5443 format!("/srv/rman/acme/s{slot}"),
5444 AttemptWorkspace::persistent_slot(nz(*slot)),
5445 fixtures::created_at(),
5446 )
5447 })
5448 .collect()
5449 };
5450
5451 assert_eq!(lowest_free_slot(&[], nz(1)), Some(nz(1)));
5452 assert_eq!(lowest_free_slot(&leased(&[1]), nz(4)), Some(nz(2)));
5453 assert_eq!(lowest_free_slot(&leased(&[1, 3]), nz(4)), Some(nz(2)));
5455 assert_eq!(lowest_free_slot(&leased(&[1]), nz(1)), None);
5457 assert_eq!(lowest_free_slot(&leased(&[1, 2]), nz(2)), None);
5458 let ephemeral = vec![RunnerAttempt::allocate(
5460 AttemptId::new_random(),
5461 fixtures::POLICY_ID,
5462 "/srv/rman/host/abc",
5463 fixtures::created_at(),
5464 )];
5465 assert_eq!(lowest_free_slot(&ephemeral, nz(1)), Some(nz(1)));
5466 }
5467
5468 #[test]
5469 fn a_slot_is_reusable_only_when_it_is_empty_or_holds_one_real_work_directory() {
5470 let root = tempfile::tempdir().unwrap();
5471 let slot = root.path().join("s1");
5472 fs::create_dir(&slot).unwrap();
5473 accept_reusable_slot(&slot).expect("an empty slot is reusable");
5474
5475 fs::create_dir(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
5476 accept_reusable_slot(&slot).expect("a retained job workspace is reusable");
5477
5478 fs::create_dir(slot.join("bin")).unwrap();
5481 fs::write(slot.join(".github-runner-id"), b"73").unwrap();
5482 let refusal = accept_reusable_slot(&slot).unwrap_err().to_string();
5483 assert!(refusal.contains("bin"), "{refusal}");
5484 assert!(refusal.contains(".github-runner-id"), "{refusal}");
5485
5486 let file_work = root.path().join("s2");
5488 fs::create_dir(&file_work).unwrap();
5489 fs::write(file_work.join(DEFAULT_WORK_FOLDER), b"not a directory").unwrap();
5490 assert!(accept_reusable_slot(&file_work).is_err());
5491 }
5492
5493 #[cfg(unix)]
5494 #[test]
5495 fn a_link_shaped_work_directory_is_refused_rather_than_followed() {
5496 let root = tempfile::tempdir().unwrap();
5500 let elsewhere = root.path().join("elsewhere");
5501 fs::create_dir(&elsewhere).unwrap();
5502
5503 let slot = root.path().join("s1");
5504 fs::create_dir(&slot).unwrap();
5505 std::os::unix::fs::symlink(&elsewhere, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
5506 assert!(accept_reusable_slot(&slot).is_err());
5507
5508 let linked_slot = root.path().join("s2");
5509 std::os::unix::fs::symlink(&elsewhere, &linked_slot).unwrap();
5510 assert!(create_or_validate_slot(&linked_slot).is_err());
5511 }
5512
5513 #[test]
5514 fn a_slot_standing_where_a_file_is_refuses_rather_than_replacing_it() {
5515 let root = tempfile::tempdir().unwrap();
5516 let occupied = root.path().join("s1");
5517 fs::write(&occupied, b"an operator's file").unwrap();
5518 let refusal = create_or_validate_slot(&occupied).unwrap_err().to_string();
5519 assert!(refusal.contains("is not a directory"), "{refusal}");
5520 assert_eq!(fs::read_to_string(&occupied).unwrap(), "an operator's file");
5521
5522 let fresh = root.path().join("s2");
5523 create_or_validate_slot(&fresh).expect("a missing slot is created");
5524 assert!(fresh.is_dir());
5525 create_or_validate_slot(&fresh).expect("an existing directory is accepted");
5526 }
5527
5528 #[test]
5529 fn the_retained_work_directory_is_matched_the_way_the_filesystem_matches_it() {
5530 assert!(is_work_folder(OsStr::new(DEFAULT_WORK_FOLDER)));
5531 assert!(!is_work_folder(OsStr::new("_work2")));
5532 assert_eq!(is_work_folder(OsStr::new("_Work")), cfg!(windows));
5536 }
5537
5538 #[test]
5539 fn package_materialization_never_overwrites_or_follows_a_retained_work_directory() {
5540 let root = tempfile::tempdir().unwrap();
5541 let package = root.path().join("package");
5542 fs::create_dir_all(package.join("bin")).unwrap();
5543 fs::write(package.join("bin").join("Runner.Listener"), b"binary").unwrap();
5544 fs::create_dir_all(package.join("externals").join(DEFAULT_WORK_FOLDER)).unwrap();
5546
5547 let slot = root.path().join("s1");
5548 let retained = slot.join(DEFAULT_WORK_FOLDER).join("repo");
5549 fs::create_dir_all(&retained).unwrap();
5550 fs::write(retained.join("checkout.txt"), b"from the first job").unwrap();
5551
5552 copy_package_tree(&package, &slot).expect("the package lays out around `_work`");
5553 assert!(slot.join("bin").join("Runner.Listener").exists());
5554 assert!(
5555 slot.join("externals").join(DEFAULT_WORK_FOLDER).is_dir(),
5556 "the guard is top-level only"
5557 );
5558 assert_eq!(
5559 fs::read_to_string(retained.join("checkout.txt")).unwrap(),
5560 "from the first job"
5561 );
5562
5563 fs::create_dir(package.join(DEFAULT_WORK_FOLDER)).unwrap();
5565 let error = copy_package_tree(&package, &slot).unwrap_err();
5566 assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
5567 assert_eq!(
5568 fs::read_to_string(retained.join("checkout.txt")).unwrap(),
5569 "from the first job"
5570 );
5571 }
5572
5573 #[test]
5574 fn rolling_back_a_materialization_keeps_a_slot_but_removes_a_disposable_directory() {
5575 let root = tempfile::tempdir().unwrap();
5576
5577 let slot = root.path().join("s1");
5578 let retained = slot.join(DEFAULT_WORK_FOLDER);
5579 fs::create_dir_all(retained.join("repo")).unwrap();
5580 fs::write(retained.join("repo").join("checkout.txt"), b"kept").unwrap();
5581 fs::create_dir_all(slot.join("bin")).unwrap();
5582 fs::write(slot.join(".github-runner-id"), b"73").unwrap();
5583 let persistent = RunnerAttempt::allocate_in(
5584 AttemptId::new_random(),
5585 fixtures::POLICY_ID,
5586 &slot,
5587 AttemptWorkspace::persistent_slot(nz(1)),
5588 fixtures::created_at(),
5589 );
5590
5591 remove_materialized_package(&persistent).unwrap();
5592 assert!(slot.is_dir(), "the slot itself is not removed");
5593 assert!(!slot.join("bin").exists());
5594 assert!(!slot.join(".github-runner-id").exists());
5595 assert_eq!(
5596 fs::read_to_string(retained.join("repo").join("checkout.txt")).unwrap(),
5597 "kept"
5598 );
5599
5600 let disposable_path = root.path().join("abcdef012345");
5601 fs::create_dir_all(disposable_path.join(DEFAULT_WORK_FOLDER)).unwrap();
5602 let disposable = RunnerAttempt::allocate(
5603 AttemptId::new_random(),
5604 fixtures::POLICY_ID,
5605 &disposable_path,
5606 fixtures::created_at(),
5607 );
5608 remove_materialized_package(&disposable).unwrap();
5609 assert!(
5610 !disposable_path.exists(),
5611 "a disposable directory is still removed whole"
5612 );
5613 }
5614
5615 fn litter_the_slot(slot: &Path) {
5625 for directory in ["bin", "externals", "_diag"] {
5626 fs::create_dir_all(slot.join(directory)).unwrap();
5627 }
5628 fs::write(slot.join("bin").join("Runner.Listener"), b"binary").unwrap();
5629 for file in SENSITIVE_SLOT_ENTRIES
5630 .iter()
5631 .filter(|entry| !slot.join(entry).is_dir())
5632 {
5633 fs::write(slot.join(file), b"runner state").unwrap();
5634 }
5635 fs::write(
5637 slot.join(format!(
5638 "{}0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0.tmp",
5639 RestrictiveHandoff::NAME_PREFIX
5640 )),
5641 JIT.as_bytes(),
5642 )
5643 .unwrap();
5644 }
5645
5646 fn retain_under_work(slot: &Path) -> PathBuf {
5648 let checkout = slot.join(DEFAULT_WORK_FOLDER).join("repo").join("target");
5649 fs::create_dir_all(&checkout).unwrap();
5650 let marker = checkout.join("build-output.bin");
5651 fs::write(&marker, RETAINED).unwrap();
5652 marker
5653 }
5654
5655 const RETAINED: &str = "a Git-ignored build output the next job reuses";
5657
5658 fn entries_of(directory: &Path) -> Vec<String> {
5660 let mut names: Vec<String> = fs::read_dir(directory)
5661 .unwrap()
5662 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
5663 .collect();
5664 names.sort();
5665 names
5666 }
5667
5668 fn only_the_job_workspace() -> Vec<String> {
5670 vec![DEFAULT_WORK_FOLDER.to_owned()]
5671 }
5672
5673 #[cfg(unix)]
5674 #[test]
5675 fn disposable_tree_removal_does_not_open_a_dotnet_diagnostic_fifo() {
5676 use std::sync::mpsc;
5677
5678 let temporary = tempfile::tempdir().unwrap();
5679 let tree = temporary.path().join("attempt");
5680 let diagnostic = tree.join("tmp/clr-debug-pipe-runner-in");
5681 fs::create_dir_all(diagnostic.parent().unwrap()).unwrap();
5682 assert!(
5683 std::process::Command::new("mkfifo")
5684 .arg(&diagnostic)
5685 .status()
5686 .unwrap()
5687 .success()
5688 );
5689
5690 let (finished, result) = mpsc::channel();
5691 std::thread::spawn(move || {
5692 let removed = remove_runtime_tree(&tree);
5693 let _ = finished.send(removed);
5694 });
5695
5696 result
5697 .recv_timeout(Duration::from_secs(2))
5698 .expect("runtime deletion must not wait for a FIFO peer")
5699 .unwrap();
5700 assert!(!diagnostic.exists());
5701 }
5702
5703 struct BlockedDeletion {
5719 directory: PathBuf,
5720 #[cfg(windows)]
5721 _handle: fs::File,
5722 }
5723
5724 impl BlockedDeletion {
5725 const HELD: &'static str = "held-open";
5726
5727 fn inject(directory: &Path) -> Option<Self> {
5730 #[cfg(unix)]
5731 if !Self::refusal_is_possible() {
5732 return None;
5733 }
5734 fs::create_dir_all(directory).unwrap();
5735 fs::write(
5736 directory.join(Self::HELD),
5737 b"a file the scrub cannot remove",
5738 )
5739 .unwrap();
5740 #[cfg(windows)]
5741 let handle = {
5742 use std::os::windows::fs::OpenOptionsExt;
5743
5744 fs::OpenOptions::new()
5745 .read(true)
5746 .share_mode(0)
5747 .open(directory.join(Self::HELD))
5748 .expect("the blocking handle opens")
5749 };
5750 #[cfg(unix)]
5751 Self::set_mode(directory, 0o555);
5752 Some(Self {
5753 directory: directory.to_path_buf(),
5754 #[cfg(windows)]
5755 _handle: handle,
5756 })
5757 }
5758
5759 fn release(self) {
5760 drop(self);
5761 }
5762
5763 #[cfg(unix)]
5764 fn refusal_is_possible() -> bool {
5765 let probe = tempfile::tempdir().unwrap();
5766 let directory = probe.path().join("probe");
5767 fs::create_dir(&directory).unwrap();
5768 fs::write(directory.join("file"), b"probe").unwrap();
5769 Self::set_mode(&directory, 0o555);
5770 let refused = fs::remove_dir_all(&directory).is_err();
5771 Self::set_mode(&directory, 0o755);
5772 refused
5773 }
5774
5775 #[cfg(unix)]
5776 fn set_mode(directory: &Path, mode: u32) {
5777 use std::os::unix::fs::PermissionsExt;
5778
5779 let mut permissions = fs::metadata(directory).unwrap().permissions();
5780 permissions.set_mode(mode);
5781 fs::set_permissions(directory, permissions).unwrap();
5782 }
5783 }
5784
5785 impl Drop for BlockedDeletion {
5786 fn drop(&mut self) {
5787 #[cfg(unix)]
5788 Self::set_mode(&self.directory, 0o755);
5789 #[cfg(not(unix))]
5790 let _ = &self.directory;
5791 }
5792 }
5793
5794 #[tokio::test]
5795 async fn two_sequential_jobs_keep_the_checkout_and_start_without_the_earlier_runner_state() {
5796 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5797 .with_persistent_workspace(1);
5798 harness.ready().await;
5799
5800 let first = harness.launch().await;
5801 let slot = harness.slot_path(1);
5802 assert_eq!(first.runtime_path(), slot);
5803 assert_eq!(
5804 read_runner_id(&slot),
5805 Some(73),
5806 "the attempt registered, so its identity is on disk"
5807 );
5808 let marker = retain_under_work(&slot);
5809 litter_the_slot(&slot);
5810
5811 harness.cleanup_retaining_work(first.id).await;
5812
5813 assert_eq!(entries_of(&slot), only_the_job_workspace());
5816 assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
5817 assert_eq!(
5818 read_runner_id(&slot),
5819 None,
5820 "the first attempt's registration identity is gone before the second starts"
5821 );
5822 assert_eq!(harness.attempt(first.id).state(), AttemptState::Cleaned);
5823 assert!(!harness.attempt(first.id).holds_slot_lease());
5824
5825 let second = harness.launch().await;
5826 assert_ne!(second.id, first.id);
5827 assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(1)));
5828 assert_eq!(
5829 second.runtime_path(),
5830 slot,
5831 "the same slot, so the same retained `_work`"
5832 );
5833 assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
5834 }
5835
5836 #[tokio::test]
5837 async fn cleaning_a_persistent_slot_needs_no_policy_and_scans_no_directory_for_ownership() {
5838 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5839 .with_persistent_workspace(1);
5840 harness.ready().await;
5841 let attempt = harness.launch().await;
5842 let slot = harness.slot_path(1);
5843 let marker = retain_under_work(&slot);
5844 litter_the_slot(&slot);
5845 harness.conclude(attempt.id);
5846
5847 harness
5853 .store
5854 .remove_policy(harness.policy.id, harness.policy.revision())
5855 .unwrap();
5856 assert!(harness.store.policy(harness.policy.id).unwrap().is_none());
5857
5858 harness
5859 .launcher
5860 .clean(attempt.id)
5861 .await
5862 .expect("journal facts alone are enough to clean the slot");
5863
5864 assert_eq!(entries_of(&slot), only_the_job_workspace());
5865 assert!(marker.exists());
5866 assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
5867 }
5868
5869 #[tokio::test]
5870 async fn an_injected_partial_deletion_quarantines_the_slot_across_a_restart() {
5871 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
5872 .with_persistent_workspace(2);
5873 harness.ready().await;
5874 let first = harness.launch().await;
5875 let slot = harness.slot_path(1);
5876 let marker = retain_under_work(&slot);
5877 litter_the_slot(&slot);
5878 harness.conclude(first.id);
5879
5880 let Some(block) = BlockedDeletion::inject(&slot.join("bin")) else {
5881 eprintln!(
5882 "skipped: this account cannot be refused a deletion, so no partial deletion can \
5883 be injected"
5884 );
5885 return;
5886 };
5887
5888 let refusal = harness
5889 .launcher
5890 .clean(first.id)
5891 .await
5892 .expect_err("a deletion that failed may not report a cleaned slot");
5893 let rendered = refusal.reason.to_string();
5894 assert!(rendered.contains("could not be removed"), "{rendered}");
5895
5896 let held = harness.attempt(first.id);
5897 assert_eq!(held.state(), AttemptState::Failed, "still not cleaned");
5898 assert!(held.holds_slot_lease(), "so the slot is still leased");
5899 assert!(
5900 !held.state().counts_against_capacity(),
5901 "and a concluded attempt still costs the host no capacity"
5902 );
5903
5904 let restarted = harness.restart();
5909 restarted
5910 .recover_startup(std::slice::from_ref(&harness.policy))
5911 .await
5912 .expect("one quarantined slot does not stop the host recovering");
5913 assert_eq!(
5914 harness.attempt(first.id).state(),
5915 AttemptState::Failed,
5916 "the quarantine survived the restart"
5917 );
5918 assert!(
5919 harness
5920 .reconcile_events
5921 .events()
5922 .iter()
5923 .any(|event| matches!(
5924 event,
5925 LifecycleEvent::AttemptCleanFailed {
5926 reason: "slot_entry_could_not_be_removed",
5927 ..
5928 }
5929 )),
5930 "the refusal is reported rather than retried in silence"
5931 );
5932
5933 let guard = harness.allocation_lock.acquire().await.unwrap();
5936 let second = restarted
5937 .launch(LaunchRequest {
5938 host: &harness.host,
5939 policy: &harness.policy,
5940 allocation_guard: &guard,
5941 })
5942 .await
5943 .expect("the host can still launch");
5944 assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
5945 drop(guard);
5946
5947 block.release();
5950 restarted
5951 .clean(first.id)
5952 .await
5953 .expect("the retried cleanup completes");
5954 assert_eq!(entries_of(&slot), only_the_job_workspace());
5955 assert!(marker.exists());
5956 assert_eq!(harness.attempt(first.id).state(), AttemptState::Cleaned);
5957 }
5958
5959 #[tokio::test]
5970 async fn an_injected_deletion_failure_leaves_a_disposable_attempt_uncleaned() {
5971 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand));
5972 harness.ready().await;
5973 let attempt = harness.launch().await;
5974 let runtime = attempt.runtime_path().to_path_buf();
5975 assert_eq!(attempt.workspace(), AttemptWorkspace::Ephemeral);
5976 harness.conclude(attempt.id);
5977
5978 let Some(block) = BlockedDeletion::inject(&runtime.join("held-open-subdirectory")) else {
5979 eprintln!(
5980 "skipped: this account cannot be refused a deletion, so no partial deletion can be injected"
5981 );
5982 return;
5983 };
5984
5985 let refusal = harness
5986 .launcher
5987 .clean(attempt.id)
5988 .await
5989 .expect_err("a deletion that failed may not report a removed workspace");
5990 let rendered = refusal.reason.to_string();
5991 assert!(
5992 rendered.contains("could not be removed"),
5993 "the refusal names what happened: {rendered}"
5994 );
5995 assert_ne!(
5996 harness.attempt(attempt.id).state(),
5997 AttemptState::Cleaned,
5998 "an attempt whose directory is still on disk is not cleaned"
5999 );
6000 assert!(
6001 runtime.is_dir(),
6002 "the directory the removal could not finish is still there, which is the fact the journal must keep agreeing with"
6003 );
6004
6005 block.release();
6008 harness
6009 .launcher
6010 .clean(attempt.id)
6011 .await
6012 .expect("the retried cleanup completes");
6013 assert!(!runtime.exists(), "the whole attempt directory goes");
6014 assert_eq!(harness.attempt(attempt.id).state(), AttemptState::Cleaned);
6015 }
6016
6017 #[tokio::test]
6018 async fn changing_a_repository_back_to_ephemeral_leaves_every_old_slot_untouched() {
6019 let mut harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
6020 .with_persistent_workspace(1);
6021 harness.ready().await;
6022 let first = harness.launch().await;
6023 let slot = harness.slot_path(1);
6024 let marker = retain_under_work(&slot);
6025 harness.cleanup_retaining_work(first.id).await;
6026
6027 harness
6031 .policy
6032 .set_workspace_policy(WorkspacePolicy::Ephemeral)
6033 .unwrap();
6034
6035 let second = harness.launch().await;
6036 assert_eq!(second.workspace(), AttemptWorkspace::Ephemeral);
6037 assert_eq!(
6038 second.runtime_path().parent().unwrap(),
6039 harness.host_root(),
6040 "a disposable attempt is a child of the host root"
6041 );
6042 assert!(slot.is_dir(), "the old slot is left where it stands");
6043 assert_eq!(fs::read_to_string(&marker).unwrap(), RETAINED);
6044
6045 harness.conclude(second.id);
6048 harness.launcher.clean(second.id).await.unwrap();
6049 assert!(!second.runtime_path().exists());
6050 assert!(marker.exists());
6051 }
6052
6053 #[tokio::test]
6054 async fn a_persistent_slot_is_scrubbed_only_after_the_process_is_signalled_and_gone() {
6055 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
6056 .with_persistent_workspace(1);
6057 harness.ready().await;
6058 let slot = harness.slot_path(1);
6059 fs::create_dir_all(&slot).unwrap();
6060 let marker = retain_under_work(&slot);
6061 litter_the_slot(&slot);
6062
6063 let id = AttemptId::new_random();
6064 let mut attempt = RunnerAttempt::allocate_in(
6065 id,
6066 harness.policy.id,
6067 &slot,
6068 AttemptWorkspace::persistent_slot(nz(1)),
6069 harness.clock.now(),
6070 );
6071 attempt.jit_received(harness.clock.now()).unwrap();
6072 attempt.started(4242, harness.clock.now()).unwrap();
6073 harness.store.record_attempt(&attempt).unwrap();
6074 harness.clock.advance_secs(11);
6075 harness.processes.set_alive(true);
6076 harness
6077 .github
6078 .observe(GithubRunnerObservation::NotRegistered);
6079
6080 harness.launcher.supervise(&harness.policy).await.unwrap();
6081
6082 let actions = harness.processes.actions.lock().unwrap().clone();
6086 let intent = actions
6087 .iter()
6088 .position(|action| *action == "terminate_intent")
6089 .unwrap();
6090 let signal = actions
6091 .iter()
6092 .position(|action| *action == "terminate")
6093 .unwrap();
6094 assert!(intent < signal, "{actions:?}");
6095 assert!(!harness.processes.alive.load(Ordering::SeqCst));
6096
6097 let cleaned = harness.attempt(id);
6098 assert_eq!(cleaned.state(), AttemptState::Cleaned);
6099 assert!(matches!(
6100 cleaned.outcome(),
6101 Some(AttemptOutcome::Failed {
6102 reason: FailureReason::TerminatedAfterRegistrationTimeout
6103 })
6104 ));
6105 assert_eq!(entries_of(&slot), only_the_job_workspace());
6106 assert!(marker.exists());
6107 }
6108
6109 #[test]
6110 fn a_scrub_retains_one_real_work_directory_and_removes_every_other_entry() {
6111 let root = tempfile::tempdir().unwrap();
6112 let slot = root.path().join("s1");
6113 fs::create_dir(&slot).unwrap();
6114 let marker = retain_under_work(&slot);
6115 litter_the_slot(&slot);
6116 fs::write(slot.join("runner-package"), b"verified").unwrap();
6117
6118 scrub_slot_entries(&slot).expect("a slot of ordinary runner state scrubs");
6119 verify_slot_scrubbed(&slot).expect("and proves it afterwards");
6120
6121 assert_eq!(entries_of(&slot), only_the_job_workspace());
6122 assert!(marker.exists());
6123 }
6124
6125 #[test]
6126 fn a_residue_refusal_never_reports_the_under_count_as_the_fact() {
6127 let slot = Path::new("/runners/s1");
6128
6129 let counted = residue_detail(slot, 2, &["`bin`".to_owned()]);
6132 assert!(counted.contains("2 entries other than"), "{counted}");
6133 assert!(counted.contains("including `bin`"), "{counted}");
6134 assert_eq!(
6135 residue_detail(slot, 1, &[]),
6136 format!(
6137 "1 entry other than `{DEFAULT_WORK_FOLDER}` survived cleanup of {}",
6138 slot.display()
6139 )
6140 );
6141
6142 let raced = residue_detail(slot, 0, &["`.credentials`".to_owned()]);
6147 assert!(!raced.contains('0'), "{raced}");
6148 assert!(raced.contains("reported nothing but"), "{raced}");
6149 assert!(raced.contains("`.credentials` survived cleanup"), "{raced}");
6150 }
6151
6152 #[test]
6153 fn verification_asks_the_filesystem_rather_than_the_listing_that_missed_an_entry() {
6154 let root = tempfile::tempdir().unwrap();
6155 let slot = root.path().join("s1");
6156 fs::create_dir(&slot).unwrap();
6157 fs::create_dir(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
6158 verify_slot_scrubbed(&slot).expect("only `_work` is a clean slot");
6159
6160 for survivor in ["bin", ".credentials", IDENTITY_FILE, RUNNER_ID_FILE] {
6164 fs::write(slot.join(survivor), b"left behind").unwrap();
6165 let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
6166 assert_eq!(quarantine.refusal, SlotRefusal::Residue);
6167 assert!(
6168 quarantine.detail.contains(&format!("`{survivor}`")),
6169 "{quarantine}"
6170 );
6171 fs::remove_file(slot.join(survivor)).unwrap();
6172 }
6173
6174 let handoff = slot.join(format!("{}whatever.tmp", RestrictiveHandoff::NAME_PREFIX));
6177 fs::write(&handoff, JIT.as_bytes()).unwrap();
6178 let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
6179 assert!(
6180 quarantine.detail.contains("an encoded JIT handoff"),
6181 "{quarantine}"
6182 );
6183 assert!(!quarantine.detail.contains(JIT), "{quarantine}");
6184 fs::remove_file(&handoff).unwrap();
6185
6186 fs::write(slot.join("ghp_DO_NOT_LEAK"), b"named by the job").unwrap();
6190 let quarantine = verify_slot_scrubbed(&slot).unwrap_err();
6191 assert!(
6192 quarantine.detail.contains("1 entry other than"),
6193 "{quarantine}"
6194 );
6195 assert!(
6196 !quarantine.detail.contains("ghp_DO_NOT_LEAK"),
6197 "{quarantine}"
6198 );
6199 }
6200
6201 #[test]
6202 fn a_slot_is_derived_from_the_journal_and_refused_when_it_disagrees() {
6203 let root = tempfile::tempdir().unwrap();
6204 let configured =
6205 LocalAbsolutePath::new(root.path().to_str().unwrap()).expect("a local absolute root");
6206 let slot = configured.as_path().join("s1");
6207 fs::create_dir(&slot).unwrap();
6208
6209 verify_journalled_slot(&slot, nz(1), Some(&configured))
6210 .expect("the journalled slot agrees");
6211 verify_journalled_slot(&slot, nz(1), None)
6212 .expect("and a policy that is gone removes a check, not the ability to clean");
6213
6214 assert_eq!(
6217 verify_journalled_slot(&slot, nz(2), None)
6218 .unwrap_err()
6219 .refusal,
6220 SlotRefusal::NotTheJournalledSlot
6221 );
6222 for stray in ["s1/nested", "not-a-slot", "s01"] {
6223 let path = configured.as_path().join(stray);
6224 assert_eq!(
6225 verify_journalled_slot(&path, nz(1), None)
6226 .unwrap_err()
6227 .refusal,
6228 SlotRefusal::NotTheJournalledSlot,
6229 "{}",
6230 path.display()
6231 );
6232 }
6233
6234 let elsewhere = tempfile::tempdir().unwrap();
6237 let other =
6238 LocalAbsolutePath::new(elsewhere.path().to_str().unwrap()).expect("a second root");
6239 assert_eq!(
6240 verify_journalled_slot(&slot, nz(1), Some(&other))
6241 .unwrap_err()
6242 .refusal,
6243 SlotRefusal::PolicyRootDisagrees
6244 );
6245 }
6246
6247 #[cfg(unix)]
6248 #[test]
6249 fn a_substituted_work_directory_quarantines_the_slot_and_deletes_nothing_outside_it() {
6250 let root = tempfile::tempdir().unwrap();
6254 let outside = root.path().join("operator-data");
6255 fs::create_dir(&outside).unwrap();
6256 let sentinel = outside.join("do-not-delete.txt");
6257 fs::write(
6258 &sentinel,
6259 b"an operator's data, outside every approved root",
6260 )
6261 .unwrap();
6262
6263 let slot = root.path().join("s1");
6264 fs::create_dir(&slot).unwrap();
6265 fs::create_dir(slot.join("bin")).unwrap();
6266 std::os::unix::fs::symlink(&outside, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
6267
6268 let quarantine = scrub_slot_entries(&slot).unwrap_err();
6269 assert_eq!(quarantine.refusal, SlotRefusal::WorkNotADirectory);
6270 assert!(
6271 sentinel.exists(),
6272 "the deletion followed the link out of the slot"
6273 );
6274 assert!(outside.is_dir());
6275 assert!(
6276 slot.join(DEFAULT_WORK_FOLDER).symlink_metadata().is_ok(),
6277 "the substituted link is left for the operator, never unlinked as if it were ours"
6278 );
6279
6280 let file_work = root.path().join("s2");
6284 fs::create_dir(&file_work).unwrap();
6285 fs::write(file_work.join(DEFAULT_WORK_FOLDER), b"not a directory").unwrap();
6286 assert_eq!(
6287 scrub_slot_entries(&file_work).unwrap_err().refusal,
6288 SlotRefusal::WorkNotADirectory
6289 );
6290 }
6291
6292 #[cfg(unix)]
6293 #[test]
6294 fn a_slot_replaced_by_a_link_out_of_its_root_is_refused_before_anything_is_read() {
6295 let root = tempfile::tempdir().unwrap();
6296 let outside = root.path().join("operator-data");
6297 fs::create_dir(&outside).unwrap();
6298 let sentinel = outside.join("do-not-delete.txt");
6299 fs::write(
6300 &sentinel,
6301 b"an operator's data, outside every approved root",
6302 )
6303 .unwrap();
6304
6305 let inside = root.path().join("inside");
6308 fs::create_dir(&inside).unwrap();
6309 let slot = inside.join("s1");
6310 std::os::unix::fs::symlink(&outside, &slot).unwrap();
6311
6312 assert_eq!(
6313 verify_journalled_slot(&slot, nz(1), None)
6314 .unwrap_err()
6315 .refusal,
6316 SlotRefusal::Containment
6317 );
6318 assert!(sentinel.exists());
6319 assert!(
6320 slot.symlink_metadata().is_ok(),
6321 "the link is left for the operator rather than removed as if it were ours"
6322 );
6323 }
6324
6325 #[cfg(windows)]
6335 #[test]
6336 fn a_slot_root_replaced_by_a_junction_is_refused_before_anything_is_read() {
6337 let root = tempfile::tempdir().unwrap();
6338 let outside = root.path().join("operator-data");
6339 fs::create_dir(&outside).unwrap();
6340 let sentinel = outside.join("do-not-delete.txt");
6341 fs::write(
6342 &sentinel,
6343 b"an operator's data, outside every approved root",
6344 )
6345 .unwrap();
6346
6347 let inside = root.path().join("inside");
6350 fs::create_dir(&inside).unwrap();
6351 let slot = inside.join("s1");
6352 let Some(()) = plant_junction(&slot, &outside) else {
6353 eprintln!("skipped: this machine would not create a directory junction");
6354 return;
6355 };
6356
6357 assert_eq!(
6358 verify_journalled_slot(&slot, nz(1), None)
6359 .unwrap_err()
6360 .refusal,
6361 SlotRefusal::Containment
6362 );
6363 assert!(
6364 sentinel.exists(),
6365 "the refusal resolved the junction and reached the operator's data"
6366 );
6367 assert!(
6368 slot.symlink_metadata().is_ok(),
6369 "the junction is left for the operator rather than removed as if it were ours"
6370 );
6371 }
6372
6373 #[cfg(windows)]
6382 fn plant_junction(link: &Path, target: &Path) -> Option<()> {
6383 let made = std::process::Command::new("cmd")
6384 .arg("/C")
6385 .arg("mklink")
6386 .arg("/J")
6387 .arg(link)
6388 .arg(target)
6389 .output()
6390 .ok()?;
6391 (made.status.success() && link.symlink_metadata().is_ok()).then_some(())
6392 }
6393
6394 #[cfg(windows)]
6395 #[test]
6396 fn a_work_directory_replaced_by_a_junction_fails_closed_and_deletes_nothing_beyond_it() {
6397 let root = tempfile::tempdir().unwrap();
6398 let outside = root.path().join("operator-data");
6399 fs::create_dir(&outside).unwrap();
6400 let sentinel = outside.join("do-not-delete.txt");
6401 fs::write(
6402 &sentinel,
6403 b"an operator's data, outside every approved root",
6404 )
6405 .unwrap();
6406
6407 let slot = root.path().join("s1");
6408 fs::create_dir(&slot).unwrap();
6409 fs::create_dir(slot.join("bin")).unwrap();
6410 let Some(()) = plant_junction(&slot.join(DEFAULT_WORK_FOLDER), &outside) else {
6411 eprintln!("skipped: this machine would not create a directory junction");
6412 return;
6413 };
6414
6415 let work = fs::symlink_metadata(slot.join(DEFAULT_WORK_FOLDER)).unwrap();
6419 assert!(is_link_like(&work), "a junction is a reparse point");
6420 let quarantine = scrub_slot_entries(&slot).unwrap_err();
6421 assert_eq!(quarantine.refusal, SlotRefusal::WorkNotADirectory);
6422 assert!(
6423 sentinel.exists(),
6424 "the deletion followed the junction out of the slot"
6425 );
6426 assert!(outside.is_dir());
6427
6428 let elsewhere = root.path().join("s2");
6431 fs::create_dir(&elsewhere).unwrap();
6432 fs::create_dir(elsewhere.join(DEFAULT_WORK_FOLDER)).unwrap();
6433 if plant_junction(&elsewhere.join("externals"), &outside).is_some() {
6434 scrub_slot_entries(&elsewhere).expect("an ordinary entry is removed, junction or not");
6435 verify_slot_scrubbed(&elsewhere).expect("and the slot verifies");
6436 assert!(sentinel.exists(), "the junction was followed, not unlinked");
6437 assert_eq!(entries_of(&elsewhere), only_the_job_workspace());
6438 }
6439 }
6440
6441 #[cfg(unix)]
6442 #[tokio::test]
6443 async fn a_substituted_work_directory_leaves_the_attempt_uncleaned_and_still_leased() {
6444 let harness = Harness::new(FakeGithubLifecycle::default(), Arc::new(PersistentDemand))
6445 .with_persistent_workspace(2);
6446 harness.ready().await;
6447 let first = harness.launch().await;
6448 let slot = harness.slot_path(1);
6449 harness.conclude(first.id);
6450
6451 let outside = harness._root.path().join("operator-data");
6452 fs::create_dir_all(&outside).unwrap();
6453 let sentinel = outside.join("do-not-delete.txt");
6454 fs::write(&sentinel, b"outside every approved root").unwrap();
6455 std::os::unix::fs::symlink(&outside, slot.join(DEFAULT_WORK_FOLDER)).unwrap();
6456
6457 harness
6458 .launcher
6459 .clean(first.id)
6460 .await
6461 .expect_err("a slot whose `_work` was substituted is quarantined");
6462 assert!(sentinel.exists());
6463
6464 let held = harness.attempt(first.id);
6465 assert_eq!(held.state(), AttemptState::Failed);
6466 assert!(held.holds_slot_lease());
6467
6468 let second = harness.launch().await;
6470 assert_eq!(second.workspace(), AttemptWorkspace::persistent_slot(nz(2)));
6471 }
6472
6473 #[test]
6474 fn a_slot_that_is_a_file_is_refused_and_a_slot_that_is_gone_is_not() {
6475 let root = tempfile::tempdir().unwrap();
6476 let occupied = root.path().join("s1");
6477 fs::write(&occupied, b"an operator's file").unwrap();
6478 verify_journalled_slot(&occupied, nz(1), None).expect("the path is the journalled slot");
6481 assert_eq!(
6482 slot_is_present(&occupied).unwrap_err().refusal,
6483 SlotRefusal::SlotNotADirectory
6484 );
6485 assert_eq!(fs::read_to_string(&occupied).unwrap(), "an operator's file");
6486
6487 assert!(!slot_is_present(&root.path().join("s2")).unwrap());
6490 let present = root.path().join("s3");
6491 fs::create_dir(&present).unwrap();
6492 assert!(slot_is_present(&present).unwrap());
6493 }
6494
6495 #[test]
6496 fn cleanup_dispatches_on_the_journalled_kind_and_not_on_what_the_directory_holds() {
6497 let root = tempfile::tempdir().unwrap();
6498
6499 let disposable = root.path().join("abcdef012345");
6503 fs::create_dir_all(disposable.join(DEFAULT_WORK_FOLDER).join("repo")).unwrap();
6504 let ephemeral = RunnerAttempt::allocate(
6505 AttemptId::new_random(),
6506 fixtures::POLICY_ID,
6507 &disposable,
6508 fixtures::created_at(),
6509 );
6510 remove_materialized_package(&ephemeral).unwrap();
6511 assert!(!disposable.exists());
6512
6513 let slot = root.path().join("s1");
6515 fs::create_dir_all(slot.join(DEFAULT_WORK_FOLDER).join("repo")).unwrap();
6516 fs::create_dir_all(slot.join("bin")).unwrap();
6517 let persistent = RunnerAttempt::allocate_in(
6518 AttemptId::new_random(),
6519 fixtures::POLICY_ID,
6520 &slot,
6521 AttemptWorkspace::persistent_slot(nz(1)),
6522 fixtures::created_at(),
6523 );
6524 remove_materialized_package(&persistent).unwrap();
6525 assert_eq!(entries_of(&slot), only_the_job_workspace());
6526 assert!(slot.join(DEFAULT_WORK_FOLDER).join("repo").is_dir());
6527 }
6528
6529 #[test]
6530 fn every_slot_refusal_names_a_distinct_event_class_and_keeps_the_lease() {
6531 let refusals = [
6532 SlotRefusal::NotTheJournalledSlot,
6533 SlotRefusal::PolicyRootDisagrees,
6534 SlotRefusal::Containment,
6535 SlotRefusal::SlotNotADirectory,
6536 SlotRefusal::Enumeration,
6537 SlotRefusal::WorkNotADirectory,
6538 SlotRefusal::Deletion,
6539 SlotRefusal::Residue,
6540 ];
6541 let classes: BTreeSet<&str> = refusals.iter().map(|refusal| refusal.class()).collect();
6542 assert_eq!(
6543 classes.len(),
6544 refusals.len(),
6545 "an event class shared by two refusals tells an operator less than it appears to"
6546 );
6547 for refusal in refusals {
6548 assert!(
6551 refusal
6552 .class()
6553 .chars()
6554 .all(|c| c.is_ascii_lowercase() || c == '_'),
6555 "{}",
6556 refusal.class()
6557 );
6558 assert!(
6559 refusal.remediation().contains("slot lease"),
6560 "every refusal has to say the lease is still held: {}",
6561 refusal.class()
6562 );
6563 }
6564 }
6565
6566 #[test]
6567 fn copy_package_tree_copies_files_and_preserves_paths_with_spaces() {
6568 let root = tempfile::tempdir().unwrap();
6569 let source = root.path().join("source with spaces");
6570 let dest = root.path().join("dest with spaces");
6571
6572 fs::create_dir_all(&source).unwrap();
6573 fs::write(source.join("file1.txt"), b"hello").unwrap();
6574
6575 let nested = source.join("nested dir");
6576 fs::create_dir_all(&nested).unwrap();
6577 fs::write(nested.join("file2.txt"), b"world").unwrap();
6578
6579 let nested_work = nested.join(DEFAULT_WORK_FOLDER);
6581 fs::create_dir_all(&nested_work).unwrap();
6582 fs::write(nested_work.join("allowed.txt"), b"allowed").unwrap();
6583
6584 copy_package_tree(&source, &dest).unwrap();
6585
6586 assert_eq!(fs::read_to_string(dest.join("file1.txt")).unwrap(), "hello");
6587 assert_eq!(
6588 fs::read_to_string(dest.join("nested dir").join("file2.txt")).unwrap(),
6589 "world"
6590 );
6591 assert_eq!(
6592 fs::read_to_string(
6593 dest.join("nested dir")
6594 .join(DEFAULT_WORK_FOLDER)
6595 .join("allowed.txt")
6596 )
6597 .unwrap(),
6598 "allowed"
6599 );
6600 }
6601
6602 #[test]
6603 fn copy_package_tree_refuses_top_level_work_folder() {
6604 let root = tempfile::tempdir().unwrap();
6605 let source = root.path().join("source");
6606 let dest = root.path().join("dest");
6607
6608 fs::create_dir_all(&source).unwrap();
6609 fs::write(source.join("file1.txt"), b"hello").unwrap();
6610
6611 let top_work = source.join(DEFAULT_WORK_FOLDER);
6613 fs::create_dir_all(&top_work).unwrap();
6614
6615 let err = copy_package_tree(&source, &dest).unwrap_err();
6616 assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
6617 }
6618}