1use std::collections::{BTreeMap, BTreeSet};
113use std::fmt;
114use std::num::NonZeroU16;
115use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
116use std::sync::{Arc, Mutex};
117use std::time::Duration;
118
119use runner_manager_domain::attempt::{
120 AttemptOutcome, AttemptState, FailureReason, IsolationProviderFailure, RunnerAttempt,
121};
122use runner_manager_domain::capacity::{Allocation, HostAllocator, LimitingFactor};
123use runner_manager_domain::model::{
124 AttemptId, Clock, Host, IdlePollInterval, Org, OwnerRepo, PolicyId, RefreshInterval,
125 ScaleTarget, Timestamp,
126};
127use runner_manager_domain::policy::{DemandTally, ScalePolicy};
128use runner_manager_github::demand::{DemandGateway, QueuedDemand, demand_requests_per_poll};
129use runner_manager_github::rest::{
130 ActivityScope, CancelToken, InventoryError, RateLimitKind, RefreshState,
131};
132use runner_manager_github::traffic::{PrimaryPressure, RateLimitSnapshot};
133
134pub const REPOSITORY_LIST_REFRESH_MULTIPLE: u32 = 30;
154
155pub const MAX_OFFLINE_BACKOFF: Duration = Duration::from_secs(15 * 60);
164
165const MAX_BACKOFF_DOUBLINGS: u32 = 5;
171
172const JITTER_RATIO: f64 = 0.5;
180
181const RATE_LIMIT_JITTER_RATIO: f64 = 0.1;
189
190pub const MAX_IDLE_REQUESTS_PER_MINUTE_PER_TARGET: u32 = 300;
198
199pub const GITHUB_CANCELS_QUEUED_JOBS_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
206
207pub const ALLOCATION_LOCK_WAIT: Duration = Duration::from_secs(5);
237
238#[derive(Debug, Clone, PartialEq, Eq)]
255pub enum PollOutcome {
256 Ready(QueuedDemand),
259 Failed(RefreshState),
262}
263
264impl PollOutcome {
265 #[must_use]
267 pub const fn reading(&self) -> Option<&QueuedDemand> {
268 match self {
269 Self::Ready(demand) => Some(demand),
270 Self::Failed(_) => None,
271 }
272 }
273
274 #[must_use]
276 pub const fn failure(&self) -> Option<&RefreshState> {
277 match self {
278 Self::Failed(state) => Some(state),
279 Self::Ready(_) => None,
280 }
281 }
282
283 #[must_use]
290 pub fn is_offline(&self) -> bool {
291 matches!(self, Self::Failed(RefreshState::Offline))
292 }
293}
294
295#[async_trait::async_trait]
303pub trait DemandSource: fmt::Debug + Send + Sync {
304 async fn poll(&self, scope: &ActivityScope) -> PollOutcome;
306}
307
308#[derive(Debug)]
313pub struct GatewayDemand<G> {
314 gateway: G,
315 cancel: CancelToken,
316}
317
318impl<G: DemandGateway> GatewayDemand<G> {
319 #[must_use]
320 pub const fn new(gateway: G, cancel: CancelToken) -> Self {
321 Self { gateway, cancel }
322 }
323
324 #[must_use]
325 pub const fn gateway(&self) -> &G {
326 &self.gateway
327 }
328}
329
330#[async_trait::async_trait]
331impl<G: DemandGateway + 'static> DemandSource for GatewayDemand<G> {
332 async fn poll(&self, scope: &ActivityScope) -> PollOutcome {
333 match self.gateway.queued_demand(scope, &self.cancel).await {
334 Ok(demand) => PollOutcome::Ready(demand),
335 Err(error) => PollOutcome::Failed(RefreshState::from_error(&error)),
339 }
340 }
341}
342
343#[async_trait::async_trait]
354pub trait RepositoryDirectory: fmt::Debug + Send + Sync {
355 async fn repositories(&self, org: &Org) -> Result<Vec<OwnerRepo>, InventoryError>;
360}
361
362#[derive(Debug, Clone)]
363struct CachedRepositories {
364 repositories: Vec<OwnerRepo>,
365 fetched_at: Timestamp,
366}
367
368#[derive(Debug)]
386pub struct RepositoryCache {
387 directory: Arc<dyn RepositoryDirectory>,
388 clock: Arc<dyn Clock>,
389 ttl: Duration,
390 entries: Mutex<BTreeMap<Org, CachedRepositories>>,
391 lookups: AtomicU64,
392}
393
394impl RepositoryCache {
395 #[must_use]
398 pub fn new(
399 directory: Arc<dyn RepositoryDirectory>,
400 clock: Arc<dyn Clock>,
401 poll: RefreshInterval,
402 ) -> Self {
403 let ttl = Duration::from_secs(u64::from(poll.as_secs()))
404 .saturating_mul(REPOSITORY_LIST_REFRESH_MULTIPLE);
405 Self {
406 directory,
407 clock,
408 ttl,
409 entries: Mutex::new(BTreeMap::new()),
410 lookups: AtomicU64::new(0),
411 }
412 }
413
414 #[must_use]
416 pub const fn ttl(&self) -> Duration {
417 self.ttl
418 }
419
420 #[must_use]
425 pub fn lookups(&self) -> u64 {
426 self.lookups.load(Ordering::SeqCst)
427 }
428
429 pub async fn scope_for(&self, target: &ScaleTarget) -> Result<ActivityScope, InventoryError> {
435 match target {
436 ScaleTarget::Repository(repository) => {
437 Ok(ActivityScope::repository(repository.clone()))
438 }
439 ScaleTarget::Organization(org) => {
440 let repositories = self.repositories_of(org).await?;
441 Ok(ActivityScope::organization(org.clone(), repositories))
442 }
443 }
444 }
445
446 async fn repositories_of(&self, org: &Org) -> Result<Vec<OwnerRepo>, InventoryError> {
447 let now = self.clock.now();
448 if let Some(fresh) = self.fresh_entry(org, now) {
449 return Ok(fresh);
450 }
451
452 let repositories = self.directory.repositories(org).await?;
459 self.lookups.fetch_add(1, Ordering::SeqCst);
460 self.store(org.clone(), repositories.clone(), now);
461 Ok(repositories)
462 }
463
464 fn fresh_entry(&self, org: &Org, now: Timestamp) -> Option<Vec<OwnerRepo>> {
465 let entries = self.entries.lock().ok()?;
466 let entry = entries.get(org)?;
467 let age = now.signed_duration_since(entry.fetched_at).to_std().ok()?;
468 (age < self.ttl).then(|| entry.repositories.clone())
469 }
470
471 fn store(&self, org: Org, repositories: Vec<OwnerRepo>, fetched_at: Timestamp) {
472 if let Ok(mut entries) = self.entries.lock() {
473 entries.insert(
474 org,
475 CachedRepositories {
476 repositories,
477 fetched_at,
478 },
479 );
480 }
481 }
482}
483
484pub trait Jitter: fmt::Debug + Send + Sync {
495 fn fraction(&self) -> f64;
498}
499
500#[derive(Debug, Clone, Copy, Default)]
502pub struct RandomJitter;
503
504impl Jitter for RandomJitter {
505 fn fraction(&self) -> f64 {
506 rand::random::<f64>()
507 }
508}
509
510#[derive(Debug, Clone, Copy)]
512pub struct FixedJitter(pub f64);
513
514impl Jitter for FixedJitter {
515 fn fraction(&self) -> f64 {
516 self.0
517 }
518}
519
520#[derive(Debug, Clone, Copy, Default)]
522pub struct NoJitter;
523
524impl Jitter for NoJitter {
525 fn fraction(&self) -> f64 {
526 0.0
527 }
528}
529
530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub enum PollPace {
542 Nominal,
544 Idle,
547 Stretched { pressure: PrimaryPressure },
552 RateLimited { kind: RateLimitKind },
554 LockedOut,
556 Offline { consecutive: u32 },
559 Blocked,
564}
565
566impl PollPace {
567 #[must_use]
569 pub const fn is_throttled(&self) -> bool {
570 !matches!(self, Self::Nominal | Self::Idle)
571 }
572
573 #[must_use]
575 pub const fn as_str(&self) -> &'static str {
576 match self {
577 Self::Nominal => "nominal",
578 Self::Idle => "idle",
579 Self::Stretched {
580 pressure: PrimaryPressure::Normal,
581 } => "nominal",
582 Self::Stretched {
583 pressure: PrimaryPressure::Low,
584 } => "stretched_low_budget",
585 Self::Stretched {
586 pressure: PrimaryPressure::Critical,
587 } => "stretched_critical_budget",
588 Self::RateLimited {
589 kind: RateLimitKind::Primary,
590 } => "rate_limited_primary",
591 Self::RateLimited {
592 kind: RateLimitKind::Secondary,
593 } => "rate_limited_secondary",
594 Self::LockedOut => "locked_out",
595 Self::Offline { .. } => "offline",
596 Self::Blocked => "blocked",
597 }
598 }
599}
600
601impl fmt::Display for PollPace {
602 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
603 f.write_str(self.as_str())
604 }
605}
606
607#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub struct NextPoll {
610 pub delay: Duration,
611 pub pace: PollPace,
612}
613
614#[derive(Debug, Clone)]
634pub struct PollSchedule {
635 interval: RefreshInterval,
636 idle: Duration,
639 consecutive_offline: u32,
640 offline_since: Option<Timestamp>,
641}
642
643#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
645pub struct PollConditions {
646 pub quiet: bool,
649 pub quota: Option<RateLimitSnapshot>,
651 pub requests_per_pass: u32,
655}
656
657impl PollSchedule {
658 #[must_use]
659 pub const fn new(interval: RefreshInterval) -> Self {
660 Self {
661 interval,
662 idle: Duration::from_secs(interval.as_secs() as u64),
663 consecutive_offline: 0,
664 offline_since: None,
665 }
666 }
667
668 #[must_use]
673 pub fn with_idle(mut self, idle: Duration) -> Self {
674 self.set_intervals(self.interval, idle);
675 self
676 }
677
678 pub fn set_intervals(&mut self, interval: RefreshInterval, idle: Duration) {
680 self.interval = interval;
681 self.idle = idle.min(self.nominal()).max(Self::idle_floor());
682 }
683
684 #[must_use]
685 pub const fn interval(&self) -> RefreshInterval {
686 self.interval
687 }
688
689 #[must_use]
691 pub const fn idle(&self) -> Duration {
692 self.idle
693 }
694
695 #[must_use]
698 pub const fn idle_floor() -> Duration {
699 Duration::from_secs(IdlePollInterval::MIN_SECS as u64)
700 }
701
702 #[must_use]
704 pub const fn nominal(&self) -> Duration {
705 Duration::from_secs(self.interval.as_secs() as u64)
706 }
707
708 #[must_use]
710 pub const fn consecutive_offline(&self) -> u32 {
711 self.consecutive_offline
712 }
713
714 #[must_use]
723 pub fn offline_for(&self, now: Timestamp) -> Option<Duration> {
724 let since = self.offline_since?;
725 now.signed_duration_since(since).to_std().ok()
726 }
727
728 #[must_use]
730 pub const fn floor() -> Duration {
731 Duration::from_secs(RefreshInterval::MIN_SECS as u64)
732 }
733
734 pub fn next_poll(
742 &mut self,
743 failure: Option<&RefreshState>,
744 now: Timestamp,
745 jitter: &dyn Jitter,
746 ) -> NextPoll {
747 self.next_poll_with(failure, PollConditions::default(), now, jitter)
748 }
749
750 pub fn next_poll_with(
765 &mut self,
766 failure: Option<&RefreshState>,
767 conditions: PollConditions,
768 now: Timestamp,
769 jitter: &dyn Jitter,
770 ) -> NextPoll {
771 let nominal = self.nominal();
772
773 let next = match failure {
774 None => {
775 self.recovered();
776 let pressure = conditions
777 .quota
778 .map_or(PrimaryPressure::Normal, |quota| quota.pressure(now));
779 match (pressure, conditions.quota) {
780 (PrimaryPressure::Low | PrimaryPressure::Critical, Some(quota)) => NextPoll {
781 delay: nominal
782 .saturating_mul(pressure.stretch_factor())
783 .min(quota.reset_in(now).max(nominal)),
784 pace: PollPace::Stretched { pressure },
785 },
786 _ if conditions.quiet && self.idle < nominal => NextPoll {
789 delay: self.idle.max(idle_floor_for(conditions.requests_per_pass)),
790 pace: PollPace::Idle,
791 },
792 _ => NextPoll {
793 delay: nominal,
794 pace: PollPace::Nominal,
795 },
796 }
797 }
798 Some(RefreshState::Offline) => {
799 self.consecutive_offline = self.consecutive_offline.saturating_add(1);
800 self.offline_since.get_or_insert(now);
802 NextPoll {
803 delay: self.offline_delay(nominal, jitter),
804 pace: PollPace::Offline {
805 consecutive: self.consecutive_offline,
806 },
807 }
808 }
809 Some(state @ RefreshState::RateLimited(limit)) => {
810 self.recovered();
811 let wait = retry_floor(state, now).max(nominal);
814 NextPoll {
815 delay: wait.saturating_add(
816 wait.mul_f64(RATE_LIMIT_JITTER_RATIO * jitter.fraction().clamp(0.0, 1.0)),
817 ),
818 pace: PollPace::RateLimited { kind: limit.kind },
819 }
820 }
821 Some(state @ RefreshState::LockedOut { .. }) => {
822 self.recovered();
823 NextPoll {
824 delay: retry_floor(state, now).max(nominal),
825 pace: PollPace::LockedOut,
826 }
827 }
828 Some(_) => {
834 self.recovered();
837 NextPoll {
838 delay: nominal,
839 pace: PollPace::Blocked,
840 }
841 }
842 };
843
844 debug_assert!(
845 next.delay >= Self::floor() || next.pace == PollPace::Idle,
846 "the 30-second floor is a rate-budget constraint and no charged branch may go below it"
847 );
848 debug_assert!(
849 next.delay >= Self::idle_floor(),
850 "the idle floor is a secondary-limit constraint and no branch may go below it"
851 );
852 next
853 }
854
855 fn recovered(&mut self) {
857 self.consecutive_offline = 0;
858 self.offline_since = None;
859 }
860
861 fn offline_delay(&self, nominal: Duration, jitter: &dyn Jitter) -> Duration {
862 let doublings = self
863 .consecutive_offline
864 .saturating_sub(1)
865 .min(MAX_BACKOFF_DOUBLINGS);
866 let grown = nominal.saturating_mul(1_u32 << doublings);
867 let capped = grown.min(MAX_OFFLINE_BACKOFF);
868 let spread = capped.mul_f64(JITTER_RATIO * jitter.fraction().clamp(0.0, 1.0));
874 capped.saturating_add(spread).max(Self::floor())
875 }
876}
877
878fn is_quiet(readings: &BTreeMap<ScaleTarget, PollOutcome>, report: &ReconcileReport) -> bool {
889 !readings.is_empty()
890 && readings
891 .values()
892 .all(|outcome| outcome.reading().is_some_and(QueuedDemand::is_quiet))
893 && report.started == 0
894 && report.host_capacity_unreadable == 0
897 && report.attempts_unreadable == 0
898 && report
902 .allocations
903 .iter()
904 .all(|allocation| allocation.active_owned == 0 && allocation.demand == 0)
905}
906
907fn idle_floor_for(requests_per_pass: u32) -> Duration {
909 Duration::from_secs(
910 u64::from(requests_per_pass) * 60 / u64::from(MAX_IDLE_REQUESTS_PER_MINUTE_PER_TARGET),
911 )
912}
913
914fn retry_floor(state: &RefreshState, now: Timestamp) -> Duration {
922 state.retry_delay(now).unwrap_or(PollSchedule::floor())
923}
924
925#[derive(Debug, Clone, Copy, PartialEq, Eq)]
938pub struct OfflineState {
939 pub consecutive: u32,
941 pub retry_in: Duration,
943 pub offline_for: Option<Duration>,
945}
946
947impl OfflineState {
948 #[must_use]
949 pub const fn new(consecutive: u32, retry_in: Duration) -> Self {
950 Self {
951 consecutive,
952 retry_in,
953 offline_for: None,
954 }
955 }
956
957 #[must_use]
958 pub const fn since(mut self, offline_for: Duration) -> Self {
959 self.offline_for = Some(offline_for);
960 self
961 }
962
963 #[must_use]
968 pub fn has_outlasted_the_queue(&self) -> bool {
969 self.offline_for
970 .is_some_and(|elapsed| elapsed >= GITHUB_CANCELS_QUEUED_JOBS_AFTER)
971 }
972}
973
974impl fmt::Display for OfflineState {
975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976 write!(
977 f,
978 "GitHub is unreachable; no new runners are being started and running \
979 runners are left alone. Retrying in {}s",
980 self.retry_in.as_secs()
981 )?;
982 if self.has_outlasted_the_queue() {
983 f.write_str(
984 ". This outage has lasted more than 24 hours, and GitHub cancels a queued \
985 job after 24 hours, so queued work has been lost",
986 )
987 } else {
988 f.write_str(
989 ". GitHub cancels a queued job after 24 hours, so an outage longer than \
990 that loses queued work",
991 )
992 }
993 }
994}
995
996#[derive(Debug, Clone, Copy)]
1002pub struct LaunchRequest<'a> {
1003 pub host: &'a Host,
1004 pub policy: &'a ScalePolicy,
1005 pub(crate) allocation_guard: &'a AllocationGuard,
1011 pub lock_wait: Duration,
1013}
1014
1015#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1022#[error("the runner could not be started: {reason}")]
1023pub struct LaunchFailure {
1024 pub reason: FailureReason,
1025}
1026
1027#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1030pub struct ReplacementIntent {
1031 pub policy: PolicyId,
1032 pub previous_attempt: AttemptId,
1033 pub operation: &'static str,
1034}
1035
1036impl LaunchFailure {
1037 #[must_use]
1038 pub const fn new(reason: FailureReason) -> Self {
1039 Self { reason }
1040 }
1041}
1042
1043#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1046pub enum HostCapacityError {
1047 MissingHost,
1048 JournalUnreadable,
1049}
1050
1051impl HostCapacityError {
1052 #[must_use]
1053 pub const fn reason(self) -> &'static str {
1054 match self {
1055 Self::MissingHost => "host_missing",
1056 Self::JournalUnreadable => "host_journal_unreadable",
1057 }
1058 }
1059}
1060
1061#[derive(Debug)]
1062enum AllocationFailure {
1063 HostCapacity(HostCapacityError),
1064 Attempts(LaunchFailure),
1065}
1066
1067#[async_trait::async_trait]
1104pub trait RunnerLauncher: fmt::Debug + Send + Sync {
1105 async fn host_capacity(&self, host: &Host) -> Result<NonZeroU16, HostCapacityError>;
1109
1110 async fn supervise(
1115 &self,
1116 _policy: &ScalePolicy,
1117 ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
1118 Ok(Vec::new())
1119 }
1120
1121 async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure>;
1134
1135 async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure>;
1182
1183 async fn clean(&self, attempt: AttemptId) -> Result<(), LaunchFailure>;
1191}
1192
1193#[derive(Debug)]
1204pub struct FitnessGatedLauncher {
1205 inner: Arc<dyn RunnerLauncher>,
1206 unfit: Arc<AtomicBool>,
1207}
1208
1209impl FitnessGatedLauncher {
1210 #[must_use]
1211 pub const fn new(inner: Arc<dyn RunnerLauncher>, unfit: Arc<AtomicBool>) -> Self {
1212 Self { inner, unfit }
1213 }
1214}
1215
1216#[async_trait::async_trait]
1217impl RunnerLauncher for FitnessGatedLauncher {
1218 async fn host_capacity(&self, host: &Host) -> Result<NonZeroU16, HostCapacityError> {
1219 self.inner.host_capacity(host).await
1220 }
1221
1222 async fn supervise(
1223 &self,
1224 policy: &ScalePolicy,
1225 ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
1226 self.inner.supervise(policy).await
1227 }
1228
1229 async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
1230 self.inner.attempts().await
1231 }
1232
1233 async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure> {
1234 if self.unfit.load(Ordering::Acquire) {
1235 return Err(LaunchFailure::new(FailureReason::HostUnfit));
1236 }
1237 self.inner.launch(request).await
1238 }
1239
1240 async fn clean(&self, attempt: AttemptId) -> Result<(), LaunchFailure> {
1241 self.inner.clean(attempt).await
1242 }
1243}
1244
1245pub struct AllocationGuard {
1255 _held: Box<dyn std::any::Any + Send + Sync>,
1256}
1257
1258impl AllocationGuard {
1259 #[must_use]
1261 fn new<T: Send + Sync + 'static>(held: T) -> Self {
1262 Self {
1263 _held: Box::new(held),
1264 }
1265 }
1266}
1267
1268impl fmt::Debug for AllocationGuard {
1269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1270 f.write_str("AllocationGuard")
1271 }
1272}
1273
1274#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1276#[error("the host-wide allocation lock is held by another allocator; no runtime was created")]
1277pub struct AllocationLockBusy;
1278
1279#[async_trait::async_trait]
1293pub trait AllocationLock: fmt::Debug + Send + Sync {
1294 async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy>;
1300}
1301
1302#[derive(Debug, Default)]
1310pub struct InProcessAllocationLock {
1311 mutex: Arc<tokio::sync::Mutex<()>>,
1312}
1313
1314impl InProcessAllocationLock {
1315 #[must_use]
1316 pub fn new() -> Self {
1317 Self::default()
1318 }
1319}
1320
1321#[async_trait::async_trait]
1322impl AllocationLock for InProcessAllocationLock {
1323 async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
1324 let mutex = Arc::clone(&self.mutex);
1325 let guard = mutex.lock_owned().await;
1326 Ok(AllocationGuard::new(guard))
1327 }
1328}
1329
1330#[derive(Debug, Clone)]
1345pub struct FileAllocationLock {
1346 paths: Arc<runner_manager_platform::paths::AppPaths>,
1347 wait: Duration,
1348}
1349
1350impl FileAllocationLock {
1351 #[must_use]
1352 pub const fn new(paths: Arc<runner_manager_platform::paths::AppPaths>) -> Self {
1353 Self {
1354 paths,
1355 wait: ALLOCATION_LOCK_WAIT,
1356 }
1357 }
1358
1359 #[must_use]
1360 pub const fn with_wait(mut self, wait: Duration) -> Self {
1361 self.wait = wait;
1362 self
1363 }
1364}
1365
1366#[async_trait::async_trait]
1367impl AllocationLock for FileAllocationLock {
1368 async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
1369 use runner_manager_platform::lock::{HostLock, LockKind};
1370
1371 let paths = Arc::clone(&self.paths);
1372 let wait = self.wait;
1373 let held = tokio::task::spawn_blocking(move || {
1374 HostLock::acquire(&paths, LockKind::Allocation, wait)
1375 })
1376 .await;
1377
1378 match held {
1379 Ok(Ok(lock)) => Ok(AllocationGuard::new(lock)),
1380 Ok(Err(_)) | Err(_) => Err(AllocationLockBusy),
1384 }
1385 }
1386}
1387
1388#[derive(Debug)]
1412pub struct WslRecoveryAllocationLock {
1413 paths: Arc<runner_manager_platform::paths::AppPaths>,
1414 inner: Arc<dyn AllocationLock>,
1415 blocked_after_refusals: u32,
1416 blocked_after: Duration,
1417 streak_gap: Duration,
1419 in_flight: Arc<std::sync::atomic::AtomicUsize>,
1420 refusals: Mutex<Refusals>,
1421}
1422
1423#[derive(Debug, Default)]
1425struct Refusals {
1426 streak: Option<Streak>,
1429 recorded: bool,
1430}
1431
1432#[derive(Debug, Clone, Copy)]
1433struct Streak {
1434 since: chrono::DateTime<chrono::Utc>,
1435 latest: chrono::DateTime<chrono::Utc>,
1436 count: u32,
1437}
1438
1439struct InFlight(Arc<std::sync::atomic::AtomicUsize>);
1441
1442impl InFlight {
1443 fn enter(count: &Arc<std::sync::atomic::AtomicUsize>) -> Self {
1444 count.fetch_add(1, Ordering::SeqCst);
1445 Self(Arc::clone(count))
1446 }
1447}
1448
1449impl Drop for InFlight {
1450 fn drop(&mut self) {
1451 self.0.fetch_sub(1, Ordering::SeqCst);
1452 }
1453}
1454
1455struct LaunchFenceGuard(Option<runner_manager_platform::wsl::fence::GuestLaunchClaim>);
1459
1460impl Drop for LaunchFenceGuard {
1461 fn drop(&mut self) {
1462 if let Some(claim) = self.0.take()
1463 && let Err(error) = claim.release()
1464 {
1465 tracing::warn!(
1466 %error,
1467 "the WSL launch fence could not be released; the next launch reclaims it"
1468 );
1469 }
1470 }
1471}
1472
1473impl WslRecoveryAllocationLock {
1474 #[must_use]
1475 pub fn new(
1476 paths: Arc<runner_manager_platform::paths::AppPaths>,
1477 inner: Arc<dyn AllocationLock>,
1478 ) -> Self {
1479 use runner_manager_platform::launch_health::{BLOCKED_AFTER, BLOCKED_AFTER_DEFERRALS};
1480 Self {
1481 paths,
1482 inner,
1483 blocked_after_refusals: BLOCKED_AFTER_DEFERRALS,
1484 blocked_after: BLOCKED_AFTER,
1485 streak_gap: BLOCKED_AFTER,
1486 in_flight: Arc::default(),
1487 refusals: Mutex::default(),
1488 }
1489 }
1490
1491 #[cfg(test)]
1494 const fn with_blocked_after(mut self, refusals: u32, after: Duration) -> Self {
1495 self.blocked_after_refusals = refusals;
1496 self.blocked_after = after;
1497 self
1498 }
1499
1500 #[cfg(test)]
1502 const fn with_streak_gap(mut self, gap: Duration) -> Self {
1503 self.streak_gap = gap;
1504 self
1505 }
1506
1507 fn refusals(&self) -> std::sync::MutexGuard<'_, Refusals> {
1508 self.refusals
1509 .lock()
1510 .unwrap_or_else(std::sync::PoisonError::into_inner)
1511 }
1512
1513 fn note_granted(&self) {
1514 let mut refusals = self.refusals();
1515 refusals.streak = None;
1516 if refusals.recorded {
1517 match runner_manager_platform::launch_health::clear_launches_blocked(&self.paths) {
1518 Ok(()) => refusals.recorded = false,
1519 Err(error) => tracing::warn!(%error, "the blocked-launch record cannot be cleared"),
1521 }
1522 }
1523 }
1524
1525 fn note_refused(&self, cause: &runner_manager_platform::launch_health::BlockCause) {
1526 use runner_manager_platform::launch_health::{Viewpoint, record_launches_blocked};
1527 use runner_manager_platform::wsl::fence::elapsed_at_least;
1528
1529 if self.in_flight.load(Ordering::SeqCst) > 0 {
1530 return;
1531 }
1532 let now = chrono::Utc::now();
1533 let mut refusals = self.refusals();
1534 let streak = match refusals.streak {
1537 Some(streak) if !elapsed_at_least(streak.latest, now, self.streak_gap) => Streak {
1538 latest: now,
1539 count: streak.count.saturating_add(1),
1540 ..streak
1541 },
1542 _ => Streak {
1543 since: now,
1544 latest: now,
1545 count: 1,
1546 },
1547 };
1548 refusals.streak = Some(streak);
1549 if streak.count < self.blocked_after_refusals
1550 || !elapsed_at_least(streak.since, now, self.blocked_after)
1551 {
1552 return;
1553 }
1554 let blocked = cause.blocked_since(streak.since, Viewpoint::Guest);
1555 if !refusals.recorded {
1556 tracing::warn!(
1557 refusals = streak.count,
1558 "runner launches are blocked {blocked}: {}",
1559 blocked.remedy
1560 );
1561 }
1562 match record_launches_blocked(&self.paths, &blocked, now) {
1565 Ok(()) => refusals.recorded = true,
1566 Err(error) => tracing::warn!(%error, "the blocked-launch record cannot be written"),
1567 }
1568 }
1569}
1570
1571#[async_trait::async_trait]
1572impl AllocationLock for WslRecoveryAllocationLock {
1573 async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
1574 use runner_manager_platform::launch_health::BlockCause;
1575 use runner_manager_platform::wsl::fence::{
1576 DrainRequest, FENCE_DIRECTORY, FenceClaim, GuestClaimAttempt, GuestRecoveryConfig,
1577 try_claim_guest_launch,
1578 };
1579
1580 let paths = Arc::clone(&self.paths);
1581 let claim = tokio::task::spawn_blocking(move || {
1582 let unusable = |error: &dyn fmt::Display| BlockCause::FenceUnusable {
1583 detail: error.to_string(),
1584 };
1585 let config = match GuestRecoveryConfig::read(&paths) {
1586 Ok(Some(config)) => config,
1587 Ok(None) => return Ok(LaunchFenceGuard(None)),
1588 Err(error) => return Err(unusable(&error)),
1589 };
1590 let root = config.shared_root;
1591 let claim = match try_claim_guest_launch(&root) {
1592 Ok(GuestClaimAttempt::Claimed { claim, reclaimed }) => {
1593 if let Some(reclaimed) = reclaimed {
1594 tracing::warn!(
1595 shared_root = %root.display(),
1596 %reclaimed,
1597 "reclaimed a WSL launch fence claim whose owner is gone"
1598 );
1599 }
1600 LaunchFenceGuard(Some(claim))
1603 }
1604 Ok(GuestClaimAttempt::Busy) => {
1605 let directory = root.join(FENCE_DIRECTORY);
1606 return Err(match FenceClaim::owner(&root) {
1607 Ok(owner) => BlockCause::FenceHeld { directory, owner },
1608 Err(error) => BlockCause::FenceOwnerUnreadable {
1609 directory,
1610 detail: error.to_string(),
1611 },
1612 });
1613 }
1614 Err(error) => {
1615 return Err(match FenceClaim::owner(&root) {
1618 Err(owner_error) => BlockCause::FenceOwnerUnreadable {
1619 directory: root.join(FENCE_DIRECTORY),
1620 detail: owner_error.to_string(),
1621 },
1622 Ok(_) => unusable(&error),
1623 });
1624 }
1625 };
1626 match DrainRequest::read(&root) {
1627 Ok(None) => Ok(claim),
1628 Ok(Some(_)) => Err(BlockCause::DrainRequested { root }),
1629 Err(error) => Err(unusable(&error)),
1630 }
1631 })
1632 .await
1633 .map_err(|_| AllocationLockBusy)?;
1634
1635 let claim = match claim {
1636 Ok(claim) => claim,
1637 Err(cause) => {
1638 self.note_refused(&cause);
1639 return Err(AllocationLockBusy);
1640 }
1641 };
1642 let Ok(inner) = self.inner.acquire().await else {
1643 self.note_refused(&BlockCause::AllocationLockBusy {
1644 path: self
1645 .paths
1646 .state_dir()
1647 .join(runner_manager_platform::lock::LockKind::Allocation.file_name()),
1648 });
1649 return Err(AllocationLockBusy);
1650 };
1651 self.note_granted();
1652 let in_flight = InFlight::enter(&self.in_flight);
1653 Ok(AllocationGuard::new((claim, inner, in_flight)))
1654 }
1655}
1656
1657#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1667pub enum OutcomeKind {
1668 CompletedJob,
1669 IdleExit,
1670 Failed,
1671 Orphaned,
1672}
1673
1674impl OutcomeKind {
1675 #[must_use]
1676 pub const fn of(outcome: &AttemptOutcome) -> Self {
1677 match outcome {
1678 AttemptOutcome::CompletedJob => Self::CompletedJob,
1679 AttemptOutcome::ExitedIdleWithoutWork => Self::IdleExit,
1680 AttemptOutcome::Failed { .. } => Self::Failed,
1681 AttemptOutcome::Orphaned => Self::Orphaned,
1682 }
1683 }
1684
1685 #[must_use]
1686 pub const fn is_failure(&self) -> bool {
1687 matches!(self, Self::Failed | Self::Orphaned)
1688 }
1689
1690 #[must_use]
1691 pub const fn as_str(&self) -> &'static str {
1692 match self {
1693 Self::CompletedJob => "completed_job",
1694 Self::IdleExit => "exited_idle_without_work",
1695 Self::Failed => "failed",
1696 Self::Orphaned => "orphaned",
1697 }
1698 }
1699}
1700
1701impl fmt::Display for OutcomeKind {
1702 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1703 f.write_str(self.as_str())
1704 }
1705}
1706
1707#[must_use]
1716pub const fn failure_reason_kind(reason: &FailureReason) -> &'static str {
1717 match reason {
1718 FailureReason::JitRequestFailed => "jit_request_failed",
1719 FailureReason::JitExpired => "jit_expired",
1720 FailureReason::RunnerPackageUnverified => "runner_package_unverified",
1721 FailureReason::RunnerVersionRejected => "runner_version_rejected",
1722 FailureReason::ProcessStartFailed => "process_start_failed",
1723 FailureReason::ProcessExitedUnexpectedly => "process_exited_unexpectedly",
1724 FailureReason::RegistrationTimedOut => "registration_timed_out",
1725 FailureReason::TerminatedAfterRegistrationTimeout => {
1726 "terminated_after_registration_timeout"
1727 }
1728 FailureReason::IsolationProvider(category) => match category {
1729 IsolationProviderFailure::Unsupported => "isolation_provider_unsupported",
1730 IsolationProviderFailure::NotInstalled => "isolation_provider_not_installed",
1731 IsolationProviderFailure::PermissionDenied => "isolation_provider_permission_denied",
1732 IsolationProviderFailure::ImageUnavailableOrIncompatible => {
1733 "isolation_image_unavailable"
1734 }
1735 IsolationProviderFailure::DiskQuotaUnavailable => "isolation_disk_quota_unavailable",
1736 IsolationProviderFailure::Degraded => "isolation_provider_degraded",
1737 IsolationProviderFailure::RuntimeOperationFailed => {
1738 "isolation_runtime_operation_failed"
1739 }
1740 IsolationProviderFailure::OwnershipMismatch => "isolation_ownership_mismatch",
1741 IsolationProviderFailure::UnsafeRuntimePath => "isolation_unsafe_runtime_path",
1742 IsolationProviderFailure::JitHandoffRejected => "isolation_jit_handoff_rejected",
1743 },
1744 FailureReason::WorkspaceCleanupDeferred => "ephemeral_workspace_could_not_be_removed",
1745 FailureReason::HostUnfit => "host_unfit",
1746 FailureReason::Other(_) => "other",
1747 }
1748}
1749
1750#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1752pub enum RoutingRefusal {
1753 OverlappingProfiles,
1754}
1755
1756impl RoutingRefusal {
1757 #[must_use]
1758 pub const fn as_str(self) -> &'static str {
1759 match self {
1760 Self::OverlappingProfiles => "overlapping_profile_matches",
1761 }
1762 }
1763}
1764
1765impl fmt::Display for RoutingRefusal {
1766 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1767 f.write_str(match self {
1768 Self::OverlappingProfiles => {
1769 "repair overlapping profile labels or require a unique profile selector"
1770 }
1771 })
1772 }
1773}
1774
1775#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1785pub enum LifecycleEvent {
1786 DemandObserved {
1788 policy: PolicyId,
1789 demand: u32,
1791 not_matched: u32,
1797 unresolvable: u32,
1806 complete: bool,
1808 },
1809 RoutingRefused {
1811 policy: PolicyId,
1812 reason: RoutingRefusal,
1813 count: u32,
1814 },
1815 TargetUnreadable {
1817 policy: PolicyId,
1818 reason: &'static str,
1819 },
1820 Allocated {
1822 policy: PolicyId,
1823 demand: u32,
1824 desired: u16,
1825 active_owned: u16,
1826 headroom: u16,
1827 to_start: u16,
1828 limiting: LimitingFactor,
1829 },
1830 MonitorOnlySkipped { policy: PolicyId },
1833 RunnerStarted {
1835 policy: PolicyId,
1836 attempt: AttemptId,
1837 },
1838 RunnerStartFailed {
1840 policy: PolicyId,
1841 reason: &'static str,
1842 },
1843 AllocationDeferred { policy: PolicyId, count: u16 },
1846 AttemptsUnreadable { reason: &'static str },
1852 HostCapacityUnreadable { reason: HostCapacityError },
1854 AttemptCleaned {
1856 policy: PolicyId,
1857 attempt: AttemptId,
1858 outcome: OutcomeKind,
1859 },
1860 AttemptCleanFailed {
1863 policy: PolicyId,
1864 attempt: AttemptId,
1865 reason: &'static str,
1866 },
1867 ScaleDownRefused {
1869 policy: PolicyId,
1870 attempt: AttemptId,
1871 },
1872 PollScheduled { retry_in_ms: u64, pace: PollPace },
1874}
1875
1876impl LifecycleEvent {
1877 #[must_use]
1879 pub const fn name(&self) -> &'static str {
1880 match self {
1881 Self::DemandObserved { .. } => "demand_observed",
1882 Self::RoutingRefused { .. } => "routing_refused",
1883 Self::TargetUnreadable { .. } => "target_unreadable",
1884 Self::Allocated { .. } => "allocated",
1885 Self::MonitorOnlySkipped { .. } => "monitor_only_skipped",
1886 Self::RunnerStarted { .. } => "runner_started",
1887 Self::RunnerStartFailed { .. } => "runner_start_failed",
1888 Self::AllocationDeferred { .. } => "allocation_deferred",
1889 Self::AttemptsUnreadable { .. } => "attempts_unreadable",
1890 Self::HostCapacityUnreadable { .. } => "host_capacity_unreadable",
1891 Self::AttemptCleaned { .. } => "attempt_cleaned",
1892 Self::AttemptCleanFailed { .. } => "attempt_clean_failed",
1893 Self::ScaleDownRefused { .. } => "scale_down_refused",
1894 Self::PollScheduled { .. } => "poll_scheduled",
1895 }
1896 }
1897
1898 #[must_use]
1900 pub const fn policy(&self) -> Option<PolicyId> {
1901 match self {
1902 Self::DemandObserved { policy, .. }
1903 | Self::RoutingRefused { policy, .. }
1904 | Self::TargetUnreadable { policy, .. }
1905 | Self::Allocated { policy, .. }
1906 | Self::MonitorOnlySkipped { policy }
1907 | Self::RunnerStarted { policy, .. }
1908 | Self::RunnerStartFailed { policy, .. }
1909 | Self::AllocationDeferred { policy, .. }
1910 | Self::AttemptCleaned { policy, .. }
1911 | Self::AttemptCleanFailed { policy, .. }
1912 | Self::ScaleDownRefused { policy, .. } => Some(*policy),
1913 Self::PollScheduled { .. }
1914 | Self::AttemptsUnreadable { .. }
1915 | Self::HostCapacityUnreadable { .. } => None,
1916 }
1917 }
1918}
1919
1920impl fmt::Display for LifecycleEvent {
1921 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1922 match self {
1923 Self::DemandObserved {
1924 policy,
1925 demand,
1926 not_matched,
1927 unresolvable,
1928 complete,
1929 } => write!(
1930 f,
1931 "policy {policy}: {demand} queued jobs for this host{}{}{}",
1932 if *not_matched == 0 {
1933 String::new()
1934 } else {
1935 format!(", {not_matched} for other labels")
1936 },
1937 if *unresolvable == 0 {
1938 String::new()
1939 } else {
1940 format!(", {unresolvable} with an unresolvable `runs-on`")
1941 },
1942 if *complete {
1943 ""
1944 } else {
1945 " (a floor, not a total)"
1946 }
1947 ),
1948 Self::TargetUnreadable { policy, reason } => {
1949 write!(f, "policy {policy}: target unreadable ({reason})")
1950 }
1951 Self::RoutingRefused {
1952 policy,
1953 reason,
1954 count,
1955 } => write!(f, "policy {policy}: {count} queued jobs blocked: {reason}"),
1956 Self::Allocated {
1957 policy,
1958 demand,
1959 desired,
1960 active_owned,
1961 headroom,
1962 to_start,
1963 limiting,
1964 } => write!(
1965 f,
1966 "policy {policy}: demand {demand}, desired {desired}, {active_owned} in \
1967 flight, {headroom} free on this host, starting {to_start} ({limiting})"
1968 ),
1969 Self::MonitorOnlySkipped { policy } => {
1970 write!(f, "policy {policy}: monitor-only, skipped")
1971 }
1972 Self::RunnerStarted { policy, attempt } => {
1973 write!(f, "policy {policy}: started attempt {attempt}")
1974 }
1975 Self::RunnerStartFailed { policy, reason } => {
1976 write!(f, "policy {policy}: could not start a runner ({reason})")
1977 }
1978 Self::AllocationDeferred { policy, count } => write!(
1979 f,
1980 "policy {policy}: the allocation lock was held; {count} granted runners \
1981 were not created"
1982 ),
1983 Self::AttemptsUnreadable { reason } => write!(
1984 f,
1985 "the host's attempt set could not be read ({reason}); nothing was started, \
1986 and this is not the same as the host being idle"
1987 ),
1988 Self::HostCapacityUnreadable { reason } => write!(
1989 f,
1990 "the host capacity could not be read ({}); new launches wait for readable host settings",
1991 reason.reason()
1992 ),
1993 Self::AttemptCleaned {
1994 policy,
1995 attempt,
1996 outcome,
1997 } => write!(f, "policy {policy}: cleaned attempt {attempt} ({outcome})"),
1998 Self::AttemptCleanFailed {
1999 policy,
2000 attempt,
2001 reason,
2002 } => write!(
2003 f,
2004 "policy {policy}: attempt {attempt} could not be cleaned ({reason}); it \
2005 will be retried"
2006 ),
2007 Self::ScaleDownRefused { policy, attempt } => write!(
2008 f,
2009 "policy {policy}: attempt {attempt} is executing a job and was not removed"
2010 ),
2011 Self::PollScheduled { retry_in_ms, pace } => {
2012 write!(f, "next poll in {retry_in_ms}ms ({pace})")
2013 }
2014 }
2015 }
2016}
2017
2018pub trait EventSink: fmt::Debug + Send + Sync {
2020 fn emit(&self, event: LifecycleEvent);
2021}
2022
2023#[derive(Debug, Clone, Copy, Default)]
2025pub struct NoEvents;
2026
2027impl EventSink for NoEvents {
2028 fn emit(&self, _event: LifecycleEvent) {}
2029}
2030
2031#[derive(Debug, Clone, Copy, Default)]
2039pub struct TracingEvents;
2040
2041impl EventSink for TracingEvents {
2042 fn emit(&self, event: LifecycleEvent) {
2043 let name = event.name();
2044 match event {
2045 LifecycleEvent::DemandObserved {
2046 policy,
2047 demand,
2048 not_matched,
2049 unresolvable,
2050 complete,
2051 } => {
2052 if demand == 0 && not_matched == 0 && unresolvable == 0 && complete {
2057 tracing::debug!(
2058 event = name,
2059 policy_id = %policy,
2060 demand,
2061 not_matched,
2062 unresolvable,
2063 count = u64::from(complete),
2064 );
2065 } else {
2066 tracing::info!(
2067 event = name,
2068 policy_id = %policy,
2069 demand,
2070 not_matched,
2071 unresolvable,
2072 count = u64::from(complete),
2073 );
2074 }
2075 }
2095 LifecycleEvent::TargetUnreadable { policy, reason } => {
2096 tracing::warn!(event = name, policy_id = %policy, reason);
2097 }
2098 LifecycleEvent::RoutingRefused {
2099 policy,
2100 reason,
2101 count,
2102 } => tracing::warn!(
2103 event = name,
2104 policy_id = %policy,
2105 reason = reason.as_str(),
2106 count,
2107 "{reason}"
2108 ),
2109 LifecycleEvent::Allocated {
2110 policy,
2111 demand,
2112 desired,
2113 active_owned,
2114 headroom,
2115 to_start,
2116 limiting,
2117 } if demand == 0 && to_start == 0 && active_owned == 0 => tracing::debug!(
2118 event = name,
2121 policy_id = %policy,
2122 demand,
2123 desired,
2124 capacity = active_owned,
2125 headroom,
2126 count = to_start,
2127 reason = %limiting,
2128 ),
2129 LifecycleEvent::Allocated {
2130 policy,
2131 demand,
2132 desired,
2133 active_owned,
2134 headroom,
2135 to_start,
2136 limiting,
2137 } => tracing::info!(
2138 event = name,
2139 policy_id = %policy,
2140 demand,
2141 desired,
2142 capacity = active_owned,
2143 headroom,
2144 count = to_start,
2145 reason = %limiting,
2146 ),
2147 LifecycleEvent::MonitorOnlySkipped { policy } => {
2148 tracing::debug!(event = name, policy_id = %policy, mode = "monitor_only");
2149 }
2150 LifecycleEvent::RunnerStarted { policy, attempt } => {
2151 tracing::info!(event = name, policy_id = %policy, attempt_id = %attempt);
2152 }
2153 LifecycleEvent::RunnerStartFailed { policy, reason } => {
2154 tracing::warn!(event = name, policy_id = %policy, reason);
2155 }
2156 LifecycleEvent::AllocationDeferred { policy, count } => {
2157 tracing::warn!(
2163 event = name,
2164 policy_id = %policy,
2165 reason = "allocation_lock_unavailable",
2166 count
2167 );
2168 }
2169 LifecycleEvent::AttemptsUnreadable { reason } => {
2170 tracing::warn!(event = name, reason);
2171 }
2172 LifecycleEvent::HostCapacityUnreadable { reason } => {
2173 tracing::warn!(event = name, reason = reason.reason());
2174 }
2175 LifecycleEvent::AttemptCleaned {
2176 policy,
2177 attempt,
2178 outcome,
2179 } => tracing::info!(
2180 event = name,
2181 policy_id = %policy,
2182 attempt_id = %attempt,
2183 outcome = outcome.as_str(),
2184 ),
2185 LifecycleEvent::AttemptCleanFailed {
2186 policy,
2187 attempt,
2188 reason,
2189 } => tracing::warn!(
2190 event = name,
2191 policy_id = %policy,
2192 attempt_id = %attempt,
2193 reason,
2194 ),
2195 LifecycleEvent::ScaleDownRefused { policy, attempt } => tracing::info!(
2196 event = name,
2197 policy_id = %policy,
2198 attempt_id = %attempt,
2199 attempt_state = "busy",
2200 ),
2201 LifecycleEvent::PollScheduled { retry_in_ms, pace } => {
2202 if pace == PollPace::Idle {
2203 tracing::debug!(event = name, retry_in_ms, state = pace.as_str());
2204 } else {
2205 tracing::info!(event = name, retry_in_ms, state = pace.as_str());
2206 }
2207 }
2208 }
2209 }
2210}
2211
2212#[derive(Debug, Default)]
2216pub struct EventLog {
2217 events: Mutex<Vec<LifecycleEvent>>,
2218}
2219
2220impl EventLog {
2221 #[must_use]
2222 pub fn new() -> Self {
2223 Self::default()
2224 }
2225
2226 #[must_use]
2227 pub fn events(&self) -> Vec<LifecycleEvent> {
2228 self.events.lock().map(|e| e.clone()).unwrap_or_default()
2229 }
2230
2231 #[must_use]
2233 pub fn count_of(&self, name: &str) -> usize {
2234 self.events()
2235 .iter()
2236 .filter(|event| event.name() == name)
2237 .count()
2238 }
2239}
2240
2241impl EventSink for EventLog {
2242 fn emit(&self, event: LifecycleEvent) {
2243 if let Ok(mut events) = self.events.lock() {
2244 events.push(event);
2245 }
2246 }
2247}
2248
2249#[derive(Debug)]
2252pub struct TeeEvents(pub Arc<dyn EventSink>, pub Arc<dyn EventSink>);
2253
2254impl EventSink for TeeEvents {
2255 fn emit(&self, event: LifecycleEvent) {
2256 self.0.emit(event);
2257 self.1.emit(event);
2258 }
2259}
2260
2261pub struct ReconcilerPorts {
2271 pub demand: Arc<dyn DemandSource>,
2272 pub launcher: Arc<dyn RunnerLauncher>,
2273 pub lock: Arc<dyn AllocationLock>,
2274 pub directory: Arc<dyn RepositoryDirectory>,
2275 pub clock: Arc<dyn Clock>,
2276 pub jitter: Arc<dyn Jitter>,
2277 pub events: Arc<dyn EventSink>,
2278}
2279
2280impl fmt::Debug for ReconcilerPorts {
2281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2282 f.debug_struct("ReconcilerPorts").finish_non_exhaustive()
2283 }
2284}
2285
2286#[derive(Debug, Clone, Default)]
2293pub struct ReconcileReport {
2294 pub allocations: Vec<Allocation>,
2296 pub monitor_only: Vec<PolicyId>,
2298 pub unreadable: Vec<PolicyId>,
2300 pub targets_read: u16,
2308 pub started: u16,
2310 pub replacement_intents: u16,
2313 pub cleaned: u16,
2315 pub idle_exits: u16,
2318 pub failures: u16,
2320 pub deferred: u16,
2329 pub attempts_unreadable: u16,
2348 pub host_capacity_unreadable: u16,
2350 pub clean_failures: u16,
2352 pub failure: Option<RefreshState>,
2354 pub offline: Option<OfflineState>,
2357 pub next_poll: NextPoll,
2359 pub demand_requests: u32,
2361}
2362
2363impl ReconcileReport {
2364 #[must_use]
2391 pub const fn reached_github(&self) -> bool {
2392 self.targets_read > 0
2393 }
2394}
2395
2396impl Default for NextPoll {
2397 fn default() -> Self {
2398 Self {
2399 delay: PollSchedule::floor(),
2400 pace: PollPace::Nominal,
2401 }
2402 }
2403}
2404
2405impl ReconcileReport {
2406 #[must_use]
2408 pub fn is_offline(&self) -> bool {
2409 matches!(self.failure, Some(RefreshState::Offline))
2410 }
2411
2412 #[must_use]
2414 pub const fn offline_state(&self) -> Option<&OfflineState> {
2415 self.offline.as_ref()
2416 }
2417
2418 #[must_use]
2420 pub const fn starts_nothing(&self) -> bool {
2421 self.started == 0
2422 }
2423}
2424
2425#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2427pub struct ScaleDownReport {
2428 pub removed: u16,
2430 pub refused_busy: u16,
2432 pub clean_failures: u16,
2434 pub retained: u16,
2437 pub attempts_unreadable: bool,
2447}
2448
2449impl ScaleDownReport {
2450 #[must_use]
2455 pub const fn is_conclusive(&self) -> bool {
2456 !self.attempts_unreadable
2457 }
2458}
2459
2460const CLEAN_RETRY_INITIAL: Duration = Duration::from_secs(30);
2468
2469const CLEAN_RETRY_MAXIMUM: Duration = Duration::from_secs(30 * 60);
2471
2472#[derive(Debug, Clone, Copy)]
2474struct CleanRetry {
2475 failures: u32,
2476 not_before: Timestamp,
2477}
2478
2479#[derive(Debug, Default)]
2483pub(crate) struct CleanBackoff {
2484 retries: BTreeMap<AttemptId, CleanRetry>,
2485}
2486
2487impl CleanBackoff {
2488 const SCHEDULE: crate::lifecycle::RetryPolicy =
2490 crate::lifecycle::RetryPolicy::bounded(u32::MAX, CLEAN_RETRY_INITIAL, CLEAN_RETRY_MAXIMUM);
2491
2492 pub(crate) fn is_due(&self, attempt: AttemptId, now: Timestamp) -> bool {
2494 self.retries
2495 .get(&attempt)
2496 .is_none_or(|retry| now >= retry.not_before)
2497 }
2498
2499 pub(crate) fn failed(&mut self, attempt: AttemptId, now: Timestamp) {
2501 let failures = self
2502 .retries
2503 .get(&attempt)
2504 .map_or(1, |retry| retry.failures.saturating_add(1));
2505 let delay = Self::SCHEDULE.delay(failures);
2506 self.retries.insert(
2507 attempt,
2508 CleanRetry {
2509 failures,
2510 not_before: now + chrono::Duration::from_std(delay).unwrap_or_default(),
2512 },
2513 );
2514 }
2515
2516 pub(crate) fn succeeded(&mut self, attempt: AttemptId) {
2518 self.retries.remove(&attempt);
2519 }
2520
2521 fn retain(&mut self, present: &BTreeSet<AttemptId>) {
2524 self.retries.retain(|attempt, _| present.contains(attempt));
2525 }
2526}
2527
2528#[derive(Debug)]
2534pub struct Reconciler {
2535 host: Host,
2536 demand: Arc<dyn DemandSource>,
2537 launcher: Arc<dyn RunnerLauncher>,
2538 lock: Arc<dyn AllocationLock>,
2539 repositories: RepositoryCache,
2540 clock: Arc<dyn Clock>,
2541 jitter: Arc<dyn Jitter>,
2542 events: Arc<dyn EventSink>,
2543 schedule: PollSchedule,
2544 clean_backoff: CleanBackoff,
2545}
2546
2547impl Reconciler {
2548 #[must_use]
2550 pub fn new(host: Host, ports: ReconcilerPorts) -> Self {
2551 let interval = host.refresh_interval;
2552 let repositories = RepositoryCache::new(
2553 Arc::clone(&ports.directory),
2554 Arc::clone(&ports.clock),
2555 interval,
2556 );
2557 Self {
2558 host,
2559 demand: ports.demand,
2560 launcher: ports.launcher,
2561 lock: ports.lock,
2562 repositories,
2563 clock: ports.clock,
2564 jitter: ports.jitter,
2565 events: ports.events,
2566 schedule: PollSchedule::new(interval),
2567 clean_backoff: CleanBackoff::default(),
2568 }
2569 }
2570
2571 #[must_use]
2572 pub const fn host(&self) -> &Host {
2573 &self.host
2574 }
2575
2576 #[must_use]
2577 pub const fn schedule(&self) -> &PollSchedule {
2578 &self.schedule
2579 }
2580
2581 pub fn set_intervals(&mut self, active: RefreshInterval, idle: Duration) {
2583 self.host.refresh_interval = active;
2584 self.schedule.set_intervals(active, idle);
2585 }
2586
2587 #[must_use]
2589 pub const fn repositories(&self) -> &RepositoryCache {
2590 &self.repositories
2591 }
2592
2593 pub async fn reconcile(&mut self, policies: &[ScalePolicy]) -> ReconcileReport {
2607 let mut report = ReconcileReport::default();
2608 let mut launched: Vec<RunnerAttempt> = Vec::new();
2612
2613 let mut pollable: Vec<&ScalePolicy> = Vec::new();
2615 let mut supervision_failed = BTreeSet::new();
2616 for policy in policies {
2617 if !policy.owns_runners() {
2618 report.monitor_only.push(policy.id);
2619 self.events
2620 .emit(LifecycleEvent::MonitorOnlySkipped { policy: policy.id });
2621 continue;
2622 }
2623 if !policy.is_owned_by(self.host.id) {
2624 continue;
2628 }
2629 match self.launcher.supervise(policy).await {
2630 Ok(intents) => {
2631 report.replacement_intents = report
2632 .replacement_intents
2633 .saturating_add(u16::try_from(intents.len()).unwrap_or(u16::MAX));
2634 }
2635 Err(failure) => {
2636 supervision_failed.insert(policy.id);
2637 self.report_unreadable_attempts(&mut report, &failure);
2638 continue;
2639 }
2640 }
2641 if !policy.may_start_runners() {
2642 continue;
2643 }
2644 pollable.push(policy);
2645 }
2646
2647 let readings = self.poll_targets(&pollable, &mut report).await;
2648 report.targets_read = u16::try_from(
2649 readings
2650 .values()
2651 .filter(|outcome| matches!(outcome, PollOutcome::Ready(_)))
2652 .count(),
2653 )
2654 .unwrap_or(u16::MAX);
2655 let mut routed = BTreeMap::new();
2656 for (target, outcome) in &readings {
2657 let PollOutcome::Ready(reading) = outcome else {
2658 continue;
2659 };
2660 let profiles: Vec<&ScalePolicy> = pollable
2661 .iter()
2662 .copied()
2663 .filter(|policy| &policy.target == target)
2664 .collect();
2665 let (tallies, refusals) = route_demand(policies, &profiles, reading);
2666 if let Some(first) = profiles.first() {
2667 for (reason, count) in refusals {
2668 self.events.emit(LifecycleEvent::RoutingRefused {
2669 policy: first.id,
2670 reason,
2671 count,
2672 });
2673 }
2674 }
2675 routed.insert(target.clone(), tallies);
2676 }
2677
2678 self.clean_terminal_attempts(&mut report).await;
2688
2689 for policy in policies {
2704 if !policy.owns_runners() {
2705 continue;
2711 }
2712 if !policy.is_owned_by(self.host.id) || !policy.may_start_runners() {
2713 match self.allocate_only(policy, 0, &launched).await {
2717 Ok(allocation) => {
2718 self.emit_allocation(&allocation);
2719 report.allocations.push(allocation);
2720 }
2721 Err(failure) => self.report_allocation_failure(&mut report, &failure),
2722 }
2723 continue;
2724 }
2725 if supervision_failed.contains(&policy.id) {
2726 continue;
2727 }
2728 let Some(reading) = readings.get(&policy.target) else {
2729 debug_assert!(false, "a pollable policy's target has no reading");
2732 continue;
2733 };
2734 match reading {
2735 PollOutcome::Failed(state) => {
2736 report.unreadable.push(policy.id);
2737 self.events.emit(LifecycleEvent::TargetUnreadable {
2738 policy: policy.id,
2739 reason: unreadable_reason(state),
2740 });
2741 }
2742 PollOutcome::Ready(demand) => {
2743 let tally = routed
2744 .get(&policy.target)
2745 .and_then(|tallies| tallies.get(&policy.id))
2746 .expect("every pollable profile has a routed tally");
2747 let count = tally.demand();
2748 self.events.emit(LifecycleEvent::DemandObserved {
2749 policy: policy.id,
2750 demand: count,
2751 not_matched: tally.not_matched,
2752 unresolvable: u32::try_from(tally.unresolvable.len()).unwrap_or(u32::MAX),
2753 complete: demand.is_complete(),
2754 });
2755 self.start_runners(policy, count, &mut report, &mut launched)
2756 .await;
2757 }
2758 }
2759 }
2760
2761 let failure = readings
2763 .values()
2764 .filter_map(PollOutcome::failure)
2765 .max_by_key(|state| severity(state))
2766 .cloned();
2767 let now = self.clock.now();
2768 let conditions = PollConditions {
2769 quiet: is_quiet(&readings, &report),
2770 requests_per_pass: report.demand_requests,
2771 quota: readings
2772 .values()
2773 .filter_map(PollOutcome::reading)
2774 .filter_map(QueuedDemand::rate_limit)
2775 .max_by_key(|quota| quota.observed_at)
2776 .copied(),
2777 };
2778 report.next_poll =
2779 self.schedule
2780 .next_poll_with(failure.as_ref(), conditions, now, self.jitter.as_ref());
2781 report.failure = failure;
2782 if let PollPace::Offline { consecutive } = report.next_poll.pace {
2786 let state = OfflineState::new(consecutive, report.next_poll.delay);
2787 report.offline = Some(match self.schedule.offline_for(now) {
2788 Some(elapsed) => state.since(elapsed),
2789 None => state,
2790 });
2791 }
2792 self.events.emit(LifecycleEvent::PollScheduled {
2793 retry_in_ms: u64::try_from(report.next_poll.delay.as_millis()).unwrap_or(u64::MAX),
2794 pace: report.next_poll.pace,
2795 });
2796
2797 report
2798 }
2799
2800 async fn poll_targets(
2808 &self,
2809 pollable: &[&ScalePolicy],
2810 report: &mut ReconcileReport,
2811 ) -> BTreeMap<ScaleTarget, PollOutcome> {
2812 let targets: BTreeSet<ScaleTarget> = pollable.iter().map(|p| p.target.clone()).collect();
2813
2814 let mut readings = BTreeMap::new();
2815 for target in targets {
2816 let outcome = match self.repositories.scope_for(&target).await {
2817 Ok(scope) => {
2818 report.demand_requests = report
2819 .demand_requests
2820 .saturating_add(demand_requests_per_poll(&scope));
2821 self.demand.poll(&scope).await
2822 }
2823 Err(error) => PollOutcome::Failed(RefreshState::from_error(&error)),
2829 };
2830 readings.insert(target, outcome);
2831 }
2832 readings
2833 }
2834
2835 async fn allocate_only(
2853 &self,
2854 policy: &ScalePolicy,
2855 demand: u32,
2856 launched: &[RunnerAttempt],
2857 ) -> Result<Allocation, AllocationFailure> {
2858 let mut host = self.host.clone();
2861 host.host_capacity = self
2862 .launcher
2863 .host_capacity(&self.host)
2864 .await
2865 .map_err(AllocationFailure::HostCapacity)?;
2866 let attempts = self
2867 .host_attempts(launched)
2868 .await
2869 .map_err(AllocationFailure::Attempts)?;
2870 let mut allocator = HostAllocator::from_attempts(&host, &attempts);
2871 Ok(allocator.allocate(policy, demand))
2872 }
2873
2874 async fn start_runners(
2896 &self,
2897 policy: &ScalePolicy,
2898 demand: u32,
2899 report: &mut ReconcileReport,
2900 launched: &mut Vec<RunnerAttempt>,
2901 ) {
2902 let intent = match self.allocate_only(policy, demand, launched).await {
2914 Ok(intent) => intent,
2915 Err(failure) => {
2916 self.report_allocation_failure(report, &failure);
2917 return;
2918 }
2919 };
2920
2921 let mut decided: Option<Allocation> = None;
2925 let mut budget = intent.to_start;
2926
2927 while budget > 0 {
2928 let waiting_since = std::time::Instant::now();
2929 let guard = match self.lock.acquire().await {
2930 Ok(guard) => guard,
2931 Err(_) => {
2932 report.deferred = report.deferred.saturating_add(budget);
2935 self.events.emit(LifecycleEvent::AllocationDeferred {
2936 policy: policy.id,
2937 count: budget,
2938 });
2939 break;
2940 }
2941 };
2942 let lock_wait = waiting_since.elapsed();
2943
2944 let allocation = match self.allocate_only(policy, demand, launched).await {
2950 Ok(allocation) => allocation,
2951 Err(failure) => {
2952 drop(guard);
2953 self.report_allocation_failure(report, &failure);
2954 break;
2955 }
2956 };
2957
2958 if decided.is_none() {
2959 budget = budget.min(allocation.to_start);
2963 decided = Some(allocation.clone());
2964 }
2965
2966 if allocation.starts_nothing() || budget == 0 {
2969 drop(guard);
2970 break;
2971 }
2972
2973 let created = self
2974 .launcher
2975 .launch(LaunchRequest {
2976 host: &self.host,
2977 policy,
2978 allocation_guard: &guard,
2979 lock_wait,
2980 })
2981 .await;
2982 drop(guard);
2983
2984 match created {
2985 Ok(attempt) => {
2986 let id = attempt.id;
2987 launched.push(attempt);
2991 report.started = report.started.saturating_add(1);
2992 budget -= 1;
2993 self.events.emit(LifecycleEvent::RunnerStarted {
2994 policy: policy.id,
2995 attempt: id,
2996 });
2997 }
2998 Err(failure) => {
2999 self.events.emit(LifecycleEvent::RunnerStartFailed {
3000 policy: policy.id,
3001 reason: failure_reason_kind(&failure.reason),
3002 });
3003 break;
3004 }
3005 }
3006 }
3007
3008 let allocation = decided.unwrap_or(intent);
3009 self.emit_allocation(&allocation);
3010 report.allocations.push(allocation);
3011 }
3012
3013 async fn host_attempts(
3026 &self,
3027 launched: &[RunnerAttempt],
3028 ) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
3029 let mut attempts = self.launcher.attempts().await?;
3030
3031 debug_assert!(
3038 launched
3039 .iter()
3040 .map(|attempt| attempt.id)
3041 .collect::<BTreeSet<AttemptId>>()
3042 .len()
3043 == launched.len(),
3044 "`RunnerLauncher::launch` returned an AttemptId this pass had already seen; \
3045 the host ceiling is enforced against a set keyed on that identifier, so a \
3046 duplicate is two runtimes counted as one"
3047 );
3048
3049 let known: BTreeSet<AttemptId> = attempts.iter().map(|attempt| attempt.id).collect();
3050 attempts.extend(
3051 launched
3052 .iter()
3053 .filter(|attempt| !known.contains(&attempt.id))
3054 .cloned(),
3055 );
3056 Ok(attempts)
3057 }
3058
3059 fn report_allocation_failure(&self, report: &mut ReconcileReport, failure: &AllocationFailure) {
3060 match failure {
3061 AllocationFailure::HostCapacity(reason) => {
3062 report.host_capacity_unreadable = report.host_capacity_unreadable.saturating_add(1);
3063 self.events
3064 .emit(LifecycleEvent::HostCapacityUnreadable { reason: *reason });
3065 }
3066 AllocationFailure::Attempts(failure) => {
3067 self.report_unreadable_attempts(report, failure)
3068 }
3069 }
3070 }
3071
3072 fn report_unreadable_attempts(&self, report: &mut ReconcileReport, failure: &LaunchFailure) {
3079 report.attempts_unreadable = report.attempts_unreadable.saturating_add(1);
3080 self.events.emit(LifecycleEvent::AttemptsUnreadable {
3087 reason: failure_reason_kind(&failure.reason),
3088 });
3089 }
3090
3091 async fn clean_terminal_attempts(&mut self, report: &mut ReconcileReport) {
3097 let attempts = match self.launcher.attempts().await {
3098 Ok(attempts) => attempts,
3099 Err(failure) => {
3100 self.report_unreadable_attempts(report, &failure);
3101 return;
3102 }
3103 };
3104 self.clean_backoff
3105 .retain(&attempts.iter().map(|attempt| attempt.id).collect());
3106 let now = self.clock.now();
3107 for attempt in attempts {
3108 if !attempt.state().is_concluded() {
3109 continue;
3110 }
3111 let Some(outcome) = attempt.outcome() else {
3112 continue;
3113 };
3114 if !self.clean_backoff.is_due(attempt.id, now) {
3117 continue;
3118 }
3119 let kind = OutcomeKind::of(outcome);
3120 match self.launcher.clean(attempt.id).await {
3121 Ok(()) => {
3122 self.clean_backoff.succeeded(attempt.id);
3123 report.cleaned = report.cleaned.saturating_add(1);
3124 if kind.is_failure() {
3125 report.failures = report.failures.saturating_add(1);
3126 } else if kind == OutcomeKind::IdleExit {
3127 report.idle_exits = report.idle_exits.saturating_add(1);
3132 }
3133 self.events.emit(LifecycleEvent::AttemptCleaned {
3134 policy: attempt.policy_id,
3135 attempt: attempt.id,
3136 outcome: kind,
3137 });
3138 }
3139 Err(failure) => {
3149 self.clean_backoff.failed(attempt.id, now);
3150 report.clean_failures = report.clean_failures.saturating_add(1);
3151 self.events.emit(LifecycleEvent::AttemptCleanFailed {
3152 policy: attempt.policy_id,
3153 attempt: attempt.id,
3154 reason: failure_reason_kind(&failure.reason),
3155 });
3156 }
3157 }
3158 }
3159 }
3160
3161 pub async fn scale_down(&self, policy: &ScalePolicy) -> ScaleDownReport {
3169 let mut report = ScaleDownReport::default();
3170 let attempts = match self.launcher.attempts().await {
3171 Ok(attempts) => attempts,
3172 Err(failure) => {
3173 self.events.emit(LifecycleEvent::AttemptsUnreadable {
3178 reason: failure_reason_kind(&failure.reason),
3179 });
3180 report.attempts_unreadable = true;
3181 return report;
3182 }
3183 };
3184 for attempt in attempts {
3185 if attempt.policy_id != policy.id {
3186 continue;
3187 }
3188 match attempt.state() {
3189 AttemptState::Busy => {
3190 report.refused_busy = report.refused_busy.saturating_add(1);
3191 self.events.emit(LifecycleEvent::ScaleDownRefused {
3192 policy: policy.id,
3193 attempt: attempt.id,
3194 });
3195 }
3196 state if state.is_concluded() => {
3197 let kind = attempt
3198 .outcome()
3199 .map_or(OutcomeKind::Failed, OutcomeKind::of);
3200 match self.launcher.clean(attempt.id).await {
3201 Ok(()) => {
3202 report.removed = report.removed.saturating_add(1);
3203 self.events.emit(LifecycleEvent::AttemptCleaned {
3204 policy: policy.id,
3205 attempt: attempt.id,
3206 outcome: kind,
3207 });
3208 }
3209 Err(failure) => {
3210 report.clean_failures = report.clean_failures.saturating_add(1);
3211 self.events.emit(LifecycleEvent::AttemptCleanFailed {
3212 policy: policy.id,
3213 attempt: attempt.id,
3214 reason: failure_reason_kind(&failure.reason),
3215 });
3216 }
3217 }
3218 }
3219 AttemptState::Cleaned => {}
3220 _ => report.retained = report.retained.saturating_add(1),
3223 }
3224 }
3225 report
3226 }
3227
3228 fn emit_allocation(&self, allocation: &Allocation) {
3229 self.events.emit(LifecycleEvent::Allocated {
3230 policy: allocation.policy_id,
3231 demand: allocation.demand,
3232 desired: allocation.desired,
3233 active_owned: allocation.active_owned,
3234 headroom: allocation.headroom_before,
3235 to_start: allocation.to_start,
3236 limiting: allocation.limiting_factor,
3237 });
3238 }
3239}
3240
3241fn demand_for(policy: &ScalePolicy, reading: &QueuedDemand) -> DemandTally {
3265 let Some(labels) = policy.routing_labels() else {
3266 debug_assert!(
3267 false,
3268 "a monitor-only policy is skipped before the demand poll (D19)"
3269 );
3270 return DemandTally::default();
3271 };
3272
3273 match &policy.target {
3274 ScaleTarget::Repository(repository) => labels.tally(reading.jobs_for(repository)),
3275 ScaleTarget::Organization(_) => labels.tally(reading.jobs()),
3276 }
3277}
3278
3279fn route_demand(
3283 all_policies: &[ScalePolicy],
3284 profiles: &[&ScalePolicy],
3285 reading: &QueuedDemand,
3286) -> (
3287 BTreeMap<PolicyId, DemandTally>,
3288 BTreeMap<RoutingRefusal, u32>,
3289) {
3290 let mut tallies: BTreeMap<PolicyId, DemandTally> = profiles
3291 .iter()
3292 .map(|policy| (policy.id, demand_for(policy, reading)))
3293 .collect();
3294 let mut refusals: BTreeMap<RoutingRefusal, u32> = BTreeMap::new();
3295 let Some(first) = profiles.first() else {
3296 return (tallies, refusals);
3297 };
3298 let owners: Vec<_> = all_policies
3299 .iter()
3300 .filter(|policy| policy.target == first.target && policy.host_id == first.host_id)
3301 .filter(|policy| policy.owns_runners())
3302 .collect();
3303 let jobs: Vec<&runner_manager_domain::policy::RunsOn> = match &first.target {
3304 ScaleTarget::Repository(repository) => reading.jobs_for(repository).iter().collect(),
3305 ScaleTarget::Organization(_) => reading.jobs().collect(),
3306 };
3307 for job in jobs {
3308 let Ok(_) = job.required_labels() else {
3309 continue;
3311 };
3312 let matched: Vec<PolicyId> = owners
3313 .iter()
3314 .filter(|policy| {
3315 policy
3316 .routing_labels()
3317 .is_some_and(|labels| labels.matches(job).is_match())
3318 })
3319 .map(|policy| policy.id)
3320 .collect();
3321 if matched.len() > 1 {
3322 *refusals
3323 .entry(RoutingRefusal::OverlappingProfiles)
3324 .or_default() += 1;
3325 for id in matched {
3326 if let Some(tally) = tallies.get_mut(&id) {
3327 tally.matched -= 1;
3328 tally.not_matched += 1;
3329 }
3330 }
3331 }
3332 }
3333 (tallies, refusals)
3334}
3335
3336const fn severity(state: &RefreshState) -> u8 {
3343 match state {
3344 RefreshState::Offline => 5,
3345 RefreshState::RateLimited(_) => 4,
3346 RefreshState::LockedOut { .. } => 3,
3347 RefreshState::Unauthorized => 2,
3348 RefreshState::Forbidden { .. } | RefreshState::Failed { .. } => 1,
3349 RefreshState::Cancelled | RefreshState::Ready(_) => 0,
3350 }
3351}
3352
3353const fn unreadable_reason(state: &RefreshState) -> &'static str {
3364 match state {
3365 RefreshState::Ready(_) => "ready",
3366 RefreshState::Offline => "offline",
3367 RefreshState::RateLimited(_) => "rate_limited",
3368 RefreshState::LockedOut { .. } => "locked_out",
3369 RefreshState::Unauthorized => "unauthorized",
3370 RefreshState::Forbidden { .. } => "forbidden",
3371 RefreshState::Failed { .. } => "failed",
3372 RefreshState::Cancelled => "cancelled",
3373 }
3374}
3375
3376#[cfg(test)]
3377mod tests {
3378 use super::*;
3379
3380 #[test]
3388 fn a_pass_that_reached_no_target_does_not_claim_it_reached_github() {
3389 let mut report = ReconcileReport::default();
3390 assert!(
3391 !report.reached_github(),
3392 "a pass that polled nothing -- every policy draining, owned elsewhere, or \
3393 monitor-only -- reached nobody. This is the case the old guard let through, and \
3394 the only one it ever let through."
3395 );
3396
3397 report.unreadable.push(PolicyId::from_u128(1));
3398 assert!(
3399 !report.reached_github(),
3400 "every target this pass tried was unreadable, so there is no contact to record"
3401 );
3402
3403 report.targets_read = 1;
3404 assert!(
3405 report.reached_github(),
3406 "one target answering is contact, whatever else failed alongside it"
3407 );
3408
3409 let mut unowned = ReconcileReport::default();
3413 unowned.unreadable.push(PolicyId::from_u128(2));
3414 unowned.allocations.push(Allocation {
3415 policy_id: PolicyId::from_u128(2),
3416 demand: 0,
3417 desired: 0,
3418 active_owned: 0,
3419 headroom_before: 0,
3420 to_start: 0,
3421 limiting_factor: LimitingFactor::Demand,
3422 });
3423 assert!(
3424 !unowned.reached_github(),
3425 "an allocation is not evidence that GitHub answered"
3426 );
3427 }
3428
3429 #[test]
3439 fn an_unauthorized_target_is_a_failure_and_not_merely_unreadable() {
3440 assert!(
3441 severity(&RefreshState::Unauthorized) > 0,
3442 "an unauthorized reading must survive `max_by_key(severity)` into `report.failure`, \
3443 or a pass where every target was refused would report no failure at all"
3444 );
3445 }
3446
3447 use std::sync::atomic::AtomicUsize;
3448
3449 use std::num::NonZeroU16;
3450
3451 use runner_manager_domain::attempt::PersistedAttempt;
3452 use runner_manager_domain::model::{CachePolicy, HostId};
3453 use runner_manager_domain::policy::PolicyMode;
3454 use runner_manager_domain::workspace::WorkspaceKind;
3455 use runner_manager_github::rest::RateLimited;
3456 use runner_manager_testkit::clock::FakeClock;
3457 use runner_manager_testkit::fixtures;
3458 use runner_manager_testkit::github::FakeGithub;
3459
3460 fn host_with(capacity: u16) -> Host {
3465 fixtures::host().capacity(capacity).build()
3466 }
3467
3468 fn repo(raw: &str) -> OwnerRepo {
3469 OwnerRepo::parse(raw).expect("a valid OWNER/REPO")
3470 }
3471
3472 use runner_manager_domain::policy::RunsOn;
3474
3475 fn policy(id: u128, target: &str, max: u16) -> ScalePolicy {
3476 fixtures::policy()
3477 .id(PolicyId::from_u128(id))
3478 .repository(target)
3479 .autoscale("home", max)
3480 .active()
3481 .build()
3482 }
3483
3484 const HOST_LABEL: &str = "rm-home-win-x64";
3491
3492 fn jobs(n: usize) -> Vec<RunsOn> {
3498 fixtures::queued_jobs(&[HOST_LABEL], n)
3499 }
3500
3501 #[derive(Debug, Default)]
3503 struct FakeLauncher {
3504 capacity: Mutex<Option<NonZeroU16>>,
3505 capacity_unreadable: AtomicBool,
3506 capacity_after_launch: Mutex<Option<NonZeroU16>>,
3507 attempts: Mutex<Vec<RunnerAttempt>>,
3508 next_id: AtomicU64,
3509 launches: AtomicUsize,
3510 cleaned: Mutex<Vec<AttemptId>>,
3511 yields_before_recording: usize,
3514 forgetful: bool,
3518 fail_next: Mutex<Option<FailureReason>>,
3519 attempts_fail: Mutex<bool>,
3522 clean_fails: bool,
3525 replacements: Mutex<Vec<ReplacementIntent>>,
3526 }
3527
3528 impl FakeLauncher {
3529 fn new() -> Self {
3530 Self::default()
3531 }
3532
3533 fn with_yields(mut self, yields: usize) -> Self {
3534 self.yields_before_recording = yields;
3535 self
3536 }
3537
3538 fn forgetful() -> Self {
3539 Self {
3540 forgetful: true,
3541 ..Self::default()
3542 }
3543 }
3544
3545 fn seeded(self, attempts: Vec<RunnerAttempt>) -> Self {
3546 *self.attempts.lock().unwrap() = attempts;
3547 self
3548 }
3549
3550 fn launches(&self) -> usize {
3551 self.launches.load(Ordering::SeqCst)
3552 }
3553
3554 fn snapshot(&self) -> Vec<RunnerAttempt> {
3555 self.attempts.lock().unwrap().clone()
3556 }
3557
3558 fn live_count(&self) -> usize {
3559 self.snapshot()
3560 .iter()
3561 .filter(|a| a.counts_against_capacity())
3562 .count()
3563 }
3564
3565 fn fail_next(&self, reason: FailureReason) {
3566 *self.fail_next.lock().unwrap() = Some(reason);
3567 }
3568
3569 fn fail_attempts(&self, failing: bool) {
3570 *self.attempts_fail.lock().unwrap() = failing;
3571 }
3572
3573 fn refusing_cleanup(attempts: Vec<RunnerAttempt>) -> Self {
3574 Self {
3575 clean_fails: true,
3576 ..Self::default()
3577 }
3578 .seeded(attempts)
3579 }
3580
3581 fn cleaned(&self) -> Vec<AttemptId> {
3582 self.cleaned.lock().unwrap().clone()
3583 }
3584
3585 fn replacing(self, intent: ReplacementIntent) -> Self {
3586 self.replacements.lock().unwrap().push(intent);
3587 self
3588 }
3589 }
3590
3591 #[async_trait::async_trait]
3592 impl RunnerLauncher for FakeLauncher {
3593 async fn host_capacity(&self, host: &Host) -> Result<NonZeroU16, HostCapacityError> {
3594 if self.capacity_unreadable.load(Ordering::SeqCst) {
3595 return Err(HostCapacityError::JournalUnreadable);
3596 }
3597 Ok(self.capacity.lock().unwrap().unwrap_or(host.host_capacity))
3598 }
3599
3600 async fn supervise(
3601 &self,
3602 policy: &ScalePolicy,
3603 ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
3604 let mut replacements = self.replacements.lock().unwrap();
3605 let selected: Vec<_> = replacements
3606 .extract_if(.., |intent| intent.policy == policy.id)
3607 .collect();
3608 if !selected.is_empty() {
3609 let retired: BTreeSet<_> = selected
3610 .iter()
3611 .map(|intent| intent.previous_attempt)
3612 .collect();
3613 self.attempts
3614 .lock()
3615 .unwrap()
3616 .retain(|attempt| !retired.contains(&attempt.id));
3617 }
3618 Ok(selected)
3619 }
3620
3621 async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
3622 if *self.attempts_fail.lock().unwrap() {
3623 return Err(LaunchFailure::new(FailureReason::Other(
3624 "the journal could not be read".into(),
3625 )));
3626 }
3627 Ok(self.snapshot())
3628 }
3629
3630 async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure> {
3631 if let Some(reason) = self.fail_next.lock().unwrap().take() {
3632 return Err(LaunchFailure::new(reason));
3633 }
3634 for _ in 0..self.yields_before_recording {
3636 tokio::task::yield_now().await;
3637 }
3638 let id =
3639 AttemptId::from_u128(u128::from(self.next_id.fetch_add(1, Ordering::SeqCst) + 1));
3640 let created = RunnerAttempt::allocate(
3641 id,
3642 request.policy.id,
3643 "runtime/p/a",
3644 request.host.created_at,
3645 );
3646 self.launches.fetch_add(1, Ordering::SeqCst);
3647 if let Some(capacity) = self.capacity_after_launch.lock().unwrap().take() {
3648 *self.capacity.lock().unwrap() = Some(capacity);
3649 }
3650 if !self.forgetful {
3651 self.attempts.lock().unwrap().push(created.clone());
3652 }
3653 Ok(created)
3654 }
3655
3656 async fn clean(&self, attempt: AttemptId) -> Result<(), LaunchFailure> {
3657 if self.clean_fails {
3658 return Err(LaunchFailure::new(FailureReason::Other(
3659 "the runtime directory is locked".into(),
3660 )));
3661 }
3662 self.cleaned.lock().unwrap().push(attempt);
3663 let mut attempts = self.attempts.lock().unwrap();
3664 attempts.retain(|a| a.id != attempt);
3665 Ok(())
3666 }
3667 }
3668
3669 #[derive(Debug, Default)]
3671 struct FakeDemand {
3672 outcome: Mutex<Option<PollOutcome>>,
3673 per_target: Mutex<BTreeMap<ScaleTarget, PollOutcome>>,
3675 scopes: Mutex<Vec<ActivityScope>>,
3676 }
3677
3678 impl FakeDemand {
3679 fn ready(count: u32, repository: &OwnerRepo) -> Self {
3680 let fake = Self::default();
3681 fake.set(PollOutcome::Ready(QueuedDemand::of(
3682 repository.clone(),
3683 jobs(count as usize),
3684 )));
3685 fake
3686 }
3687
3688 fn failing(state: RefreshState) -> Self {
3689 let fake = Self::default();
3690 fake.set(PollOutcome::Failed(state));
3691 fake
3692 }
3693
3694 fn set(&self, outcome: PollOutcome) {
3695 *self.outcome.lock().unwrap() = Some(outcome);
3696 }
3697
3698 fn set_for(&self, target: &ScaleTarget, outcome: PollOutcome) {
3700 self.per_target
3701 .lock()
3702 .unwrap()
3703 .insert(target.clone(), outcome);
3704 }
3705
3706 fn polls(&self) -> Vec<ActivityScope> {
3707 self.scopes.lock().unwrap().clone()
3708 }
3709 }
3710
3711 #[async_trait::async_trait]
3712 impl DemandSource for FakeDemand {
3713 async fn poll(&self, scope: &ActivityScope) -> PollOutcome {
3714 self.scopes.lock().unwrap().push(scope.clone());
3715 if let Some(outcome) = self.per_target.lock().unwrap().get(scope.target()) {
3716 return outcome.clone();
3717 }
3718 self.outcome
3719 .lock()
3720 .unwrap()
3721 .clone()
3722 .unwrap_or(PollOutcome::Ready(QueuedDemand::default()))
3723 }
3724 }
3725
3726 #[derive(Debug, Default)]
3727 struct FakeDirectory {
3728 repositories: Vec<OwnerRepo>,
3729 calls: AtomicUsize,
3730 }
3731
3732 impl FakeDirectory {
3733 fn of(repositories: Vec<OwnerRepo>) -> Self {
3734 Self {
3735 repositories,
3736 calls: AtomicUsize::new(0),
3737 }
3738 }
3739
3740 fn calls(&self) -> usize {
3741 self.calls.load(Ordering::SeqCst)
3742 }
3743 }
3744
3745 #[async_trait::async_trait]
3746 impl RepositoryDirectory for FakeDirectory {
3747 async fn repositories(&self, _org: &Org) -> Result<Vec<OwnerRepo>, InventoryError> {
3748 self.calls.fetch_add(1, Ordering::SeqCst);
3749 Ok(self.repositories.clone())
3750 }
3751 }
3752
3753 #[derive(Debug)]
3759 struct CountingLock {
3760 inner: InProcessAllocationLock,
3761 concurrent: Arc<AtomicUsize>,
3762 peak: Arc<AtomicUsize>,
3763 acquisitions: Arc<AtomicUsize>,
3764 }
3765
3766 impl CountingLock {
3767 fn new() -> Self {
3768 Self {
3769 inner: InProcessAllocationLock::new(),
3770 concurrent: Arc::new(AtomicUsize::new(0)),
3771 peak: Arc::new(AtomicUsize::new(0)),
3772 acquisitions: Arc::new(AtomicUsize::new(0)),
3773 }
3774 }
3775
3776 fn peak(&self) -> usize {
3777 self.peak.load(Ordering::SeqCst)
3778 }
3779
3780 fn acquisitions(&self) -> usize {
3781 self.acquisitions.load(Ordering::SeqCst)
3782 }
3783 }
3784
3785 #[derive(Debug)]
3786 struct CountingGuard {
3787 _inner: AllocationGuard,
3788 concurrent: Arc<AtomicUsize>,
3789 }
3790
3791 impl Drop for CountingGuard {
3792 fn drop(&mut self) {
3793 self.concurrent.fetch_sub(1, Ordering::SeqCst);
3794 }
3795 }
3796
3797 #[async_trait::async_trait]
3798 impl AllocationLock for CountingLock {
3799 async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
3800 let inner = self.inner.acquire().await?;
3801 self.acquisitions.fetch_add(1, Ordering::SeqCst);
3802 let now = self.concurrent.fetch_add(1, Ordering::SeqCst) + 1;
3803 self.peak.fetch_max(now, Ordering::SeqCst);
3804 Ok(AllocationGuard::new(CountingGuard {
3805 _inner: inner,
3806 concurrent: Arc::clone(&self.concurrent),
3807 }))
3808 }
3809 }
3810
3811 #[derive(Debug, Default)]
3814 struct NoLock;
3815
3816 #[async_trait::async_trait]
3817 impl AllocationLock for NoLock {
3818 async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
3819 Ok(AllocationGuard::new(()))
3820 }
3821 }
3822
3823 #[tokio::test]
3824 async fn a_wsl_drain_request_fences_the_exact_pre_launch_boundary() {
3825 use runner_manager_platform::wsl::fence::DrainRequest;
3826
3827 let (_local, shared, paths) = guest_paths();
3828 DrainRequest::new(4, chrono::Utc::now())
3829 .write(shared.path())
3830 .unwrap();
3831 let lock = WslRecoveryAllocationLock::new(paths, Arc::new(NoLock));
3832
3833 assert!(lock.acquire().await.is_err());
3834 }
3835
3836 #[tokio::test]
3837 async fn a_guest_launch_claim_is_released_with_its_allocation_guard() {
3838 use runner_manager_platform::wsl::fence::FENCE_DIRECTORY;
3839
3840 let (_local, shared, paths) = guest_paths();
3841 let lock = WslRecoveryAllocationLock::new(paths, Arc::new(NoLock));
3842 let guard = lock.acquire().await.unwrap();
3843 assert!(shared.path().join(FENCE_DIRECTORY).exists());
3844 drop(guard);
3845 assert!(!shared.path().join(FENCE_DIRECTORY).exists());
3846 }
3847
3848 #[derive(Clone, Default)]
3850 struct Logs(Arc<Mutex<Vec<u8>>>);
3851
3852 impl std::io::Write for Logs {
3853 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
3854 self.0.lock().unwrap().extend_from_slice(buf);
3855 Ok(buf.len())
3856 }
3857 fn flush(&mut self) -> std::io::Result<()> {
3858 Ok(())
3859 }
3860 }
3861
3862 #[tokio::test]
3865 async fn a_launch_fence_that_cannot_be_released_is_logged_with_its_path() {
3866 use runner_manager_platform::wsl::fence::FENCE_DIRECTORY;
3867
3868 let (_local, shared, paths) = guest_paths();
3869 let lock = WslRecoveryAllocationLock::new(paths, Arc::new(NoLock));
3870 let guard = lock.acquire().await.unwrap();
3871 let fence = shared.path().join(FENCE_DIRECTORY);
3874 std::fs::remove_dir_all(&fence).unwrap();
3875 std::fs::write(&fence, b"not a directory").unwrap();
3876
3877 let logs = Logs::default();
3878 let writer = logs.clone();
3879 let subscriber = tracing_subscriber::fmt()
3880 .with_writer(move || writer.clone())
3881 .with_ansi(false)
3882 .finish();
3883 tracing::subscriber::with_default(subscriber, || drop(guard));
3884
3885 let text = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
3886 assert!(text.contains("WARN"), "{text}");
3887 assert!(text.contains("could not be released"), "{text}");
3888 assert!(text.contains(FENCE_DIRECTORY), "the path is named: {text}");
3889 }
3890
3891 fn guest_paths() -> (
3892 tempfile::TempDir,
3893 tempfile::TempDir,
3894 Arc<runner_manager_platform::paths::AppPaths>,
3895 ) {
3896 use runner_manager_platform::paths::AppPaths;
3897 use runner_manager_platform::wsl::fence::GuestRecoveryConfig;
3898
3899 let local = tempfile::tempdir().unwrap();
3900 let shared = tempfile::tempdir().unwrap();
3901 let paths = Arc::new(AppPaths::rooted_at(local.path()));
3902 paths.create_all().unwrap();
3903 GuestRecoveryConfig::new(shared.path().to_path_buf())
3904 .write(&paths)
3905 .unwrap();
3906 (local, shared, paths)
3907 }
3908
3909 #[tokio::test]
3912 async fn a_stale_guest_claim_no_longer_blocks_the_next_launch() {
3913 use runner_manager_platform::wsl::fence::{FENCE_DIRECTORY, OWNER_FILE};
3914
3915 let (_local, shared, paths) = guest_paths();
3916 let fence = shared.path().join(FENCE_DIRECTORY);
3917 std::fs::create_dir_all(&fence).unwrap();
3918 let pid = std::process::id();
3919 std::fs::write(
3920 fence.join(OWNER_FILE),
3921 format!(
3922 r#"{{"schema_version":1,"kind":"guest_launch","generation":null,"process_id":{pid},"acquired_at":"2026-09-24T00:47:18.724Z","identity":{{"pid":{pid},"start_token":"linux:earlier-boot:1"}}}}"#
3923 ),
3924 )
3925 .unwrap();
3926 let lock = WslRecoveryAllocationLock::new(paths, Arc::new(NoLock));
3927
3928 let guard = lock.acquire().await.expect("the stale claim was reclaimed");
3929 drop(guard);
3930 assert!(!fence.exists());
3931 }
3932
3933 #[tokio::test]
3934 async fn refusals_that_persist_are_recorded_and_a_grant_clears_them() {
3935 use runner_manager_platform::launch_health::recorded_launches_blocked;
3936 use runner_manager_platform::wsl::fence::{FenceClaim, FenceOwnerKind};
3937
3938 let (_local, shared, paths) = guest_paths();
3939 let lock = WslRecoveryAllocationLock::new(Arc::clone(&paths), Arc::new(NoLock))
3940 .with_blocked_after(3, Duration::ZERO);
3941 let windows =
3943 FenceClaim::try_claim(shared.path(), FenceOwnerKind::WindowsRecovery, Some(1))
3944 .unwrap()
3945 .unwrap();
3946
3947 for _ in 0..2 {
3948 assert!(lock.acquire().await.is_err());
3949 }
3950 assert_eq!(
3951 recorded_launches_blocked(&paths, chrono::Utc::now()).unwrap(),
3952 None,
3953 "not yet"
3954 );
3955 assert!(lock.acquire().await.is_err());
3956 let blocked = recorded_launches_blocked(&paths, chrono::Utc::now())
3957 .unwrap()
3958 .expect("three refusals in a row are recorded");
3959 assert!(
3960 blocked.reason.contains("Windows WSL recovery"),
3961 "{blocked:?}"
3962 );
3963
3964 windows.release().unwrap();
3965 let guard = lock.acquire().await.unwrap();
3966 assert_eq!(
3967 recorded_launches_blocked(&paths, chrono::Utc::now()).unwrap(),
3968 None
3969 );
3970 drop(guard);
3971 }
3972
3973 #[tokio::test]
3974 async fn refusals_while_this_process_is_launching_are_its_own_contention() {
3975 use runner_manager_platform::launch_health::recorded_launches_blocked;
3976
3977 let (_local, _shared, paths) = guest_paths();
3978 let lock = WslRecoveryAllocationLock::new(Arc::clone(&paths), Arc::new(NoLock))
3979 .with_blocked_after(1, Duration::ZERO);
3980 let launching = lock.acquire().await.unwrap();
3981 for _ in 0..3 {
3982 assert!(lock.acquire().await.is_err());
3983 }
3984 assert_eq!(
3985 recorded_launches_blocked(&paths, chrono::Utc::now()).unwrap(),
3986 None
3987 );
3988 drop(launching);
3989 }
3990
3991 #[tokio::test]
3994 async fn refusals_with_quiet_spells_between_them_never_add_up() {
3995 use runner_manager_platform::launch_health::recorded_launches_blocked;
3996 use runner_manager_platform::wsl::fence::{FenceClaim, FenceOwnerKind};
3997
3998 let (_local, shared, paths) = guest_paths();
3999 let lock = WslRecoveryAllocationLock::new(Arc::clone(&paths), Arc::new(NoLock))
4000 .with_blocked_after(3, Duration::ZERO)
4001 .with_streak_gap(Duration::ZERO);
4002 let windows =
4003 FenceClaim::try_claim(shared.path(), FenceOwnerKind::WindowsRecovery, Some(1))
4004 .unwrap()
4005 .unwrap();
4006 for _ in 0..5 {
4007 assert!(lock.acquire().await.is_err());
4008 }
4009 assert_eq!(
4010 recorded_launches_blocked(&paths, chrono::Utc::now()).unwrap(),
4011 None
4012 );
4013 windows.release().unwrap();
4014 }
4015
4016 #[tokio::test]
4019 async fn a_claim_refused_by_a_drain_request_is_released() {
4020 use runner_manager_platform::wsl::fence::{DrainRequest, FENCE_DIRECTORY};
4021
4022 let (_local, shared, paths) = guest_paths();
4023 DrainRequest::new(4, chrono::Utc::now())
4024 .write(shared.path())
4025 .unwrap();
4026 let lock = WslRecoveryAllocationLock::new(paths, Arc::new(NoLock));
4027 assert!(lock.acquire().await.is_err());
4028 assert!(!shared.path().join(FENCE_DIRECTORY).exists());
4029 }
4030
4031 #[derive(Debug, Default)]
4033 struct HeldLock;
4034
4035 #[async_trait::async_trait]
4036 impl AllocationLock for HeldLock {
4037 async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
4038 Err(AllocationLockBusy)
4039 }
4040 }
4041
4042 struct Harness {
4044 launcher: Arc<FakeLauncher>,
4045 demand: Arc<FakeDemand>,
4046 events: Arc<EventLog>,
4047 clock: Arc<FakeClock>,
4048 reconciler: Reconciler,
4049 }
4050
4051 impl Harness {
4052 fn build(
4053 host: Host,
4054 launcher: Arc<FakeLauncher>,
4055 demand: Arc<FakeDemand>,
4056 lock: Arc<dyn AllocationLock>,
4057 ) -> Self {
4058 let events = Arc::new(EventLog::new());
4059 let clock = Arc::new(FakeClock::default());
4060 let reconciler = Reconciler::new(
4061 host,
4062 ReconcilerPorts {
4063 demand: Arc::clone(&demand) as Arc<dyn DemandSource>,
4064 launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
4065 lock,
4066 directory: Arc::new(FakeDirectory::default()),
4067 clock: Arc::clone(&clock) as Arc<dyn Clock>,
4068 jitter: Arc::new(NoJitter) as Arc<dyn Jitter>,
4069 events: Arc::clone(&events) as Arc<dyn EventSink>,
4070 },
4071 );
4072 Self {
4073 launcher,
4074 demand,
4075 events,
4076 clock,
4077 reconciler,
4078 }
4079 }
4080
4081 fn simple(capacity: u16, demand_count: u32, target: &str) -> Self {
4082 let launcher = Arc::new(FakeLauncher::new());
4083 let demand = Arc::new(FakeDemand::ready(demand_count, &repo(target)));
4084 Self::build(
4085 host_with(capacity),
4086 launcher,
4087 demand,
4088 Arc::new(InProcessAllocationLock::new()),
4089 )
4090 }
4091 }
4092
4093 fn attempt_in(state: AttemptState, id: u128, policy: u128) -> RunnerAttempt {
4094 let outcome = state.is_terminal().then(|| match state {
4095 AttemptState::Failed => {
4096 AttemptOutcome::failed(FailureReason::ProcessExitedUnexpectedly)
4097 }
4098 AttemptState::Orphaned => AttemptOutcome::Orphaned,
4099 _ => AttemptOutcome::CompletedJob,
4100 });
4101 RunnerAttempt::from_persisted(PersistedAttempt {
4102 id: AttemptId::from_u128(id),
4103 policy_id: PolicyId::from_u128(policy),
4104 github_runner_id: None,
4105 state,
4106 outcome,
4107 process_id: None,
4108 execution: runner_manager_domain::execution::AttemptExecution::Native {
4109 process_id: None,
4110 },
4111 runtime_path: "runtime/p/a".into(),
4112 workspace_kind: WorkspaceKind::Ephemeral,
4113 workspace_slot: None,
4114 created_at: fixtures::created_at(),
4115 terminal_at: state.is_terminal().then(fixtures::created_at),
4116 last_state_change_at: fixtures::created_at(),
4117 })
4118 .expect("a state/outcome pair the domain accepts")
4119 }
4120
4121 fn concluded(id: u128, policy: u128, outcome: AttemptOutcome) -> RunnerAttempt {
4123 RunnerAttempt::from_persisted(PersistedAttempt {
4124 id: AttemptId::from_u128(id),
4125 policy_id: PolicyId::from_u128(policy),
4126 github_runner_id: None,
4127 state: outcome.terminal_state(),
4128 outcome: Some(outcome),
4129 process_id: None,
4130 execution: runner_manager_domain::execution::AttemptExecution::Native {
4131 process_id: None,
4132 },
4133 runtime_path: "runtime/p/a".into(),
4134 workspace_kind: WorkspaceKind::Ephemeral,
4135 workspace_slot: None,
4136 created_at: fixtures::created_at(),
4137 terminal_at: Some(fixtures::created_at()),
4138 last_state_change_at: fixtures::created_at(),
4139 })
4140 .expect("a state/outcome pair the domain accepts")
4141 }
4142
4143 #[tokio::test]
4172 async fn three_polls_of_one_still_queued_run_yield_exactly_one_attempt() {
4173 let mut harness = Harness::simple(4, 1, "acme/app");
4174 let policy = policy(1, "acme/app", 4);
4175
4176 for poll in 1..=3 {
4177 let report = harness
4178 .reconciler
4179 .reconcile(std::slice::from_ref(&policy))
4180 .await;
4181 assert_eq!(
4182 harness.launcher.launches(),
4183 1,
4184 "poll {poll} started another runner for a job already being served; the \
4185 `- active_owned_runners` term reached `HostAllocator` as a set this host \
4186 does not hold"
4187 );
4188 assert_eq!(report.allocations.len(), 1);
4189 let allocation = &report.allocations[0];
4190 assert_eq!(allocation.demand, 1, "poll {poll}: still queued at GitHub");
4191 if poll == 1 {
4192 assert_eq!(allocation.to_start, 1);
4193 assert_eq!(report.started, 1);
4194 } else {
4195 assert_eq!(allocation.active_owned, 1, "poll {poll}");
4196 assert_eq!(allocation.to_start, 0, "poll {poll}");
4197 assert_eq!(report.started, 0, "poll {poll}");
4198 }
4199 }
4200 assert_eq!(harness.launcher.live_count(), 1);
4201 }
4202
4203 #[tokio::test]
4204 async fn draining_parallel_workflow_starts_runners_for_the_remaining_queue() {
4205 let mut harness = Harness::simple(10, 8, "acme/app");
4206 let policy = policy(1, "acme/app", 10);
4207 let first = harness
4208 .reconciler
4209 .reconcile(std::slice::from_ref(&policy))
4210 .await;
4211 assert_eq!(first.started, 8);
4212
4213 let attempts = harness.launcher.snapshot();
4215 *harness.launcher.attempts.lock().unwrap() = attempts
4216 .iter()
4217 .take(3)
4218 .map(|attempt| attempt_in(AttemptState::Busy, attempt.id.as_uuid().as_u128(), 1))
4219 .collect();
4220 harness.demand.set(PollOutcome::Ready(QueuedDemand::of(
4221 repo("acme/app"),
4222 jobs(2),
4223 )));
4224
4225 for poll in 0..3 {
4226 let report = harness
4227 .reconciler
4228 .reconcile(std::slice::from_ref(&policy))
4229 .await;
4230 assert_eq!(report.started, if poll == 0 { 2 } else { 0 });
4231 assert_eq!(harness.launcher.live_count(), 5);
4232 }
4233 }
4234
4235 #[tokio::test]
4246 async fn a_launcher_whose_attempts_never_appear_cannot_wedge_the_pass() {
4247 let launcher = Arc::new(FakeLauncher::forgetful());
4248 let mut harness = Harness::build(
4249 host_with(64),
4250 Arc::clone(&launcher),
4251 Arc::new(FakeDemand::ready(3, &repo("acme/app"))),
4252 Arc::new(InProcessAllocationLock::new()),
4253 );
4254
4255 let report = harness
4256 .reconciler
4257 .reconcile(&[policy(1, "acme/app", 8)])
4258 .await;
4259
4260 assert_eq!(
4261 report.started, 3,
4262 "the pass is bounded by the grant it was given, not by the attempt set catching \
4263 up with it"
4264 );
4265 assert_eq!(launcher.launches(), 3);
4266 assert!(
4267 launcher.snapshot().is_empty(),
4268 "the launcher never recorded anything, which is the whole point of the fixture"
4269 );
4270 }
4271
4272 #[tokio::test]
4284 async fn two_policies_cannot_exceed_host_capacity_even_when_the_launcher_lags() {
4285 let launcher = Arc::new(FakeLauncher::forgetful());
4286 let demand = Arc::new(FakeDemand::default());
4287 demand.set_for(
4288 &ScaleTarget::repository("acme/left").unwrap(),
4289 PollOutcome::Ready(QueuedDemand::of(repo("acme/left"), jobs(3))),
4290 );
4291 demand.set_for(
4292 &ScaleTarget::repository("acme/right").unwrap(),
4293 PollOutcome::Ready(QueuedDemand::of(repo("acme/right"), jobs(3))),
4294 );
4295 let mut harness = Harness::build(
4296 host_with(3),
4297 Arc::clone(&launcher),
4298 demand,
4299 Arc::new(InProcessAllocationLock::new()),
4300 );
4301
4302 let report = harness
4303 .reconciler
4304 .reconcile(&[policy(1, "acme/left", 3), policy(2, "acme/right", 3)])
4305 .await;
4306
4307 assert_eq!(
4308 report.started, 3,
4309 "host_capacity is 3 and two policies each allowed 3 started {} runners \
4310 between them; the second policy's grant was computed from a set that did \
4311 not yet contain the first policy's launches",
4312 report.started
4313 );
4314 assert_eq!(launcher.launches(), 3);
4315 }
4316
4317 #[tokio::test]
4328 async fn an_unreadable_attempt_set_starts_nothing_and_is_not_read_as_an_idle_host() {
4329 let launcher = Arc::new(FakeLauncher::new());
4330 let mut harness = Harness::build(
4331 host_with(8),
4332 Arc::clone(&launcher),
4333 Arc::new(FakeDemand::ready(4, &repo("acme/app"))),
4334 Arc::new(InProcessAllocationLock::new()),
4335 );
4336 let policy = policy(1, "acme/app", 8);
4337
4338 launcher.fail_attempts(true);
4339 let unreadable = harness
4340 .reconciler
4341 .reconcile(std::slice::from_ref(&policy))
4342 .await;
4343
4344 assert_eq!(
4345 unreadable.started, 0,
4346 "nothing may be decided from a set that was not read"
4347 );
4348 assert_eq!(launcher.launches(), 0);
4349 assert!(unreadable.attempts_unreadable > 0, "and the pass says so");
4350 assert!(
4351 unreadable.allocations.is_empty(),
4352 "no allocation is reported either: there was no set to compute one from, and \
4353 an allocation of zero would claim a decision nobody made"
4354 );
4355 assert!(harness.events.count_of("attempts_unreadable") > 0);
4356
4357 launcher.fail_attempts(false);
4359 let readable = harness
4360 .reconciler
4361 .reconcile(std::slice::from_ref(&policy))
4362 .await;
4363 assert_eq!(
4364 readable.started, 4,
4365 "the difference between the two passes is only whether the set could be read"
4366 );
4367 assert_eq!(readable.attempts_unreadable, 0);
4368 }
4369
4370 #[tokio::test]
4380 async fn a_cleanup_that_cannot_succeed_is_reported_rather_than_retried_in_silence() {
4381 let launcher = Arc::new(FakeLauncher::refusing_cleanup(vec![concluded(
4382 1,
4383 1,
4384 AttemptOutcome::ExitedIdleWithoutWork,
4385 )]));
4386 let mut harness = Harness::build(
4387 host_with(4),
4388 Arc::clone(&launcher),
4389 Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
4390 Arc::new(InProcessAllocationLock::new()),
4391 );
4392
4393 let report = harness
4394 .reconciler
4395 .reconcile(&[policy(1, "acme/app", 4)])
4396 .await;
4397
4398 assert_eq!(report.cleaned, 0);
4399 assert_eq!(report.clean_failures, 1);
4400 assert_eq!(harness.events.count_of("attempt_clean_failed"), 1);
4401 assert_eq!(
4402 harness.events.count_of("attempt_cleaned"),
4403 0,
4404 "and it is not reported as cleaned"
4405 );
4406 assert_eq!(
4407 launcher.snapshot().len(),
4408 1,
4409 "the attempt is still there, so the retry is real -- what changed is that it \
4410 is no longer silent"
4411 );
4412
4413 let reasons: Vec<&'static str> = harness
4416 .events
4417 .events()
4418 .into_iter()
4419 .filter_map(|event| match event {
4420 LifecycleEvent::AttemptCleanFailed { reason, .. } => Some(reason),
4421 _ => None,
4422 })
4423 .collect();
4424 assert_eq!(reasons, vec!["other"]);
4425 }
4426
4427 #[tokio::test]
4430 async fn a_failing_cleanup_backs_off_exponentially_per_attempt() {
4431 let launcher = Arc::new(FakeLauncher::refusing_cleanup(vec![concluded(
4432 1,
4433 1,
4434 AttemptOutcome::ExitedIdleWithoutWork,
4435 )]));
4436 let mut harness = Harness::build(
4437 host_with(4),
4438 Arc::clone(&launcher),
4439 Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
4440 Arc::new(InProcessAllocationLock::new()),
4441 );
4442 let policies = [policy(1, "acme/app", 4)];
4443 let start = harness.clock.now();
4444 let at = |offset: Duration| start + chrono::Duration::from_std(offset).unwrap();
4445 let mut failures_at = async |offset: Duration| {
4446 harness.clock.set(at(offset));
4447 harness.reconciler.reconcile(&policies).await.clean_failures
4448 };
4449
4450 assert_eq!(failures_at(Duration::ZERO).await, 1);
4451 assert_eq!(
4453 failures_at(CLEAN_RETRY_INITIAL - Duration::from_secs(1)).await,
4454 0,
4455 "a failed cleanup was retried on the very next pass"
4456 );
4457 assert_eq!(failures_at(CLEAN_RETRY_INITIAL).await, 1);
4458 let second = CLEAN_RETRY_INITIAL + CLEAN_RETRY_INITIAL * 2;
4460 assert_eq!(
4461 failures_at(second - Duration::from_secs(1)).await,
4462 0,
4463 "the delay did not double after a second failure"
4464 );
4465 assert_eq!(failures_at(second).await, 1);
4466 assert_eq!(harness.events.count_of("attempt_clean_failed"), 3);
4467
4468 let mut backoff = CleanBackoff::default();
4470 let id = AttemptId::from_u128(9);
4471 for _ in 0..40 {
4472 backoff.failed(id, start);
4473 }
4474 assert!(!backoff.is_due(id, at(CLEAN_RETRY_MAXIMUM - Duration::from_secs(1))));
4475 assert!(backoff.is_due(id, at(CLEAN_RETRY_MAXIMUM)));
4476 backoff.succeeded(id);
4477 assert!(
4478 backoff.is_due(id, start),
4479 "a cleaned attempt kept its backoff"
4480 );
4481 }
4482
4483 #[tokio::test]
4496 async fn an_unreadable_attempt_set_makes_scale_down_inconclusive_rather_than_empty() {
4497 let launcher = Arc::new(FakeLauncher::new().seeded(vec![
4498 attempt_in(AttemptState::Busy, 1, 1),
4499 concluded(2, 1, AttemptOutcome::CompletedJob),
4500 ]));
4501 let harness = Harness::build(
4502 host_with(4),
4503 Arc::clone(&launcher),
4504 Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
4505 Arc::new(InProcessAllocationLock::new()),
4506 );
4507 let policy = policy(1, "acme/app", 4);
4508
4509 launcher.fail_attempts(true);
4510 let blind = harness.reconciler.scale_down(&policy).await;
4511
4512 assert!(!blind.is_conclusive(), "the machine was never read");
4513 assert_ne!(
4514 blind,
4515 ScaleDownReport::default(),
4516 "a scale-down that could not see the host must not be equal to one that saw \
4517 an idle host; that equality is the whole finding"
4518 );
4519 assert_eq!(blind.removed, 0);
4520 assert_eq!(
4521 blind.refused_busy, 0,
4522 "and this zero means `unknown`, not `none`"
4523 );
4524 assert_eq!(harness.events.count_of("attempts_unreadable"), 1);
4525
4526 launcher.fail_attempts(false);
4528 let seeing = harness.reconciler.scale_down(&policy).await;
4529
4530 assert!(seeing.is_conclusive());
4531 assert_eq!(seeing.removed, 1, "the concluded attempt was reclaimed");
4532 assert_eq!(seeing.refused_busy, 1, "and the busy one was left alone");
4533 assert_ne!(
4534 seeing, blind,
4535 "the difference between the two is only whether the set could be read"
4536 );
4537 }
4538
4539 #[tokio::test]
4547 async fn demand_below_min_capacity_is_raised_to_min_capacity() {
4548 let mut warm = ScalePolicy::new(
4549 PolicyId::from_u128(1),
4550 ScaleTarget::repository("acme/app").unwrap(),
4551 1,
4552 fixtures::HOST_ID,
4553 PolicyMode::autoscale(
4554 fixtures::routing_labels("home"),
4555 2,
4556 NonZeroU16::new(5).expect("non-zero"),
4557 )
4558 .expect("min <= max"),
4559 CachePolicy::default(),
4560 );
4561 warm.activate().expect("pending -> active");
4562
4563 let mut harness = Harness::simple(8, 0, "acme/app");
4564 let report = harness.reconciler.reconcile(&[warm]).await;
4565
4566 assert_eq!(
4567 report.allocations[0].demand, 0,
4568 "GitHub reported no queued runs"
4569 );
4570 assert_eq!(
4571 report.allocations[0].desired, 2,
4572 "min_capacity raised the target above demand"
4573 );
4574 assert_eq!(
4575 report.allocations[0].limiting_factor,
4576 LimitingFactor::MinCapacity
4577 );
4578 assert_eq!(report.started, 2, "and two runners were actually started");
4579 assert_eq!(harness.launcher.live_count(), 2);
4580 }
4581
4582 #[tokio::test]
4587 async fn demand_above_max_capacity_is_clamped_to_max_capacity() {
4588 let mut harness = Harness::simple(100, 10, "acme/app");
4589 let report = harness
4590 .reconciler
4591 .reconcile(&[policy(1, "acme/app", 3)])
4592 .await;
4593
4594 assert_eq!(report.allocations[0].demand, 10);
4595 assert_eq!(
4596 report.allocations[0].desired, 3,
4597 "max_capacity beats demand"
4598 );
4599 assert_eq!(report.started, 3);
4600 assert_eq!(
4601 report.allocations[0].limiting_factor,
4602 LimitingFactor::MaxCapacity
4603 );
4604 }
4605
4606 #[tokio::test]
4607 async fn demand_below_min_capacity_starts_nothing_in_v1() {
4608 let mut harness = Harness::simple(8, 0, "acme/app");
4611 let report = harness
4612 .reconciler
4613 .reconcile(&[policy(1, "acme/app", 4)])
4614 .await;
4615
4616 assert_eq!(report.allocations[0].desired, 0);
4617 assert_eq!(report.started, 0);
4618 assert!(report.starts_nothing());
4619 }
4620
4621 #[tokio::test]
4622 async fn lifecycle_replacement_intent_is_consumed_by_the_ordinary_allocator() {
4623 let policy = policy(1, "octo/repo", 1);
4624 let previous = attempt_in(AttemptState::Starting, 41, 1);
4625 let intent = ReplacementIntent {
4626 policy: policy.id,
4627 previous_attempt: previous.id,
4628 operation: "exit_before_acceptance_replacement",
4629 };
4630 let launcher = Arc::new(FakeLauncher::new().seeded(vec![previous]).replacing(intent));
4631 let demand = Arc::new(FakeDemand::ready(1, &repo("octo/repo")));
4632 let mut harness = Harness::build(
4633 host_with(1),
4634 Arc::clone(&launcher),
4635 demand,
4636 Arc::new(InProcessAllocationLock::new()),
4637 );
4638
4639 let report = harness.reconciler.reconcile(&[policy]).await;
4640
4641 assert_eq!(report.replacement_intents, 1);
4642 assert_eq!(report.started, 1);
4643 assert_eq!(launcher.launches(), 1);
4644 assert_eq!(launcher.live_count(), 1);
4645 }
4646
4647 #[tokio::test]
4648 async fn zero_host_headroom_starts_nothing_at_maximum_demand() {
4649 let launcher = Arc::new(FakeLauncher::new().seeded(vec![
4650 attempt_in(AttemptState::Busy, 1, 1),
4651 attempt_in(AttemptState::Busy, 2, 1),
4652 ]));
4653 let demand = Arc::new(FakeDemand::ready(u32::from(u16::MAX), &repo("acme/app")));
4654 let mut harness = Harness::build(
4655 host_with(2),
4656 launcher,
4657 demand,
4658 Arc::new(InProcessAllocationLock::new()),
4659 );
4660
4661 let report = harness
4662 .reconciler
4663 .reconcile(&[policy(1, "acme/app", 2)])
4664 .await;
4665 assert_eq!(report.started, 0);
4666 assert_eq!(report.allocations[0].headroom_before, 0);
4667 assert_eq!(harness.launcher.launches(), 0);
4668 }
4669
4670 #[tokio::test]
4671 async fn headroom_smaller_than_the_per_policy_allowance_wins() {
4672 let launcher = Arc::new(FakeLauncher::new().seeded(vec![
4675 attempt_in(AttemptState::Busy, 1, 99),
4676 attempt_in(AttemptState::Busy, 2, 99),
4677 attempt_in(AttemptState::Idle, 3, 99),
4678 attempt_in(AttemptState::Starting, 4, 99),
4679 ]));
4680 let demand = Arc::new(FakeDemand::ready(5, &repo("acme/app")));
4681 let mut harness = Harness::build(
4682 host_with(6),
4683 launcher,
4684 demand,
4685 Arc::new(InProcessAllocationLock::new()),
4686 );
4687
4688 let report = harness
4689 .reconciler
4690 .reconcile(&[policy(1, "acme/app", 5)])
4691 .await;
4692 assert_eq!(
4693 report.allocations[0].desired, 5,
4694 "its own ceiling allows five"
4695 );
4696 assert_eq!(report.started, 2, "the host has two slots free");
4697 assert_eq!(
4698 report.allocations[0].limiting_factor,
4699 LimitingFactor::HostCapacity
4700 );
4701 assert_eq!(harness.launcher.live_count(), 6);
4702 }
4703
4704 #[tokio::test]
4705 async fn the_idle_host_assertion_holds() {
4706 let mut harness = Harness::simple(8, 0, "acme/app");
4709 let report = harness
4710 .reconciler
4711 .reconcile(&[policy(1, "acme/app", 4), policy(2, "acme/app", 4)])
4712 .await;
4713
4714 assert_eq!(report.started, 0);
4715 assert_eq!(harness.launcher.launches(), 0);
4716 assert!(harness.launcher.snapshot().is_empty());
4717 assert_eq!(
4718 harness
4719 .launcher
4720 .snapshot()
4721 .iter()
4722 .filter(|a| !a.is_terminal())
4723 .count(),
4724 0
4725 );
4726 }
4727
4728 #[tokio::test]
4733 async fn live_capacity_increase_is_used_without_rebuilding_the_reconciler() {
4734 let mut harness = Harness::simple(1, 5, "acme/app");
4735 let policies = [policy(1, "acme/app", 5)];
4736 assert_eq!(harness.reconciler.reconcile(&policies).await.started, 1);
4737
4738 *harness.launcher.capacity.lock().unwrap() = NonZeroU16::new(4);
4739 assert_eq!(harness.reconciler.reconcile(&policies).await.started, 3);
4740 assert_eq!(harness.launcher.live_count(), 4);
4741 }
4742
4743 #[tokio::test]
4744 async fn live_capacity_decrease_keeps_busy_runners_and_waits_for_headroom() {
4745 let mut harness = Harness::simple(5, 5, "acme/app");
4746 let busy: Vec<_> = (1..=3)
4747 .map(|id| attempt_in(AttemptState::Busy, id, 1))
4748 .collect();
4749 *harness.launcher.attempts.lock().unwrap() = busy.clone();
4750 *harness.launcher.capacity.lock().unwrap() = NonZeroU16::new(2);
4751 let policies = [policy(1, "acme/app", 5)];
4752
4753 assert_eq!(harness.reconciler.reconcile(&policies).await.started, 0);
4754 assert_eq!(harness.launcher.snapshot(), busy);
4755 assert!(harness.launcher.cleaned().is_empty());
4756
4757 harness.launcher.attempts.lock().unwrap().truncate(1);
4759 assert_eq!(harness.reconciler.reconcile(&policies).await.started, 1);
4760 assert_eq!(harness.launcher.live_count(), 2);
4761 }
4762
4763 #[tokio::test]
4764 async fn live_capacity_is_rechecked_between_launches_in_the_same_pass() {
4765 let mut harness = Harness::simple(5, 5, "acme/app");
4766 *harness.launcher.capacity_after_launch.lock().unwrap() = NonZeroU16::new(1);
4767
4768 let report = harness
4769 .reconciler
4770 .reconcile(&[policy(1, "acme/app", 5)])
4771 .await;
4772 assert_eq!(report.started, 1);
4773 assert_eq!(harness.launcher.live_count(), 1);
4774 }
4775
4776 #[tokio::test]
4777 async fn live_capacity_unreadable_blocks_launches_until_the_journal_recovers() {
4778 let mut harness = Harness::simple(5, 5, "acme/app");
4779 harness
4780 .launcher
4781 .capacity_unreadable
4782 .store(true, Ordering::SeqCst);
4783 let policies = [policy(1, "acme/app", 5)];
4784 let report = harness.reconciler.reconcile(&policies).await;
4785 assert_eq!(report.started, 0);
4786 assert_eq!(report.host_capacity_unreadable, 1);
4787 assert_eq!(report.attempts_unreadable, 0);
4788 assert_eq!(harness.events.count_of("attempts_unreadable"), 0);
4789 assert!(
4790 harness
4791 .events
4792 .events()
4793 .contains(&LifecycleEvent::HostCapacityUnreadable {
4794 reason: HostCapacityError::JournalUnreadable,
4795 })
4796 );
4797
4798 harness
4799 .launcher
4800 .capacity_unreadable
4801 .store(false, Ordering::SeqCst);
4802 *harness.launcher.capacity.lock().unwrap() = NonZeroU16::new(2);
4803 assert_eq!(harness.reconciler.reconcile(&policies).await.started, 2);
4804 }
4805
4806 #[tokio::test]
4807 async fn unreadable_local_state_does_not_treat_a_busy_host_as_idle() {
4808 for host_failure in [true, false] {
4809 let mut harness = Harness::simple(5, 0, "acme/app");
4810 harness
4811 .reconciler
4812 .set_intervals(RefreshInterval::default(), Duration::from_secs(10));
4813 *harness.launcher.attempts.lock().unwrap() = vec![attempt_in(AttemptState::Busy, 1, 1)];
4814 harness
4815 .launcher
4816 .capacity_unreadable
4817 .store(host_failure, Ordering::SeqCst);
4818 harness.launcher.fail_attempts(!host_failure);
4819 let report = harness
4820 .reconciler
4821 .reconcile(&[policy(1, "acme/app", 5)])
4822 .await;
4823 assert_eq!(report.host_capacity_unreadable, u16::from(host_failure));
4824 assert_eq!(report.next_poll.pace, PollPace::Nominal);
4825 assert_eq!(harness.launcher.live_count(), 1);
4826 }
4827 }
4828
4829 #[derive(Debug)]
4830 struct HostEditOnLock {
4831 inner: InProcessAllocationLock,
4832 launcher: Arc<FakeLauncher>,
4833 unreadable: bool,
4834 }
4835
4836 #[async_trait::async_trait]
4837 impl AllocationLock for HostEditOnLock {
4838 async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
4839 let guard = self.inner.acquire().await?;
4840 *self.launcher.capacity.lock().unwrap() = NonZeroU16::new(1);
4841 self.launcher
4842 .capacity_unreadable
4843 .store(self.unreadable, Ordering::SeqCst);
4844 Ok(guard)
4845 }
4846 }
4847
4848 #[tokio::test]
4849 async fn live_capacity_edits_and_read_failures_while_waiting_for_the_lock_block_launches() {
4850 for unreadable in [false, true] {
4851 let launcher =
4852 Arc::new(FakeLauncher::new().seeded(vec![attempt_in(AttemptState::Busy, 1, 1)]));
4853 let lock = Arc::new(HostEditOnLock {
4854 inner: InProcessAllocationLock::new(),
4855 launcher: Arc::clone(&launcher),
4856 unreadable,
4857 });
4858 let mut harness = Harness::build(
4859 host_with(5),
4860 Arc::clone(&launcher),
4861 Arc::new(FakeDemand::ready(5, &repo("acme/app"))),
4862 lock,
4863 );
4864 let report = harness
4865 .reconciler
4866 .reconcile(&[policy(1, "acme/app", 5)])
4867 .await;
4868 assert_eq!(report.started, 0);
4869 assert_eq!(launcher.live_count(), 1);
4870 assert!(launcher.cleaned().is_empty());
4871 assert_eq!(report.host_capacity_unreadable, u16::from(unreadable));
4872 assert_eq!(report.attempts_unreadable, 0);
4873 }
4874 }
4875
4876 #[tokio::test(flavor = "current_thread")]
4899 async fn two_policies_reconciling_concurrently_never_exceed_host_capacity() {
4900 let lock = Arc::new(CountingLock::new());
4901 let (launches, live) =
4902 two_policies_concurrently(Arc::clone(&lock) as Arc<dyn AllocationLock>, None).await;
4903
4904 assert_eq!(
4905 launches, 3,
4906 "the sum across policies must never exceed host_capacity, and each policy is \
4907 individually within its own max_capacity of 3"
4908 );
4909 assert_eq!(live, 3, "and no duplicate runner survived the race");
4910 assert_eq!(
4911 lock.peak(),
4912 1,
4913 "the allocation lock had one holder at a time; without that the read of the \
4914 headroom and the creation of the runtime are not atomic"
4915 );
4916 assert!(
4917 (3..=5).contains(&lock.acquisitions()),
4918 "the lock is taken before *each* runtime, not once per pass: three runtimes \
4919 means at least three holds, and at most one further hold per policy to \
4920 discover the host filled up underneath it. It was taken {} times",
4921 lock.acquisitions()
4922 );
4923 }
4924
4925 #[tokio::test(flavor = "current_thread")]
4932 async fn without_the_allocation_lock_two_policies_oversubscribe_the_host() {
4933 let (launches, _) =
4934 two_policies_concurrently(Arc::new(NoLock) as Arc<dyn AllocationLock>, None).await;
4935
4936 assert!(
4937 launches > 3,
4938 "with no serialisation both policies must be able to spend the same headroom; \
4939 they started {launches} runners on a host of 3. If this is ever 3, the \
4940 contention window closed and `two_policies_reconciling_concurrently_never_\
4941 exceed_host_capacity` has stopped proving anything"
4942 );
4943 }
4944
4945 async fn two_policies_concurrently(
4949 lock: Arc<dyn AllocationLock>,
4950 live_capacity: Option<NonZeroU16>,
4951 ) -> (usize, usize) {
4952 let launcher = Arc::new(FakeLauncher::new().with_yields(4));
4953 *launcher.capacity.lock().unwrap() = live_capacity;
4954 let host = host_with(3);
4955
4956 let mut left = Harness::build(
4957 host.clone(),
4958 Arc::clone(&launcher),
4959 Arc::new(FakeDemand::ready(3, &repo("acme/left"))),
4960 Arc::clone(&lock),
4961 )
4962 .reconciler;
4963 let mut right = Harness::build(
4964 host,
4965 Arc::clone(&launcher),
4966 Arc::new(FakeDemand::ready(3, &repo("acme/right"))),
4967 Arc::clone(&lock),
4968 )
4969 .reconciler;
4970
4971 let a = policy(1, "acme/left", 3);
4972 let b = policy(2, "acme/right", 3);
4973
4974 let left = tokio::spawn(async move { left.reconcile(&[a]).await });
4975 let right = tokio::spawn(async move { right.reconcile(&[b]).await });
4976 let (_, _) = (left.await.unwrap(), right.await.unwrap());
4977
4978 (launcher.launches(), launcher.live_count())
4979 }
4980
4981 #[tokio::test(flavor = "current_thread")]
4982 async fn live_capacity_is_shared_by_concurrent_targets_with_stale_startup_hosts() {
4983 let (launches, live) =
4984 two_policies_concurrently(Arc::new(InProcessAllocationLock::new()), NonZeroU16::new(2))
4985 .await;
4986 assert_eq!(launches, 2);
4987 assert_eq!(live, 2);
4988 }
4989
4990 #[tokio::test]
5002 async fn a_monitor_only_policy_under_maximum_demand_starts_nothing_and_polls_nothing() {
5003 let gateway = FakeGithub::new().with_queued_jobs(repo("acme/app"), jobs(10_000));
5004 let gateway = Arc::new(GatewayDemand::new(gateway, CancelToken::new()));
5005 let launcher = Arc::new(FakeLauncher::new());
5006 let events = Arc::new(EventLog::new());
5007
5008 let mut reconciler = Reconciler::new(
5009 host_with(10),
5010 ReconcilerPorts {
5011 demand: Arc::clone(&gateway) as Arc<dyn DemandSource>,
5012 launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
5013 lock: Arc::new(InProcessAllocationLock::new()),
5014 directory: Arc::new(FakeDirectory::default()),
5015 clock: Arc::new(FakeClock::default()),
5016 jitter: Arc::new(NoJitter),
5017 events: Arc::clone(&events) as Arc<dyn EventSink>,
5018 },
5019 );
5020
5021 let monitor = fixtures::policy()
5022 .id(PolicyId::from_u128(1))
5023 .repository("acme/app")
5024 .monitor_only()
5025 .active()
5026 .build();
5027
5028 let report = reconciler.reconcile(&[monitor]).await;
5029
5030 assert_eq!(report.started, 0);
5031 assert_eq!(launcher.launches(), 0);
5032 assert_eq!(report.monitor_only, vec![PolicyId::from_u128(1)]);
5033 assert_eq!(
5034 report.demand_requests, 0,
5035 "a monitor-only policy spends nothing from the shared hourly ceiling"
5036 );
5037 assert!(
5038 gateway.gateway().calls().is_empty(),
5039 "a monitor-only policy issued a demand request: {:?}",
5040 gateway.gateway().calls()
5041 );
5042 assert_eq!(events.count_of("monitor_only_skipped"), 1);
5043 assert_eq!(
5044 events.count_of("demand_observed"),
5045 0,
5046 "and it contributed no demand"
5047 );
5048 }
5049
5050 #[tokio::test]
5068 async fn a_monitor_only_policy_sharing_a_target_is_still_skipped_entirely() {
5069 let lock = Arc::new(CountingLock::new());
5070 let launcher = Arc::new(FakeLauncher::new());
5071 let events = Arc::new(EventLog::new());
5072 let mut reconciler = Reconciler::new(
5073 host_with(4),
5074 ReconcilerPorts {
5075 demand: Arc::new(FakeDemand::ready(2, &repo("acme/app"))),
5076 launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
5077 lock: Arc::clone(&lock) as Arc<dyn AllocationLock>,
5078 directory: Arc::new(FakeDirectory::default()),
5079 clock: Arc::new(FakeClock::default()),
5080 jitter: Arc::new(NoJitter),
5081 events: Arc::clone(&events) as Arc<dyn EventSink>,
5082 },
5083 );
5084
5085 let watcher = fixtures::policy()
5086 .id(PolicyId::from_u128(2))
5087 .repository("acme/app")
5088 .monitor_only()
5089 .active()
5090 .build();
5091
5092 let report = reconciler
5093 .reconcile(&[policy(1, "acme/app", 4), watcher])
5094 .await;
5095
5096 assert_eq!(report.started, 2, "the autoscale policy is served normally");
5097 assert_eq!(report.monitor_only, vec![PolicyId::from_u128(2)]);
5098 assert_eq!(
5099 events.count_of("demand_observed"),
5100 1,
5101 "the demand observation belongs to the autoscale policy alone"
5102 );
5103 assert!(
5104 report
5105 .allocations
5106 .iter()
5107 .all(|a| a.policy_id == PolicyId::from_u128(1)),
5108 "a monitor-only policy was allocated for: {:?}",
5109 report.allocations
5110 );
5111 assert_eq!(
5112 lock.acquisitions(),
5113 2,
5114 "one hold per runtime created, and none on behalf of the monitor-only policy. \
5115 It was three before the budget was checked at the top of the loop rather than \
5116 after the re-read, which cost every policy a surplus hold to discover there \
5117 was nothing left to grant"
5118 );
5119 }
5120
5121 #[tokio::test]
5122 async fn the_monitor_only_refusal_is_asserted_on_the_mode_not_on_a_missing_ceiling() {
5123 let monitor = fixtures::monitor_only_policy();
5128 assert!(!monitor.owns_runners());
5129 assert_eq!(monitor.max_capacity(), None);
5130
5131 let host = host_with(10);
5132 let attempts: Vec<RunnerAttempt> = Vec::new();
5133 let mut allocator = HostAllocator::from_attempts(&host, &attempts);
5134 let allocation = allocator.allocate(&monitor, 10_000);
5135 assert_eq!(allocation.limiting_factor, LimitingFactor::MonitorOnly);
5136 assert_eq!(allocation.to_start, 0);
5137 assert_eq!(
5138 allocator.headroom(),
5139 10,
5140 "and it consumes no headroom, so an autoscale policy on the same host is \
5141 unaffected"
5142 );
5143 }
5144
5145 #[tokio::test]
5153 async fn a_surplus_attempt_is_cleaned_as_an_idle_exit_and_not_as_a_failure() {
5154 let launcher = Arc::new(FakeLauncher::new().seeded(vec![
5155 concluded(1, 1, AttemptOutcome::ExitedIdleWithoutWork),
5156 concluded(
5157 2,
5158 1,
5159 AttemptOutcome::failed(FailureReason::JitRequestFailed),
5160 ),
5161 concluded(3, 1, AttemptOutcome::CompletedJob),
5162 ]));
5163 let mut harness = Harness::build(
5164 host_with(4),
5165 Arc::clone(&launcher),
5166 Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
5167 Arc::new(InProcessAllocationLock::new()),
5168 );
5169
5170 let report = harness
5171 .reconciler
5172 .reconcile(&[policy(1, "acme/app", 4)])
5173 .await;
5174
5175 assert_eq!(report.cleaned, 3);
5176 assert_eq!(report.idle_exits, 1, "the surplus case, counted apart");
5177 assert_eq!(
5178 report.failures, 1,
5179 "only the failed attempt is a failure; the idle exit and the completed job are \
5180 not"
5181 );
5182 assert_eq!(launcher.cleaned().len(), 3);
5183 assert!(launcher.snapshot().is_empty());
5184
5185 let cleaned: Vec<OutcomeKind> = harness
5186 .events
5187 .events()
5188 .into_iter()
5189 .filter_map(|event| match event {
5190 LifecycleEvent::AttemptCleaned { outcome, .. } => Some(outcome),
5191 _ => None,
5192 })
5193 .collect();
5194 assert!(cleaned.contains(&OutcomeKind::IdleExit));
5195 assert!(
5196 !OutcomeKind::IdleExit.is_failure(),
5197 "an idle exit rendered as a failure sends an operator hunting a fault that does \
5198 not exist"
5199 );
5200 }
5201
5202 #[tokio::test]
5205 async fn scale_down_removes_nothing_from_a_busy_attempt() {
5206 let busy = attempt_in(AttemptState::Busy, 1, 1);
5207 let launcher = Arc::new(FakeLauncher::new().seeded(vec![
5208 busy.clone(),
5209 attempt_in(AttemptState::Starting, 2, 1),
5210 concluded(3, 1, AttemptOutcome::CompletedJob),
5211 ]));
5212 let harness = Harness::build(
5213 host_with(4),
5214 Arc::clone(&launcher),
5215 Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
5216 Arc::new(InProcessAllocationLock::new()),
5217 );
5218
5219 let report = harness
5220 .reconciler
5221 .scale_down(&policy(1, "acme/app", 4))
5222 .await;
5223
5224 assert_eq!(report.refused_busy, 1);
5225 assert_eq!(
5226 report.retained, 1,
5227 "the `starting` attempt is not ended either"
5228 );
5229 assert_eq!(report.removed, 1, "only the concluded attempt is reclaimed");
5230
5231 let after = launcher.snapshot();
5232 let still_busy = after
5233 .iter()
5234 .find(|a| a.id == AttemptId::from_u128(1))
5235 .expect("the busy attempt is still there");
5236 assert_eq!(
5237 still_busy.state(),
5238 AttemptState::Busy,
5239 "scale-down removed nothing from a runner that is executing a job, and left it \
5240 busy"
5241 );
5242 assert!(!launcher.cleaned().contains(&AttemptId::from_u128(1)));
5243
5244 let mut busy = busy;
5248 assert!(matches!(
5249 busy.clean(fixtures::created_at()),
5250 Err(runner_manager_domain::attempt::AttemptError::BusyCannotBeCleaned)
5251 ));
5252 assert_eq!(harness.events.count_of("scale_down_refused"), 1);
5253 }
5254
5255 #[test]
5260 fn the_default_interval_is_sixty_seconds_and_the_floor_is_thirty() {
5261 assert_eq!(RefreshInterval::DEFAULT_SECS, 60);
5262 assert_eq!(RefreshInterval::MIN_SECS, 30);
5263 assert_eq!(PollSchedule::floor(), Duration::from_secs(30));
5264 assert!(
5265 RefreshInterval::from_secs(29).is_err(),
5266 "the floor is a rate-budget constraint, and a caller must not be able to write \
5267 a shorter interval at all"
5268 );
5269
5270 let mut schedule = PollSchedule::new(RefreshInterval::default());
5271 let next = schedule.next_poll(None, fixtures::created_at(), &NoJitter);
5272 assert_eq!(next.delay, Duration::from_secs(60));
5273 assert_eq!(next.pace, PollPace::Nominal);
5274
5275 let mut floored = PollSchedule::new(RefreshInterval::from_secs(30).unwrap());
5276 assert_eq!(
5277 floored
5278 .next_poll(None, fixtures::created_at(), &NoJitter)
5279 .delay,
5280 Duration::from_secs(30)
5281 );
5282 }
5283
5284 #[test]
5288 fn a_rate_limit_increases_the_delay_and_names_itself() {
5289 let now = fixtures::created_at();
5290 let mut schedule = PollSchedule::new(RefreshInterval::default());
5291
5292 let limited = RefreshState::RateLimited(RateLimited {
5293 kind: RateLimitKind::Secondary,
5294 retry_after: Some(Duration::from_secs(300)),
5295 remaining: None,
5296 reset_unix_secs: None,
5297 });
5298 let next = schedule.next_poll(Some(&limited), now, &NoJitter);
5299
5300 assert_eq!(next.delay, Duration::from_secs(300));
5301 assert_eq!(
5302 next.pace,
5303 PollPace::RateLimited {
5304 kind: RateLimitKind::Secondary
5305 },
5306 "the increase is reported, never hidden"
5307 );
5308 assert!(next.pace.is_throttled());
5309 assert_eq!(next.pace.as_str(), "rate_limited_secondary");
5310 }
5311
5312 #[test]
5315 fn the_retry_delay_is_an_absolute_floor_and_never_an_addend() {
5316 let now = fixtures::created_at();
5317 let mut schedule = PollSchedule::new(RefreshInterval::default());
5318
5319 let limited = RefreshState::RateLimited(RateLimited {
5320 kind: RateLimitKind::Primary,
5321 retry_after: Some(Duration::from_secs(300)),
5322 remaining: Some(0),
5323 reset_unix_secs: None,
5324 });
5325
5326 for _ in 0..5 {
5329 let next = schedule.next_poll(Some(&limited), now, &NoJitter);
5330 assert_eq!(
5331 next.delay,
5332 Duration::from_secs(300),
5333 "the delay is `max(interval, retry_delay)`; `interval + retry_delay` would \
5334 have compounded on every successive retry"
5335 );
5336 }
5337
5338 let brief = RefreshState::RateLimited(RateLimited {
5341 kind: RateLimitKind::Secondary,
5342 retry_after: Some(Duration::from_secs(5)),
5343 remaining: None,
5344 reset_unix_secs: None,
5345 });
5346 let next = schedule.next_poll(Some(&brief), now, &NoJitter);
5347 assert_eq!(
5348 next.delay,
5349 Duration::from_secs(60),
5350 "a short `retry-after` may not drop the loop below its own interval"
5351 );
5352 assert!(next.delay >= PollSchedule::floor());
5353 }
5354
5355 #[test]
5356 fn no_branch_of_the_schedule_can_go_below_the_thirty_second_floor() {
5357 let now = fixtures::created_at();
5358 let states = [
5359 None,
5360 Some(RefreshState::Offline),
5361 Some(RefreshState::RateLimited(RateLimited {
5362 kind: RateLimitKind::Secondary,
5363 retry_after: Some(Duration::from_secs(1)),
5364 remaining: None,
5365 reset_unix_secs: None,
5366 })),
5367 Some(RefreshState::LockedOut {
5368 retry_after: Duration::from_secs(1),
5369 }),
5370 Some(RefreshState::Unauthorized),
5371 Some(RefreshState::Forbidden { message: None }),
5372 Some(RefreshState::Failed {
5373 status: Some(500),
5374 message: "server error".into(),
5375 }),
5376 Some(RefreshState::Cancelled),
5377 ];
5378
5379 for state in &states {
5380 let mut schedule = PollSchedule::new(RefreshInterval::from_secs(30).unwrap());
5381 let next = schedule.next_poll(state.as_ref(), now, &NoJitter);
5382 assert!(
5383 next.delay >= PollSchedule::floor(),
5384 "{state:?} scheduled a poll {}ms away, under the 30-second floor",
5385 next.delay.as_millis()
5386 );
5387 }
5388 }
5389
5390 #[test]
5391 fn an_offline_run_backs_off_with_jitter_and_a_recovery_resets_it() {
5392 let now = fixtures::created_at();
5393 let mut schedule = PollSchedule::new(RefreshInterval::default());
5394
5395 let mut previous = Duration::ZERO;
5397 for consecutive in 1..=6_u32 {
5398 let next = schedule.next_poll(Some(&RefreshState::Offline), now, &NoJitter);
5399 assert_eq!(next.pace, PollPace::Offline { consecutive });
5400 assert!(
5401 next.delay >= previous,
5402 "the back-off must not shrink while the outage continues"
5403 );
5404 assert!(next.delay >= Duration::from_secs(60));
5405 previous = next.delay;
5406 }
5407 assert!(previous <= MAX_OFFLINE_BACKOFF, "and it is capped");
5408
5409 let mut jittered = PollSchedule::new(RefreshInterval::default());
5412 let none = jittered.next_poll(Some(&RefreshState::Offline), now, &NoJitter);
5413 let mut jittered = PollSchedule::new(RefreshInterval::default());
5414 let full = jittered.next_poll(Some(&RefreshState::Offline), now, &FixedJitter(0.999));
5415 assert!(full.delay > none.delay);
5416 assert!(full.delay <= none.delay.mul_f64(1.0 + JITTER_RATIO));
5417
5418 assert_eq!(schedule.consecutive_offline(), 6);
5420 let recovered = schedule.next_poll(None, now, &NoJitter);
5421 assert_eq!(recovered.pace, PollPace::Nominal);
5422 assert_eq!(recovered.delay, Duration::from_secs(60));
5423 assert_eq!(schedule.consecutive_offline(), 0);
5424 }
5425
5426 #[test]
5427 fn the_offline_state_states_the_twenty_four_hour_bound() {
5428 assert_eq!(
5429 GITHUB_CANCELS_QUEUED_JOBS_AFTER,
5430 Duration::from_secs(24 * 60 * 60)
5431 );
5432
5433 let brief = OfflineState::new(1, Duration::from_secs(120));
5434 let rendered = brief.to_string();
5435 assert!(rendered.contains("24 hours"), "{rendered}");
5436 assert!(rendered.contains("Retrying in 120s"), "{rendered}");
5437 assert!(!brief.has_outlasted_the_queue());
5438
5439 let long = brief.since(GITHUB_CANCELS_QUEUED_JOBS_AFTER + Duration::from_secs(1));
5440 assert!(long.has_outlasted_the_queue());
5441 assert!(
5442 long.to_string().contains("queued work has been lost"),
5443 "{long}"
5444 );
5445
5446 assert!(!OfflineState::new(9, Duration::from_secs(60)).has_outlasted_the_queue());
5448 }
5449
5450 fn quota(remaining: u64, reset_in_secs: i64, now: Timestamp) -> RateLimitSnapshot {
5455 RateLimitSnapshot {
5456 limit: 5_000,
5457 remaining,
5458 used: Some(5_000 - remaining),
5459 reset_unix_secs: u64::try_from(now.timestamp() + reset_in_secs).expect("positive"),
5460 observed_at: now,
5461 }
5462 }
5463
5464 fn quiet() -> PollConditions {
5465 PollConditions {
5466 quiet: true,
5467 quota: None,
5468 requests_per_pass: 0,
5469 }
5470 }
5471
5472 #[test]
5473 fn a_quiet_pass_polls_at_the_idle_interval_and_a_busy_one_at_the_active_interval() {
5474 let now = fixtures::created_at();
5475 let mut schedule =
5476 PollSchedule::new(RefreshInterval::default()).with_idle(Duration::from_secs(10));
5477
5478 let idle = schedule.next_poll_with(None, quiet(), now, &NoJitter);
5479 assert_eq!(idle.delay, Duration::from_secs(10));
5480 assert_eq!(idle.pace, PollPace::Idle);
5481 assert!(!idle.pace.is_throttled(), "idle is faster, not a slowdown");
5482
5483 let busy = schedule.next_poll_with(None, PollConditions::default(), now, &NoJitter);
5484 assert_eq!(busy.delay, Duration::from_secs(60));
5485 assert_eq!(busy.pace, PollPace::Nominal);
5486 }
5487
5488 #[test]
5489 fn a_schedule_never_told_an_idle_interval_keeps_its_active_one() {
5490 let now = fixtures::created_at();
5491 let mut schedule = PollSchedule::new(RefreshInterval::default());
5492 assert_eq!(
5493 schedule.next_poll_with(None, quiet(), now, &NoJitter).delay,
5494 Duration::from_secs(60)
5495 );
5496 }
5497
5498 #[test]
5499 fn an_idle_interval_is_clamped_between_its_floor_and_the_active_interval() {
5500 let schedule = PollSchedule::new(RefreshInterval::from_secs(30).expect("the floor"))
5501 .with_idle(Duration::from_secs(120));
5502 assert_eq!(
5503 schedule.idle(),
5504 Duration::from_secs(30),
5505 "an idle interval above the active one would make quiet targets slower to react"
5506 );
5507 let schedule =
5508 PollSchedule::new(RefreshInterval::default()).with_idle(Duration::from_secs(1));
5509 assert_eq!(schedule.idle(), PollSchedule::idle_floor());
5510 }
5511
5512 #[test]
5515 fn a_low_quota_stretches_polling_and_wins_over_idle() {
5516 let now = fixtures::created_at();
5517 let mut schedule =
5518 PollSchedule::new(RefreshInterval::default()).with_idle(Duration::from_secs(10));
5519
5520 let healthy = schedule.next_poll_with(
5521 None,
5522 PollConditions {
5523 quiet: true,
5524 quota: Some(quota(1_000, 3_000, now)),
5525 requests_per_pass: 0,
5526 },
5527 now,
5528 &NoJitter,
5529 );
5530 assert_eq!(healthy.pace, PollPace::Idle, "a fifth left is still normal");
5531
5532 let low = schedule.next_poll_with(
5533 None,
5534 PollConditions {
5535 quiet: true,
5536 quota: Some(quota(999, 3_000, now)),
5537 requests_per_pass: 0,
5538 },
5539 now,
5540 &NoJitter,
5541 );
5542 assert_eq!(low.delay, Duration::from_secs(120));
5543 assert_eq!(
5544 low.pace,
5545 PollPace::Stretched {
5546 pressure: PrimaryPressure::Low
5547 }
5548 );
5549 assert!(low.pace.is_throttled());
5550 assert_eq!(low.pace.as_str(), "stretched_low_budget");
5551
5552 let critical = schedule.next_poll_with(
5553 None,
5554 PollConditions {
5555 quiet: false,
5556 quota: Some(quota(100, 3_000, now)),
5557 requests_per_pass: 0,
5558 },
5559 now,
5560 &NoJitter,
5561 );
5562 assert_eq!(critical.delay, Duration::from_secs(240));
5563 assert_eq!(critical.pace.as_str(), "stretched_critical_budget");
5564 }
5565
5566 #[test]
5567 fn a_stretch_never_outlasts_the_quotas_reset_nor_undercuts_the_active_interval() {
5568 let now = fixtures::created_at();
5569 let mut schedule = PollSchedule::new(RefreshInterval::default());
5570
5571 let soon = schedule.next_poll_with(
5572 None,
5573 PollConditions {
5574 quiet: false,
5575 quota: Some(quota(10, 90, now)),
5576 requests_per_pass: 0,
5577 },
5578 now,
5579 &NoJitter,
5580 );
5581 assert_eq!(
5582 soon.delay,
5583 Duration::from_secs(90),
5584 "the bucket refills in 90 s; waiting 240 s buys nothing"
5585 );
5586
5587 let imminent = schedule.next_poll_with(
5588 None,
5589 PollConditions {
5590 quiet: false,
5591 quota: Some(quota(10, 5, now)),
5592 requests_per_pass: 0,
5593 },
5594 now,
5595 &NoJitter,
5596 );
5597 assert_eq!(imminent.delay, Duration::from_secs(60));
5598
5599 let expired = schedule.next_poll_with(
5600 None,
5601 PollConditions {
5602 quiet: true,
5603 quota: Some(quota(10, -5, now)),
5604 requests_per_pass: 0,
5605 },
5606 now,
5607 &NoJitter,
5608 );
5609 assert_eq!(
5610 expired.pace,
5611 PollPace::Nominal,
5612 "a reading from a window that has reset says nothing; the schedule here had no \
5613 idle interval, so it is the active one"
5614 );
5615 }
5616
5617 #[test]
5618 fn an_idle_target_too_large_to_poll_that_often_stretches_its_idle_interval() {
5619 let now = fixtures::created_at();
5620 let mut schedule =
5621 PollSchedule::new(RefreshInterval::default()).with_idle(Duration::from_secs(10));
5622 let small = schedule.next_poll_with(
5623 None,
5624 PollConditions {
5625 quiet: true,
5626 quota: None,
5627 requests_per_pass: 40,
5628 },
5629 now,
5630 &NoJitter,
5631 );
5632 assert_eq!(small.delay, Duration::from_secs(10), "ten repositories fit");
5633 let organization = schedule.next_poll_with(
5634 None,
5635 PollConditions {
5636 quiet: true,
5637 quota: None,
5638 requests_per_pass: 400,
5639 },
5640 now,
5641 &NoJitter,
5642 );
5643 assert_eq!(
5644 organization.delay,
5645 Duration::from_secs(80),
5646 "400 requests a pass at 300 a minute is one pass every 80 s"
5647 );
5648 assert_eq!(organization.pace, PollPace::Idle);
5649 }
5650
5651 #[test]
5652 fn a_rate_limit_wait_is_jittered_upward_only() {
5653 let now = fixtures::created_at();
5654 let mut schedule = PollSchedule::new(RefreshInterval::default());
5655 let limited = RefreshState::RateLimited(RateLimited {
5656 kind: RateLimitKind::Secondary,
5657 retry_after: Some(Duration::from_secs(300)),
5658 remaining: None,
5659 reset_unix_secs: None,
5660 });
5661 assert_eq!(
5662 schedule
5663 .next_poll(Some(&limited), now, &FixedJitter(0.5))
5664 .delay,
5665 Duration::from_secs(315),
5666 "every loop shares one quiet period; without jitter they all wake together"
5667 );
5668 assert_eq!(
5669 schedule.next_poll(Some(&limited), now, &NoJitter).delay,
5670 Duration::from_secs(300),
5671 "never shorter than GitHub asked"
5672 );
5673 }
5674
5675 #[tokio::test]
5676 async fn demand_this_host_did_not_serve_keeps_the_target_off_the_idle_pace() {
5677 let launcher =
5680 Arc::new(FakeLauncher::new().seeded(vec![attempt_in(AttemptState::Busy, 9, 9)]));
5681 let demand = Arc::new(FakeDemand::ready(2, &repo("acme/app")));
5682 let mut harness = Harness::build(
5683 host_with(1),
5684 launcher,
5685 demand,
5686 Arc::new(InProcessAllocationLock::new()),
5687 );
5688 harness
5689 .reconciler
5690 .set_intervals(RefreshInterval::default(), Duration::from_secs(10));
5691 let policy = policy(1, "acme/app", 4);
5692
5693 let report = harness
5694 .reconciler
5695 .reconcile(std::slice::from_ref(&policy))
5696 .await;
5697
5698 assert_eq!(report.started, 0, "the host is full");
5699 assert_eq!(
5700 report.next_poll.pace,
5701 PollPace::Nominal,
5702 "matched demand it could not serve is work waiting, not idle"
5703 );
5704 }
5705
5706 #[tokio::test]
5707 async fn a_target_with_nothing_to_do_is_polled_at_the_idle_interval() {
5708 let mut harness = Harness::simple(4, 0, "acme/app");
5709 harness
5710 .reconciler
5711 .set_intervals(RefreshInterval::default(), Duration::from_secs(10));
5712 let policy = policy(1, "acme/app", 4);
5713
5714 let report = harness
5715 .reconciler
5716 .reconcile(std::slice::from_ref(&policy))
5717 .await;
5718
5719 assert_eq!(report.next_poll.pace, PollPace::Idle);
5720 assert_eq!(report.next_poll.delay, Duration::from_secs(10));
5721 }
5722
5723 #[tokio::test]
5724 async fn a_target_whose_runs_are_changing_is_polled_at_the_active_interval() {
5725 let mut harness = Harness::simple(4, 0, "acme/app");
5726 harness
5727 .reconciler
5728 .set_intervals(RefreshInterval::default(), Duration::from_secs(10));
5729 harness.demand.set(PollOutcome::Ready(
5730 QueuedDemand::of(repo("acme/app"), Vec::new()).with_busy(repo("acme/app")),
5731 ));
5732 let policy = policy(1, "acme/app", 4);
5733
5734 let report = harness
5735 .reconciler
5736 .reconcile(std::slice::from_ref(&policy))
5737 .await;
5738
5739 assert_eq!(report.next_poll.pace, PollPace::Nominal);
5740 assert_eq!(report.next_poll.delay, Duration::from_secs(60));
5741 }
5742
5743 #[tokio::test]
5744 async fn a_target_with_a_live_runner_is_polled_at_the_active_interval() {
5745 let launcher =
5746 Arc::new(FakeLauncher::new().seeded(vec![attempt_in(AttemptState::Busy, 1, 1)]));
5747 let demand = Arc::new(FakeDemand::ready(0, &repo("acme/app")));
5748 let mut harness = Harness::build(
5749 host_with(4),
5750 launcher,
5751 demand,
5752 Arc::new(InProcessAllocationLock::new()),
5753 );
5754 harness
5755 .reconciler
5756 .set_intervals(RefreshInterval::default(), Duration::from_secs(10));
5757 let policy = policy(1, "acme/app", 4);
5758
5759 let report = harness
5760 .reconciler
5761 .reconcile(std::slice::from_ref(&policy))
5762 .await;
5763
5764 assert_eq!(
5765 report.next_poll.pace,
5766 PollPace::Nominal,
5767 "a job is running: its follow-on work is what the active interval watches for"
5768 );
5769 }
5770
5771 #[tokio::test]
5772 async fn a_pass_that_starts_a_runner_is_not_idle() {
5773 let mut harness = Harness::simple(4, 2, "acme/app");
5774 harness
5775 .reconciler
5776 .set_intervals(RefreshInterval::default(), Duration::from_secs(10));
5777 let policy = policy(1, "acme/app", 4);
5778
5779 let report = harness
5780 .reconciler
5781 .reconcile(std::slice::from_ref(&policy))
5782 .await;
5783
5784 assert!(report.started > 0);
5785 assert_eq!(report.next_poll.pace, PollPace::Nominal);
5786 }
5787
5788 #[tokio::test]
5789 async fn the_quota_reported_with_a_reading_stretches_the_next_poll() {
5790 let mut harness = Harness::simple(4, 0, "acme/app");
5791 harness
5792 .reconciler
5793 .set_intervals(RefreshInterval::default(), Duration::from_secs(10));
5794 let now = harness.clock.now();
5795 harness.demand.set(PollOutcome::Ready(
5796 QueuedDemand::of(repo("acme/app"), Vec::new())
5797 .with_rate_limit(Some(quota(200, 1_800, now))),
5798 ));
5799 let policy = policy(1, "acme/app", 4);
5800
5801 let report = harness
5802 .reconciler
5803 .reconcile(std::slice::from_ref(&policy))
5804 .await;
5805
5806 assert_eq!(
5807 report.next_poll.pace,
5808 PollPace::Stretched {
5809 pressure: PrimaryPressure::Critical
5810 }
5811 );
5812 assert_eq!(report.next_poll.delay, Duration::from_secs(240));
5813 }
5814
5815 #[tokio::test]
5824 async fn an_unreachable_github_starts_nothing_retains_everything_and_backs_off() {
5825 let live = vec![
5826 attempt_in(AttemptState::Busy, 1, 1),
5827 attempt_in(AttemptState::Starting, 2, 1),
5828 ];
5829 let launcher = Arc::new(FakeLauncher::new().seeded(live.clone()));
5830 let demand = Arc::new(FakeDemand::failing(RefreshState::Offline));
5831 let mut harness = Harness::build(
5832 host_with(8),
5833 Arc::clone(&launcher),
5834 Arc::clone(&demand),
5835 Arc::new(InProcessAllocationLock::new()),
5836 );
5837 let policy = policy(1, "acme/app", 8);
5838
5839 let report = harness
5840 .reconciler
5841 .reconcile(std::slice::from_ref(&policy))
5842 .await;
5843
5844 assert!(report.is_offline());
5845 assert_eq!(report.started, 0, "no new runner during an outage");
5846 assert_eq!(launcher.launches(), 0);
5847 assert_eq!(
5848 launcher.snapshot(),
5849 live,
5850 "existing runner processes are retained, untouched"
5851 );
5852 assert_eq!(report.unreadable, vec![PolicyId::from_u128(1)]);
5853 assert_eq!(report.next_poll.pace, PollPace::Offline { consecutive: 1 });
5854 assert!(report.next_poll.delay >= Duration::from_secs(60));
5855 let offline = report.offline_state().expect("an offline state to display");
5856 assert!(offline.to_string().contains("24 hours"));
5857
5858 demand.set(PollOutcome::Ready(QueuedDemand::of(
5861 repo("acme/app"),
5862 jobs(2),
5863 )));
5864 let recovered = harness.reconciler.reconcile(&[policy]).await;
5865
5866 assert!(!recovered.is_offline());
5867 assert_eq!(recovered.next_poll.pace, PollPace::Nominal);
5868 assert_eq!(
5869 recovered.started, 1,
5870 "two queued jobs and one starting runner leave one job uncovered"
5871 );
5872 assert_eq!(recovered.allocations[0].active_owned, 2);
5873 assert_eq!(launcher.live_count(), 3);
5874 }
5875
5876 #[tokio::test]
5886 async fn one_offline_target_does_not_stop_a_reachable_one() {
5887 let mut harness = Harness::simple(8, 0, "acme/app");
5888 harness.demand.set_for(
5889 &ScaleTarget::repository("acme/app").unwrap(),
5890 PollOutcome::Ready(QueuedDemand::of(repo("acme/app"), jobs(2))),
5891 );
5892 harness.demand.set_for(
5893 &ScaleTarget::repository("acme/broken").unwrap(),
5894 PollOutcome::Failed(RefreshState::Offline),
5895 );
5896
5897 let report = harness
5898 .reconciler
5899 .reconcile(&[policy(1, "acme/app", 4), policy(2, "acme/broken", 4)])
5900 .await;
5901
5902 assert_eq!(
5903 report.started, 2,
5904 "the reachable target was served; an unreachable sibling repository must not \
5905 idle the host"
5906 );
5907 assert_eq!(report.unreadable, vec![PolicyId::from_u128(2)]);
5908 assert_eq!(harness.demand.polls().len(), 2, "both targets were polled");
5909
5910 assert!(report.is_offline());
5912 assert_eq!(report.next_poll.pace, PollPace::Offline { consecutive: 1 });
5913 }
5914
5915 #[tokio::test]
5930 async fn a_day_long_outage_says_that_queued_work_has_already_been_lost() {
5931 let clock = Arc::new(FakeClock::default());
5932 let launcher = Arc::new(FakeLauncher::new());
5933 let demand = Arc::new(FakeDemand::failing(RefreshState::Offline));
5934 let mut reconciler = Reconciler::new(
5935 host_with(4),
5936 ReconcilerPorts {
5937 demand: Arc::clone(&demand) as Arc<dyn DemandSource>,
5938 launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
5939 lock: Arc::new(InProcessAllocationLock::new()),
5940 directory: Arc::new(FakeDirectory::default()),
5941 clock: Arc::clone(&clock) as Arc<dyn Clock>,
5942 jitter: Arc::new(NoJitter),
5943 events: Arc::new(NoEvents),
5944 },
5945 );
5946 let policy = policy(1, "acme/app", 4);
5947
5948 let first = reconciler.reconcile(std::slice::from_ref(&policy)).await;
5950 let state = first.offline_state().expect("an offline state");
5951 assert!(!state.has_outlasted_the_queue());
5952 assert!(
5953 state
5954 .to_string()
5955 .contains("an outage longer than that loses"),
5956 "{state}"
5957 );
5958
5959 clock.advance_secs(24 * 60 * 60 + 60);
5961 let later = reconciler.reconcile(std::slice::from_ref(&policy)).await;
5962 let state = later.offline_state().expect("an offline state");
5963 assert!(state.has_outlasted_the_queue());
5964 assert!(
5965 state.to_string().contains("queued work has been lost"),
5966 "{state}"
5967 );
5968 assert_eq!(launcher.launches(), 0, "and still nothing was started");
5969
5970 demand.set(PollOutcome::Ready(QueuedDemand::of(
5973 repo("acme/app"),
5974 jobs(0),
5975 )));
5976 let recovered = reconciler.reconcile(std::slice::from_ref(&policy)).await;
5977 assert!(recovered.offline_state().is_none());
5978 assert_eq!(reconciler.schedule().offline_for(clock.now()), None);
5979
5980 demand.set(PollOutcome::Failed(RefreshState::Offline));
5981 let again = reconciler.reconcile(std::slice::from_ref(&policy)).await;
5982 assert!(
5983 !again
5984 .offline_state()
5985 .expect("an offline state")
5986 .has_outlasted_the_queue(),
5987 "a new outage must not inherit the age of the one before it"
5988 );
5989 }
5990
5991 #[tokio::test]
6007 async fn the_file_allocation_lock_excludes_a_second_holder_and_releases_on_drop() {
6008 let root = tempfile::tempdir().expect("a temporary directory");
6009 let paths = Arc::new(runner_manager_platform::paths::AppPaths::rooted_at(
6010 root.path(),
6011 ));
6012 let lock = FileAllocationLock::new(paths).with_wait(Duration::from_millis(50));
6013
6014 let held = lock.acquire().await.expect("an uncontended lock is free");
6015 assert!(
6016 matches!(lock.acquire().await, Err(AllocationLockBusy)),
6017 "a second holder was admitted; on Unix the lock is per open file description \
6018 and on Windows the share mode denies write, so this must be refused even \
6019 from inside the same process"
6020 );
6021
6022 drop(held);
6023 let regained = lock.acquire().await;
6024 assert!(
6025 regained.is_ok(),
6026 "dropping the guard is the only release there is, so a guard that does not \
6027 hold the `HostLock` leaves it held forever"
6028 );
6029 }
6030
6031 #[test]
6032 fn tee_events_reaches_both_sinks() {
6033 let left = Arc::new(EventLog::new());
6037 let right = Arc::new(EventLog::new());
6038 let tee = TeeEvents(
6039 Arc::clone(&left) as Arc<dyn EventSink>,
6040 Arc::clone(&right) as Arc<dyn EventSink>,
6041 );
6042
6043 tee.emit(LifecycleEvent::MonitorOnlySkipped {
6044 policy: PolicyId::from_u128(1),
6045 });
6046
6047 assert_eq!(left.count_of("monitor_only_skipped"), 1);
6048 assert_eq!(right.count_of("monitor_only_skipped"), 1);
6049 }
6050
6051 #[tokio::test]
6056 async fn the_repository_list_refreshes_far_more_slowly_than_the_demand_poll() {
6057 let clock = Arc::new(FakeClock::default());
6058 let directory = Arc::new(FakeDirectory::of(vec![repo("acme/one"), repo("acme/two")]));
6059 let cache = RepositoryCache::new(
6060 Arc::clone(&directory) as Arc<dyn RepositoryDirectory>,
6061 Arc::clone(&clock) as Arc<dyn Clock>,
6062 RefreshInterval::default(),
6063 );
6064 let target = ScaleTarget::organization("acme").unwrap();
6065
6066 assert_eq!(
6067 cache.ttl(),
6068 Duration::from_secs(60 * u64::from(REPOSITORY_LIST_REFRESH_MULTIPLE))
6069 );
6070
6071 for _ in 0..REPOSITORY_LIST_REFRESH_MULTIPLE {
6073 let scope = cache.scope_for(&target).await.unwrap();
6074 assert_eq!(scope.repositories().len(), 2);
6075 clock.advance_secs(60);
6076 }
6077 assert_eq!(
6078 directory.calls(),
6079 1,
6080 "re-listing an organization at demand-poll frequency is what exhausts the \
6081 shared request budget"
6082 );
6083 assert_eq!(cache.lookups(), 1);
6084
6085 cache.scope_for(&target).await.unwrap();
6087 assert_eq!(directory.calls(), 2);
6088 }
6089
6090 #[tokio::test]
6091 async fn a_repository_target_never_consults_the_directory() {
6092 let directory = Arc::new(FakeDirectory::of(vec![repo("acme/other")]));
6093 let cache = RepositoryCache::new(
6094 Arc::clone(&directory) as Arc<dyn RepositoryDirectory>,
6095 Arc::new(FakeClock::default()) as Arc<dyn Clock>,
6096 RefreshInterval::default(),
6097 );
6098 let target = ScaleTarget::repository("acme/app").unwrap();
6099
6100 let scope = cache.scope_for(&target).await.unwrap();
6101 assert_eq!(scope.repositories(), &[repo("acme/app")]);
6102 assert_eq!(directory.calls(), 0);
6103 }
6104
6105 #[tokio::test]
6106 async fn two_policies_on_one_target_cost_one_demand_poll_not_two() {
6107 let mut harness = Harness::simple(8, 4, "o/r");
6111 harness.demand.set(PollOutcome::Ready(QueuedDemand::of(
6112 repo("o/r"),
6113 [
6114 fixtures::queued_job(&[HOST_LABEL]),
6115 fixtures::queued_job(&[HOST_LABEL]),
6116 fixtures::queued_job(&["rm-home-win-x64-py-isolated"]),
6117 fixtures::queued_job(&["rm-home-win-x64-py-isolated"]),
6118 ],
6119 )));
6120 let mut isolated = fixtures::named_policy("py-isolated", PolicyId::from_u128(2));
6121 isolated.activate().unwrap();
6122 let report = harness
6123 .reconciler
6124 .reconcile(&[policy(1, "o/r", 2), isolated])
6125 .await;
6126
6127 assert_eq!(harness.demand.polls().len(), 1);
6128 assert_eq!(report.targets_read, 1, "profiles share one target reading");
6129 assert_eq!(
6130 report.demand_requests,
6131 runner_manager_github::demand::DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL,
6132 "one repository's worth of demand requests, not two policies' worth. Read from the constant rather than written as a literal so that repricing the poll cannot silently turn this into an assertion about the wrong thing"
6133 );
6134 assert_eq!(
6135 report.started, 4,
6136 "native and isolated profiles each get two"
6137 );
6138 }
6139
6140 #[tokio::test]
6141 async fn subset_labels_without_selector_scale_only_the_compatible_local_profile() {
6142 use runner_manager_domain::model::{Arch, HostLabel, Os};
6143 use runner_manager_domain::policy::RoutingLabels;
6144 let mut harness = Harness::build(
6145 fixtures::host()
6146 .os(Os::MacOs)
6147 .architecture(Arch::Arm64)
6148 .capacity(10)
6149 .build(),
6150 Arc::new(FakeLauncher::new()),
6151 Arc::new(FakeDemand::ready(0, &repo("o/r"))),
6152 Arc::new(InProcessAllocationLock::new()),
6153 );
6154 harness.demand.set(PollOutcome::Ready(QueuedDemand::of(
6155 repo("o/r"),
6156 [
6157 fixtures::queued_job(&["self-hosted", "macOS", "ARM64"]),
6158 fixtures::queued_job(&["SELF-HOSTED", "MACOS", "arm64"]),
6159 fixtures::queued_job(&["self-hosted", "macOS", "X64"]),
6160 fixtures::queued_job(&["self-hosted", "Windows", "ARM64"]),
6161 fixtures::queued_job(&["self-hosted", "macOS", "ARM64", "gpu"]),
6162 fixtures::queued_job(&["rm-other-osx-arm64", "macOS", "ARM64"]),
6163 ],
6164 )));
6165 let mut local = fixtures::policy()
6166 .id(PolicyId::from_u128(1))
6167 .repository("o/r")
6168 .autoscale("macmini", 10)
6169 .routing_labels(RoutingLabels::derive(
6170 &HostLabel::new("macmini").unwrap(),
6171 Os::MacOs,
6172 Arch::Arm64,
6173 ))
6174 .active()
6175 .build();
6176 for label in ["self-hosted", "macos", "arm64", "extra"] {
6177 local.add_routing_label(fixtures::label(label)).unwrap();
6178 }
6179 let mut foreign = local.to_persisted();
6180 foreign.id = PolicyId::from_u128(2);
6181 foreign.host_id = HostId::from_u128(0xdead);
6182 let foreign = ScalePolicy::from_persisted(foreign).unwrap();
6183 let report = harness.reconciler.reconcile(&[local, foreign]).await;
6184 assert_eq!(report.started, 2);
6185 assert_eq!(report.targets_read, 1);
6186 assert!(harness.events.events().iter().any(|event| matches!(
6187 event,
6188 LifecycleEvent::DemandObserved {
6189 demand: 2,
6190 not_matched: 4,
6191 ..
6192 }
6193 )));
6194 assert!(
6195 !harness
6196 .events
6197 .events()
6198 .iter()
6199 .any(|event| matches!(event, LifecycleEvent::RoutingRefused { .. }))
6200 );
6201 }
6202
6203 #[tokio::test]
6204 async fn isolated_overlap_never_falls_back_to_native_in_either_state_or_order() {
6205 use runner_manager_domain::execution::{
6206 Backend, ExecutionPolicy, ImageReference, ResourceLimits,
6207 };
6208 let mut native = policy(1, "o/r", 2);
6209 native
6210 .add_routing_label(fixtures::label("self-hosted"))
6211 .unwrap();
6212 let mut isolated = fixtures::named_policy("py-isolated", PolicyId::from_u128(2));
6213 isolated
6214 .add_routing_label(fixtures::label("self-hosted"))
6215 .unwrap();
6216 isolated
6217 .set_execution_policy(ExecutionPolicy::Isolated {
6218 backend: Backend::Oci,
6219 image: ImageReference::new(format!(
6220 "registry.example/runner@sha256:{}",
6221 "a".repeat(64)
6222 ))
6223 .unwrap(),
6224 resources: ResourceLimits {
6225 cpu_millis: 1000,
6226 memory_mib: 512,
6227 disk_mib: 1024,
6228 },
6229 })
6230 .unwrap();
6231 assert!(!isolated.may_start_runners());
6232 let mut active_isolated = isolated.clone();
6233 active_isolated.activate().unwrap();
6234 for profiles in [
6235 [native.clone(), isolated.clone()],
6236 [isolated.clone(), native.clone()],
6237 [native.clone(), active_isolated.clone()],
6238 [active_isolated, native.clone()],
6239 ] {
6240 let mut harness = Harness::simple(4, 0, "o/r");
6241 harness.demand.set(PollOutcome::Ready(QueuedDemand::of(
6242 repo("o/r"),
6243 [fixtures::queued_job(&["SELF-HOSTED"])],
6244 )));
6245 let report = harness.reconciler.reconcile(&profiles).await;
6246 assert_eq!(report.started, 0);
6247 assert!(harness.events.events().iter().any(|event| matches!(
6248 event,
6249 LifecycleEvent::RoutingRefused {
6250 reason: RoutingRefusal::OverlappingProfiles,
6251 count: 1,
6252 ..
6253 }
6254 )));
6255 }
6256 let mut harness = Harness::simple(4, 0, "o/r");
6259 harness.demand.set(PollOutcome::Ready(QueuedDemand::of(
6260 repo("o/r"),
6261 [fixtures::queued_job(&["rm-home-win-x64-py-isolated"])],
6262 )));
6263 assert_eq!(
6264 harness
6265 .reconciler
6266 .reconcile(&[native, isolated])
6267 .await
6268 .started,
6269 0
6270 );
6271 }
6272
6273 #[tokio::test]
6274 async fn shared_optional_labels_do_not_duplicate_native_and_isolated_demand() {
6275 let mut harness = Harness::simple(2, 0, "o/r");
6276 harness.demand.set(PollOutcome::Ready(QueuedDemand::of(
6277 repo("o/r"),
6278 [
6279 fixtures::queued_job(&[HOST_LABEL, "gpu"]),
6280 fixtures::queued_job(&["rm-home-win-x64-py-isolated", "gpu"]),
6281 fixtures::queued_job(&["gpu"]),
6282 fixtures::unresolvable_job(),
6283 ],
6284 )));
6285 let mut native = policy(1, "o/r", 2);
6286 native.add_routing_label(fixtures::label("gpu")).unwrap();
6287 let mut isolated = fixtures::named_policy("py-isolated", PolicyId::from_u128(2));
6288 isolated.add_routing_label(fixtures::label("gpu")).unwrap();
6289 isolated.activate().unwrap();
6290
6291 let report = harness.reconciler.reconcile(&[native, isolated]).await;
6292 assert_eq!(harness.demand.polls().len(), 1);
6293 assert_eq!(report.targets_read, 1);
6294 assert_eq!(report.started, 2);
6295 assert_eq!(report.allocations.len(), 2);
6296 assert!(
6297 report
6298 .allocations
6299 .iter()
6300 .all(|allocation| allocation.to_start == 1)
6301 );
6302 assert!(harness.events.events().iter().any(|event| matches!(
6303 event,
6304 LifecycleEvent::RoutingRefused {
6305 reason: RoutingRefusal::OverlappingProfiles,
6306 count: 1,
6307 ..
6308 }
6309 )));
6310 assert_eq!(
6311 harness
6312 .events
6313 .events()
6314 .iter()
6315 .filter(|event| matches!(
6316 event,
6317 LifecycleEvent::DemandObserved {
6318 unresolvable: 1,
6319 ..
6320 }
6321 ))
6322 .count(),
6323 2,
6324 "an expression stays unresolvable for both profiles"
6325 );
6326 }
6327
6328 #[tokio::test]
6329 async fn missing_required_selector_labels_do_not_match_and_overlaps_show_remedies() {
6330 let mut harness = Harness::simple(4, 0, "o/r");
6331 harness.demand.set(PollOutcome::Ready(QueuedDemand::of(
6332 repo("o/r"),
6333 [fixtures::queued_job(&[
6334 HOST_LABEL,
6335 "rm-home-win-x64-py-isolated",
6336 ])],
6337 )));
6338 let mut isolated = fixtures::named_policy("py-isolated", PolicyId::from_u128(2));
6339 isolated.activate().unwrap();
6340 let report = harness
6341 .reconciler
6342 .reconcile(&[policy(1, "o/r", 2), isolated])
6343 .await;
6344 assert_eq!(report.started, 0);
6345 assert_eq!(
6346 harness
6347 .events
6348 .events()
6349 .iter()
6350 .filter(|event| matches!(
6351 event,
6352 LifecycleEvent::DemandObserved {
6353 demand: 0,
6354 not_matched: 1,
6355 ..
6356 }
6357 ))
6358 .count(),
6359 2
6360 );
6361
6362 let mut superset = policy(1, "o/r", 2);
6366 assert!(
6367 superset
6368 .add_routing_label(fixtures::label("rm-home-win-x64-py-isolated"))
6369 .unwrap()
6370 );
6371 let mut sibling = fixtures::named_policy("py-isolated", PolicyId::from_u128(2));
6372 sibling.activate().unwrap();
6373 let mut unique = Harness::simple(4, 0, "o/r");
6374 unique.demand.set(PollOutcome::Ready(QueuedDemand::of(
6375 repo("o/r"),
6376 [fixtures::queued_job(&[
6377 HOST_LABEL,
6378 "rm-home-win-x64-py-isolated",
6379 ])],
6380 )));
6381 let report = unique.reconciler.reconcile(&[superset, sibling]).await;
6382 assert_eq!(report.started, 1);
6383 assert_eq!(
6384 report
6385 .allocations
6386 .iter()
6387 .find(|allocation| allocation.to_start == 1)
6388 .unwrap()
6389 .policy_id,
6390 PolicyId::from_u128(1)
6391 );
6392 assert!(
6393 !unique
6394 .events
6395 .events()
6396 .iter()
6397 .any(|event| matches!(event, LifecycleEvent::RoutingRefused { .. }))
6398 );
6399
6400 let mut overlap = Harness::simple(4, 1, "o/r");
6401 let report = overlap
6402 .reconciler
6403 .reconcile(&[policy(1, "o/r", 2), policy(2, "o/r", 2)])
6404 .await;
6405 assert_eq!(report.started, 0);
6406 assert!(overlap.events.events().iter().any(|event| matches!(
6407 event,
6408 LifecycleEvent::RoutingRefused {
6409 reason: RoutingRefusal::OverlappingProfiles,
6410 count: 1,
6411 ..
6412 }
6413 )));
6414 assert!(
6415 RoutingRefusal::OverlappingProfiles
6416 .to_string()
6417 .contains("repair")
6418 );
6419 }
6420
6421 #[tokio::test]
6426 async fn a_failed_launch_stops_the_run_and_is_reported_without_free_text() {
6427 let launcher = Arc::new(FakeLauncher::new());
6428 launcher.fail_next(FailureReason::Other("token ghp_0123456789abcdef".into()));
6429 let mut harness = Harness::build(
6430 host_with(4),
6431 Arc::clone(&launcher),
6432 Arc::new(FakeDemand::ready(3, &repo("acme/app"))),
6433 Arc::new(InProcessAllocationLock::new()),
6434 );
6435
6436 let report = harness
6437 .reconciler
6438 .reconcile(&[policy(1, "acme/app", 4)])
6439 .await;
6440 assert_eq!(report.started, 0);
6441 assert_eq!(report.allocations[0].to_start, 3, "the decision stands");
6442
6443 let failures: Vec<&'static str> = harness
6444 .events
6445 .events()
6446 .into_iter()
6447 .filter_map(|event| match event {
6448 LifecycleEvent::RunnerStartFailed { reason, .. } => Some(reason),
6449 _ => None,
6450 })
6451 .collect();
6452 assert_eq!(failures, vec!["other"]);
6453 assert!(
6454 !failures[0].contains("ghp_"),
6455 "an event carried a `FailureReason::Other` detail verbatim"
6456 );
6457 }
6458
6459 #[tokio::test]
6464 async fn an_unfit_host_registers_no_runner_and_reports_host_unfit() {
6465 let launcher = Arc::new(FakeLauncher::new());
6466 let unfit = Arc::new(AtomicBool::new(true));
6467 let events = Arc::new(EventLog::new());
6468 let mut reconciler = Reconciler::new(
6469 host_with(4),
6470 ReconcilerPorts {
6471 demand: Arc::new(FakeDemand::ready(2, &repo("acme/app"))),
6472 launcher: Arc::new(FitnessGatedLauncher::new(
6473 Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
6474 Arc::clone(&unfit),
6475 )),
6476 lock: Arc::new(InProcessAllocationLock::new()),
6477 directory: Arc::new(FakeDirectory::default()),
6478 clock: Arc::new(FakeClock::default()) as Arc<dyn Clock>,
6479 jitter: Arc::new(NoJitter) as Arc<dyn Jitter>,
6480 events: Arc::clone(&events) as Arc<dyn EventSink>,
6481 },
6482 );
6483 let policies = [policy(1, "acme/app", 4)];
6484
6485 let report = reconciler.reconcile(&policies).await;
6486 assert_eq!(report.started, 0);
6487 assert_eq!(launcher.launches(), 0, "the inner launcher must not run");
6488 let reasons: Vec<&'static str> = events
6489 .events()
6490 .into_iter()
6491 .filter_map(|event| match event {
6492 LifecycleEvent::RunnerStartFailed { reason, .. } => Some(reason),
6493 _ => None,
6494 })
6495 .collect();
6496 assert_eq!(reasons, ["host_unfit"]);
6497
6498 unfit.store(false, Ordering::Release);
6499 let report = reconciler.reconcile(&policies).await;
6500 assert_eq!(report.started, 2);
6501 assert_eq!(launcher.launches(), 2);
6502 }
6503
6504 #[tokio::test]
6505 async fn a_held_allocation_lock_starts_nothing_and_says_so() {
6506 let launcher = Arc::new(FakeLauncher::new());
6507 let mut harness = Harness::build(
6508 host_with(4),
6509 Arc::clone(&launcher),
6510 Arc::new(FakeDemand::ready(3, &repo("acme/app"))),
6511 Arc::new(HeldLock),
6512 );
6513
6514 let report = harness
6515 .reconciler
6516 .reconcile(&[policy(1, "acme/app", 4)])
6517 .await;
6518 assert_eq!(report.started, 0);
6519 assert_eq!(
6520 report.deferred, 3,
6521 "three runners were granted and none was created; `deferred` counts grants, \
6522 not policies -- it reported `1` when a policy that launched two of five and \
6523 then lost the lock had left three unstarted"
6524 );
6525 assert_eq!(launcher.launches(), 0);
6526 assert_eq!(harness.events.count_of("allocation_deferred"), 1);
6527 assert!(
6528 harness
6529 .events
6530 .events()
6531 .iter()
6532 .any(|event| matches!(event, LifecycleEvent::AllocationDeferred { count: 3, .. })),
6533 "the event carries the same number the report does"
6534 );
6535 assert_eq!(
6536 report.allocations.len(),
6537 1,
6538 "the intent is still reported, so an operator staring at a queue sees why \
6539 nothing started"
6540 );
6541 }
6542
6543 #[tokio::test]
6544 async fn a_foreign_or_draining_policy_is_reported_by_name_and_polls_nothing() {
6545 let mut harness = Harness::simple(8, 5, "acme/app");
6546
6547 let foreign = fixtures::policy()
6548 .id(PolicyId::from_u128(1))
6549 .repository("acme/app")
6550 .host(HostId::from_u128(0xdead))
6551 .autoscale("office", 4)
6552 .active()
6553 .build();
6554 let mut draining = policy(2, "acme/app", 4);
6555 draining.request_disable().unwrap();
6556
6557 let report = harness.reconciler.reconcile(&[foreign, draining]).await;
6558
6559 assert_eq!(report.started, 0);
6560 assert_eq!(
6561 harness.demand.polls().len(),
6562 0,
6563 "neither can act on an answer"
6564 );
6565 let factors: Vec<LimitingFactor> = report
6566 .allocations
6567 .iter()
6568 .map(|a| a.limiting_factor)
6569 .collect();
6570 assert!(factors.contains(&LimitingFactor::ForeignHost));
6571 assert!(factors.contains(&LimitingFactor::NotReconciling));
6572 }
6573
6574 #[tokio::test]
6575 async fn an_unreadable_repository_list_makes_the_target_unreadable_not_empty() {
6576 #[derive(Debug)]
6579 struct BrokenDirectory;
6580
6581 #[async_trait::async_trait]
6582 impl RepositoryDirectory for BrokenDirectory {
6583 async fn repositories(&self, _org: &Org) -> Result<Vec<OwnerRepo>, InventoryError> {
6584 Err(InventoryError::Cancelled)
6585 }
6586 }
6587
6588 let launcher = Arc::new(FakeLauncher::new());
6589 let events = Arc::new(EventLog::new());
6590 let mut reconciler = Reconciler::new(
6591 host_with(4),
6592 ReconcilerPorts {
6593 demand: Arc::new(FakeDemand::default()),
6594 launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
6595 lock: Arc::new(InProcessAllocationLock::new()),
6596 directory: Arc::new(BrokenDirectory),
6597 clock: Arc::new(FakeClock::default()),
6598 jitter: Arc::new(NoJitter),
6599 events: Arc::clone(&events) as Arc<dyn EventSink>,
6600 },
6601 );
6602
6603 let org_policy = fixtures::policy()
6604 .id(PolicyId::from_u128(1))
6605 .organization("acme")
6606 .autoscale("home", 4)
6607 .active()
6608 .build();
6609
6610 let report = reconciler.reconcile(&[org_policy]).await;
6611 assert_eq!(report.started, 0);
6612 assert_eq!(report.unreadable, vec![PolicyId::from_u128(1)]);
6613 assert_eq!(events.count_of("target_unreadable"), 1);
6614 }
6615
6616 fn every_event() -> Vec<LifecycleEvent> {
6628 let policy = PolicyId::from_u128(0xabcd_ef01);
6629 let attempt = AttemptId::from_u128(0x1234_5678);
6630 vec![
6631 LifecycleEvent::DemandObserved {
6632 policy,
6633 demand: u32::MAX,
6634 not_matched: u32::MAX,
6635 unresolvable: u32::MAX,
6636 complete: false,
6637 },
6638 LifecycleEvent::TargetUnreadable {
6639 policy,
6640 reason: unreadable_reason(&RefreshState::Failed {
6641 status: Some(500),
6642 message: "Authorization: Bearer ghp_0123456789abcdefghijklmnopqrstuvwxyz"
6643 .into(),
6644 }),
6645 },
6646 LifecycleEvent::Allocated {
6647 policy,
6648 demand: u32::MAX,
6649 desired: u16::MAX,
6650 active_owned: 7,
6651 headroom: 9,
6652 to_start: 2,
6653 limiting: LimitingFactor::HostCapacity,
6654 },
6655 LifecycleEvent::MonitorOnlySkipped { policy },
6656 LifecycleEvent::RunnerStarted { policy, attempt },
6657 LifecycleEvent::RunnerStartFailed {
6658 policy,
6659 reason: failure_reason_kind(&FailureReason::Other(
6660 "Authorization: Bearer ghp_0123456789abcdefghijklmnopqrstuvwxyz".into(),
6661 )),
6662 },
6663 LifecycleEvent::AllocationDeferred { policy, count: 4 },
6664 LifecycleEvent::AttemptsUnreadable {
6665 reason: failure_reason_kind(&FailureReason::Other(
6666 "x-api-key: ghp_0123456789abcdefghijklmnopqrstuvwxyz".into(),
6667 )),
6668 },
6669 LifecycleEvent::HostCapacityUnreadable {
6670 reason: HostCapacityError::MissingHost,
6671 },
6672 LifecycleEvent::HostCapacityUnreadable {
6673 reason: HostCapacityError::JournalUnreadable,
6674 },
6675 LifecycleEvent::AttemptCleanFailed {
6676 policy,
6677 attempt,
6678 reason: failure_reason_kind(&FailureReason::ProcessExitedUnexpectedly),
6679 },
6680 LifecycleEvent::AttemptCleaned {
6681 policy,
6682 attempt,
6683 outcome: OutcomeKind::IdleExit,
6684 },
6685 LifecycleEvent::ScaleDownRefused { policy, attempt },
6686 LifecycleEvent::PollScheduled {
6687 retry_in_ms: 900_000,
6688 pace: PollPace::RateLimited {
6689 kind: RateLimitKind::Primary,
6690 },
6691 },
6692 ]
6693 }
6694
6695 #[test]
6704 fn no_emitted_event_can_carry_a_credential() {
6705 use runner_manager_platform::logging::redact;
6706
6707 for event in every_event() {
6708 let displayed = event.to_string();
6709 assert_eq!(
6710 redact(&displayed),
6711 displayed,
6712 "`{}` renders something `d1`'s sink would have to redact",
6713 event.name()
6714 );
6715
6716 let debugged = format!("{event:?}");
6717 assert_eq!(
6718 redact(&debugged),
6719 debugged,
6720 "`{}`'s Debug renders something `d1`'s sink would have to redact",
6721 event.name()
6722 );
6723 }
6724
6725 let secret = "Authorization: Bearer ghp_0123456789abcdefghijklmnopqrstuvwxyz";
6728 assert_ne!(
6729 redact(secret),
6730 secret,
6731 "the scan above proves nothing if `redact` no longer recognises a credential"
6732 );
6733 }
6734
6735 #[test]
6736 fn every_field_name_this_sink_emits_is_one_d1_allows() {
6737 use runner_manager_platform::logging::is_field_allowed;
6738
6739 for field in [
6743 "event",
6744 "policy_id",
6745 "attempt_id",
6746 "attempt_state",
6747 "demand",
6748 "desired",
6749 "capacity",
6750 "headroom",
6751 "count",
6752 "reason",
6753 "outcome",
6754 "mode",
6755 "lock",
6756 "retry_in_ms",
6757 "state",
6758 ] {
6759 assert!(
6760 is_field_allowed(field),
6761 "`{field}` is not on `d1`'s allow-list, so this sink would emit \
6762 `[redacted]` in its place and the line would lose its meaning"
6763 );
6764 }
6765 }
6766
6767 #[test]
6768 fn every_failure_reason_has_a_credential_free_kind() {
6769 for reason in FailureReason::ALL {
6770 let kind = failure_reason_kind(&reason);
6771 assert!(!kind.is_empty());
6772 assert!(
6773 kind.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
6774 "`{kind}` is not a fixed identifier"
6775 );
6776 }
6777 assert_eq!(
6778 failure_reason_kind(&FailureReason::Other("ghp_secret".into())),
6779 "other",
6780 "the detail of an `Other` reason never reaches an event"
6781 );
6782 let categories = [
6783 IsolationProviderFailure::NotInstalled,
6784 IsolationProviderFailure::PermissionDenied,
6785 IsolationProviderFailure::ImageUnavailableOrIncompatible,
6786 IsolationProviderFailure::DiskQuotaUnavailable,
6787 IsolationProviderFailure::RuntimeOperationFailed,
6788 ];
6789 let mut kinds = std::collections::BTreeSet::new();
6790 for category in categories {
6791 let kind = failure_reason_kind(&FailureReason::IsolationProvider(category));
6792 assert_ne!(kind, "other");
6793 assert!(!kind.contains("secret"));
6794 kinds.insert(kind);
6795 }
6796 assert_eq!(kinds.len(), categories.len());
6797 }
6798
6799 fn production_half_of(source: &str) -> String {
6814 let production = source
6815 .split_once("\n#[cfg(test)]")
6816 .map_or(source, |(production, _)| production);
6817 production
6818 .lines()
6819 .filter(|line| !line.trim_start().starts_with("//"))
6820 .collect::<Vec<_>>()
6821 .join("\n")
6822 }
6823
6824 fn this_file_above_its_tests_without_prose() -> String {
6826 production_half_of(include_str!("reconcile.rs"))
6827 }
6828
6829 fn normalise_for_scan(text: &str) -> String {
6848 text.to_ascii_lowercase().replace(['_', ' '], "")
6849 }
6850
6851 const FORBIDDEN: &[&str] = &[
6861 concat!("fn ", "acquire", "_job"),
6862 concat!("fn ", "claim", "_job"),
6863 concat!("fn ", "lease", "_job"),
6864 concat!("fn ", "reserve", "_job"),
6865 concat!("fn ", "ack", "nowledge"),
6866 concat!("struct ", "Job", "Lease"),
6867 concat!("struct ", "Job", "Claim"),
6868 concat!("struct ", "Job", "Reservation"),
6869 ];
6870
6871 fn forbidden_shape_in(source: &str) -> Option<&'static str> {
6872 let haystack = normalise_for_scan(source);
6873 FORBIDDEN
6874 .iter()
6875 .copied()
6876 .find(|forbidden| haystack.contains(&normalise_for_scan(forbidden)))
6877 }
6878
6879 #[test]
6913 fn nothing_in_this_crate_reserves_or_claims_a_job() {
6914 const SOURCES: &[(&str, &str)] = &[
6915 ("dependency_caches.rs", include_str!("dependency_caches.rs")),
6916 ("docker_cleanup.rs", include_str!("docker_cleanup.rs")),
6917 (
6918 "docker_cleanup/http.rs",
6919 include_str!("docker_cleanup/http.rs"),
6920 ),
6921 (
6922 "docker_cleanup/proxy.rs",
6923 include_str!("docker_cleanup/proxy.rs"),
6924 ),
6925 (
6926 "docker_cleanup/tests.rs",
6927 include_str!("docker_cleanup/tests.rs"),
6928 ),
6929 ("lib.rs", include_str!("lib.rs")),
6930 ("lifecycle.rs", include_str!("lifecycle.rs")),
6931 (
6932 "lifecycle/windows_hyperv.rs",
6933 include_str!("lifecycle/windows_hyperv.rs"),
6934 ),
6935 ("oci.rs", include_str!("oci.rs")),
6936 ("package.rs", include_str!("package.rs")),
6937 ("reconcile.rs", include_str!("reconcile.rs")),
6938 ];
6939
6940 fn walk(directory: &std::path::Path, prefix: &str, found: &mut Vec<String>) {
6941 for entry in std::fs::read_dir(directory).expect("the crate's own src/ is readable") {
6942 let entry = entry.expect("a readable directory entry");
6943 let name = entry.file_name().to_string_lossy().into_owned();
6944 let joined = if prefix.is_empty() {
6947 name.clone()
6948 } else {
6949 format!("{prefix}/{name}")
6950 };
6951 if entry.path().is_dir() {
6952 walk(&entry.path(), &joined, found);
6953 } else if name.ends_with(".rs") {
6954 found.push(joined);
6955 }
6956 }
6957 }
6958
6959 let mut listed: Vec<&str> = SOURCES.iter().map(|(name, _)| *name).collect();
6960 listed.sort_unstable();
6961 let mut on_disk = Vec::new();
6962 walk(
6963 std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")),
6964 "",
6965 &mut on_disk,
6966 );
6967 on_disk.sort_unstable();
6968 assert_eq!(
6969 listed, on_disk,
6970 "a source file was added or removed; this scan claims to cover the whole crate \
6971 and a stale list makes that claim false"
6972 );
6973
6974 for (name, source) in SOURCES {
6975 assert_eq!(
6976 forbidden_shape_in(&production_half_of(source)),
6977 None,
6978 "{name} names a forbidden shape: there is no `AcquireJobs` equivalent over \
6979 REST, and a local lease coordinates this host with itself and with nothing \
6980 else. If an owner decision restored one, that decision belongs in this \
6981 module's documentation and in this test before it belongs in the code"
6982 );
6983 }
6984
6985 assert!(
6988 forbidden_shape_in("async fn acquire_jobs(&self) -> Vec<Job> { todo!() }").is_some(),
6989 "the scan above proves nothing if the needles no longer match"
6990 );
6991 }
6992
6993 #[test]
7021 fn the_label_predicate_is_b1s_and_this_module_only_applies_it() {
7022 let production = this_file_above_its_tests_without_prose();
7023
7024 assert!(
7025 production.contains("DemandTally"),
7026 "the reconciliation loop must tally queued jobs against this policy's routing \
7027 labels. A production half that named `DemandTally` nowhere would mean the \
7028 label filtering had been removed, and a repository whose jobs target \
7029 `ubuntu-latest` would drive its policy toward `max_capacity` again"
7030 );
7031
7032 for second_implementation in ["RunsOnMatch", "UnresolvableRunsOn"] {
7033 assert!(
7034 !production.contains(second_implementation),
7035 "the reconciliation loop names `{second_implementation}`, which is the \
7036 vocabulary of deciding one job's `runs-on` -- and `RoutingLabels::tally` \
7037 has already decided it. This module applies the predicate and does not \
7038 re-implement it; if an owner decision changed that, it belongs in this \
7039 module's documentation and in this test before it belongs in the code"
7040 );
7041 }
7042 }
7043
7044 #[test]
7052 fn demand_is_the_queued_jobs_this_policy_can_actually_serve() {
7053 let policy = policy(1, "acme/app", 10);
7054 let reading = QueuedDemand::of(
7055 repo("acme/app"),
7056 [
7057 fixtures::queued_job(&[HOST_LABEL]),
7058 fixtures::queued_job(&[HOST_LABEL]),
7059 fixtures::queued_job(&["ubuntu-latest"]),
7060 fixtures::unresolvable_job(),
7061 ],
7062 );
7063
7064 let tally = demand_for(&policy, &reading);
7065
7066 assert_eq!(
7067 tally.demand(),
7068 2,
7069 "only the jobs whose required labels this policy carries are demand"
7070 );
7071 assert_eq!(
7072 tally.not_matched, 1,
7073 "a `ubuntu-latest` job is somebody else's work; counting it would start a \
7074 runner that idles until it times out"
7075 );
7076 assert_eq!(
7077 tally.unresolvable.len(),
7078 1,
7079 "an unresolvable `runs-on` is never demand and never discarded"
7080 );
7081 }
7082
7083 #[test]
7086 fn an_organization_policy_tallies_every_repository_its_scope_covers() {
7087 let mut per_repository = BTreeMap::new();
7088 per_repository.insert(repo("acme/left"), fixtures::queued_jobs(&[HOST_LABEL], 3));
7089 per_repository.insert(repo("acme/right"), fixtures::queued_jobs(&[HOST_LABEL], 4));
7090 let reading = QueuedDemand::new(per_repository);
7091
7092 let repository_policy = policy(1, "acme/left", 10);
7093 assert_eq!(
7094 demand_for(&repository_policy, &reading).demand(),
7095 3,
7096 "a repository target reads its own repository's queue and not the aggregate"
7097 );
7098
7099 let org_policy = fixtures::policy()
7100 .id(PolicyId::from_u128(2))
7101 .organization("acme")
7102 .autoscale("home", 10)
7103 .active()
7104 .build();
7105 assert_eq!(
7106 demand_for(&org_policy, &reading).demand(),
7107 7,
7108 "an organization policy serves any repository in its scope, so its demand is \
7109 the whole aggregate's"
7110 );
7111 }
7112
7113 #[test]
7114 fn the_accepted_over_count_is_bounded_by_the_two_ceilings_and_nothing_else() {
7115 let host = host_with(2);
7120 let policy = policy(1, "acme/app", 5);
7121 let attempts: Vec<RunnerAttempt> = Vec::new();
7122 let mut allocator = HostAllocator::from_attempts(&host, &attempts);
7123
7124 let allocation = allocator.allocate(&policy, u32::MAX);
7125 assert_eq!(allocation.desired, 5, "max_capacity beats reported demand");
7126 assert_eq!(allocation.to_start, 2, "host_capacity beats max_capacity");
7127 assert_eq!(allocation.limiting_factor, LimitingFactor::HostCapacity);
7128 }
7129}