Skip to main content

runner_manager_agent/
reconcile.rs

1// owner: e1-reconciliation-capacity
2
3//! The loop that turns GitHub demand into a decision to start runners — and
4//! that refuses to start them when it should not.
5//!
6//! Every ceiling in this product is enforced from here, so the module is
7//! organised around the four things that can go wrong silently:
8//!
9//! * [`PollSchedule`] — the budget-aware interval. Demand shares one 5,000
10//!   requests/hour ceiling with inventory and workflow counts, so this loop
11//!   polls an *active* target on a bounded interval (default 60 s, hard floor
12//!   30 s per target) and *increases* the delay under a rate-limit signal,
13//!   never decreases it to catch up. A target with nothing happening is polled
14//!   at the shorter *idle* interval (default 10 s), because its polls are
15//!   conditional requests answered `304`, which GitHub does not charge against
16//!   the hourly ceiling — and because work usually arrives after idle. When
17//!   the account's remaining quota runs low, the schedule stretches.
18//! * [`RepositoryCache`] — the per-organization repository list, refreshed on
19//!   an interval materially slower than the demand poll. Re-listing an
20//!   organization at demand-poll frequency is what exhausts the shared budget
21//!   the paragraph above exists to protect.
22//! * [`Reconciler::reconcile`] — the allocation pass. It re-reads the attempt
23//!   set **under the host-wide allocation lock, once per runtime created**, so
24//!   two policies reconciling concurrently cannot both spend the same headroom.
25//! * [`LifecycleEvent`] — what `g2` and the local log sink see. Every field is
26//!   an identifier, a count, an enumerated state or a duration; nothing free
27//!   text, and nothing that came off the wire.
28//!
29//! # There is no acquisition step, and none may be added
30//!
31//! The scale-set model called `AcquireJobs` to reserve an assignment before
32//! scaling. The REST path has no equivalent (`01-current-architecture.md`, edge
33//! case 6), so demand is **advisory**. Two consequences are load-bearing here
34//! and neither is a defect:
35//!
36//! 1. **A surplus runner is an accepted outcome.** Another host serving the
37//!    same labels may take the job first; this host's runner then finds no work
38//!    and exits on its idle timeout, having cost one capacity slot and one cold
39//!    start. That terminal outcome is
40//!    [`AttemptOutcome::ExitedIdleWithoutWork`], is cleaned like any other, and
41//!    is counted apart from a failure — see [`ReconcileReport::idle_exits`].
42//! 2. **The same job is still `queued` on the next poll** while its runner
43//!    starts. Subtracting only unassigned supply in
44//!    [`HostAllocator::allocate`] is what stops that from starting a second
45//!    runner, and then a third. This module's only job in that arithmetic is to
46//!    hand the allocator the attempt set the host actually holds — which is why
47//!    [`RunnerLauncher`] supplies both the attempts and the launch, from one
48//!    supply point, for the reason `b1` gives at
49//!    [`HostAllocator::from_attempts`].
50//!
51//! `tests::nothing_in_this_module_reserves_or_claims_a_job` is a tripwire on the
52//! obvious shape of a reservation being added back.
53//!
54//! # Demand is measured in JOBS, filtered by this policy's routing labels
55//!
56//! `02-target-architecture.md` writes the formula as *"queued jobs whose
57//! `runs-on` matches this policy's routing labels"*, and that is now exactly
58//! what this module clamps. It was not always: an earlier owner decision priced
59//! the per-run job listing out and left this module clamping a count of
60//! **runs**, unfiltered. `crates/github/src/demand.rs` records that decision,
61//! why it was reversed, and what the reversal costs in requests.
62//!
63//! What the reversal means here is two changes to one line:
64//!
65//! * **A run of eight jobs is now eight units of demand, not one.** Under the
66//!   run count a matrix filled one runner per poll while the rest of the matrix
67//!   waited, so a host configured for ten concurrent runners served an
68//!   eight-job matrix nearly serially. That was the defect that forced the
69//!   decision back.
70//! * **A job this host cannot serve is no longer demand.** A repository whose
71//!   jobs target `ubuntu-latest`, or another host's `rm-<host>-…` label, used to
72//!   drive its policy toward `max_capacity` and start runners that idled until
73//!   they timed out. The gateway now returns each queued job's `runs-on`, so
74//!   `b1`'s predicate finally has its input.
75//!
76//! **The predicate is still `b1`'s and the input is still `c4`'s.** This module
77//! calls [`runner_manager_domain::policy::RoutingLabels`]'s `tally` and
78//! implements no label comparison of its own;
79//! `tests::the_label_predicate_is_b1s_and_this_module_only_applies_it` scans
80//! this file's own source and fails if a second implementation grows here, which
81//! is the same tripwire `c4` carries one layer down.
82//!
83//! # The filtering happens here rather than in the gateway, on purpose
84//!
85//! One target can be watched by more than one policy, each with its own routing
86//! labels, and [`Reconciler`]'s `poll_targets` deliberately polls a target **once**
87//! for all of them. A gateway that filtered would have to be told whose labels to
88//! filter by, which would make the poll per-policy and multiply its request cost
89//! by the number of policies sharing the target — the budget model prices a
90//! target, not a policy. So the gateway returns the jobs and each policy tallies
91//! them against its own labels.
92//!
93//! # What is still approximate
94//!
95//! The surplus-runner path above is narrowed by this change and not closed. A
96//! `runs-on: ${{ matrix.runner }}` cannot be resolved without evaluating the
97//! workflow, so `b1` reports it as unresolvable: never counted as demand, never
98//! silently dropped, and surfaced through
99//! [`LifecycleEvent::DemandObserved::unresolvable`] so that an operator can see
100//! a workflow this host will never serve sitting in the queue. And demand
101//! remains advisory — another host may still take a job this one started a
102//! runner for — which is what the two ceilings bound.
103//!
104//! # What is testable without a network, a filesystem, or a process
105//!
106//! All of it. [`DemandSource`], [`RunnerLauncher`], [`AllocationLock`],
107//! [`RepositoryDirectory`], [`Jitter`] and [`EventSink`] are ports;
108//! [`GatewayDemand`], [`FileAllocationLock`], [`RandomJitter`] and
109//! [`TracingEvents`] are the production adapters, and every one of them is a
110//! thin shell over a decision made in this file.
111
112use 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
134// ---------------------------------------------------------------------------
135// Constants
136// ---------------------------------------------------------------------------
137
138/// How much slower than the demand poll the per-organization repository list is
139/// refreshed.
140///
141/// There is no organization-wide workflow-runs endpoint, so an organization
142/// target costs one demand request **per repository the App is installed on**
143/// (`crates/github/src/demand.rs`). Discovering that repository list costs
144/// requests of its own, and it is the one input to a demand poll that changes on
145/// a human timescale: repositories are added to an installation by hand, not by
146/// a workflow starting.
147///
148/// Thirty polls is 30 minutes at the 60-second default and 15 at the 30-second
149/// floor — slow enough that the list is a rounding error against the demand
150/// requests it scopes, and fast enough that a repository added to the
151/// installation starts being served within one coffee break rather than at the
152/// next restart.
153pub const REPOSITORY_LIST_REFRESH_MULTIPLE: u32 = 30;
154
155/// The longest the *unjittered* offline back-off may grow to.
156///
157/// A back-off is a safety mechanism, and an unclamped one is an outage with
158/// extra steps. Fifteen minutes matches
159/// [`runner_manager_github::rest::MAX_RATE_LIMIT_BACKOFF`], which is the other
160/// place in this product where a delay is allowed to grow, and it is far inside
161/// the 24-hour bound at which GitHub cancels the queued jobs this loop exists to
162/// serve.
163pub const MAX_OFFLINE_BACKOFF: Duration = Duration::from_secs(15 * 60);
164
165/// The most the offline back-off is doubled, before the cap applies.
166///
167/// At the 60-second default this reaches [`MAX_OFFLINE_BACKOFF`] on the sixth
168/// consecutive failure, which is roughly half an hour of outage. Past that the
169/// cap holds it flat.
170const MAX_BACKOFF_DOUBLINGS: u32 = 5;
171
172/// How much of the computed back-off is jitter.
173///
174/// Jitter is **added** rather than subtracted, so a back-off never comes out
175/// shorter than the delay it was computed from. Subtractive jitter would let the
176/// first offline poll retry sooner than the nominal interval, which is the
177/// opposite of backing off; it is spelled out because "add jitter" reads as
178/// symmetric and is not.
179const JITTER_RATIO: f64 = 0.5;
180
181/// How much of a rate-limit wait is jitter: added, never subtracted.
182///
183/// Every target loop on a host shares one rate-limit quiet period, so without
184/// it they all wake at the same instant the period ends, and a burst is the
185/// shape most likely to meet the secondary limit again. A tenth spreads them
186/// over a few seconds to a minute and a half without overshooting a
187/// 15-minute wait by much.
188const RATE_LIMIT_JITTER_RATIO: f64 = 0.1;
189
190/// The most demand requests a minute one target's idle polling may cost.
191///
192/// A third of GitHub's 900-a-minute secondary limit. A target of one or a few
193/// repositories never reaches it at the 5-second floor, but an organization of
194/// a hundred repositories costs about four hundred requests a pass, and at a
195/// 10-second idle interval that alone would exceed the whole account's
196/// secondary limit. Its idle interval stretches instead.
197pub const MAX_IDLE_REQUESTS_PER_MINUTE_PER_TARGET: u32 = 300;
198
199/// GitHub cancels a queued job after this long.
200///
201/// `01-current-architecture.md` records the measurement; `03-control-flows.md`
202/// flow 3.3 requires that the offline state **states** it, because an agent
203/// offline for longer than this has lost queued work and the operator cannot
204/// infer that from "offline". [`OfflineState`] is where it is said.
205pub const GITHUB_CANCELS_QUEUED_JOBS_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
206
207/// How long [`FileAllocationLock`] waits for the host-wide allocation lock
208/// before reporting contention.
209///
210/// Contention here is expected rather than exceptional — it is two of this
211/// host's own policies creating runtimes at the same moment — and each hold
212/// lasts only as long as one runtime creation. Waiting a few seconds turns the
213/// common case into a short pause instead of a skipped runner.
214///
215/// # How many of these a poll actually costs
216///
217/// One per runtime created, none for a policy that is granted nothing, and at
218/// most one further hold per policy — the case where the pre-check proposed a
219/// grant and the under-lock re-read found the host had filled up underneath it,
220/// so that hold creates nothing and ends the loop. `(3..=5)` in
221/// `two_policies_reconciling_concurrently_never_exceed_host_capacity` is that
222/// bound with two policies and three runtimes; the deterministic single-policy
223/// case is pinned at exactly one per runtime.
224///
225/// That is worth stating because it did not used to be true and the
226/// difference only shows up here: the budget was checked *after* the lock had
227/// been taken and the attempt set re-read, so a policy granted N runners took
228/// N+1 holds, and `start_runners` ran for every readable autoscale policy
229/// including the zero-demand ones — so an idle host with P policies took P
230/// host-wide locks per poll for nothing. Free under
231/// [`InProcessAllocationLock`]; under [`FileAllocationLock`] each one is a
232/// `spawn_blocking` plus a filesystem lock, with this wait behind it.
233///
234/// [`Reconciler::start_runners`] now pre-checks lock-free and stops as soon as
235/// the budget is spent. The under-lock re-read still decides.
236pub const ALLOCATION_LOCK_WAIT: Duration = Duration::from_secs(5);
237
238// ---------------------------------------------------------------------------
239// What one demand poll produced
240// ---------------------------------------------------------------------------
241
242/// One target's demand poll, as a value this module can decide from.
243///
244/// The failure half is `c3`'s [`RefreshState`] rather than an
245/// [`InventoryError`], for the reason `c3` gives: `InventoryError` owns a
246/// `reqwest::Error` and a `serde_json::Error`, so it is neither `Clone` nor
247/// `PartialEq` and cannot be stored, compared, or rendered. Summarising at the
248/// gateway boundary — exactly once, in [`GatewayDemand`] — is what lets the
249/// whole schedule below be a pure function of values a test can construct.
250///
251/// [`RefreshState::Ready`] never appears in [`PollOutcome::Failed`]:
252/// [`RefreshState::from_error`] cannot produce it, and a demand poll returns a
253/// [`QueuedDemand`] rather than the runner inventory that variant carries.
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub enum PollOutcome {
256    /// GitHub answered. The count may still be a floor — see
257    /// [`QueuedDemand::is_complete`].
258    Ready(QueuedDemand),
259    /// GitHub did not answer, or answered something this loop must slow down
260    /// for.
261    Failed(RefreshState),
262}
263
264impl PollOutcome {
265    /// The demand reading, when there is one.
266    #[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    /// The failure, when there is one.
275    #[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    /// Whether GitHub could not be reached at all, as opposed to answering
284    /// something unwelcome.
285    ///
286    /// The whole of flow 3.3 turns on this distinction: an outage retains
287    /// running runners and backs off, while a rejection is a configuration
288    /// problem that waiting does not fix.
289    #[must_use]
290    pub fn is_offline(&self) -> bool {
291        matches!(self, Self::Failed(RefreshState::Offline))
292    }
293}
294
295/// Where this loop gets its demand from.
296///
297/// A port rather than a direct [`DemandGateway`] dependency, because the two
298/// failures this loop must handle differently — unreachable and rate-limited —
299/// are distinguished by [`RefreshState`], and a test that wants to drive the
300/// offline path should not have to manufacture a `reqwest::Error` to do it.
301/// [`GatewayDemand`] is the one adapter that talks to `c4`.
302#[async_trait::async_trait]
303pub trait DemandSource: fmt::Debug + Send + Sync {
304    /// Queued runs across `scope`, or why there are none to report.
305    async fn poll(&self, scope: &ActivityScope) -> PollOutcome;
306}
307
308/// [`DemandSource`] over `c4`'s [`DemandGateway`].
309///
310/// Holds the [`CancelToken`] so that a shutting-down daemon can withdraw a poll
311/// that is already blocked on a socket; `f3` keeps a clone and cancels it.
312#[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            // The one place an `InventoryError` is summarised. `c3` owns the
336            // mapping — including transport-to-`Offline`, which is what flow
337            // 3.3 branches on — so this loop never re-decides it.
338            Err(error) => PollOutcome::Failed(RefreshState::from_error(&error)),
339        }
340    }
341}
342
343// ---------------------------------------------------------------------------
344// The repository list, cached
345// ---------------------------------------------------------------------------
346
347/// Which repositories an organization installation reaches.
348///
349/// `f1` already holds this, from
350/// [`runner_manager_github::AuthenticatedClient::discover_installations`]. It is
351/// a port here so that [`RepositoryCache`] can be tested for the property that
352/// matters — how *often* it asks — without a network.
353#[async_trait::async_trait]
354pub trait RepositoryDirectory: fmt::Debug + Send + Sync {
355    /// The repositories this credential reaches in `org`.
356    ///
357    /// # Errors
358    /// Anything the underlying gateway reports.
359    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/// The per-organization repository list, refreshed far more slowly than demand.
369///
370/// # Why this is not just "call the directory each poll"
371///
372/// An organization demand poll already costs one request per repository. Adding
373/// the installation listing to every poll makes the *scoping* of a poll cost
374/// requests on the same schedule as the poll itself, which is how a
375/// ten-repository organization at the 30-second floor stops fitting inside the
376/// half-of-5,000 allowance `f2` admits targets against. The repository list is
377/// also the one input that changes on a human timescale, so refreshing it
378/// [`REPOSITORY_LIST_REFRESH_MULTIPLE`] times more slowly costs nothing real.
379///
380/// # A repository target never consults the directory at all
381///
382/// Its scope is itself. That is not an optimisation; asking an installation
383/// listing which repositories a single named repository covers would be asking a
384/// question whose answer is already in the target.
385#[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    /// Build a cache whose refresh interval is `poll` slowed by
396    /// [`REPOSITORY_LIST_REFRESH_MULTIPLE`].
397    #[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    /// How long a cached repository list is reused for.
415    #[must_use]
416    pub const fn ttl(&self) -> Duration {
417        self.ttl
418    }
419
420    /// How many times the underlying directory was actually asked.
421    ///
422    /// Measured rather than assumed, for the reason `c4` measures its own
423    /// request count: a budget nothing counts is a table in a document.
424    #[must_use]
425    pub fn lookups(&self) -> u64 {
426        self.lookups.load(Ordering::SeqCst)
427    }
428
429    /// The scope one demand poll of `target` covers.
430    ///
431    /// # Errors
432    /// Whatever the directory reported, for an organization target whose list is
433    /// stale or absent. A repository target cannot fail.
434    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        // The directory call is deliberately made with no lock held. Two
453        // concurrent misses can therefore both ask, which costs one extra
454        // listing on the poll that follows a restart; holding a `std::sync`
455        // mutex across an `await` would cost a blocked executor thread and, on
456        // a current-thread runtime, a deadlock. The cheaper mistake is the one
457        // that spends a request.
458        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
484// ---------------------------------------------------------------------------
485// Jitter
486// ---------------------------------------------------------------------------
487
488/// The randomness in the offline back-off, as a port.
489///
490/// Flow 3.3 requires jittered back-off, and a jittered delay is by construction
491/// not reproducible — so the source of the randomness is a port, and every test
492/// below asserts the *bounds* of the delay against a fixed fraction rather than
493/// asserting a number it could only have got by running the generator.
494pub trait Jitter: fmt::Debug + Send + Sync {
495    /// A fraction in `[0.0, 1.0)`. Values outside that range are clamped by the
496    /// caller, so an implementation cannot lengthen a back-off without bound.
497    fn fraction(&self) -> f64;
498}
499
500/// The production source.
501#[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/// A fixed fraction, for tests and for the acceptance suite.
511#[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/// No jitter at all: the back-off is exactly what the schedule computed.
521#[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// ---------------------------------------------------------------------------
531// The schedule
532// ---------------------------------------------------------------------------
533
534/// Why the next poll is when it is.
535///
536/// Reported rather than inferred, because
537/// `04-subsystem-contracts.md` requires that rate limiting be *"displayed, never
538/// hidden"* — and a delay that grew for a reason the caller cannot name is
539/// hidden however visible the number is.
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub enum PollPace {
542    /// The configured (active) interval. Nothing is throttling this loop.
543    Nominal,
544    /// The idle interval: nothing is happening on this target, so its polls
545    /// are `304`s and cost nothing against the hourly quota. Not a slowdown.
546    Idle,
547    /// The account's remaining hourly quota is low, so this loop waits a
548    /// multiple of its active interval. GitHub's quota is per user, shared by
549    /// every host signed in as that user, so this can be another machine's
550    /// doing.
551    Stretched { pressure: PrimaryPressure },
552    /// GitHub's rate limit is exhausted. Resolves by waiting.
553    RateLimited { kind: RateLimitKind },
554    /// GitHub's temporary authentication lockout. The credential is fine.
555    LockedOut,
556    /// GitHub could not be reached. `consecutive` counts the unbroken run of
557    /// failures the back-off was computed from.
558    Offline { consecutive: u32 },
559    /// GitHub answered something no amount of waiting fixes — a rejected
560    /// credential, a permissions refusal, or an error status. The loop keeps
561    /// polling at its nominal interval so that a fix is noticed, and says that
562    /// it is blocked rather than pretending the poll succeeded.
563    Blocked,
564}
565
566impl PollPace {
567    /// Whether this pace is a slowdown the operator should be told about.
568    #[must_use]
569    pub const fn is_throttled(&self) -> bool {
570        !matches!(self, Self::Nominal | Self::Idle)
571    }
572
573    /// A fixed, credential-free name for the log sink and for `g2`.
574    #[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/// When to poll next, and why then.
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub struct NextPoll {
610    pub delay: Duration,
611    pub pace: PollPace,
612}
613
614/// The bounded, budget-aware poll interval.
615///
616/// # The floor is a rate-budget constraint, not a preference
617///
618/// [`RefreshInterval`] refuses anything under 30 seconds at construction, and
619/// every delay this type produces is at least that — including the ones it
620/// computes from a remote header. A rate limit may only ever make this loop
621/// *slower*.
622///
623/// # `retry_delay` is an absolute floor, not an addend
624///
625/// `c3` documents [`RefreshState::retry_delay`] as *"the earliest time a retry
626/// may occur"*: the scheduling rule is `next_attempt_at = now + retry_delay`,
627/// and **not** the ordinary interval plus it. Adding the two compounds on every
628/// successive retry — each new answer carries the remaining window, so an
629/// addend ratchets outward — and the symptom is a dashboard that stays dark
630/// long after GitHub said it could come back, which reads as a hang rather than
631/// as a rate limit. So the two are combined with `max`, which is what makes the
632/// floor a floor.
633#[derive(Debug, Clone)]
634pub struct PollSchedule {
635    interval: RefreshInterval,
636    /// The idle interval. Equal to the active one until [`Self::with_idle`]
637    /// says otherwise, so a caller that never heard of it keeps its schedule.
638    idle: Duration,
639    consecutive_offline: u32,
640    offline_since: Option<Timestamp>,
641}
642
643/// What a successful pass found, beyond "GitHub answered".
644#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
645pub struct PollConditions {
646    /// Nothing is happening: no live runner, no run whose listings changed.
647    /// See `QueuedDemand::is_quiet`.
648    pub quiet: bool,
649    /// The account's hourly quota as GitHub last reported it.
650    pub quota: Option<RateLimitSnapshot>,
651    /// What one poll of this target costs, in demand requests. Stretches the
652    /// idle interval of a target too large to poll that often; see
653    /// [`MAX_IDLE_REQUESTS_PER_MINUTE_PER_TARGET`].
654    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    /// Poll a quiet target every `idle` instead of every active interval.
669    ///
670    /// Never longer than the active interval: an idle interval above it would
671    /// make a quiet target *slower* to notice work than a busy one.
672    #[must_use]
673    pub fn with_idle(mut self, idle: Duration) -> Self {
674        self.set_intervals(self.interval, idle);
675        self
676    }
677
678    /// Change both intervals while running.
679    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    /// The interval a quiet target is polled at.
690    #[must_use]
691    pub const fn idle(&self) -> Duration {
692        self.idle
693    }
694
695    /// The shortest delay this schedule ever produces: the idle interval's
696    /// floor. See `IdlePollInterval` for why it is lower than [`Self::floor`].
697    #[must_use]
698    pub const fn idle_floor() -> Duration {
699        Duration::from_secs(IdlePollInterval::MIN_SECS as u64)
700    }
701
702    /// The nominal interval as a [`Duration`].
703    #[must_use]
704    pub const fn nominal(&self) -> Duration {
705        Duration::from_secs(self.interval.as_secs() as u64)
706    }
707
708    /// The unbroken run of offline polls this schedule has seen.
709    #[must_use]
710    pub const fn consecutive_offline(&self) -> u32 {
711        self.consecutive_offline
712    }
713
714    /// How long GitHub has been unreachable, or `None` when it is not.
715    ///
716    /// Measured from the first poll of the current run rather than inferred
717    /// from [`Self::consecutive_offline`] times the interval. The two diverge
718    /// as soon as the back-off starts doubling, and this is the number the
719    /// 24-hour queue-cancellation warning is compared against — an estimate
720    /// would make that warning fire early or late, and it is the one thing the
721    /// offline state exists to say.
722    #[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    /// The hard floor no computed delay may go below.
729    #[must_use]
730    pub const fn floor() -> Duration {
731        Duration::from_secs(RefreshInterval::MIN_SECS as u64)
732    }
733
734    /// Decide when to poll next, given how this pass ended.
735    ///
736    /// `failure` is the most severe failure across the targets polled this pass,
737    /// or `None` when every target answered. A pass that answered resets the
738    /// offline run, which is the whole of "recovery needs no bookkeeping":
739    /// demand is recomputed from the current queued-run set on every poll, so
740    /// there is nothing else to unwind.
741    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    /// [`Self::next_poll`], with what a successful pass found.
751    ///
752    /// # On success, three paces, in this order
753    ///
754    /// 1. **Stretched**, when the account's remaining quota is under
755    ///    `LOW_PRIMARY_REMAINING_PERCENT`: the active interval times
756    ///    [`PrimaryPressure::stretch_factor`] (2, or 4 under
757    ///    `CRITICAL_PRIMARY_REMAINING_PERCENT`), but never past the quota's
758    ///    reset — waiting longer than that buys nothing, because the bucket is
759    ///    full again. This wins over idle: a `304` is free, but the poll that
760    ///    finds new work is not, and every host on the account draws from the
761    ///    same bucket.
762    /// 2. **Idle**, when the pass was quiet.
763    /// 3. **Nominal**, the active interval, otherwise.
764    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                    // An idle interval no shorter than the active one is no
787                    // idle interval at all, and naming it would be noise.
788                    _ 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                // The instant the *run* began, not the instant of this poll.
801                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                // `max`, never `+`. See the type documentation. The jitter is
812                // added to the result, never to the floor GitHub named.
813                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            // Unauthorized, Forbidden, Failed, Cancelled. `retry_delay` is
829            // `None` for all of them, and deliberately: no wait fixes a revoked
830            // credential or a missing grant. Polling stops being useful but
831            // does not stop, because the poll is also how a re-authentication
832            // is noticed.
833            Some(_) => {
834                // GitHub answered, so it is reachable: whatever is wrong, it is
835                // not an outage, and an outage run that was open must close.
836                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    /// GitHub answered something. Whatever it was, the outage run is over.
856    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        // Additive, never subtractive: see `JITTER_RATIO`. The result may exceed
869        // `MAX_OFFLINE_BACKOFF` by up to the jitter ratio, which is the price of
870        // keeping a fleet of agents from retrying in lockstep at the plateau —
871        // a cap applied *after* jitter would collapse every agent onto the same
872        // instant precisely when the outage is longest.
873        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
878/// Whether a pass found nothing happening, so the next one may come at the
879/// idle interval.
880///
881/// All three are needed. Every target answered, and quietly
882/// (`QueuedDemand::is_quiet`); this pass started no runner; and no policy
883/// here holds a live one. A live runner means a job is running or about to,
884/// and its follow-on work (`needs:`, the next matrix wave) is exactly what an
885/// active target is polled for. A pass that polled nothing is not quiet: there
886/// is nothing to be quiet about, and the active interval is what it had
887/// before.
888fn 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        // A missing allocation after a journal failure is unknown activity,
895        // not evidence that the host is idle.
896        && report.host_capacity_unreadable == 0
897        && report.attempts_unreadable == 0
898        // Demand this host matched and did not serve is not quiet either: a
899        // launch that keeps failing (a refused JIT registration) would
900        // otherwise be retried, and charged, every few seconds.
901        && report
902            .allocations
903            .iter()
904            .all(|allocation| allocation.active_owned == 0 && allocation.demand == 0)
905}
906
907/// The shortest idle delay a poll of `requests_per_pass` requests may have.
908fn 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
914/// `c3`'s retry floor, with the one fallback this loop needs.
915///
916/// [`RefreshState::retry_delay`] answers `None` for the states no wait fixes,
917/// and those never reach here — the caller matches them into
918/// [`PollPace::Blocked`] first. The fallback exists so that a future
919/// `RefreshState` variant added to the two arms above cannot silently schedule a
920/// zero-second retry against an endpoint that asked for quiet.
921fn retry_floor(state: &RefreshState, now: Timestamp) -> Duration {
922    state.retry_delay(now).unwrap_or(PollSchedule::floor())
923}
924
925// ---------------------------------------------------------------------------
926// Offline
927// ---------------------------------------------------------------------------
928
929/// What an operator is told while GitHub is unreachable.
930///
931/// Flow 3.3 requires four things of an outage — start no new runner, retain
932/// existing runner processes, report `offline`, back off with jitter — and one
933/// thing of the *state*: that it says GitHub cancels queued jobs after 24 hours,
934/// so a prolonged outage loses queued work. That bound is stated here rather
935/// than left for a reader to infer, because an operator who does not know it has
936/// no reason to treat a long outage as urgent.
937#[derive(Debug, Clone, Copy, PartialEq, Eq)]
938pub struct OfflineState {
939    /// The unbroken run of failed polls.
940    pub consecutive: u32,
941    /// How long until the next attempt.
942    pub retry_in: Duration,
943    /// How long this loop has been unable to reach GitHub, when it is known.
944    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    /// Whether the outage has already outlasted GitHub's queue.
964    ///
965    /// `false` when the duration is unknown: this reports a fact, and "we cannot
966    /// tell" is not the same fact as "not yet".
967    #[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// ---------------------------------------------------------------------------
997// The launcher port
998// ---------------------------------------------------------------------------
999
1000/// What this loop asks `e3` to create.
1001#[derive(Debug, Clone, Copy)]
1002pub struct LaunchRequest<'a> {
1003    pub host: &'a Host,
1004    pub policy: &'a ScalePolicy,
1005    /// Proof that e1 still owns the host allocation lock for every package,
1006    /// prune, and process-start effect performed by e3.
1007    // Crate-visible so only this allocator can mint the request that reaches
1008    // package pruning. A caller holding an unrelated public AllocationLock can
1009    // no longer assemble a LaunchRequest and present that guard as authority.
1010    pub(crate) allocation_guard: &'a AllocationGuard,
1011    /// How long this loop waited for that lock, for the launch's timings.
1012    pub lock_wait: Duration,
1013}
1014
1015/// Why one runner could not be started.
1016///
1017/// Carries `b1`'s [`FailureReason`] rather than a taxonomy of this module's own:
1018/// the reasons a runner fails to start are `e3`'s to know and `b1`'s to name,
1019/// and a third vocabulary here would be a third answer to a question the
1020/// operator asks once.
1021#[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/// A lifecycle conclusion that must return through ordinary demand and
1028/// capacity allocation before another runner may start.
1029#[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/// Why the persisted host ceiling could not be read. Closed, non-secret reasons
1044/// remain distinguishable in reports and structured logs.
1045#[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/// The seam between the decision to start a runner and the act of starting one.
1068///
1069/// `e3` implements this; every test in this file fakes it, which is what makes
1070/// the whole allocator path decidable with no process, no filesystem and no
1071/// network.
1072///
1073/// # Why the attempt set comes through the same port as the launch
1074///
1075/// `b1` makes this argument at [`HostAllocator::from_attempts`] and it applies
1076/// one layer up: the host-wide total (D9) and every per-policy count (D7) are
1077/// two questions asked of **one** set, and a design that let the caller supply
1078/// the set separately from the thing that creates its members is a design in
1079/// which the two can disagree. Worse, it makes `&[]` expressible — and an empty
1080/// attempt set is exactly the shape that drops the `- active_owned_runners`
1081/// term, starts a second runner for a job already being served, and reports no
1082/// error while doing it.
1083///
1084/// So the launcher is asked, under the allocation lock, immediately before each
1085/// runtime is created. There is no second supply point and no cached copy.
1086///
1087/// # The two ways an implementer can say "I hold no attempts"
1088///
1089/// The argument above closes the hole for a *caller*. It stayed open one level
1090/// down for the **implementer**, in two shapes that both oversubscribe the
1091/// machine and neither of which reports anything:
1092///
1093/// * **By failing.** `attempts()` used to be infallible, which left `e3` — which
1094///   reads a journal off a disk — a choice between panicking and answering
1095///   `vec![]` on an I/O error. An empty set is indistinguishable from an idle
1096///   host, so a transient read failure reads as "nothing is running" and the
1097///   next pass allocates the whole machine for jobs already being served. It is
1098///   fallible now, and [`Reconciler`] treats a failure the way it treats a lock
1099///   it could not take: start nothing, say so, try again next pass.
1100/// * **By lagging.** [`Self::launch`] returns the attempt it created rather than
1101///   its identifier, so the caller can carry it. See that method for the
1102///   measurement that made this necessary.
1103#[async_trait::async_trait]
1104pub trait RunnerLauncher: fmt::Debug + Send + Sync {
1105    /// Read this host's current ceiling from the journal, including edits made
1106    /// after daemon startup. An unreadable or missing host is an error, never
1107    /// permission to fall back to the startup ceiling.
1108    async fn host_capacity(&self, host: &Host) -> Result<NonZeroU16, HostCapacityError>;
1109
1110    /// Reconcile this policy's existing processes before demand is read and
1111    /// capacity is recomputed. A concluded pre-acceptance attempt thereby
1112    /// becomes an ordinary allocation candidate in this same pass; replacement
1113    /// never bypasses the allocator.
1114    async fn supervise(
1115        &self,
1116        _policy: &ScalePolicy,
1117    ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
1118        Ok(Vec::new())
1119    }
1120
1121    /// Every attempt this host holds, across every policy, terminal ones
1122    /// included.
1123    ///
1124    /// Terminal attempts are included rather than filtered out because the
1125    /// caller needs both answers from one set:
1126    /// [`AttemptState::counts_against_capacity`] decides the ceiling, and the
1127    /// terminal ones are what [`RunnerLauncher::clean`] is for.
1128    ///
1129    /// # Errors
1130    /// [`LaunchFailure`] when the set could not be read. **Never answer `Ok`
1131    /// with an empty vector to signal a failure** — the caller cannot tell that
1132    /// from an idle host, and the two lead to opposite actions.
1133    async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure>;
1134
1135    /// Create exactly one runtime and start one runner, and return the attempt
1136    /// that now exists.
1137    ///
1138    /// Called once per grant, with the host-wide allocation lock held.
1139    ///
1140    /// # The attempt is returned, not just its identifier
1141    ///
1142    /// The host ceiling is enforced against a host-wide total, and that total is
1143    /// recomputed from [`Self::attempts`] on every hold. If a launch is not yet
1144    /// visible there when the *next* policy is allocated for — a journal write
1145    /// that has not landed, an asynchronous store, a cache — then that policy's
1146    /// grant is computed from a set missing the previous policy's runners, and
1147    /// it is too large.
1148    ///
1149    /// That is measured, not hypothetical. With a launcher whose attempts never
1150    /// became visible, two policies on a host of **three** started **six**
1151    /// runners, with the allocation lock held correctly throughout:
1152    /// `host_capacity=3, started=6, launches=6`. Serialisation was never the
1153    /// problem; the arithmetic under it was reading a stale set.
1154    ///
1155    /// So an implementer *should* make the new attempt visible to
1156    /// [`Self::attempts`] before returning — and the caller does not depend on
1157    /// it. [`Reconciler`] carries what this pass created and merges it, by
1158    /// [`RunnerAttempt::id`], with whatever the launcher reports. A launcher
1159    /// that honours the contract is not double-counted, and one that lags cannot
1160    /// oversubscribe the host.
1161    ///
1162    /// # Every call must return a **fresh** [`RunnerAttempt::id`]
1163    ///
1164    /// This is a requirement, not a convention, because the merge above is what
1165    /// carries the host ceiling and the merge is keyed on the identifier. Two
1166    /// calls that answer with the same id are two runtimes that the host-wide
1167    /// total counts once, and the machine is then allocated past
1168    /// `host_capacity`: probed at `host_capacity = 3` with one slot already
1169    /// busy and a launcher answering with a duplicate id, the pass started
1170    /// **four** runners for five occupied slots.
1171    ///
1172    /// That is a narrower defect than the lagging launcher above — that one
1173    /// needed no bug at all, this one needs a broken id generator — but `e3` is
1174    /// the implementor and cannot honour a requirement nobody states.
1175    /// [`Reconciler::host_attempts`] carries a `debug_assert` that fires on a
1176    /// collision, so a development build finds it at the first duplicate rather
1177    /// than through an oversubscribed host.
1178    ///
1179    /// # Errors
1180    /// [`LaunchFailure`], carrying the [`FailureReason`] `e3` recorded.
1181    async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure>;
1182
1183    /// Remove a terminal attempt's runtime and mark it `cleaned`.
1184    ///
1185    /// Never called for a non-terminal attempt: capacity is reclaimed when an
1186    /// attempt reaches a terminal state and at no other time.
1187    ///
1188    /// # Errors
1189    /// [`LaunchFailure`], carrying the [`FailureReason`] `e3` recorded.
1190    async fn clean(&self, attempt: AttemptId) -> Result<(), LaunchFailure>;
1191}
1192
1193/// A [`RunnerLauncher`] that refuses every launch with
1194/// [`FailureReason::HostUnfit`] while `unfit` is set, and passes everything
1195/// else straight through.
1196///
1197/// The daemon sets the flag while a required host check fails (`host
1198/// doctor`). The refusal comes before the inner launcher runs, so nothing is
1199/// registered with GitHub, and the reconciler reports it as a
1200/// `runner_start_failed` event with reason `host_unfit` -- visible, rather than
1201/// a host that silently stopped serving. Supervision, the attempt set and
1202/// cleanup are never gated: what already runs is still looked after.
1203#[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
1245// ---------------------------------------------------------------------------
1246// The host-wide allocation lock
1247// ---------------------------------------------------------------------------
1248
1249/// The lock is held for as long as this value lives.
1250///
1251/// Opaque on purpose: what is being held differs between the in-process and the
1252/// file-backed implementation, and a caller that could see which one it has
1253/// would eventually branch on it.
1254pub struct AllocationGuard {
1255    _held: Box<dyn std::any::Any + Send + Sync>,
1256}
1257
1258impl AllocationGuard {
1259    /// Wrap whatever the implementation holds. Dropping the guard drops it.
1260    #[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/// The host-wide allocation lock could not be taken.
1275#[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/// Flow 2.4's *"takes the host-wide allocation lock before creating each local
1280/// runtime"*, as a port.
1281///
1282/// # Why a lock is needed at all, given the allocator already exists
1283///
1284/// [`HostAllocator`] enforces D9 across the policies of **one** pass. It cannot
1285/// enforce anything across two passes running at once, and `f3` runs one
1286/// demand-polling loop per target: without serialisation, two loops read the
1287/// same headroom, each finds it sufficient, and the host ends up with the sum of
1288/// two grants it only ever had room for one of. The lock is what makes the
1289/// read-decide-create sequence atomic, and it is taken once per runtime rather
1290/// than once per pass so that a slow package download in one policy does not
1291/// hold the whole host still.
1292#[async_trait::async_trait]
1293pub trait AllocationLock: fmt::Debug + Send + Sync {
1294    /// Take the lock, waiting briefly for it.
1295    ///
1296    /// # Errors
1297    /// [`AllocationLockBusy`] when it could not be taken. A refused grant is
1298    /// always safe: the next pass re-reads the headroom and tries again.
1299    async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy>;
1300}
1301
1302/// The lock every task inside one agent process contends for.
1303///
1304/// This is the implementation that matters in practice, because the
1305/// single-instance lock (`d1`) already guarantees one agent per host: the
1306/// concurrency the allocation lock actually has to serialise is `f3`'s
1307/// per-target loops inside that one process. A `tokio` mutex rather than a
1308/// `std` one because it is held across the `await` that creates the runtime.
1309#[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/// `d1`'s file lock, which is host-wide across processes as well as across
1331/// tasks.
1332///
1333/// Defence in depth behind [`InProcessAllocationLock`], for the configuration
1334/// `d1` documents as the one where two agents can genuinely coexist: the
1335/// platform state directory is per-account, so a service-account daemon and an
1336/// interactive `daemon run` resolve different paths and do not contend for the
1337/// single-instance lock. They do contend here if they share a state directory.
1338///
1339/// [`runner_manager_platform::lock::HostLock::acquire`] blocks the calling
1340/// thread and its own documentation names this caller: *"Async callers must wrap
1341/// it in [`tokio::task::spawn_blocking`]"*. That is what this does, and the
1342/// returned `HostLock` lives inside the guard, because dropping it is the
1343/// release.
1344#[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            // A refused lock and a panicked blocking task are the same outcome
1381            // to this caller: no runtime was created and the next pass will
1382            // re-read the headroom. Neither is allowed to look like a grant.
1383            Ok(Err(_)) | Err(_) => Err(AllocationLockBusy),
1384        }
1385    }
1386}
1387
1388/// Adds the Windows/WSL recovery fence to an ordinary allocation lock, and
1389/// says on disk when allocations keep being refused.
1390///
1391/// A Windows watchdog writes its drain request before attempting the same
1392/// atomic directory claim. Therefore either this guard owns the directory and
1393/// finishes the one launch already in progress, or Windows owns it and no new
1394/// launch can pass. A malformed configured fence fails closed. A guest claim
1395/// whose owner is provably gone is reclaimed first; see
1396/// [`runner_manager_platform::wsl::fence`].
1397///
1398/// # Refusals that persist are recorded
1399///
1400/// A refusal is always safe for one pass, and a refusal on every pass is a host
1401/// that starts nothing while it looks healthy -- 13 days of it, once. So after
1402/// [`launch_health::BLOCKED_AFTER_DEFERRALS`] consecutive refusals spanning at
1403/// least [`launch_health::BLOCKED_AFTER`], with no launch of this process in
1404/// progress, the lock writes the `state/` record `status`, `service status`,
1405/// `wsl status` and `host doctor` read. The next granted allocation removes it.
1406/// Refusals while this process is itself launching are its own contention and
1407/// count neither way.
1408///
1409/// [`launch_health::BLOCKED_AFTER_DEFERRALS`]: runner_manager_platform::launch_health::BLOCKED_AFTER_DEFERRALS
1410/// [`launch_health::BLOCKED_AFTER`]: runner_manager_platform::launch_health::BLOCKED_AFTER
1411#[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    /// A quiet spell this long between refusals starts a new run.
1418    streak_gap: Duration,
1419    in_flight: Arc<std::sync::atomic::AtomicUsize>,
1420    refusals: Mutex<Refusals>,
1421}
1422
1423/// The refusals since the last grant.
1424#[derive(Debug, Default)]
1425struct Refusals {
1426    /// The current run of refusals: when it began, the latest one, and how
1427    /// many it holds.
1428    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
1439/// Counts a launch of this process as in progress until dropped.
1440struct 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
1455/// Releases the guest launch claim when the allocation ends, and says so when
1456/// it cannot: this once failed silently while a distribution started nothing
1457/// for 13 days.
1458struct 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    /// Record blocked launches after `refusals` consecutive refusals spanning
1492    /// at least `after`, instead of the defaults.
1493    #[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    /// Start a new run of refusals after a quiet spell of `gap`.
1501    #[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                // Kept, so the next grant tries again.
1520                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        // A refusal long after the previous one starts a new run: two brief
1535        // contentions days apart are not five minutes of nothing but refusals.
1536        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        // Rewritten on every refusal, so readers can tell a record nobody
1563        // refreshes -- no demand any more -- from one still being refused.
1564        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                    // Guarded at once, so a claim let go on the drain path below
1601                    // is released -- and logged when it cannot be -- like any other.
1602                    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                    // An owner record nobody can decode stops the reclaim the
1616                    // same way on every pass; name it rather than the config.
1617                    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// ---------------------------------------------------------------------------
1658// Lifecycle events
1659// ---------------------------------------------------------------------------
1660
1661/// Which terminal thing happened, as a closed vocabulary.
1662///
1663/// The distinction `g2` renders: an idle exit is the accepted surplus case and
1664/// **not** a failure, and showing it as one sends an operator hunting a fault
1665/// that does not exist.
1666#[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/// A [`FailureReason`]'s variant name, with no detail.
1708///
1709/// [`FailureReason::Other`] carries a `String` that `e3` fills in, and an event
1710/// is not the place for it: `07-security.md`'s log scan runs over everything
1711/// this loop emits, and free text is the one shape that can carry a credential
1712/// past a field allow-list. The operator-facing detail reaches the journal
1713/// through `b2` and the screen through `g2`; what reaches an *event* is the
1714/// variant.
1715#[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/// Fixed, credential-free reasons a queued job cannot route to one profile.
1751#[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/// What `g2`'s activity view and the local log sink see.
1776///
1777/// **Every field is an identifier, a count, a duration, or a `&'static str`
1778/// drawn from a closed set.** There is no `String` anywhere in this enum, which
1779/// is what makes "no emitted event contains a token, a JIT blob, or a credential
1780/// header" a property of the type rather than a discipline each call site has to
1781/// keep. `tests::no_emitted_event_can_carry_a_credential` renders every variant
1782/// through `d1`'s scrubber and asserts nothing changes, with a positive control
1783/// so the assertion cannot pass vacuously.
1784#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1785pub enum LifecycleEvent {
1786    /// A demand poll answered for one target.
1787    DemandObserved {
1788        policy: PolicyId,
1789        /// Queued jobs this policy's routing labels match. The number clamped.
1790        demand: u32,
1791        /// Queued jobs whose required labels this policy does not carry.
1792        ///
1793        /// Never demand. Reported because the difference between this and
1794        /// `demand` is the whole value of the label filtering, and an operator
1795        /// wondering why a busy repository started no runners is owed it.
1796        not_matched: u32,
1797        /// Queued jobs whose `runs-on` could not be resolved statically.
1798        ///
1799        /// `b1` requires these be "reported as unresolvable rather than silently
1800        /// counted or silently dropped": counting one would start a runner for a
1801        /// job that may not be ours, and dropping it would hide a workflow this
1802        /// host can never serve. A count rather than the reasons themselves
1803        /// because this type is `Copy`, and `c4` logs the reasons where it
1804        /// builds them.
1805        unresolvable: u32,
1806        /// `false` when the count is a floor rather than a total.
1807        complete: bool,
1808    },
1809    /// A queued job cannot be assigned unambiguously to this target's profiles.
1810    RoutingRefused {
1811        policy: PolicyId,
1812        reason: RoutingRefusal,
1813        count: u32,
1814    },
1815    /// A target could not be polled, so its policies start nothing this pass.
1816    TargetUnreadable {
1817        policy: PolicyId,
1818        reason: &'static str,
1819    },
1820    /// One policy's share of the pass.
1821    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    /// A monitor-only policy was skipped entirely, before any demand request
1831    /// was issued for it (D19).
1832    MonitorOnlySkipped { policy: PolicyId },
1833    /// One runtime was created and one runner started.
1834    RunnerStarted {
1835        policy: PolicyId,
1836        attempt: AttemptId,
1837    },
1838    /// One runner could not be started.
1839    RunnerStartFailed {
1840        policy: PolicyId,
1841        reason: &'static str,
1842    },
1843    /// The allocation lock was not free, so `count` runners this policy was
1844    /// granted were not created this pass.
1845    AllocationDeferred { policy: PolicyId, count: u16 },
1846    /// The host's attempt set could not be read at all.
1847    ///
1848    /// Distinct from an empty set on purpose, and the whole reason
1849    /// [`RunnerLauncher::attempts`] is fallible: the two produce the same
1850    /// *number* and demand opposite actions.
1851    AttemptsUnreadable { reason: &'static str },
1852    /// The ceiling is unknown; this does not imply that the attempt set is unreadable.
1853    HostCapacityUnreadable { reason: HostCapacityError },
1854    /// A terminal attempt's runtime was removed.
1855    AttemptCleaned {
1856        policy: PolicyId,
1857        attempt: AttemptId,
1858        outcome: OutcomeKind,
1859    },
1860    /// A terminal attempt's runtime could not be removed. It will be retried on
1861    /// the next pass, and this is what keeps that retry from being silent.
1862    AttemptCleanFailed {
1863        policy: PolicyId,
1864        attempt: AttemptId,
1865        reason: &'static str,
1866    },
1867    /// Scale-down declined to remove a runner that is executing a job.
1868    ScaleDownRefused {
1869        policy: PolicyId,
1870        attempt: AttemptId,
1871    },
1872    /// When the next poll is, and why then.
1873    PollScheduled { retry_in_ms: u64, pace: PollPace },
1874}
1875
1876impl LifecycleEvent {
1877    /// A fixed name, for the `event` field `d1`'s sink allows verbatim.
1878    #[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    /// Which policy this event is about.
1899    #[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
2018/// Where lifecycle events go.
2019pub trait EventSink: fmt::Debug + Send + Sync {
2020    fn emit(&self, event: LifecycleEvent);
2021}
2022
2023/// Discards everything. For callers that only want the report.
2024#[derive(Debug, Clone, Copy, Default)]
2025pub struct NoEvents;
2026
2027impl EventSink for NoEvents {
2028    fn emit(&self, _event: LifecycleEvent) {}
2029}
2030
2031/// The local log sink, through `d1`'s redacting layer.
2032///
2033/// Every field name below is on
2034/// [`runner_manager_platform::logging::ALLOWED_FIELDS`]; anything else would be
2035/// replaced with `[redacted]` and the line would lose its meaning rather than
2036/// its safety. `tests::every_field_name_this_sink_emits_is_one_d1_allows` keeps
2037/// that true.
2038#[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                // An empty reading is the idle steady state, and the idle
2053                // interval repeats it every few seconds per target: at `info`
2054                // it would be most of the log. Anything worth reading is still
2055                // `info`.
2056                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                // There is deliberately no `warn!` here for the "demand is zero
2076                // but jobs were not matched" shape, though it is the one this
2077                // change introduced: before demand was filtered, a repository
2078                // with work in it always produced some, and now a policy whose
2079                // labels do not cover its jobs produces none.
2080                //
2081                // The reason is that the shape is indistinguishable from a
2082                // healthy one. A repository served by a Windows host and a macOS
2083                // host has the other host's jobs queued in it constantly, so
2084                // each agent would warn on every poll about work that is being
2085                // served correctly by the other machine. Telling the two apart
2086                // needs to know whether this policy has *ever* matched anything,
2087                // which is state across polls that this loop does not keep.
2088                //
2089                // What an operator gets instead is the `not_matched` count, on
2090                // this event and in its `Display`, which `g2` renders. "0 queued
2091                // jobs for this host, 5 for other labels" is the diagnosis; a
2092                // warning that fired on every healthy minute would be the kind
2093                // nobody reads.
2094            }
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                // Nothing wanted, nothing held, nothing started: the idle
2119                // steady state, see `DemandObserved` above.
2120                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                // Contention is normally brief, but a configured WSL recovery
2158                // fence whose shared root is unwritable reaches the same
2159                // fail-closed result forever. Demand was already observed and
2160                // capacity was already granted, so hiding this at DEBUG makes
2161                // a host claim healthy while it starts nothing.
2162                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/// Keeps every event, in order.
2213///
2214/// `g2`'s activity view is a reader of this, and so is every test below.
2215#[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    /// How many events of one name were emitted.
2232    #[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/// Both sinks at once: the log sink for the operator's file, the buffer for
2250/// `g2`'s screen.
2251#[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
2261// ---------------------------------------------------------------------------
2262// The reconciler
2263// ---------------------------------------------------------------------------
2264
2265/// Everything one reconciler needs, written down at the call site.
2266///
2267/// A struct rather than seven positional arguments, for the reason `b1` gives at
2268/// `PersistedAttempt`: several of these are `Arc<dyn …>` and transposing two of
2269/// them type-checks. Construct it with a struct literal so every port is named.
2270pub 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/// What one reconciliation pass did.
2287///
2288/// `started` and the allocations are reported separately on purpose: an
2289/// allocation is what the pass *decided* under the lock, and `started` is what
2290/// actually came up. They differ when a launch fails or when the lock was held,
2291/// and collapsing them would hide both.
2292#[derive(Debug, Clone, Default)]
2293pub struct ReconcileReport {
2294    /// One entry per policy that got as far as being allocated for.
2295    pub allocations: Vec<Allocation>,
2296    /// Policies skipped because they are monitor-only (D19).
2297    pub monitor_only: Vec<PolicyId>,
2298    /// Policies whose target could not be polled this pass.
2299    pub unreadable: Vec<PolicyId>,
2300    /// Policies whose target GitHub actually answered for this pass.
2301    ///
2302    /// The counterpart to [`Self::unreadable`], and the only honest evidence
2303    /// that this host reached GitHub at all. [`Self::allocations`] is not: a
2304    /// policy this host does not own is allocated for with no demand and
2305    /// without any target being polled, so a pass where every poll failed can
2306    /// still end with allocations in it.
2307    pub targets_read: u16,
2308    /// Runners actually started.
2309    pub started: u16,
2310    /// Pre-acceptance attempts routed back through this pass's ordinary
2311    /// demand/capacity decision.
2312    pub replacement_intents: u16,
2313    /// Terminal attempts whose runtime was removed.
2314    pub cleaned: u16,
2315    /// Of those, the surplus case: registered, got no job, exited on its idle
2316    /// timeout. **Not** a failure.
2317    pub idle_exits: u16,
2318    /// Of those, the ones an operator should look at.
2319    pub failures: u16,
2320    /// Runners this pass was granted but did not start because the allocation
2321    /// lock was held.
2322    ///
2323    /// **Grants, not policies.** It used to be incremented once per
2324    /// `start_runners` call that met a held lock, so a policy that launched two
2325    /// of five and then lost the lock reported `1` while three runners went
2326    /// unstarted -- a number that agreed with neither its own name nor its
2327    /// documentation.
2328    pub deferred: u16,
2329    /// Times the host's attempt set could not be read this pass.
2330    ///
2331    /// Non-zero means the pass decided less than it looks like it decided: a
2332    /// policy whose attempt set was unreadable started nothing and is *not* in
2333    /// [`Self::allocations`], because there was no set to compute an allocation
2334    /// from. It is not the same as the host being idle, which is the whole
2335    /// reason [`RunnerLauncher::attempts`] is fallible.
2336    ///
2337    /// **A count, where [`Self::unreadable`] is a `Vec<PolicyId>`, and that
2338    /// asymmetry is deliberate.** An unreadable *target* is a fact about one
2339    /// policy's GitHub target; an unreadable *attempt set* is a fact about this
2340    /// host's journal, which no policy owns — two of the three paths that reach
2341    /// it (`clean_terminal_attempts` and `scale_down`) have no policy in hand at
2342    /// all. Naming policies here would mean either inventing an owner for a
2343    /// host-wide failure or reporting a partial list, and both read as more
2344    /// precision than there is. The pass is distinguishable from an idle one,
2345    /// which is what the field exists for; the per-policy attribution is not
2346    /// available, and is recorded as missing rather than faked.
2347    pub attempts_unreadable: u16,
2348    /// Allocation checks blocked by a missing or unreadable host ceiling.
2349    pub host_capacity_unreadable: u16,
2350    /// Terminal attempts whose runtime could not be removed. Retried next pass.
2351    pub clean_failures: u16,
2352    /// The most severe failure across the targets polled, when there was one.
2353    pub failure: Option<RefreshState>,
2354    /// What to display while GitHub is unreachable, including how long the
2355    /// outage has run and therefore whether queued work has already been lost.
2356    pub offline: Option<OfflineState>,
2357    /// When to poll next, and why then.
2358    pub next_poll: NextPoll,
2359    /// Demand requests this pass projected against the shared hourly ceiling.
2360    pub demand_requests: u32,
2361}
2362
2363impl ReconcileReport {
2364    /// Whether this pass actually reached GitHub, which is the only thing that
2365    /// entitles it to write a `last GitHub contact`.
2366    ///
2367    /// # Positive evidence, because the absence of a failure is not evidence
2368    ///
2369    /// The record used to be written whenever [`Self::failure`] was `None`, on
2370    /// the belief that an unauthorized target lands in [`Self::unreadable`]
2371    /// rather than in `failure`. **That belief is wrong.** `unreadable` is
2372    /// pushed only from the `PollOutcome::Failed` arm, `failure` is the maximum
2373    /// over every `Failed` reading, and `RefreshState::Unauthorized` scores 2 —
2374    /// so a non-empty `unreadable` always implies `failure.is_some()`, and
2375    /// guarding on both would have changed nothing at all.
2376    ///
2377    /// The path that really writes a contact record without touching GitHub is
2378    /// a pass that polls **nothing**: every policy draining, owned by another
2379    /// host, or monitor-only. `pollable` is then empty, no reading exists, no
2380    /// failure is computed, and the old guard passed. That is how
2381    /// `service status` can answer `healthy` on a host doing nothing at all.
2382    ///
2383    /// So this asks for evidence rather than for the absence of a complaint. A
2384    /// pass with nothing to ask reaches nobody and records nothing, which is
2385    /// what `never` in `service status` is for.
2386    ///
2387    /// Conservative on purpose: `repositories.scope_for` is a real request that
2388    /// can succeed before a demand poll fails, and it is not counted. Contact
2389    /// that cannot be proven is not claimed.
2390    #[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    /// Whether GitHub was unreachable this pass.
2407    #[must_use]
2408    pub fn is_offline(&self) -> bool {
2409        matches!(self.failure, Some(RefreshState::Offline))
2410    }
2411
2412    /// The offline state to display, when this pass was one.
2413    #[must_use]
2414    pub const fn offline_state(&self) -> Option<&OfflineState> {
2415        self.offline.as_ref()
2416    }
2417
2418    /// Attempts this pass created. The idle-host assertion reads this.
2419    #[must_use]
2420    pub const fn starts_nothing(&self) -> bool {
2421        self.started == 0
2422    }
2423}
2424
2425/// What one scale-down request did.
2426#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2427pub struct ScaleDownReport {
2428    /// Terminal attempts whose runtime was removed.
2429    pub removed: u16,
2430    /// Attempts executing a job. **Removed nothing, left `busy`.**
2431    pub refused_busy: u16,
2432    /// Terminal attempts whose runtime could not be removed.
2433    pub clean_failures: u16,
2434    /// Live attempts that are not yet busy. Also removed nothing: capacity is
2435    /// reclaimed only when an attempt reaches a terminal state.
2436    pub retained: u16,
2437    /// The host's attempt set could not be read, so **every other field here is
2438    /// meaningless** rather than zero.
2439    ///
2440    /// This is the same distinction [`ReconcileReport::attempts_unreadable`]
2441    /// draws, and it is here for the same reason: a default
2442    /// [`ScaleDownReport`] and a scale-down that could not see the machine are
2443    /// both all-zeros, and they mean opposite things — "there was nothing to
2444    /// reclaim" against "we do not know what there was". Check
2445    /// [`Self::is_conclusive`] before reading a zero as an answer.
2446    pub attempts_unreadable: bool,
2447}
2448
2449impl ScaleDownReport {
2450    /// Whether the counts here describe the machine at all.
2451    ///
2452    /// `false` means the attempt set could not be read, so every zero is
2453    /// "unknown" rather than "none".
2454    #[must_use]
2455    pub const fn is_conclusive(&self) -> bool {
2456        !self.attempts_unreadable
2457    }
2458}
2459
2460/// How long a failed cleanup of one attempt waits before it is tried again,
2461/// doubling per consecutive failure up to [`CLEAN_RETRY_MAXIMUM`].
2462///
2463/// A runtime that cannot be removed used to be retried on every pass, about
2464/// every six seconds, and each failure logs a warning: one stuck Windows
2465/// workspace wrote some 15,000 of them a day. The retry is still real; it is
2466/// just no longer a log flood.
2467const CLEAN_RETRY_INITIAL: Duration = Duration::from_secs(30);
2468
2469/// The longest a failing cleanup waits between tries.
2470const CLEAN_RETRY_MAXIMUM: Duration = Duration::from_secs(30 * 60);
2471
2472/// One attempt's consecutive cleanup failures, and when it may be tried again.
2473#[derive(Debug, Clone, Copy)]
2474struct CleanRetry {
2475    failures: u32,
2476    not_before: Timestamp,
2477}
2478
2479/// Per-attempt cleanup backoff. One each in the [`Reconciler`]'s sweep of
2480/// concluded attempts and in the lifecycle launcher's own supervision pass,
2481/// the two places a failed cleanup is retried.
2482#[derive(Debug, Default)]
2483pub(crate) struct CleanBackoff {
2484    retries: BTreeMap<AttemptId, CleanRetry>,
2485}
2486
2487impl CleanBackoff {
2488    /// The doubling-with-a-ceiling schedule; the attempt bound is unused.
2489    const SCHEDULE: crate::lifecycle::RetryPolicy =
2490        crate::lifecycle::RetryPolicy::bounded(u32::MAX, CLEAN_RETRY_INITIAL, CLEAN_RETRY_MAXIMUM);
2491
2492    /// Whether `attempt`'s cleanup should be tried at `now`.
2493    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    /// Records a failed cleanup and schedules the next try.
2500    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                // At most `CLEAN_RETRY_MAXIMUM`, so always representable.
2511                not_before: now + chrono::Duration::from_std(delay).unwrap_or_default(),
2512            },
2513        );
2514    }
2515
2516    /// Forgets `attempt`: it was cleaned.
2517    pub(crate) fn succeeded(&mut self, attempt: AttemptId) {
2518        self.retries.remove(&attempt);
2519    }
2520
2521    /// Forgets every attempt not in `present`, so the map cannot outgrow the
2522    /// journal.
2523    fn retain(&mut self, present: &BTreeSet<AttemptId>) {
2524        self.retries.retain(|attempt, _| present.contains(attempt));
2525    }
2526}
2527
2528/// The reconciliation loop.
2529///
2530/// One per target, as `f3` runs them; they share a [`RunnerLauncher`] and an
2531/// [`AllocationLock`], which is what keeps the host ceiling true across all of
2532/// them.
2533#[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    /// Build a reconciler polling at the host's configured interval.
2549    #[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    /// Adopt intervals an operator changed while the loop runs.
2582    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    /// The repository-list cache, so `f1` can report what it has spent.
2588    #[must_use]
2589    pub const fn repositories(&self) -> &RepositoryCache {
2590        &self.repositories
2591    }
2592
2593    /// One reconciliation pass over `policies`.
2594    ///
2595    /// The order of operations is `03-control-flows.md` flow 2, and the two
2596    /// steps most worth naming are the ones that are silent when they are wrong:
2597    ///
2598    /// * **Monitor-only policies are removed before the demand poll**, not
2599    ///   after. D19 says such a policy "is skipped entirely by reconciliation",
2600    ///   and a poll issued on its behalf would spend requests from the shared
2601    ///   ceiling for a policy that can never act on the answer. This is asserted
2602    ///   on [`ScalePolicy::owns_runners`] rather than deduced from
2603    ///   `max_capacity` being absent.
2604    /// * **The attempt set is re-read under the lock, once per runtime.** See
2605    ///   [`RunnerLauncher`] for why it comes from there and nowhere else.
2606    pub async fn reconcile(&mut self, policies: &[ScalePolicy]) -> ReconcileReport {
2607        let mut report = ReconcileReport::default();
2608        // Everything this pass has created, carried across policies so that the
2609        // host-wide total cannot be computed from a set that is missing it. See
2610        // `RunnerLauncher::launch`.
2611        let mut launched: Vec<RunnerAttempt> = Vec::new();
2612
2613        // --- Flow 2.1-2.2: who is even asking, and what did GitHub say -------
2614        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                // Ownership rule 2 and precedence rule 4. The allocator reports
2625                // both by name below; polling on their behalf would spend
2626                // requests for an answer that cannot be acted on.
2627                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        // --- Flow 2.8: terminal attempts, whatever else this pass does -------
2679        //
2680        // Run before the allocation phase so that a report's `cleaned` count
2681        // describes the same instant its allocations do. It does not change the
2682        // arithmetic: a terminal attempt already stopped counting against
2683        // capacity when it became terminal, which is `b1`'s
2684        // `counts_against_capacity`. It touches no live process, so it is also
2685        // safe during an outage — flow 3.3 requires that running runners be
2686        // retained, and nothing here can reach one.
2687        self.clean_terminal_attempts(&mut report).await;
2688
2689        // --- Flow 2.3-2.6: the allocation -----------------------------------
2690        //
2691        // The predicates are re-tested here rather than the reading being looked
2692        // up by target, and that is not redundancy. **Targets are shared.** A
2693        // monitor-only policy watching `acme/app` alongside an autoscale policy
2694        // on the *same* repository finds a reading in the map that the other
2695        // policy paid for, and a lookup-driven loop then serves it: it emits a
2696        // demand observation on its behalf and clamps a number it has no
2697        // business seeing.
2698        //
2699        // Nothing downstream goes wrong when that happens — `may_start_runners`
2700        // is false for a monitor-only policy, so `HostAllocator` refuses it and
2701        // `to_start` is zero. It simply is not *skipped*, and D19's word is
2702        // "entirely".
2703        for policy in policies {
2704            if !policy.owns_runners() {
2705                // Already recorded and reported above, before any demand request
2706                // was issued. It owns no routing labels, takes no part in
2707                // demand, and can never be the reason a runner starts. Asserted
2708                // on the mode rather than deduced from `max_capacity` being
2709                // absent, which is what the specification requires.
2710                continue;
2711            }
2712            if !policy.is_owned_by(self.host.id) || !policy.may_start_runners() {
2713                // Ownership rule 2 and precedence rule 4. Allocated for with no
2714                // demand, so the refusal is reported by name rather than by
2715                // absence.
2716                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                // Unreachable: every policy reaching here was in `pollable`, and
2730                // `poll_targets` inserts an outcome for each of their targets.
2731                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        // --- Flow 2.1 / 3.3: when to come back ------------------------------
2762        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        // Flow 3.3's fourth obligation: the offline state carries the 24-hour
2783        // bound, and it can only say whether that bound has passed if it is
2784        // given the real elapsed time rather than an estimate from the interval.
2785        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    /// Poll each distinct target once, however many policies share it.
2801    ///
2802    /// Two policies on one repository are one demand request, not two. That is
2803    /// not a micro-optimisation: the budget model in
2804    /// `04-subsystem-contracts.md` prices a *target*, and a loop that spent per
2805    /// policy would quietly exceed the projection `f2` admitted the
2806    /// configuration against.
2807    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                // The repository list could not be refreshed, so the scope of
2824                // the poll is unknown. Polling a stale or empty scope would
2825                // report a demand number for a set of repositories nobody
2826                // chose, which is worse than reporting that the target could
2827                // not be read.
2828                Err(error) => PollOutcome::Failed(RefreshState::from_error(&error)),
2829            };
2830            readings.insert(target, outcome);
2831        }
2832        readings
2833    }
2834
2835    /// Compute one policy's allocation without creating anything.
2836    ///
2837    /// # Why this is safe without the lock
2838    ///
2839    /// **Not** because it cannot grant — it can, and
2840    /// [`Reconciler::start_runners`] uses it as a pre-check precisely for the
2841    /// number it returns. That was the original reason and this function
2842    /// outgrew it; the reason now is that it *decides* nothing. Nothing is
2843    /// created here, the headroom it read is re-read under the lock before any
2844    /// runtime exists, and the under-lock allocation may only lower what this
2845    /// one proposed. So there is no read-decide-create sequence here to make
2846    /// atomic, and the worst this can be is optimistic — which the lock then
2847    /// corrects.
2848    ///
2849    /// # Errors
2850    /// A host-ceiling or attempt-journal read failure. Neither permits an
2851    /// allocation, and they remain distinct in diagnostics.
2852    async fn allocate_only(
2853        &self,
2854        policy: &ScalePolicy,
2855        demand: u32,
2856        launched: &[RunnerAttempt],
2857    ) -> Result<Allocation, AllocationFailure> {
2858        // Read again under the shared launch lock, not just at each target's
2859        // poll boundary: another target must not use an old, higher ceiling.
2860        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    /// Flow 2.4-2.6: start runners for one policy, one lock hold per runtime.
2875    ///
2876    /// # Two stopping conditions, and both are needed
2877    ///
2878    /// The loop re-reads the attempt set under every hold, so the obvious stop
2879    /// is "the allocator granted nothing". That condition **alone does not
2880    /// terminate**, and the failure is not hypothetical — it was measured.
2881    /// Handing the allocator a set that does not include the runners this loop
2882    /// just started (an empty one, a stale one, or a launcher whose journal
2883    /// write has not landed yet) makes every grant look like the first, and the
2884    /// pass starts runners until something outside it intervenes. With the set
2885    /// dropped entirely, the three-consecutive-polls test below does not report
2886    /// three attempts; it *never returns*.
2887    ///
2888    /// So the grant decided on the first hold is also a **budget**. A later hold
2889    /// may lower it — the host may have filled up meanwhile — and can never
2890    /// raise it, which bounds the pass at the number this policy was actually
2891    /// allocated. That is `c2`'s reasoning for `MAX_PAGES` one layer down: the
2892    /// reconciliation loop is the one place in this product that must not be
2893    /// able to wedge, so the bound is structural rather than a consequence of
2894    /// every input being well behaved.
2895    async fn start_runners(
2896        &self,
2897        policy: &ScalePolicy,
2898        demand: u32,
2899        report: &mut ReconcileReport,
2900        launched: &mut Vec<RunnerAttempt>,
2901    ) {
2902        // A lock-free pre-check, for one reason only: the host-wide lock should
2903        // not be taken by a policy that is going to be granted nothing. On an
2904        // idle host with P policies that was P lock acquisitions per poll --
2905        // free under `InProcessAllocationLock`, a `spawn_blocking` and a
2906        // filesystem lock apiece under `FileAllocationLock`.
2907        //
2908        // It is safe because it can only be optimistic. Anything it grants is
2909        // re-decided under the lock below and may be lowered there; the only
2910        // thing it can get wrong in the other direction is refusing a grant that
2911        // headroom freed a moment later would have allowed, which the next poll
2912        // picks up.
2913        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        // The allocation that is *reported* is the one taken under the lock when
2922        // a lock was taken, because that is the one that decided anything. The
2923        // pre-check stands in only when no hold was ever obtained.
2924        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                    // Grants, not policies: this is what the policy was owed and
2933                    // did not get.
2934                    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            // The read and the decision are both inside the hold, and so is the
2945            // creation below. Two concurrent passes therefore serialise on the
2946            // whole sequence rather than on the decision alone -- reading the
2947            // headroom outside the lock is the shape in which two policies both
2948            // find room for the last slot.
2949            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                // The under-lock decision may be smaller than the pre-check, and
2960                // never larger: `min` rather than assignment, so a later hold
2961                // cannot raise the bound either.
2962                budget = budget.min(allocation.to_start);
2963                decided = Some(allocation.clone());
2964            }
2965
2966            // Either stop is sufficient on its own in the well-behaved case;
2967            // neither is sufficient when the launcher lags. See the doc comment.
2968            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                    // Carried across policies for the rest of this pass, so the
2988                    // host-wide total cannot be computed from a set that is
2989                    // missing it. See `RunnerLauncher::launch`.
2990                    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    /// The attempt set the host holds, plus everything this pass has already
3014    /// created.
3015    ///
3016    /// The merge is by [`RunnerAttempt::id`], so a launcher that makes its
3017    /// launches visible before returning -- which
3018    /// [`RunnerLauncher::launch`] asks for -- contributes each attempt once, and
3019    /// one that lags still cannot hide a runner from the host-wide total. The
3020    /// ceiling therefore holds on the strength of this function rather than on
3021    /// the strength of an implementer honouring a comment.
3022    ///
3023    /// # Errors
3024    /// Whatever [`RunnerLauncher::attempts`] reported.
3025    async fn host_attempts(
3026        &self,
3027        launched: &[RunnerAttempt],
3028    ) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
3029        let mut attempts = self.launcher.attempts().await?;
3030
3031        // Each `launch` creates one runtime, so each must answer with an
3032        // identifier no other attempt has. Two entries sharing one here are two
3033        // runtimes the host-wide total below counts once, which is the ceiling
3034        // failing silently -- so a development build stops at the first
3035        // duplicate instead. `RunnerLauncher::launch` states the requirement;
3036        // this is what makes it findable.
3037        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    /// The attempt set could not be read, so nothing may be decided from it.
3073    ///
3074    /// Counted rather than swallowed for the reason the module documentation
3075    /// gives: an unreadable set and an idle host produce the same *number* and
3076    /// demand opposite actions, so the difference has to survive into the
3077    /// report.
3078    fn report_unreadable_attempts(&self, report: &mut ReconcileReport, failure: &LaunchFailure) {
3079        report.attempts_unreadable = report.attempts_unreadable.saturating_add(1);
3080        // The variant, never a literal and never the detail. A hand-written
3081        // `"attempts_unreadable"` said only what the event's own name already
3082        // said, and threw away the one thing the field is for -- *which* failure
3083        // it was. `FailureReason::Other` carries free text that must not reach
3084        // an event, which is what `failure_reason_kind` is for and what
3085        // `a_cleanup_that_cannot_succeed_...` pins for the sibling path.
3086        self.events.emit(LifecycleEvent::AttemptsUnreadable {
3087            reason: failure_reason_kind(&failure.reason),
3088        });
3089    }
3090
3091    /// Remove the runtimes of attempts that have already concluded.
3092    ///
3093    /// `is_concluded` and not `is_terminal`: `cleaned` is terminal and already
3094    /// done, and `busy` is not terminal at all. That is what makes it impossible
3095    /// for this path to reach a runner executing a job.
3096    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            // Backed off after failing: not tried, so neither cleaned nor a
3115            // fresh failure to report.
3116            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                        // The surplus case. Counted apart from a failure because
3128                        // `g2` renders it apart, and because an operator told
3129                        // that a normal surplus exit is an error goes hunting a
3130                        // fault that does not exist.
3131                        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                // A runtime directory that cannot be removed is retried on every
3140                // poll. Silently, before this arm existed: no event, no counter,
3141                // no report field, so a cleanup that can never succeed was an
3142                // invisible permanent loop. It wedges no capacity -- a terminal
3143                // attempt already stopped counting -- but this module's
3144                // organising principle is the things that go wrong silently, and
3145                // `clean` returns a `Result` precisely so the caller can say
3146                // something. It is retried with per-attempt backoff
3147                // ([`CLEAN_RETRY_INITIAL`]) so the saying is not a flood.
3148                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    /// Reclaim what can be reclaimed for one policy, and nothing else.
3162    ///
3163    /// **A busy attempt is never removed.** `04-subsystem-contracts.md`:
3164    /// *"`busy` cannot transition to cleanup due to a scale-down request"*.
3165    /// Capacity comes back when an attempt reaches a terminal state and at no
3166    /// other time, so a scale-down against a host full of busy runners removes
3167    /// nothing, changes nothing, and says so.
3168    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                // The same rule as everywhere else, and this was the one place
3174                // it was still broken: an unreadable set is not an empty one,
3175                // and a bare `default()` here reported all zeros -- byte for
3176                // byte an idle host with nothing to reclaim.
3177                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                // `allocated`, `jit_received`, `starting`, `idle`: live, holding
3221                // a slot, and not this function's to end.
3222                _ => 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
3241/// One policy's demand, from the reading its target answered with.
3242///
3243/// A repository target tallies its own repository's queued jobs; an organization
3244/// target tallies every repository its scope covered, because one policy watching
3245/// an organization serves any repository in it.
3246///
3247/// # Why this takes a whole policy rather than a target and a label set
3248///
3249/// Because both halves have to come from the same policy, and a signature that
3250/// took them separately made it possible for them not to. The predecessor took a
3251/// `&ScaleTarget` alone and could not filter at all; the obvious repair was to
3252/// add a `&RoutingLabels` beside it, and at three call sites — two of them in
3253/// tests — nothing would have caught passing one policy's target with another
3254/// policy's labels. It compiles, it runs, and it silently serves the wrong
3255/// repository's queue.
3256///
3257/// # A monitor-only policy has no labels, and cannot reach here
3258///
3259/// [`Reconciler::reconcile`] filters on [`ScalePolicy::owns_runners`] before any
3260/// demand request is issued (D19), so the `None` arm is unreachable rather than
3261/// merely unlikely. It returns an empty tally instead of unwrapping, because a
3262/// panic in the reconciliation loop would take the daemon down over a policy
3263/// that was only ever going to start nothing.
3264fn 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
3279/// Tally one shared target reading using GitHub's required-label subset rule.
3280/// Refuse ambiguous ownership, including inactive local profiles: disabling an
3281/// isolated profile must not redirect its broad-label demand to a native sibling.
3282fn 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            // `demand_for` already preserves this as unresolvable for each profile.
3310            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
3336/// How urgently one failure should slow the loop down.
3337///
3338/// Ordering matters only for picking the worst of several targets: an outage
3339/// outranks a rate limit because backing off a socket that is not answering is
3340/// the safer error, and both outrank a per-target rejection that says nothing
3341/// about the credential as a whole.
3342const 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
3353/// Why one target could not be read, as a fixed, credential-free name.
3354///
3355/// Deliberately not a [`PollPace`]: a pace describes the *schedule*, which is a
3356/// property of the whole pass, and stamping one onto a single target would have
3357/// meant inventing a `consecutive` count for a target that has none. What an
3358/// event needs here is the reason, and `c3`'s [`RefreshState`] already names it.
3359///
3360/// `RefreshState::Failed` carries GitHub's own message and
3361/// `RefreshState::Forbidden` may carry one too. Neither reaches the event: this
3362/// returns the variant, for the reason [`failure_reason_kind`] states.
3363const 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    /// The reading that said `healthy` for 28 hours while nothing worked.
3381    ///
3382    /// A daemon every one of whose targets answered `401` kept writing a fresh
3383    /// `last GitHub contact`, because an unauthorized target is `unreadable`
3384    /// rather than a `failure`. Both that record and the `service status` built
3385    /// on it were used as evidence during the investigation, and both were
3386    /// wrong; see `docs/spikes/token-expiry-and-renewal.md`.
3387    #[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        // `allocations` deliberately does not count: a policy this host does
3410        // not own is allocated for with no demand and without polling anything,
3411        // so a pass where every poll failed can still carry allocations.
3412        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    /// The claim the old guard rested on, checked rather than assumed.
3430    ///
3431    /// `report.failure.is_none()` was believed to be compatible with an
3432    /// all-unauthorized pass. It is not: `unreadable` is pushed only from the
3433    /// `Failed` arm and `failure` is the maximum over every `Failed` reading,
3434    /// so guarding on `failure.is_none() && reached_github()` would have been
3435    /// `failure.is_none()` with extra words. This pins the severity that makes
3436    /// it so, because a future `severity(Unauthorized) == 0` would quietly
3437    /// restore the belief.
3438    #[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    // =======================================================================
3461    // Fakes
3462    // =======================================================================
3463
3464    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    /// An `active`, enabled autoscale policy on the fixture host.
3473    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    /// The host label every policy in these tests carries.
3485    ///
3486    /// `policy` above builds through `fixtures::policy().autoscale("home", …)`,
3487    /// which derives `rm-home-win-x64`. A job fixture that did not carry it
3488    /// would be filtered out as another host's work, so the two are tied
3489    /// together here rather than repeated as a literal at each call site.
3490    const HOST_LABEL: &str = "rm-home-win-x64";
3491
3492    /// `n` queued jobs this host's policies match.
3493    ///
3494    /// The ordinary demand fixture. Since the reversal of the run-counting
3495    /// decision the unit `e1` clamps is a job, so a test wanting demand `n` asks
3496    /// for `n` jobs rather than for `n` runs.
3497    fn jobs(n: usize) -> Vec<RunsOn> {
3498        fixtures::queued_jobs(&[HOST_LABEL], n)
3499    }
3500
3501    /// `e3`, faked: an attempt table and a launch counter, no process anywhere.
3502    #[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 this many times between reading the attempt set and recording
3512        /// a new one, so an unserialised allocator has a window to be wrong in.
3513        yields_before_recording: usize,
3514        /// Reports success without the attempt ever becoming visible, which is
3515        /// the shape a slow journal write has. Every grant then looks like the
3516        /// first.
3517        forgetful: bool,
3518        fail_next: Mutex<Option<FailureReason>>,
3519        /// Reports that the attempt set cannot be read at all, which is the one
3520        /// answer a caller must never confuse with an idle host.
3521        attempts_fail: Mutex<bool>,
3522        /// Refuses every cleanup, so the silent-retry path has something to be
3523        /// loud about.
3524        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            // The window an unserialised caller would lose the race in.
3635            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    /// A demand source a test programs directly, with no gateway underneath.
3670    #[derive(Debug, Default)]
3671    struct FakeDemand {
3672        outcome: Mutex<Option<PollOutcome>>,
3673        /// Answers programmed for one target, which beat the blanket one.
3674        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        /// Program one target's answer, overriding the blanket one.
3699        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    /// A lock that grants everything and counts how many holders it had at once.
3754    ///
3755    /// The counter is the assertion: "under simulated lock contention" is only
3756    /// meaningful if something measures that the contention was actually
3757    /// serialised.
3758    #[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    /// The lock that is not one: what the host looks like with the serialisation
3812    /// removed. Used only by the control half of the contention test.
3813    #[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    /// Captures what `tracing` writes on this thread.
3849    #[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    /// The release that once failed with no trace while a distribution
3863    /// started nothing for 13 days is now in the log, with its path.
3864    #[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        // Something the removal cannot take away: a file where the claim
3872        // directory was.
3873        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    /// The incident end to end: a guest claim left by a daemon of an earlier
3910    /// WSL boot no longer stops a launch.
3911    #[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        // Windows owns the fence, so every guest launch is refused.
3942        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    /// Refusals separated by quiet spells -- brief contention days apart --
3992    /// never add up to a blocked host.
3993    #[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    /// A drain request refuses the launch after the claim was made; that
4017    /// claim is released rather than left to block the next pass.
4018    #[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    /// A lock nobody can take.
4032    #[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    /// Everything one test needs, wired together.
4043    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    /// A concluded attempt carrying a specific outcome.
4122    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    // =======================================================================
4144    // The in-flight term: the single most likely way this task goes wrong
4145    // =======================================================================
4146
4147    /// `e1`'s Definition of Done, verbatim: *"A job that remains `queued` across
4148    /// three consecutive polls while its attempt is `starting` yields exactly
4149    /// one attempt — the test fails if the in-flight term is dropped from the
4150    /// formula."*
4151    ///
4152    /// `b1` tests the arithmetic underneath this
4153    /// (`capacity::tests::the_same_queued_job_on_two_polls_yields_one_attempt_
4154    /// not_two`). What *this* test covers is the only way `e1` can drop the
4155    /// term without touching `b1` at all: handing the allocator an attempt set
4156    /// that is not the one the host holds.
4157    ///
4158    /// # This was measured, not assumed, and the first measurement was worse
4159    /// # than the failure it was looking for
4160    ///
4161    /// Replacing `self.launcher.attempts().await` in
4162    /// [`Reconciler::start_runners`] with `Vec::new()` compiles and runs. Before
4163    /// that function carried a budget, this test did not go red — it **never
4164    /// returned**: every grant looked like the first, so the pass started
4165    /// runners forever inside poll 1. That is the runaway-runner failure exactly
4166    /// as an operator would meet it, and it is why the budget exists.
4167    ///
4168    /// With the budget in place the same injection fails cleanly and says what
4169    /// happened: `poll 2 … left: 2, right: 1`. Both measurements were run
4170    /// before this assertion was written.
4171    #[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        // Five jobs finish while three longer jobs keep their runners busy.
4214        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    /// The other half of the measurement above: the loop must terminate even
4236    /// when the attempt set never catches up with it.
4237    ///
4238    /// Dropping the in-flight term made
4239    /// `three_polls_of_one_still_queued_run_yield_exactly_one_attempt` hang
4240    /// rather than fail — the loop had one stopping condition and it was the one
4241    /// the bug removed. A launcher whose journal write has not landed presents
4242    /// exactly the same shape without any bug at all, so the budget in
4243    /// [`Reconciler::start_runners`] bounds the pass structurally. This is what
4244    /// asserts the bound is really there.
4245    #[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    /// The host-wide ceiling must hold across policies even when the launcher
4273    /// lags, and the per-policy budget alone does not reach that case.
4274    ///
4275    /// Review found this, with this file's own `forgetful` fixture and one more
4276    /// policy: the budget bounds *each policy's* loop to its own first grant,
4277    /// but policy B's first grant is computed from a set that does not yet
4278    /// contain policy A's launches, so B's bound is itself too large. Two
4279    /// policies on a host of three started **six** runners --
4280    /// `host_capacity=3, started=6, launches=6` -- with the lock held correctly
4281    /// throughout. Serialisation was never the problem; the arithmetic under it
4282    /// was reading a stale set.
4283    #[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    /// Finding 1: an attempt set that cannot be read is not an empty one.
4318    ///
4319    /// `attempts()` used to be infallible, which left `e3` — reading a journal
4320    /// off a disk — a choice between panicking and answering `vec![]`. The
4321    /// second is silent and catastrophic: an empty set is indistinguishable from
4322    /// an idle host, so a transient read failure reads as "nothing is running"
4323    /// and the pass allocates the whole machine for jobs already being served.
4324    ///
4325    /// The contrast is the assertion. Identical host, identical demand,
4326    /// identical policy; the only difference is whether the launcher can answer.
4327    #[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        // The same everything, with a launcher that can answer.
4358        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    /// Finding 3: a cleanup that can never succeed was an invisible permanent
4371    /// loop.
4372    ///
4373    /// `if …clean(…).await.is_ok()` had no `else`, so a runtime directory that
4374    /// could not be removed was retried on every poll with no event, no counter
4375    /// and no report field. It wedges no capacity — a terminal attempt already
4376    /// stopped counting — but `clean` returns a `Result` precisely so the caller
4377    /// can say something, and this module's organising principle is the things
4378    /// that go wrong silently.
4379    #[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        // The reason is the variant, never the detail: the fixture's failure
4414        // carries free text and none of it reaches the event.
4415        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    /// A cleanup that keeps failing is retried with per-attempt exponential
4428    /// backoff rather than on every pass, and a success forgets the backoff.
4429    #[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        // Inside the first delay: not tried, so nothing new to report.
4452        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        // The second delay is twice the first.
4459        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        // The delay never exceeds the ceiling, however many failures accrue.
4469        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    /// N2: an unreadable attempt set makes a scale-down inconclusive, not empty.
4484    ///
4485    /// Making `attempts()` fallible closed this everywhere the allocation path
4486    /// touches, and left it open in the one place that returns a different type:
4487    /// `scale_down` answered `ScaleDownReport::default()`, which is all zeros
4488    /// and byte-for-byte identical to an idle host with nothing to reclaim. The
4489    /// two mean opposite things — "there was nothing to remove" against "we
4490    /// cannot see what there was".
4491    ///
4492    /// Measured as the sibling test measures it: identical host, identical
4493    /// attempts, identical policy, and the only difference is whether the
4494    /// launcher can answer.
4495    #[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        // The same everything, with a launcher that can answer.
4527        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    /// Finding 7: the lower arm of the clamp, driven through the reconciler.
4540    ///
4541    /// `demand_below_min_capacity_starts_nothing_in_v1` runs `demand = 0`
4542    /// against `min_capacity = 0`, which is *at* the floor and never raises
4543    /// `desired` — the assertion held for a reason unrelated to the boundary it
4544    /// named. D7 fixes `min` at 0 for v1, but `AutoscaleConfig::new` accepts
4545    /// `min > 0` today, so the path is representable and was undriven.
4546    #[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    // =======================================================================
4583    // Capacity, at the boundaries
4584    // =======================================================================
4585
4586    #[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        // D7 fixes `min_capacity` at 0, so "below the floor" is "no demand", and
4609        // the product requirement it satisfies is "no idle runners when unused".
4610        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        // Four slots held by *another* policy on a host of six: this policy is
4673        // allowed five and gets two.
4674        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        // "No demand means zero runner processes and zero attempts out of
4707        // terminal state."
4708        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    // =======================================================================
4729    // Live host capacity, including changes while a pass is creating runners.
4730    // =======================================================================
4731
4732    #[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        // Two jobs finish; one busy job still owns a slot.
4758        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    // =======================================================================
4877    // D9 under concurrency: the other silent failure
4878    // =======================================================================
4879
4880    /// `e1`'s Definition of Done: *"Two policies on one host with
4881    /// `host_capacity` smaller than the sum of their `max_capacity` values never
4882    /// exceed `host_capacity` under concurrent reconciliation — asserted under
4883    /// simulated lock contention, with no duplicate runners."*
4884    ///
4885    /// The contention is simulated by [`FakeLauncher::with_yields`], which puts
4886    /// executor yield points *between* the launcher reading the attempt set and
4887    /// recording the new one. Without serialisation both tasks read a headroom
4888    /// of three and both spend it.
4889    ///
4890    /// # Watched failing before it was made to pass
4891    ///
4892    /// Granting from this lock without taking the inner mutex — leaving every
4893    /// counter and every yield point exactly as they are — fails this assertion
4894    /// with `left: 4, right: 3`: four runners on a host of three, from two
4895    /// policies each individually inside their own `max_capacity`. The control
4896    /// test below keeps that measurement standing permanently by running the
4897    /// same body against [`NoLock`].
4898    #[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    /// The control for the test above: the same body with the lock removed.
4926    ///
4927    /// It exists so that the assertion above cannot pass vacuously. If a future
4928    /// change makes the unserialised path safe by accident — a launcher that
4929    /// records synchronously, say — this test goes red and says so, rather than
4930    /// the other one silently proving nothing.
4931    #[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    /// Two policies, one host of three, each allowed three, reconciled at once.
4946    ///
4947    /// Returns `(launches, live attempts)`.
4948    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    // =======================================================================
4991    // D19: monitor-only
4992    // =======================================================================
4993
4994    /// `e1`'s Definition of Done: *"A `MonitorOnly` policy under maximum demand
4995    /// starts zero runners and issues no demand request."*
4996    ///
4997    /// Driven through `c4`'s real gateway fake so that "issued no demand
4998    /// request" is asserted against the thing that would have issued it, rather
4999    /// than against this module's own bookkeeping. `FakeGithub` records every
5000    /// call it is asked to make.
5001    #[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    /// D19 says a monitor-only policy is *"skipped entirely by
5051    /// reconciliation"*, and "entirely" is the load-bearing word once two
5052    /// policies share a target.
5053    ///
5054    /// This defect was found by review rather than by the test above, which
5055    /// cannot see it: there, the monitor-only policy is the *only* policy, so
5056    /// nobody polls its target and the lookup finds nothing. Give it a
5057    /// repository an autoscale policy already polls and the lookup succeeds —
5058    /// and the monitor-only policy was then allocated for and had a demand
5059    /// observation emitted on its behalf. It still started nothing, because
5060    /// `may_start_runners` is false for it and `HostAllocator` refuses it by
5061    /// name, so no ceiling was ever at risk. It simply was not skipped.
5062    ///
5063    /// Removing the `owns_runners` guard from the allocation loop was watched
5064    /// failing this test before it was restored:
5065    /// `a monitor-only policy was allocated for: [… limiting_factor:
5066    /// MonitorOnly]`.
5067    #[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        // The specification requires this to be asserted rather than deduced
5124        // from `max_capacity` being absent. `HostAllocator` reports it by name,
5125        // and this loop reaches that arm through `owns_runners`, which is a
5126        // question about the mode.
5127        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    // =======================================================================
5146    // The surplus runner, and busy protection
5147    // =======================================================================
5148
5149    /// `e1`'s Definition of Done: *"A surplus attempt that receives no job
5150    /// reaches a terminal state recorded as an idle exit, is cleaned, and is not
5151    /// reported as a failure."*
5152    #[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    /// `e1`'s Definition of Done: *"A scale-down request with a busy attempt
5203    /// removes nothing and leaves the attempt `busy`."*
5204    #[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        // And the domain refuses it from the other side too, by name, so a
5245        // future caller that tried anyway would not get a generic transition
5246        // error.
5247        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    // =======================================================================
5256    // The schedule
5257    // =======================================================================
5258
5259    #[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    /// `e1`'s Definition of Done: *"The poll interval … increases under a
5285    /// rate-limit signal, and the increase is visible in emitted state rather
5286    /// than silent."*
5287    #[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    /// Constraint on this task: *"Read `RefreshState::retry_delay` as an
5313    /// absolute floor, not an addend."*
5314    #[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        // Five successive answers, each carrying the window that is *left*.
5327        // An addend would compound: 360, 660, 960 … and look like a hang.
5328        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        // And when GitHub asks for less than the interval, the interval wins:
5339        // the floor is never crossed to catch up.
5340        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        // Doubling, from the nominal interval.
5396        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        // Jitter widens the delay rather than narrowing it, so a fleet of
5410        // agents does not retry in lockstep.
5411        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        // Recovery resets the run with no bookkeeping of its own.
5419        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        // "We cannot tell" is not "not yet".
5447        assert!(!OfflineState::new(9, Duration::from_secs(60)).has_outlasted_the_queue());
5448    }
5449
5450    // =======================================================================
5451    // Idle polling and the shared quota
5452    // =======================================================================
5453
5454    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    /// The owner's fourth requirement: when the shared quota runs low, stretch
5513    /// the interval automatically, and say so.
5514    #[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        // Capacity zero would refuse the policy outright; a host already full
5678        // is the ordinary way matched demand goes unserved for a pass.
5679        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    // =======================================================================
5816    // Offline, end to end
5817    // =======================================================================
5818
5819    /// `e1`'s Definition of Done: *"An unreachable GitHub yields `offline`, zero
5820    /// new runners, retained existing processes, and jittered backoff; recovery
5821    /// resumes polling and does not double-count a job that was already being
5822    /// served."*
5823    #[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        // Recovery: two jobs are queued, but only the starting runner can
5859        // cover them. The busy runner consumes capacity and serves other work.
5860        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    /// One unreachable target must not idle a whole host.
5877    ///
5878    /// The failure that decides the *schedule* is the most severe across every
5879    /// target polled — backing the whole loop off during an outage is the safe
5880    /// error, and `f3` runs one reconciler per target anyway, so in production
5881    /// the two are usually the same thing. What must not follow from that is
5882    /// refusing to serve a policy whose own target answered perfectly well, and
5883    /// the two are easy to conflate because the offline reading is sitting in
5884    /// the same map.
5885    #[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        // And the schedule takes the worse of the two.
5911        assert!(report.is_offline());
5912        assert_eq!(report.next_poll.pace, PollPace::Offline { consecutive: 1 });
5913    }
5914
5915    /// The 24-hour bound has to be reachable in production, not only in a unit
5916    /// test of [`OfflineState`].
5917    ///
5918    /// This was a real gap: the reconciler built its offline state from the
5919    /// back-off count alone, so `offline_for` was always `None` and
5920    /// [`OfflineState::has_outlasted_the_queue`] could never be true outside a
5921    /// test that constructed the value by hand. An operator whose agent had been
5922    /// offline for two days would have been told that an outage longer than 24
5923    /// hours *would* lose queued work, in the future tense, having already lost
5924    /// it.
5925    ///
5926    /// The elapsed time is measured from the first poll of the run rather than
5927    /// derived from the interval, because the back-off doubles and the two
5928    /// diverge immediately.
5929    #[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        // The outage begins.
5949        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        // A day and a minute later, still unreachable.
5960        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        // Recovery closes the run, so a *later* outage measures from itself
5971        // rather than from the first one.
5972        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    /// Finding 5: the adapter, not the lock underneath it.
5992    ///
5993    /// `d1` covers `LockKind::Allocation` including a contended `acquire_at`
5994    /// with a wait. What that does not reach is this adapter: the
5995    /// `spawn_blocking` wrapper, the collapse of both a refused lock and a
5996    /// panicked blocking task into `AllocationLockBusy`, and — the one that
5997    /// would be silent — whether [`AllocationGuard`] really holds the
5998    /// `HostLock`, since dropping it is the only release there is. A guard that
5999    /// dropped the lock on the way out would make every acquisition succeed and
6000    /// the ceiling would hold by luck.
6001    ///
6002    /// The original disclosure said this needed a real filesystem and was
6003    /// therefore expensive. `AppPaths::rooted_at` plus `tempfile` — already a
6004    /// non-dev dependency of this crate — makes it about fifteen lines, so the
6005    /// reason was weaker than stated.
6006    #[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        // `f3` wires the log sink and `g2`'s buffer at once, and an event that
6034        // reached only one of them would be an activity view missing lines the
6035        // log file has, or the reverse.
6036        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    // =======================================================================
6052    // Budget: the repository list, and the per-target poll
6053    // =======================================================================
6054
6055    #[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        // Every poll inside the window reuses the list.
6072        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        // Past it, exactly one more.
6086        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        // `04-subsystem-contracts.md` prices a *target*. A loop that spent per
6108        // policy would exceed the projection `f2` admitted the configuration
6109        // against, silently.
6110        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        // A job explicitly requiring the unavailable isolated selector cannot
6257        // be served by the native sibling either.
6258        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        // Domain constructors permit extra selector-shaped labels. Routing
6363        // depends on all required labels and unique ownership, not their shape.
6364        // The store separately rejects sibling selector reuse on write/load.
6365        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    // =======================================================================
6422    // Failure paths
6423    // =======================================================================
6424
6425    #[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    /// The host-fitness preflight: while a required host check fails, the pass
6460    /// still decides what it would start, but nothing reaches the inner
6461    /// launcher -- so nothing is registered with GitHub -- and the event names
6462    /// `host_unfit`. Clearing the flag lets the next pass start runners.
6463    #[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        // Polling a scope nobody chose would report a demand number for the
6577        // wrong set of repositories, which is worse than reporting nothing.
6578        #[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    // =======================================================================
6617    // What the events may carry
6618    // =======================================================================
6619
6620    /// One value of every [`LifecycleEvent`] variant.
6621    ///
6622    /// Hand-written, and what keeps it honest is the wildcard-free `match` in
6623    /// [`LifecycleEvent::name`]: adding a variant stops that compiling and puts
6624    /// the author here. The same residual `b1` records for `FailureReason::ALL`
6625    /// applies — an author who writes the `name` arm and forgets this list gets
6626    /// a green suite with the variant unscanned.
6627    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    /// `e1`'s Definition of Done: *"No emitted event contains a token, a JIT
6696    /// blob, or a credential header."*
6697    ///
6698    /// Asserted by rendering every variant and putting the result through `d1`'s
6699    /// own scrubber: if any of it looked like a credential to the redactor that
6700    /// guards the log file, the round trip would not be the identity. The
6701    /// positive control at the bottom is what stops that assertion passing
6702    /// because the scrubber is asleep.
6703    #[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        // The control: the scrubber is awake, and would have caught a credential
6726        // had one been there.
6727        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        // The names `TracingEvents` writes. Kept beside the sink rather than
6740        // derived from it, because a derived list would move with the code and
6741        // assert nothing.
6742        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    // =======================================================================
6800    // The two tripwires
6801    // =======================================================================
6802
6803    /// One source file's production half, with comment lines dropped.
6804    ///
6805    /// Both exclusions are `c4`'s, and load-bearing for the same reasons. The
6806    /// **test module** goes because the tests in it legitimately name the shapes
6807    /// they forbid — this module's own positive control is a literal
6808    /// `async fn acquire_jobs`, which would accuse the file of the thing it is
6809    /// proving it does not do. The **comments** go because this module's
6810    /// documentation explains the seam at length and has to name what does not
6811    /// exist in order to say why; a scan that forbade the explanation is a scan
6812    /// that gets the explanation deleted.
6813    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    /// This file's own production half.
6825    fn this_file_above_its_tests_without_prose() -> String {
6826        production_half_of(include_str!("reconcile.rs"))
6827    }
6828
6829    /// The one normalisation both halves of the scan use.
6830    ///
6831    /// # This is a second copy of `crates/github/src/demand.rs`, deliberately
6832    ///
6833    /// `production_half_of`, this function, [`FORBIDDEN`] and
6834    /// `forbidden_shape_in` together duplicate `demand.rs:1530-1619`. Sharing
6835    /// them would mean putting them in `crates/testkit`, which `e1` does not
6836    /// own, so the copy was the only option available to this task.
6837    ///
6838    /// **It is worth consolidating later, and here is the specific hazard.**
6839    /// The last defect in `c4`'s copy was two spellings of "the same"
6840    /// normalisation drifting apart — the haystack lower-cased and the needle
6841    /// not — which made three of its seven assertions vacuously true from the
6842    /// day they were written. Two copies is the same hazard one level up. The
6843    /// mitigation inside *this* copy is that one function serves both the scan
6844    /// and its positive control, so a normaliser that stops matching fails the
6845    /// control loudly rather than passing the scan silently; what that cannot
6846    /// catch is this copy and `c4`'s diverging from each other.
6847    fn normalise_for_scan(text: &str) -> String {
6848        text.to_ascii_lowercase().replace(['_', ' '], "")
6849    }
6850
6851    /// The Actions-service call this design has no equivalent of, plus the
6852    /// shapes an implementer would invent in its place.
6853    ///
6854    /// Spelled in halves so that no needle ever appears whole in the text being
6855    /// scanned, and keyed to `fn`/`struct` so that the prose above may keep
6856    /// explaining why there is no reservation. `c4` records both trades at
6857    /// length; this list is its counterpart one layer up. Note that the
6858    /// allocation lock's own `fn acquire` is deliberately *not* matched: the
6859    /// needle is `acquire`-a-**job**, and a lock is not one.
6860    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    /// `e1`'s Definition of Done: *"No reservation, claim, lease, or acquisition
6880    /// call exists in the crate; a test or review note records that this is
6881    /// deliberate rather than missing."*
6882    ///
6883    /// **Deliberate, not missing.** The scale-set model let a listener call
6884    /// `AcquireJobs` to claim an assignment before scaling; the REST path has no
6885    /// equivalent, so demand is advisory and two hosts serving the same labels
6886    /// can both start a runner for one queued run. Adding a local reservation
6887    /// table would not remove that — the other host cannot see it — it would
6888    /// only hide the surplus case from the tests that measure it. The three
6889    /// controls that actually bound it are host-scoped routing labels,
6890    /// `max_capacity`, and `host_capacity`, and the last two are enforced in
6891    /// this file.
6892    ///
6893    /// The scan is a tripwire on the obvious shape rather than a proof: a
6894    /// reservation reached through a trait method or a differently-named helper
6895    /// would walk past it. Review is the primary control, exactly as `c4` states
6896    /// for its own copy.
6897    ///
6898    /// # It scans the crate, because the bullet says "in the crate"
6899    ///
6900    /// It used to scan this file alone while quoting a crate-wide claim, which
6901    /// left `lifecycle.rs` — `e3`, the launcher, and by far the likeliest place
6902    /// for someone to "fix" the surplus-runner case with a local lease — covered
6903    /// by nothing. Reading another owner's file is not editing it, so ownership
6904    /// was never the obstacle.
6905    ///
6906    /// The walk below is `c4`'s, and it **recurses** for the reason `c4`
6907    /// records: a module directory (`src/reconcile/mod.rs`) arrives as an entry
6908    /// that does not end in `.rs`, so a flat filter drops it and takes every
6909    /// file underneath with it, leaving the scan passing over files it covers
6910    /// by nothing at all. The listed-versus-on-disk assertion is what stops
6911    /// `SOURCES` going stale the moment `e2` or `e3` adds a module.
6912    #[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                // `/`-joined, which is what `include_str!` takes on every
6945                // platform, so the two sides compare directly.
6946                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        // The control: the scan can see a shape when there is one, through the
6986        // same matcher the loop above uses.
6987        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    /// This module **applies** `b1`'s label predicate and implements none of it.
6994    ///
6995    /// The counterpart to `c4`'s scan over `crates/github/src/demand.rs`, and it
6996    /// checks the opposite thing, because the two modules sit on opposite sides
6997    /// of the same seam. `c4` builds a `RunsOn` per queued job and must name no
6998    /// `RoutingLabels`; this module holds the policy whose labels decide, so it
6999    /// must call `RoutingLabels::tally` and must not re-derive what that call
7000    /// answers.
7001    ///
7002    /// So the scan is in two halves:
7003    ///
7004    /// * **Present.** `DemandTally` has to appear, because [`demand_for`]
7005    ///   returns one. A production half that named it nowhere would mean the
7006    ///   filtering had been dropped and every queued job in a watched repository
7007    ///   was driving this policy toward `max_capacity` again.
7008    /// * **Absent.** The vocabulary of a *second* implementation. `b1` names the
7009    ///   three outcomes of matching one job; this module consumes the aggregate
7010    ///   and never a single job's verdict, so naming `RunsOnMatch` or
7011    ///   `UnresolvableRunsOn` here means a `match` on an outcome that
7012    ///   `RoutingLabels::tally` has already decided — which is how two copies of
7013    ///   a predicate start.
7014    ///
7015    /// Like the needles in `nothing_in_this_module_reserves_or_claims_a_job`,
7016    /// this is a tripwire on the obvious shape rather than a proof: a hand-rolled
7017    /// comparison of raw label strings that never names a `policy` type would
7018    /// walk past it. Stated rather than implied, for the same reason it is
7019    /// stated there.
7020    #[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    /// The demand this module clamps is the *matched* count, and a job this host
7045    /// cannot serve is not demand.
7046    ///
7047    /// The behaviour the whole reversal was for, asserted end to end through
7048    /// `demand_for` rather than through `b1`'s predicate in isolation: a policy
7049    /// carrying this host's labels, a reading holding some of its jobs and some
7050    /// of somebody else's, and the three counts kept apart.
7051    #[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    /// A repository target reads its own repository; an organization target
7084    /// reads the whole scope.
7085    #[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        // The owner decision accepts that a repository whose jobs only target
7116        // `ubuntu-latest` still drives its policy toward `max_capacity`. What
7117        // stops that being unbounded is exactly what stops any other demand
7118        // being unbounded, which is asserted here rather than assumed.
7119        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}