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 on a bounded interval (default 60 s, hard floor 30 s per target) and
12//!   *increases* the delay under a rate-limit signal, never decreases it to
13//!   catch up.
14//! * [`RepositoryCache`] — the per-organization repository list, refreshed on
15//!   an interval materially slower than the demand poll. Re-listing an
16//!   organization at demand-poll frequency is what exhausts the shared budget
17//!   the paragraph above exists to protect.
18//! * [`Reconciler::reconcile`] — the allocation pass. It re-reads the attempt
19//!   set **under the host-wide allocation lock, once per runtime created**, so
20//!   two policies reconciling concurrently cannot both spend the same headroom.
21//! * [`LifecycleEvent`] — what `g2` and the local log sink see. Every field is
22//!   an identifier, a count, an enumerated state or a duration; nothing free
23//!   text, and nothing that came off the wire.
24//!
25//! # There is no acquisition step, and none may be added
26//!
27//! The scale-set model called `AcquireJobs` to reserve an assignment before
28//! scaling. The REST path has no equivalent (`01-current-architecture.md`, edge
29//! case 6), so demand is **advisory**. Two consequences are load-bearing here
30//! and neither is a defect:
31//!
32//! 1. **A surplus runner is an accepted outcome.** Another host serving the
33//!    same labels may take the job first; this host's runner then finds no work
34//!    and exits on its idle timeout, having cost one capacity slot and one cold
35//!    start. That terminal outcome is
36//!    [`AttemptOutcome::ExitedIdleWithoutWork`], is cleaned like any other, and
37//!    is counted apart from a failure — see [`ReconcileReport::idle_exits`].
38//! 2. **The same job is still `queued` on the next poll** while its runner
39//!    starts. The `- active_owned_runners` term in
40//!    [`HostAllocator::allocate`] is what stops that from starting a second
41//!    runner, and then a third. This module's only job in that arithmetic is to
42//!    hand the allocator the attempt set the host actually holds — which is why
43//!    [`RunnerLauncher`] supplies both the attempts and the launch, from one
44//!    supply point, for the reason `b1` gives at
45//!    [`HostAllocator::from_attempts`].
46//!
47//! `tests::nothing_in_this_module_reserves_or_claims_a_job` is a tripwire on the
48//! obvious shape of a reservation being added back.
49//!
50//! # Demand is measured in JOBS, filtered by this policy's routing labels
51//!
52//! `02-target-architecture.md` writes the formula as *"queued jobs whose
53//! `runs-on` matches this policy's routing labels"*, and that is now exactly
54//! what this module clamps. It was not always: an earlier owner decision priced
55//! the per-run job listing out and left this module clamping a count of
56//! **runs**, unfiltered. `crates/github/src/demand.rs` records that decision,
57//! why it was reversed, and what the reversal costs in requests.
58//!
59//! What the reversal means here is two changes to one line:
60//!
61//! * **A run of eight jobs is now eight units of demand, not one.** Under the
62//!   run count a matrix filled one runner per poll while the rest of the matrix
63//!   waited, so a host configured for ten concurrent runners served an
64//!   eight-job matrix nearly serially. That was the defect that forced the
65//!   decision back.
66//! * **A job this host cannot serve is no longer demand.** A repository whose
67//!   jobs target `ubuntu-latest`, or another host's `rm-<host>-…` label, used to
68//!   drive its policy toward `max_capacity` and start runners that idled until
69//!   they timed out. The gateway now returns each queued job's `runs-on`, so
70//!   `b1`'s predicate finally has its input.
71//!
72//! **The predicate is still `b1`'s and the input is still `c4`'s.** This module
73//! calls [`runner_manager_domain::policy::RoutingLabels`]'s `tally` and
74//! implements no label comparison of its own;
75//! `tests::the_label_predicate_is_b1s_and_this_module_only_applies_it` scans
76//! this file's own source and fails if a second implementation grows here, which
77//! is the same tripwire `c4` carries one layer down.
78//!
79//! # The filtering happens here rather than in the gateway, on purpose
80//!
81//! One target can be watched by more than one policy, each with its own routing
82//! labels, and [`Reconciler`]'s `poll_targets` deliberately polls a target **once**
83//! for all of them. A gateway that filtered would have to be told whose labels to
84//! filter by, which would make the poll per-policy and multiply its request cost
85//! by the number of policies sharing the target — the budget model prices a
86//! target, not a policy. So the gateway returns the jobs and each policy tallies
87//! them against its own labels.
88//!
89//! # What is still approximate
90//!
91//! The surplus-runner path above is narrowed by this change and not closed. A
92//! `runs-on: ${{ matrix.runner }}` cannot be resolved without evaluating the
93//! workflow, so `b1` reports it as unresolvable: never counted as demand, never
94//! silently dropped, and surfaced through
95//! [`LifecycleEvent::DemandObserved::unresolvable`] so that an operator can see
96//! a workflow this host will never serve sitting in the queue. And demand
97//! remains advisory — another host may still take a job this one started a
98//! runner for — which is what the two ceilings bound.
99//!
100//! # What is testable without a network, a filesystem, or a process
101//!
102//! All of it. [`DemandSource`], [`RunnerLauncher`], [`AllocationLock`],
103//! [`RepositoryDirectory`], [`Jitter`] and [`EventSink`] are ports;
104//! [`GatewayDemand`], [`FileAllocationLock`], [`RandomJitter`] and
105//! [`TracingEvents`] are the production adapters, and every one of them is a
106//! thin shell over a decision made in this file.
107
108use std::collections::{BTreeMap, BTreeSet};
109use std::fmt;
110use std::sync::atomic::{AtomicU64, Ordering};
111use std::sync::{Arc, Mutex};
112use std::time::Duration;
113
114use runner_manager_domain::attempt::{AttemptOutcome, AttemptState, FailureReason, RunnerAttempt};
115use runner_manager_domain::capacity::{Allocation, HostAllocator, LimitingFactor};
116use runner_manager_domain::model::{
117    AttemptId, Clock, Host, Org, OwnerRepo, PolicyId, RefreshInterval, ScaleTarget, Timestamp,
118};
119use runner_manager_domain::policy::{DemandTally, ScalePolicy};
120use runner_manager_github::demand::{DemandGateway, QueuedDemand, demand_requests_per_poll};
121use runner_manager_github::rest::{
122    ActivityScope, CancelToken, InventoryError, RateLimitKind, RefreshState,
123};
124
125// ---------------------------------------------------------------------------
126// Constants
127// ---------------------------------------------------------------------------
128
129/// How much slower than the demand poll the per-organization repository list is
130/// refreshed.
131///
132/// There is no organization-wide workflow-runs endpoint, so an organization
133/// target costs one demand request **per repository the App is installed on**
134/// (`crates/github/src/demand.rs`). Discovering that repository list costs
135/// requests of its own, and it is the one input to a demand poll that changes on
136/// a human timescale: repositories are added to an installation by hand, not by
137/// a workflow starting.
138///
139/// Thirty polls is 30 minutes at the 60-second default and 15 at the 30-second
140/// floor — slow enough that the list is a rounding error against the demand
141/// requests it scopes, and fast enough that a repository added to the
142/// installation starts being served within one coffee break rather than at the
143/// next restart.
144pub const REPOSITORY_LIST_REFRESH_MULTIPLE: u32 = 30;
145
146/// The longest the *unjittered* offline back-off may grow to.
147///
148/// A back-off is a safety mechanism, and an unclamped one is an outage with
149/// extra steps. Fifteen minutes matches
150/// [`runner_manager_github::rest::MAX_RATE_LIMIT_BACKOFF`], which is the other
151/// place in this product where a delay is allowed to grow, and it is far inside
152/// the 24-hour bound at which GitHub cancels the queued jobs this loop exists to
153/// serve.
154pub const MAX_OFFLINE_BACKOFF: Duration = Duration::from_secs(15 * 60);
155
156/// The most the offline back-off is doubled, before the cap applies.
157///
158/// At the 60-second default this reaches [`MAX_OFFLINE_BACKOFF`] on the sixth
159/// consecutive failure, which is roughly half an hour of outage. Past that the
160/// cap holds it flat.
161const MAX_BACKOFF_DOUBLINGS: u32 = 5;
162
163/// How much of the computed back-off is jitter.
164///
165/// Jitter is **added** rather than subtracted, so a back-off never comes out
166/// shorter than the delay it was computed from. Subtractive jitter would let the
167/// first offline poll retry sooner than the nominal interval, which is the
168/// opposite of backing off; it is spelled out because "add jitter" reads as
169/// symmetric and is not.
170const JITTER_RATIO: f64 = 0.5;
171
172/// GitHub cancels a queued job after this long.
173///
174/// `01-current-architecture.md` records the measurement; `03-control-flows.md`
175/// flow 3.3 requires that the offline state **states** it, because an agent
176/// offline for longer than this has lost queued work and the operator cannot
177/// infer that from "offline". [`OfflineState`] is where it is said.
178pub const GITHUB_CANCELS_QUEUED_JOBS_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
179
180/// How long [`FileAllocationLock`] waits for the host-wide allocation lock
181/// before reporting contention.
182///
183/// Contention here is expected rather than exceptional — it is two of this
184/// host's own policies creating runtimes at the same moment — and each hold
185/// lasts only as long as one runtime creation. Waiting a few seconds turns the
186/// common case into a short pause instead of a skipped runner.
187///
188/// # How many of these a poll actually costs
189///
190/// One per runtime created, none for a policy that is granted nothing, and at
191/// most one further hold per policy — the case where the pre-check proposed a
192/// grant and the under-lock re-read found the host had filled up underneath it,
193/// so that hold creates nothing and ends the loop. `(3..=5)` in
194/// `two_policies_reconciling_concurrently_never_exceed_host_capacity` is that
195/// bound with two policies and three runtimes; the deterministic single-policy
196/// case is pinned at exactly one per runtime.
197///
198/// That is worth stating because it did not used to be true and the
199/// difference only shows up here: the budget was checked *after* the lock had
200/// been taken and the attempt set re-read, so a policy granted N runners took
201/// N+1 holds, and `start_runners` ran for every readable autoscale policy
202/// including the zero-demand ones — so an idle host with P policies took P
203/// host-wide locks per poll for nothing. Free under
204/// [`InProcessAllocationLock`]; under [`FileAllocationLock`] each one is a
205/// `spawn_blocking` plus a filesystem lock, with this wait behind it.
206///
207/// [`Reconciler::start_runners`] now pre-checks lock-free and stops as soon as
208/// the budget is spent. The under-lock re-read still decides.
209pub const ALLOCATION_LOCK_WAIT: Duration = Duration::from_secs(5);
210
211// ---------------------------------------------------------------------------
212// What one demand poll produced
213// ---------------------------------------------------------------------------
214
215/// One target's demand poll, as a value this module can decide from.
216///
217/// The failure half is `c3`'s [`RefreshState`] rather than an
218/// [`InventoryError`], for the reason `c3` gives: `InventoryError` owns a
219/// `reqwest::Error` and a `serde_json::Error`, so it is neither `Clone` nor
220/// `PartialEq` and cannot be stored, compared, or rendered. Summarising at the
221/// gateway boundary — exactly once, in [`GatewayDemand`] — is what lets the
222/// whole schedule below be a pure function of values a test can construct.
223///
224/// [`RefreshState::Ready`] never appears in [`PollOutcome::Failed`]:
225/// [`RefreshState::from_error`] cannot produce it, and a demand poll returns a
226/// [`QueuedDemand`] rather than the runner inventory that variant carries.
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub enum PollOutcome {
229    /// GitHub answered. The count may still be a floor — see
230    /// [`QueuedDemand::is_complete`].
231    Ready(QueuedDemand),
232    /// GitHub did not answer, or answered something this loop must slow down
233    /// for.
234    Failed(RefreshState),
235}
236
237impl PollOutcome {
238    /// The demand reading, when there is one.
239    #[must_use]
240    pub const fn reading(&self) -> Option<&QueuedDemand> {
241        match self {
242            Self::Ready(demand) => Some(demand),
243            Self::Failed(_) => None,
244        }
245    }
246
247    /// The failure, when there is one.
248    #[must_use]
249    pub const fn failure(&self) -> Option<&RefreshState> {
250        match self {
251            Self::Failed(state) => Some(state),
252            Self::Ready(_) => None,
253        }
254    }
255
256    /// Whether GitHub could not be reached at all, as opposed to answering
257    /// something unwelcome.
258    ///
259    /// The whole of flow 3.3 turns on this distinction: an outage retains
260    /// running runners and backs off, while a rejection is a configuration
261    /// problem that waiting does not fix.
262    #[must_use]
263    pub fn is_offline(&self) -> bool {
264        matches!(self, Self::Failed(RefreshState::Offline))
265    }
266}
267
268/// Where this loop gets its demand from.
269///
270/// A port rather than a direct [`DemandGateway`] dependency, because the two
271/// failures this loop must handle differently — unreachable and rate-limited —
272/// are distinguished by [`RefreshState`], and a test that wants to drive the
273/// offline path should not have to manufacture a `reqwest::Error` to do it.
274/// [`GatewayDemand`] is the one adapter that talks to `c4`.
275#[async_trait::async_trait]
276pub trait DemandSource: fmt::Debug + Send + Sync {
277    /// Queued runs across `scope`, or why there are none to report.
278    async fn poll(&self, scope: &ActivityScope) -> PollOutcome;
279}
280
281/// [`DemandSource`] over `c4`'s [`DemandGateway`].
282///
283/// Holds the [`CancelToken`] so that a shutting-down daemon can withdraw a poll
284/// that is already blocked on a socket; `f3` keeps a clone and cancels it.
285#[derive(Debug)]
286pub struct GatewayDemand<G> {
287    gateway: G,
288    cancel: CancelToken,
289}
290
291impl<G: DemandGateway> GatewayDemand<G> {
292    #[must_use]
293    pub const fn new(gateway: G, cancel: CancelToken) -> Self {
294        Self { gateway, cancel }
295    }
296
297    #[must_use]
298    pub const fn gateway(&self) -> &G {
299        &self.gateway
300    }
301}
302
303#[async_trait::async_trait]
304impl<G: DemandGateway + 'static> DemandSource for GatewayDemand<G> {
305    async fn poll(&self, scope: &ActivityScope) -> PollOutcome {
306        match self.gateway.queued_demand(scope, &self.cancel).await {
307            Ok(demand) => PollOutcome::Ready(demand),
308            // The one place an `InventoryError` is summarised. `c3` owns the
309            // mapping — including transport-to-`Offline`, which is what flow
310            // 3.3 branches on — so this loop never re-decides it.
311            Err(error) => PollOutcome::Failed(RefreshState::from_error(&error)),
312        }
313    }
314}
315
316// ---------------------------------------------------------------------------
317// The repository list, cached
318// ---------------------------------------------------------------------------
319
320/// Which repositories an organization installation reaches.
321///
322/// `f1` already holds this, from
323/// [`runner_manager_github::AuthenticatedClient::discover_installations`]. It is
324/// a port here so that [`RepositoryCache`] can be tested for the property that
325/// matters — how *often* it asks — without a network.
326#[async_trait::async_trait]
327pub trait RepositoryDirectory: fmt::Debug + Send + Sync {
328    /// The repositories this credential reaches in `org`.
329    ///
330    /// # Errors
331    /// Anything the underlying gateway reports.
332    async fn repositories(&self, org: &Org) -> Result<Vec<OwnerRepo>, InventoryError>;
333}
334
335#[derive(Debug, Clone)]
336struct CachedRepositories {
337    repositories: Vec<OwnerRepo>,
338    fetched_at: Timestamp,
339}
340
341/// The per-organization repository list, refreshed far more slowly than demand.
342///
343/// # Why this is not just "call the directory each poll"
344///
345/// An organization demand poll already costs one request per repository. Adding
346/// the installation listing to every poll makes the *scoping* of a poll cost
347/// requests on the same schedule as the poll itself, which is how a
348/// ten-repository organization at the 30-second floor stops fitting inside the
349/// half-of-5,000 allowance `f2` admits targets against. The repository list is
350/// also the one input that changes on a human timescale, so refreshing it
351/// [`REPOSITORY_LIST_REFRESH_MULTIPLE`] times more slowly costs nothing real.
352///
353/// # A repository target never consults the directory at all
354///
355/// Its scope is itself. That is not an optimisation; asking an installation
356/// listing which repositories a single named repository covers would be asking a
357/// question whose answer is already in the target.
358#[derive(Debug)]
359pub struct RepositoryCache {
360    directory: Arc<dyn RepositoryDirectory>,
361    clock: Arc<dyn Clock>,
362    ttl: Duration,
363    entries: Mutex<BTreeMap<Org, CachedRepositories>>,
364    lookups: AtomicU64,
365}
366
367impl RepositoryCache {
368    /// Build a cache whose refresh interval is `poll` slowed by
369    /// [`REPOSITORY_LIST_REFRESH_MULTIPLE`].
370    #[must_use]
371    pub fn new(
372        directory: Arc<dyn RepositoryDirectory>,
373        clock: Arc<dyn Clock>,
374        poll: RefreshInterval,
375    ) -> Self {
376        let ttl = Duration::from_secs(u64::from(poll.as_secs()))
377            .saturating_mul(REPOSITORY_LIST_REFRESH_MULTIPLE);
378        Self {
379            directory,
380            clock,
381            ttl,
382            entries: Mutex::new(BTreeMap::new()),
383            lookups: AtomicU64::new(0),
384        }
385    }
386
387    /// How long a cached repository list is reused for.
388    #[must_use]
389    pub const fn ttl(&self) -> Duration {
390        self.ttl
391    }
392
393    /// How many times the underlying directory was actually asked.
394    ///
395    /// Measured rather than assumed, for the reason `c4` measures its own
396    /// request count: a budget nothing counts is a table in a document.
397    #[must_use]
398    pub fn lookups(&self) -> u64 {
399        self.lookups.load(Ordering::SeqCst)
400    }
401
402    /// The scope one demand poll of `target` covers.
403    ///
404    /// # Errors
405    /// Whatever the directory reported, for an organization target whose list is
406    /// stale or absent. A repository target cannot fail.
407    pub async fn scope_for(&self, target: &ScaleTarget) -> Result<ActivityScope, InventoryError> {
408        match target {
409            ScaleTarget::Repository(repository) => {
410                Ok(ActivityScope::repository(repository.clone()))
411            }
412            ScaleTarget::Organization(org) => {
413                let repositories = self.repositories_of(org).await?;
414                Ok(ActivityScope::organization(org.clone(), repositories))
415            }
416        }
417    }
418
419    async fn repositories_of(&self, org: &Org) -> Result<Vec<OwnerRepo>, InventoryError> {
420        let now = self.clock.now();
421        if let Some(fresh) = self.fresh_entry(org, now) {
422            return Ok(fresh);
423        }
424
425        // The directory call is deliberately made with no lock held. Two
426        // concurrent misses can therefore both ask, which costs one extra
427        // listing on the poll that follows a restart; holding a `std::sync`
428        // mutex across an `await` would cost a blocked executor thread and, on
429        // a current-thread runtime, a deadlock. The cheaper mistake is the one
430        // that spends a request.
431        let repositories = self.directory.repositories(org).await?;
432        self.lookups.fetch_add(1, Ordering::SeqCst);
433        self.store(org.clone(), repositories.clone(), now);
434        Ok(repositories)
435    }
436
437    fn fresh_entry(&self, org: &Org, now: Timestamp) -> Option<Vec<OwnerRepo>> {
438        let entries = self.entries.lock().ok()?;
439        let entry = entries.get(org)?;
440        let age = now.signed_duration_since(entry.fetched_at).to_std().ok()?;
441        (age < self.ttl).then(|| entry.repositories.clone())
442    }
443
444    fn store(&self, org: Org, repositories: Vec<OwnerRepo>, fetched_at: Timestamp) {
445        if let Ok(mut entries) = self.entries.lock() {
446            entries.insert(
447                org,
448                CachedRepositories {
449                    repositories,
450                    fetched_at,
451                },
452            );
453        }
454    }
455}
456
457// ---------------------------------------------------------------------------
458// Jitter
459// ---------------------------------------------------------------------------
460
461/// The randomness in the offline back-off, as a port.
462///
463/// Flow 3.3 requires jittered back-off, and a jittered delay is by construction
464/// not reproducible — so the source of the randomness is a port, and every test
465/// below asserts the *bounds* of the delay against a fixed fraction rather than
466/// asserting a number it could only have got by running the generator.
467pub trait Jitter: fmt::Debug + Send + Sync {
468    /// A fraction in `[0.0, 1.0)`. Values outside that range are clamped by the
469    /// caller, so an implementation cannot lengthen a back-off without bound.
470    fn fraction(&self) -> f64;
471}
472
473/// The production source.
474#[derive(Debug, Clone, Copy, Default)]
475pub struct RandomJitter;
476
477impl Jitter for RandomJitter {
478    fn fraction(&self) -> f64 {
479        rand::random::<f64>()
480    }
481}
482
483/// A fixed fraction, for tests and for the acceptance suite.
484#[derive(Debug, Clone, Copy)]
485pub struct FixedJitter(pub f64);
486
487impl Jitter for FixedJitter {
488    fn fraction(&self) -> f64 {
489        self.0
490    }
491}
492
493/// No jitter at all: the back-off is exactly what the schedule computed.
494#[derive(Debug, Clone, Copy, Default)]
495pub struct NoJitter;
496
497impl Jitter for NoJitter {
498    fn fraction(&self) -> f64 {
499        0.0
500    }
501}
502
503// ---------------------------------------------------------------------------
504// The schedule
505// ---------------------------------------------------------------------------
506
507/// Why the next poll is when it is.
508///
509/// Reported rather than inferred, because
510/// `04-subsystem-contracts.md` requires that rate limiting be *"displayed, never
511/// hidden"* — and a delay that grew for a reason the caller cannot name is
512/// hidden however visible the number is.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub enum PollPace {
515    /// The configured interval. Nothing is throttling this loop.
516    Nominal,
517    /// GitHub's rate limit is exhausted. Resolves by waiting.
518    RateLimited { kind: RateLimitKind },
519    /// GitHub's temporary authentication lockout. The credential is fine.
520    LockedOut,
521    /// GitHub could not be reached. `consecutive` counts the unbroken run of
522    /// failures the back-off was computed from.
523    Offline { consecutive: u32 },
524    /// GitHub answered something no amount of waiting fixes — a rejected
525    /// credential, a permissions refusal, or an error status. The loop keeps
526    /// polling at its nominal interval so that a fix is noticed, and says that
527    /// it is blocked rather than pretending the poll succeeded.
528    Blocked,
529}
530
531impl PollPace {
532    /// Whether this pace is a slowdown the operator should be told about.
533    #[must_use]
534    pub const fn is_throttled(&self) -> bool {
535        !matches!(self, Self::Nominal)
536    }
537
538    /// A fixed, credential-free name for the log sink and for `g2`.
539    #[must_use]
540    pub const fn as_str(&self) -> &'static str {
541        match self {
542            Self::Nominal => "nominal",
543            Self::RateLimited {
544                kind: RateLimitKind::Primary,
545            } => "rate_limited_primary",
546            Self::RateLimited {
547                kind: RateLimitKind::Secondary,
548            } => "rate_limited_secondary",
549            Self::LockedOut => "locked_out",
550            Self::Offline { .. } => "offline",
551            Self::Blocked => "blocked",
552        }
553    }
554}
555
556impl fmt::Display for PollPace {
557    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
558        f.write_str(self.as_str())
559    }
560}
561
562/// When to poll next, and why then.
563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
564pub struct NextPoll {
565    pub delay: Duration,
566    pub pace: PollPace,
567}
568
569/// The bounded, budget-aware poll interval.
570///
571/// # The floor is a rate-budget constraint, not a preference
572///
573/// [`RefreshInterval`] refuses anything under 30 seconds at construction, and
574/// every delay this type produces is at least that — including the ones it
575/// computes from a remote header. A rate limit may only ever make this loop
576/// *slower*.
577///
578/// # `retry_delay` is an absolute floor, not an addend
579///
580/// `c3` documents [`RefreshState::retry_delay`] as *"the earliest time a retry
581/// may occur"*: the scheduling rule is `next_attempt_at = now + retry_delay`,
582/// and **not** the ordinary interval plus it. Adding the two compounds on every
583/// successive retry — each new answer carries the remaining window, so an
584/// addend ratchets outward — and the symptom is a dashboard that stays dark
585/// long after GitHub said it could come back, which reads as a hang rather than
586/// as a rate limit. So the two are combined with `max`, which is what makes the
587/// floor a floor.
588#[derive(Debug, Clone)]
589pub struct PollSchedule {
590    interval: RefreshInterval,
591    consecutive_offline: u32,
592    offline_since: Option<Timestamp>,
593}
594
595impl PollSchedule {
596    #[must_use]
597    pub const fn new(interval: RefreshInterval) -> Self {
598        Self {
599            interval,
600            consecutive_offline: 0,
601            offline_since: None,
602        }
603    }
604
605    #[must_use]
606    pub const fn interval(&self) -> RefreshInterval {
607        self.interval
608    }
609
610    /// The nominal interval as a [`Duration`].
611    #[must_use]
612    pub const fn nominal(&self) -> Duration {
613        Duration::from_secs(self.interval.as_secs() as u64)
614    }
615
616    /// The unbroken run of offline polls this schedule has seen.
617    #[must_use]
618    pub const fn consecutive_offline(&self) -> u32 {
619        self.consecutive_offline
620    }
621
622    /// How long GitHub has been unreachable, or `None` when it is not.
623    ///
624    /// Measured from the first poll of the current run rather than inferred
625    /// from [`Self::consecutive_offline`] times the interval. The two diverge
626    /// as soon as the back-off starts doubling, and this is the number the
627    /// 24-hour queue-cancellation warning is compared against — an estimate
628    /// would make that warning fire early or late, and it is the one thing the
629    /// offline state exists to say.
630    #[must_use]
631    pub fn offline_for(&self, now: Timestamp) -> Option<Duration> {
632        let since = self.offline_since?;
633        now.signed_duration_since(since).to_std().ok()
634    }
635
636    /// The hard floor no computed delay may go below.
637    #[must_use]
638    pub const fn floor() -> Duration {
639        Duration::from_secs(RefreshInterval::MIN_SECS as u64)
640    }
641
642    /// Decide when to poll next, given how this pass ended.
643    ///
644    /// `failure` is the most severe failure across the targets polled this pass,
645    /// or `None` when every target answered. A pass that answered resets the
646    /// offline run, which is the whole of "recovery needs no bookkeeping":
647    /// demand is recomputed from the current queued-run set on every poll, so
648    /// there is nothing else to unwind.
649    pub fn next_poll(
650        &mut self,
651        failure: Option<&RefreshState>,
652        now: Timestamp,
653        jitter: &dyn Jitter,
654    ) -> NextPoll {
655        let nominal = self.nominal();
656
657        let next = match failure {
658            None => {
659                self.recovered();
660                NextPoll {
661                    delay: nominal,
662                    pace: PollPace::Nominal,
663                }
664            }
665            Some(RefreshState::Offline) => {
666                self.consecutive_offline = self.consecutive_offline.saturating_add(1);
667                // The instant the *run* began, not the instant of this poll.
668                self.offline_since.get_or_insert(now);
669                NextPoll {
670                    delay: self.offline_delay(nominal, jitter),
671                    pace: PollPace::Offline {
672                        consecutive: self.consecutive_offline,
673                    },
674                }
675            }
676            Some(state @ RefreshState::RateLimited(limit)) => {
677                self.recovered();
678                NextPoll {
679                    // `max`, never `+`. See the type documentation.
680                    delay: retry_floor(state, now).max(nominal),
681                    pace: PollPace::RateLimited { kind: limit.kind },
682                }
683            }
684            Some(state @ RefreshState::LockedOut { .. }) => {
685                self.recovered();
686                NextPoll {
687                    delay: retry_floor(state, now).max(nominal),
688                    pace: PollPace::LockedOut,
689                }
690            }
691            // Unauthorized, Forbidden, Failed, Cancelled. `retry_delay` is
692            // `None` for all of them, and deliberately: no wait fixes a revoked
693            // credential or a missing grant. Polling stops being useful but
694            // does not stop, because the poll is also how a re-authentication
695            // is noticed.
696            Some(_) => {
697                // GitHub answered, so it is reachable: whatever is wrong, it is
698                // not an outage, and an outage run that was open must close.
699                self.recovered();
700                NextPoll {
701                    delay: nominal,
702                    pace: PollPace::Blocked,
703                }
704            }
705        };
706
707        debug_assert!(
708            next.delay >= Self::floor(),
709            "the 30-second floor is a rate-budget constraint and no branch may go below it"
710        );
711        next
712    }
713
714    /// GitHub answered something. Whatever it was, the outage run is over.
715    fn recovered(&mut self) {
716        self.consecutive_offline = 0;
717        self.offline_since = None;
718    }
719
720    fn offline_delay(&self, nominal: Duration, jitter: &dyn Jitter) -> Duration {
721        let doublings = self
722            .consecutive_offline
723            .saturating_sub(1)
724            .min(MAX_BACKOFF_DOUBLINGS);
725        let grown = nominal.saturating_mul(1_u32 << doublings);
726        let capped = grown.min(MAX_OFFLINE_BACKOFF);
727        // Additive, never subtractive: see `JITTER_RATIO`. The result may exceed
728        // `MAX_OFFLINE_BACKOFF` by up to the jitter ratio, which is the price of
729        // keeping a fleet of agents from retrying in lockstep at the plateau —
730        // a cap applied *after* jitter would collapse every agent onto the same
731        // instant precisely when the outage is longest.
732        let spread = capped.mul_f64(JITTER_RATIO * jitter.fraction().clamp(0.0, 1.0));
733        capped.saturating_add(spread).max(Self::floor())
734    }
735}
736
737/// `c3`'s retry floor, with the one fallback this loop needs.
738///
739/// [`RefreshState::retry_delay`] answers `None` for the states no wait fixes,
740/// and those never reach here — the caller matches them into
741/// [`PollPace::Blocked`] first. The fallback exists so that a future
742/// `RefreshState` variant added to the two arms above cannot silently schedule a
743/// zero-second retry against an endpoint that asked for quiet.
744fn retry_floor(state: &RefreshState, now: Timestamp) -> Duration {
745    state.retry_delay(now).unwrap_or(PollSchedule::floor())
746}
747
748// ---------------------------------------------------------------------------
749// Offline
750// ---------------------------------------------------------------------------
751
752/// What an operator is told while GitHub is unreachable.
753///
754/// Flow 3.3 requires four things of an outage — start no new runner, retain
755/// existing runner processes, report `offline`, back off with jitter — and one
756/// thing of the *state*: that it says GitHub cancels queued jobs after 24 hours,
757/// so a prolonged outage loses queued work. That bound is stated here rather
758/// than left for a reader to infer, because an operator who does not know it has
759/// no reason to treat a long outage as urgent.
760#[derive(Debug, Clone, Copy, PartialEq, Eq)]
761pub struct OfflineState {
762    /// The unbroken run of failed polls.
763    pub consecutive: u32,
764    /// How long until the next attempt.
765    pub retry_in: Duration,
766    /// How long this loop has been unable to reach GitHub, when it is known.
767    pub offline_for: Option<Duration>,
768}
769
770impl OfflineState {
771    #[must_use]
772    pub const fn new(consecutive: u32, retry_in: Duration) -> Self {
773        Self {
774            consecutive,
775            retry_in,
776            offline_for: None,
777        }
778    }
779
780    #[must_use]
781    pub const fn since(mut self, offline_for: Duration) -> Self {
782        self.offline_for = Some(offline_for);
783        self
784    }
785
786    /// Whether the outage has already outlasted GitHub's queue.
787    ///
788    /// `false` when the duration is unknown: this reports a fact, and "we cannot
789    /// tell" is not the same fact as "not yet".
790    #[must_use]
791    pub fn has_outlasted_the_queue(&self) -> bool {
792        self.offline_for
793            .is_some_and(|elapsed| elapsed >= GITHUB_CANCELS_QUEUED_JOBS_AFTER)
794    }
795}
796
797impl fmt::Display for OfflineState {
798    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
799        write!(
800            f,
801            "GitHub is unreachable; no new runners are being started and running \
802             runners are left alone. Retrying in {}s",
803            self.retry_in.as_secs()
804        )?;
805        if self.has_outlasted_the_queue() {
806            f.write_str(
807                ". This outage has lasted more than 24 hours, and GitHub cancels a queued \
808                 job after 24 hours, so queued work has been lost",
809            )
810        } else {
811            f.write_str(
812                ". GitHub cancels a queued job after 24 hours, so an outage longer than \
813                 that loses queued work",
814            )
815        }
816    }
817}
818
819// ---------------------------------------------------------------------------
820// The launcher port
821// ---------------------------------------------------------------------------
822
823/// What this loop asks `e3` to create.
824#[derive(Debug, Clone, Copy)]
825pub struct LaunchRequest<'a> {
826    pub host: &'a Host,
827    pub policy: &'a ScalePolicy,
828    /// Proof that e1 still owns the host allocation lock for every package,
829    /// prune, and process-start effect performed by e3.
830    // Crate-visible so only this allocator can mint the request that reaches
831    // package pruning. A caller holding an unrelated public AllocationLock can
832    // no longer assemble a LaunchRequest and present that guard as authority.
833    pub(crate) allocation_guard: &'a AllocationGuard,
834}
835
836/// Why one runner could not be started.
837///
838/// Carries `b1`'s [`FailureReason`] rather than a taxonomy of this module's own:
839/// the reasons a runner fails to start are `e3`'s to know and `b1`'s to name,
840/// and a third vocabulary here would be a third answer to a question the
841/// operator asks once.
842#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
843#[error("the runner could not be started: {reason}")]
844pub struct LaunchFailure {
845    pub reason: FailureReason,
846}
847
848/// A lifecycle conclusion that must return through ordinary demand and
849/// capacity allocation before another runner may start.
850#[derive(Debug, Clone, Copy, PartialEq, Eq)]
851pub struct ReplacementIntent {
852    pub policy: PolicyId,
853    pub previous_attempt: AttemptId,
854    pub operation: &'static str,
855}
856
857impl LaunchFailure {
858    #[must_use]
859    pub const fn new(reason: FailureReason) -> Self {
860        Self { reason }
861    }
862}
863
864/// The seam between the decision to start a runner and the act of starting one.
865///
866/// `e3` implements this; every test in this file fakes it, which is what makes
867/// the whole allocator path decidable with no process, no filesystem and no
868/// network.
869///
870/// # Why the attempt set comes through the same port as the launch
871///
872/// `b1` makes this argument at [`HostAllocator::from_attempts`] and it applies
873/// one layer up: the host-wide total (D9) and every per-policy count (D7) are
874/// two questions asked of **one** set, and a design that let the caller supply
875/// the set separately from the thing that creates its members is a design in
876/// which the two can disagree. Worse, it makes `&[]` expressible — and an empty
877/// attempt set is exactly the shape that drops the `- active_owned_runners`
878/// term, starts a second runner for a job already being served, and reports no
879/// error while doing it.
880///
881/// So the launcher is asked, under the allocation lock, immediately before each
882/// runtime is created. There is no second supply point and no cached copy.
883///
884/// # The two ways an implementer can say "I hold no attempts"
885///
886/// The argument above closes the hole for a *caller*. It stayed open one level
887/// down for the **implementer**, in two shapes that both oversubscribe the
888/// machine and neither of which reports anything:
889///
890/// * **By failing.** `attempts()` used to be infallible, which left `e3` — which
891///   reads a journal off a disk — a choice between panicking and answering
892///   `vec![]` on an I/O error. An empty set is indistinguishable from an idle
893///   host, so a transient read failure reads as "nothing is running" and the
894///   next pass allocates the whole machine for jobs already being served. It is
895///   fallible now, and [`Reconciler`] treats a failure the way it treats a lock
896///   it could not take: start nothing, say so, try again next pass.
897/// * **By lagging.** [`Self::launch`] returns the attempt it created rather than
898///   its identifier, so the caller can carry it. See that method for the
899///   measurement that made this necessary.
900#[async_trait::async_trait]
901pub trait RunnerLauncher: fmt::Debug + Send + Sync {
902    /// Reconcile this policy's existing processes before demand is read and
903    /// capacity is recomputed. A concluded pre-acceptance attempt thereby
904    /// becomes an ordinary allocation candidate in this same pass; replacement
905    /// never bypasses the allocator.
906    async fn supervise(
907        &self,
908        _policy: &ScalePolicy,
909    ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
910        Ok(Vec::new())
911    }
912
913    /// Every attempt this host holds, across every policy, terminal ones
914    /// included.
915    ///
916    /// Terminal attempts are included rather than filtered out because the
917    /// caller needs both answers from one set:
918    /// [`AttemptState::counts_against_capacity`] decides the ceiling, and the
919    /// terminal ones are what [`RunnerLauncher::clean`] is for.
920    ///
921    /// # Errors
922    /// [`LaunchFailure`] when the set could not be read. **Never answer `Ok`
923    /// with an empty vector to signal a failure** — the caller cannot tell that
924    /// from an idle host, and the two lead to opposite actions.
925    async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure>;
926
927    /// Create exactly one runtime and start one runner, and return the attempt
928    /// that now exists.
929    ///
930    /// Called once per grant, with the host-wide allocation lock held.
931    ///
932    /// # The attempt is returned, not just its identifier
933    ///
934    /// The host ceiling is enforced against a host-wide total, and that total is
935    /// recomputed from [`Self::attempts`] on every hold. If a launch is not yet
936    /// visible there when the *next* policy is allocated for — a journal write
937    /// that has not landed, an asynchronous store, a cache — then that policy's
938    /// grant is computed from a set missing the previous policy's runners, and
939    /// it is too large.
940    ///
941    /// That is measured, not hypothetical. With a launcher whose attempts never
942    /// became visible, two policies on a host of **three** started **six**
943    /// runners, with the allocation lock held correctly throughout:
944    /// `host_capacity=3, started=6, launches=6`. Serialisation was never the
945    /// problem; the arithmetic under it was reading a stale set.
946    ///
947    /// So an implementer *should* make the new attempt visible to
948    /// [`Self::attempts`] before returning — and the caller does not depend on
949    /// it. [`Reconciler`] carries what this pass created and merges it, by
950    /// [`RunnerAttempt::id`], with whatever the launcher reports. A launcher
951    /// that honours the contract is not double-counted, and one that lags cannot
952    /// oversubscribe the host.
953    ///
954    /// # Every call must return a **fresh** [`RunnerAttempt::id`]
955    ///
956    /// This is a requirement, not a convention, because the merge above is what
957    /// carries the host ceiling and the merge is keyed on the identifier. Two
958    /// calls that answer with the same id are two runtimes that the host-wide
959    /// total counts once, and the machine is then allocated past
960    /// `host_capacity`: probed at `host_capacity = 3` with one slot already
961    /// busy and a launcher answering with a duplicate id, the pass started
962    /// **four** runners for five occupied slots.
963    ///
964    /// That is a narrower defect than the lagging launcher above — that one
965    /// needed no bug at all, this one needs a broken id generator — but `e3` is
966    /// the implementor and cannot honour a requirement nobody states.
967    /// [`Reconciler::host_attempts`] carries a `debug_assert` that fires on a
968    /// collision, so a development build finds it at the first duplicate rather
969    /// than through an oversubscribed host.
970    ///
971    /// # Errors
972    /// [`LaunchFailure`], carrying the [`FailureReason`] `e3` recorded.
973    async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure>;
974
975    /// Remove a terminal attempt's runtime and mark it `cleaned`.
976    ///
977    /// Never called for a non-terminal attempt: capacity is reclaimed when an
978    /// attempt reaches a terminal state and at no other time.
979    ///
980    /// # Errors
981    /// [`LaunchFailure`], carrying the [`FailureReason`] `e3` recorded.
982    async fn clean(&self, attempt: AttemptId) -> Result<(), LaunchFailure>;
983}
984
985// ---------------------------------------------------------------------------
986// The host-wide allocation lock
987// ---------------------------------------------------------------------------
988
989/// The lock is held for as long as this value lives.
990///
991/// Opaque on purpose: what is being held differs between the in-process and the
992/// file-backed implementation, and a caller that could see which one it has
993/// would eventually branch on it.
994pub struct AllocationGuard {
995    _held: Box<dyn std::any::Any + Send + Sync>,
996}
997
998impl AllocationGuard {
999    /// Wrap whatever the implementation holds. Dropping the guard drops it.
1000    #[must_use]
1001    fn new<T: Send + Sync + 'static>(held: T) -> Self {
1002        Self {
1003            _held: Box::new(held),
1004        }
1005    }
1006}
1007
1008impl fmt::Debug for AllocationGuard {
1009    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1010        f.write_str("AllocationGuard")
1011    }
1012}
1013
1014/// The host-wide allocation lock could not be taken.
1015#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1016#[error("the host-wide allocation lock is held by another allocator; no runtime was created")]
1017pub struct AllocationLockBusy;
1018
1019/// Flow 2.4's *"takes the host-wide allocation lock before creating each local
1020/// runtime"*, as a port.
1021///
1022/// # Why a lock is needed at all, given the allocator already exists
1023///
1024/// [`HostAllocator`] enforces D9 across the policies of **one** pass. It cannot
1025/// enforce anything across two passes running at once, and `f3` runs one
1026/// demand-polling loop per target: without serialisation, two loops read the
1027/// same headroom, each finds it sufficient, and the host ends up with the sum of
1028/// two grants it only ever had room for one of. The lock is what makes the
1029/// read-decide-create sequence atomic, and it is taken once per runtime rather
1030/// than once per pass so that a slow package download in one policy does not
1031/// hold the whole host still.
1032#[async_trait::async_trait]
1033pub trait AllocationLock: fmt::Debug + Send + Sync {
1034    /// Take the lock, waiting briefly for it.
1035    ///
1036    /// # Errors
1037    /// [`AllocationLockBusy`] when it could not be taken. A refused grant is
1038    /// always safe: the next pass re-reads the headroom and tries again.
1039    async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy>;
1040}
1041
1042/// The lock every task inside one agent process contends for.
1043///
1044/// This is the implementation that matters in practice, because the
1045/// single-instance lock (`d1`) already guarantees one agent per host: the
1046/// concurrency the allocation lock actually has to serialise is `f3`'s
1047/// per-target loops inside that one process. A `tokio` mutex rather than a
1048/// `std` one because it is held across the `await` that creates the runtime.
1049#[derive(Debug, Default)]
1050pub struct InProcessAllocationLock {
1051    mutex: Arc<tokio::sync::Mutex<()>>,
1052}
1053
1054impl InProcessAllocationLock {
1055    #[must_use]
1056    pub fn new() -> Self {
1057        Self::default()
1058    }
1059}
1060
1061#[async_trait::async_trait]
1062impl AllocationLock for InProcessAllocationLock {
1063    async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
1064        let mutex = Arc::clone(&self.mutex);
1065        let guard = mutex.lock_owned().await;
1066        Ok(AllocationGuard::new(guard))
1067    }
1068}
1069
1070/// `d1`'s file lock, which is host-wide across processes as well as across
1071/// tasks.
1072///
1073/// Defence in depth behind [`InProcessAllocationLock`], for the configuration
1074/// `d1` documents as the one where two agents can genuinely coexist: the
1075/// platform state directory is per-account, so a service-account daemon and an
1076/// interactive `daemon run` resolve different paths and do not contend for the
1077/// single-instance lock. They do contend here if they share a state directory.
1078///
1079/// [`runner_manager_platform::lock::HostLock::acquire`] blocks the calling
1080/// thread and its own documentation names this caller: *"Async callers must wrap
1081/// it in [`tokio::task::spawn_blocking`]"*. That is what this does, and the
1082/// returned `HostLock` lives inside the guard, because dropping it is the
1083/// release.
1084#[derive(Debug, Clone)]
1085pub struct FileAllocationLock {
1086    paths: Arc<runner_manager_platform::paths::AppPaths>,
1087    wait: Duration,
1088}
1089
1090impl FileAllocationLock {
1091    #[must_use]
1092    pub const fn new(paths: Arc<runner_manager_platform::paths::AppPaths>) -> Self {
1093        Self {
1094            paths,
1095            wait: ALLOCATION_LOCK_WAIT,
1096        }
1097    }
1098
1099    #[must_use]
1100    pub const fn with_wait(mut self, wait: Duration) -> Self {
1101        self.wait = wait;
1102        self
1103    }
1104}
1105
1106#[async_trait::async_trait]
1107impl AllocationLock for FileAllocationLock {
1108    async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
1109        use runner_manager_platform::lock::{HostLock, LockKind};
1110
1111        let paths = Arc::clone(&self.paths);
1112        let wait = self.wait;
1113        let held = tokio::task::spawn_blocking(move || {
1114            HostLock::acquire(&paths, LockKind::Allocation, wait)
1115        })
1116        .await;
1117
1118        match held {
1119            Ok(Ok(lock)) => Ok(AllocationGuard::new(lock)),
1120            // A refused lock and a panicked blocking task are the same outcome
1121            // to this caller: no runtime was created and the next pass will
1122            // re-read the headroom. Neither is allowed to look like a grant.
1123            Ok(Err(_)) | Err(_) => Err(AllocationLockBusy),
1124        }
1125    }
1126}
1127
1128/// Adds the Windows/WSL recovery fence to an ordinary allocation lock.
1129///
1130/// A Windows watchdog writes its drain request before attempting the same
1131/// atomic directory claim. Therefore either this guard owns the directory and
1132/// finishes the one launch already in progress, or Windows owns it and no new
1133/// launch can pass. A malformed configured fence fails closed.
1134#[derive(Debug)]
1135pub struct WslRecoveryAllocationLock {
1136    paths: Arc<runner_manager_platform::paths::AppPaths>,
1137    inner: Arc<dyn AllocationLock>,
1138}
1139
1140impl WslRecoveryAllocationLock {
1141    #[must_use]
1142    pub fn new(
1143        paths: Arc<runner_manager_platform::paths::AppPaths>,
1144        inner: Arc<dyn AllocationLock>,
1145    ) -> Self {
1146        Self { paths, inner }
1147    }
1148}
1149
1150#[async_trait::async_trait]
1151impl AllocationLock for WslRecoveryAllocationLock {
1152    async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
1153        use runner_manager_platform::wsl::fence::{
1154            DrainRequest, FenceClaim, FenceOwnerKind, GuestRecoveryConfig,
1155        };
1156
1157        let paths = Arc::clone(&self.paths);
1158        let claim = tokio::task::spawn_blocking(move || {
1159            let Some(config) = GuestRecoveryConfig::read(&paths).map_err(|_| ())? else {
1160                return Ok(None);
1161            };
1162            let Some(claim) =
1163                FenceClaim::try_claim(&config.shared_root, FenceOwnerKind::GuestLaunch, None)
1164                    .map_err(|_| ())?
1165            else {
1166                return Err(());
1167            };
1168            match DrainRequest::read(&config.shared_root) {
1169                Ok(None) => Ok(Some(claim)),
1170                Ok(Some(_)) | Err(_) => Err(()),
1171            }
1172        })
1173        .await
1174        .map_err(|_| AllocationLockBusy)?
1175        .map_err(|()| AllocationLockBusy)?;
1176
1177        let inner = self.inner.acquire().await?;
1178        Ok(AllocationGuard::new((claim, inner)))
1179    }
1180}
1181
1182// ---------------------------------------------------------------------------
1183// Lifecycle events
1184// ---------------------------------------------------------------------------
1185
1186/// Which terminal thing happened, as a closed vocabulary.
1187///
1188/// The distinction `g2` renders: an idle exit is the accepted surplus case and
1189/// **not** a failure, and showing it as one sends an operator hunting a fault
1190/// that does not exist.
1191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1192pub enum OutcomeKind {
1193    CompletedJob,
1194    IdleExit,
1195    Failed,
1196    Orphaned,
1197}
1198
1199impl OutcomeKind {
1200    #[must_use]
1201    pub const fn of(outcome: &AttemptOutcome) -> Self {
1202        match outcome {
1203            AttemptOutcome::CompletedJob => Self::CompletedJob,
1204            AttemptOutcome::ExitedIdleWithoutWork => Self::IdleExit,
1205            AttemptOutcome::Failed { .. } => Self::Failed,
1206            AttemptOutcome::Orphaned => Self::Orphaned,
1207        }
1208    }
1209
1210    #[must_use]
1211    pub const fn is_failure(&self) -> bool {
1212        matches!(self, Self::Failed | Self::Orphaned)
1213    }
1214
1215    #[must_use]
1216    pub const fn as_str(&self) -> &'static str {
1217        match self {
1218            Self::CompletedJob => "completed_job",
1219            Self::IdleExit => "exited_idle_without_work",
1220            Self::Failed => "failed",
1221            Self::Orphaned => "orphaned",
1222        }
1223    }
1224}
1225
1226impl fmt::Display for OutcomeKind {
1227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1228        f.write_str(self.as_str())
1229    }
1230}
1231
1232/// A [`FailureReason`]'s variant name, with no detail.
1233///
1234/// [`FailureReason::Other`] carries a `String` that `e3` fills in, and an event
1235/// is not the place for it: `07-security.md`'s log scan runs over everything
1236/// this loop emits, and free text is the one shape that can carry a credential
1237/// past a field allow-list. The operator-facing detail reaches the journal
1238/// through `b2` and the screen through `g2`; what reaches an *event* is the
1239/// variant.
1240#[must_use]
1241pub const fn failure_reason_kind(reason: &FailureReason) -> &'static str {
1242    match reason {
1243        FailureReason::JitRequestFailed => "jit_request_failed",
1244        FailureReason::JitExpired => "jit_expired",
1245        FailureReason::RunnerPackageUnverified => "runner_package_unverified",
1246        FailureReason::RunnerVersionRejected => "runner_version_rejected",
1247        FailureReason::ProcessStartFailed => "process_start_failed",
1248        FailureReason::ProcessExitedUnexpectedly => "process_exited_unexpectedly",
1249        FailureReason::RegistrationTimedOut => "registration_timed_out",
1250        FailureReason::TerminatedAfterRegistrationTimeout => {
1251            "terminated_after_registration_timeout"
1252        }
1253        FailureReason::Other(_) => "other",
1254    }
1255}
1256
1257/// What `g2`'s activity view and the local log sink see.
1258///
1259/// **Every field is an identifier, a count, a duration, or a `&'static str`
1260/// drawn from a closed set.** There is no `String` anywhere in this enum, which
1261/// is what makes "no emitted event contains a token, a JIT blob, or a credential
1262/// header" a property of the type rather than a discipline each call site has to
1263/// keep. `tests::no_emitted_event_can_carry_a_credential` renders every variant
1264/// through `d1`'s scrubber and asserts nothing changes, with a positive control
1265/// so the assertion cannot pass vacuously.
1266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1267pub enum LifecycleEvent {
1268    /// A demand poll answered for one target.
1269    DemandObserved {
1270        policy: PolicyId,
1271        /// Queued jobs this policy's routing labels match. The number clamped.
1272        demand: u32,
1273        /// Queued jobs whose required labels this policy does not carry.
1274        ///
1275        /// Never demand. Reported because the difference between this and
1276        /// `demand` is the whole value of the label filtering, and an operator
1277        /// wondering why a busy repository started no runners is owed it.
1278        not_matched: u32,
1279        /// Queued jobs whose `runs-on` could not be resolved statically.
1280        ///
1281        /// `b1` requires these be "reported as unresolvable rather than silently
1282        /// counted or silently dropped": counting one would start a runner for a
1283        /// job that may not be ours, and dropping it would hide a workflow this
1284        /// host can never serve. A count rather than the reasons themselves
1285        /// because this type is `Copy`, and `c4` logs the reasons where it
1286        /// builds them.
1287        unresolvable: u32,
1288        /// `false` when the count is a floor rather than a total.
1289        complete: bool,
1290    },
1291    /// A target could not be polled, so its policies start nothing this pass.
1292    TargetUnreadable {
1293        policy: PolicyId,
1294        reason: &'static str,
1295    },
1296    /// One policy's share of the pass.
1297    Allocated {
1298        policy: PolicyId,
1299        demand: u32,
1300        desired: u16,
1301        active_owned: u16,
1302        headroom: u16,
1303        to_start: u16,
1304        limiting: LimitingFactor,
1305    },
1306    /// A monitor-only policy was skipped entirely, before any demand request
1307    /// was issued for it (D19).
1308    MonitorOnlySkipped { policy: PolicyId },
1309    /// One runtime was created and one runner started.
1310    RunnerStarted {
1311        policy: PolicyId,
1312        attempt: AttemptId,
1313    },
1314    /// One runner could not be started.
1315    RunnerStartFailed {
1316        policy: PolicyId,
1317        reason: &'static str,
1318    },
1319    /// The allocation lock was not free, so `count` runners this policy was
1320    /// granted were not created this pass.
1321    AllocationDeferred { policy: PolicyId, count: u16 },
1322    /// The host's attempt set could not be read at all.
1323    ///
1324    /// Distinct from an empty set on purpose, and the whole reason
1325    /// [`RunnerLauncher::attempts`] is fallible: the two produce the same
1326    /// *number* and demand opposite actions.
1327    AttemptsUnreadable { reason: &'static str },
1328    /// A terminal attempt's runtime was removed.
1329    AttemptCleaned {
1330        policy: PolicyId,
1331        attempt: AttemptId,
1332        outcome: OutcomeKind,
1333    },
1334    /// A terminal attempt's runtime could not be removed. It will be retried on
1335    /// the next pass, and this is what keeps that retry from being silent.
1336    AttemptCleanFailed {
1337        policy: PolicyId,
1338        attempt: AttemptId,
1339        reason: &'static str,
1340    },
1341    /// Scale-down declined to remove a runner that is executing a job.
1342    ScaleDownRefused {
1343        policy: PolicyId,
1344        attempt: AttemptId,
1345    },
1346    /// When the next poll is, and why then.
1347    PollScheduled { retry_in_ms: u64, pace: PollPace },
1348}
1349
1350impl LifecycleEvent {
1351    /// A fixed name, for the `event` field `d1`'s sink allows verbatim.
1352    #[must_use]
1353    pub const fn name(&self) -> &'static str {
1354        match self {
1355            Self::DemandObserved { .. } => "demand_observed",
1356            Self::TargetUnreadable { .. } => "target_unreadable",
1357            Self::Allocated { .. } => "allocated",
1358            Self::MonitorOnlySkipped { .. } => "monitor_only_skipped",
1359            Self::RunnerStarted { .. } => "runner_started",
1360            Self::RunnerStartFailed { .. } => "runner_start_failed",
1361            Self::AllocationDeferred { .. } => "allocation_deferred",
1362            Self::AttemptsUnreadable { .. } => "attempts_unreadable",
1363            Self::AttemptCleaned { .. } => "attempt_cleaned",
1364            Self::AttemptCleanFailed { .. } => "attempt_clean_failed",
1365            Self::ScaleDownRefused { .. } => "scale_down_refused",
1366            Self::PollScheduled { .. } => "poll_scheduled",
1367        }
1368    }
1369
1370    /// Which policy this event is about.
1371    #[must_use]
1372    pub const fn policy(&self) -> Option<PolicyId> {
1373        match self {
1374            Self::DemandObserved { policy, .. }
1375            | Self::TargetUnreadable { policy, .. }
1376            | Self::Allocated { policy, .. }
1377            | Self::MonitorOnlySkipped { policy }
1378            | Self::RunnerStarted { policy, .. }
1379            | Self::RunnerStartFailed { policy, .. }
1380            | Self::AllocationDeferred { policy, .. }
1381            | Self::AttemptCleaned { policy, .. }
1382            | Self::AttemptCleanFailed { policy, .. }
1383            | Self::ScaleDownRefused { policy, .. } => Some(*policy),
1384            Self::PollScheduled { .. } | Self::AttemptsUnreadable { .. } => None,
1385        }
1386    }
1387}
1388
1389impl fmt::Display for LifecycleEvent {
1390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1391        match self {
1392            Self::DemandObserved {
1393                policy,
1394                demand,
1395                not_matched,
1396                unresolvable,
1397                complete,
1398            } => write!(
1399                f,
1400                "policy {policy}: {demand} queued jobs for this host{}{}{}",
1401                if *not_matched == 0 {
1402                    String::new()
1403                } else {
1404                    format!(", {not_matched} for other labels")
1405                },
1406                if *unresolvable == 0 {
1407                    String::new()
1408                } else {
1409                    format!(", {unresolvable} with an unresolvable `runs-on`")
1410                },
1411                if *complete {
1412                    ""
1413                } else {
1414                    " (a floor, not a total)"
1415                }
1416            ),
1417            Self::TargetUnreadable { policy, reason } => {
1418                write!(f, "policy {policy}: target unreadable ({reason})")
1419            }
1420            Self::Allocated {
1421                policy,
1422                demand,
1423                desired,
1424                active_owned,
1425                headroom,
1426                to_start,
1427                limiting,
1428            } => write!(
1429                f,
1430                "policy {policy}: demand {demand}, desired {desired}, {active_owned} in \
1431                 flight, {headroom} free on this host, starting {to_start} ({limiting})"
1432            ),
1433            Self::MonitorOnlySkipped { policy } => {
1434                write!(f, "policy {policy}: monitor-only, skipped")
1435            }
1436            Self::RunnerStarted { policy, attempt } => {
1437                write!(f, "policy {policy}: started attempt {attempt}")
1438            }
1439            Self::RunnerStartFailed { policy, reason } => {
1440                write!(f, "policy {policy}: could not start a runner ({reason})")
1441            }
1442            Self::AllocationDeferred { policy, count } => write!(
1443                f,
1444                "policy {policy}: the allocation lock was held; {count} granted runners \
1445                 were not created"
1446            ),
1447            Self::AttemptsUnreadable { reason } => write!(
1448                f,
1449                "the host's attempt set could not be read ({reason}); nothing was started, \
1450                 and this is not the same as the host being idle"
1451            ),
1452            Self::AttemptCleaned {
1453                policy,
1454                attempt,
1455                outcome,
1456            } => write!(f, "policy {policy}: cleaned attempt {attempt} ({outcome})"),
1457            Self::AttemptCleanFailed {
1458                policy,
1459                attempt,
1460                reason,
1461            } => write!(
1462                f,
1463                "policy {policy}: attempt {attempt} could not be cleaned ({reason}); it \
1464                 will be retried"
1465            ),
1466            Self::ScaleDownRefused { policy, attempt } => write!(
1467                f,
1468                "policy {policy}: attempt {attempt} is executing a job and was not removed"
1469            ),
1470            Self::PollScheduled { retry_in_ms, pace } => {
1471                write!(f, "next poll in {retry_in_ms}ms ({pace})")
1472            }
1473        }
1474    }
1475}
1476
1477/// Where lifecycle events go.
1478pub trait EventSink: fmt::Debug + Send + Sync {
1479    fn emit(&self, event: LifecycleEvent);
1480}
1481
1482/// Discards everything. For callers that only want the report.
1483#[derive(Debug, Clone, Copy, Default)]
1484pub struct NoEvents;
1485
1486impl EventSink for NoEvents {
1487    fn emit(&self, _event: LifecycleEvent) {}
1488}
1489
1490/// The local log sink, through `d1`'s redacting layer.
1491///
1492/// Every field name below is on
1493/// [`runner_manager_platform::logging::ALLOWED_FIELDS`]; anything else would be
1494/// replaced with `[redacted]` and the line would lose its meaning rather than
1495/// its safety. `tests::every_field_name_this_sink_emits_is_one_d1_allows` keeps
1496/// that true.
1497#[derive(Debug, Clone, Copy, Default)]
1498pub struct TracingEvents;
1499
1500impl EventSink for TracingEvents {
1501    fn emit(&self, event: LifecycleEvent) {
1502        let name = event.name();
1503        match event {
1504            LifecycleEvent::DemandObserved {
1505                policy,
1506                demand,
1507                not_matched,
1508                unresolvable,
1509                complete,
1510            } => {
1511                tracing::info!(
1512                    event = name,
1513                    policy_id = %policy,
1514                    demand,
1515                    not_matched,
1516                    unresolvable,
1517                    count = u64::from(complete),
1518                );
1519                // There is deliberately no `warn!` here for the "demand is zero
1520                // but jobs were not matched" shape, though it is the one this
1521                // change introduced: before demand was filtered, a repository
1522                // with work in it always produced some, and now a policy whose
1523                // labels do not cover its jobs produces none.
1524                //
1525                // The reason is that the shape is indistinguishable from a
1526                // healthy one. A repository served by a Windows host and a macOS
1527                // host has the other host's jobs queued in it constantly, so
1528                // each agent would warn on every poll about work that is being
1529                // served correctly by the other machine. Telling the two apart
1530                // needs to know whether this policy has *ever* matched anything,
1531                // which is state across polls that this loop does not keep.
1532                //
1533                // What an operator gets instead is the `not_matched` count, on
1534                // this event and in its `Display`, which `g2` renders. "0 queued
1535                // jobs for this host, 5 for other labels" is the diagnosis; a
1536                // warning that fired on every healthy minute would be the kind
1537                // nobody reads.
1538            }
1539            LifecycleEvent::TargetUnreadable { policy, reason } => {
1540                tracing::warn!(event = name, policy_id = %policy, reason);
1541            }
1542            LifecycleEvent::Allocated {
1543                policy,
1544                demand,
1545                desired,
1546                active_owned,
1547                headroom,
1548                to_start,
1549                limiting,
1550            } => tracing::info!(
1551                event = name,
1552                policy_id = %policy,
1553                demand,
1554                desired,
1555                capacity = active_owned,
1556                headroom,
1557                count = to_start,
1558                reason = %limiting,
1559            ),
1560            LifecycleEvent::MonitorOnlySkipped { policy } => {
1561                tracing::debug!(event = name, policy_id = %policy, mode = "monitor_only");
1562            }
1563            LifecycleEvent::RunnerStarted { policy, attempt } => {
1564                tracing::info!(event = name, policy_id = %policy, attempt_id = %attempt);
1565            }
1566            LifecycleEvent::RunnerStartFailed { policy, reason } => {
1567                tracing::warn!(event = name, policy_id = %policy, reason);
1568            }
1569            LifecycleEvent::AllocationDeferred { policy, count } => {
1570                tracing::debug!(event = name, policy_id = %policy, lock = "allocation", count);
1571            }
1572            LifecycleEvent::AttemptsUnreadable { reason } => {
1573                tracing::warn!(event = name, reason);
1574            }
1575            LifecycleEvent::AttemptCleaned {
1576                policy,
1577                attempt,
1578                outcome,
1579            } => tracing::info!(
1580                event = name,
1581                policy_id = %policy,
1582                attempt_id = %attempt,
1583                outcome = outcome.as_str(),
1584            ),
1585            LifecycleEvent::AttemptCleanFailed {
1586                policy,
1587                attempt,
1588                reason,
1589            } => tracing::warn!(
1590                event = name,
1591                policy_id = %policy,
1592                attempt_id = %attempt,
1593                reason,
1594            ),
1595            LifecycleEvent::ScaleDownRefused { policy, attempt } => tracing::info!(
1596                event = name,
1597                policy_id = %policy,
1598                attempt_id = %attempt,
1599                attempt_state = "busy",
1600            ),
1601            LifecycleEvent::PollScheduled { retry_in_ms, pace } => {
1602                tracing::info!(event = name, retry_in_ms, state = pace.as_str());
1603            }
1604        }
1605    }
1606}
1607
1608/// Keeps every event, in order.
1609///
1610/// `g2`'s activity view is a reader of this, and so is every test below.
1611#[derive(Debug, Default)]
1612pub struct EventLog {
1613    events: Mutex<Vec<LifecycleEvent>>,
1614}
1615
1616impl EventLog {
1617    #[must_use]
1618    pub fn new() -> Self {
1619        Self::default()
1620    }
1621
1622    #[must_use]
1623    pub fn events(&self) -> Vec<LifecycleEvent> {
1624        self.events.lock().map(|e| e.clone()).unwrap_or_default()
1625    }
1626
1627    /// How many events of one name were emitted.
1628    #[must_use]
1629    pub fn count_of(&self, name: &str) -> usize {
1630        self.events()
1631            .iter()
1632            .filter(|event| event.name() == name)
1633            .count()
1634    }
1635}
1636
1637impl EventSink for EventLog {
1638    fn emit(&self, event: LifecycleEvent) {
1639        if let Ok(mut events) = self.events.lock() {
1640            events.push(event);
1641        }
1642    }
1643}
1644
1645/// Both sinks at once: the log sink for the operator's file, the buffer for
1646/// `g2`'s screen.
1647#[derive(Debug)]
1648pub struct TeeEvents(pub Arc<dyn EventSink>, pub Arc<dyn EventSink>);
1649
1650impl EventSink for TeeEvents {
1651    fn emit(&self, event: LifecycleEvent) {
1652        self.0.emit(event);
1653        self.1.emit(event);
1654    }
1655}
1656
1657// ---------------------------------------------------------------------------
1658// The reconciler
1659// ---------------------------------------------------------------------------
1660
1661/// Everything one reconciler needs, written down at the call site.
1662///
1663/// A struct rather than seven positional arguments, for the reason `b1` gives at
1664/// `PersistedAttempt`: several of these are `Arc<dyn …>` and transposing two of
1665/// them type-checks. Construct it with a struct literal so every port is named.
1666pub struct ReconcilerPorts {
1667    pub demand: Arc<dyn DemandSource>,
1668    pub launcher: Arc<dyn RunnerLauncher>,
1669    pub lock: Arc<dyn AllocationLock>,
1670    pub directory: Arc<dyn RepositoryDirectory>,
1671    pub clock: Arc<dyn Clock>,
1672    pub jitter: Arc<dyn Jitter>,
1673    pub events: Arc<dyn EventSink>,
1674}
1675
1676impl fmt::Debug for ReconcilerPorts {
1677    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1678        f.debug_struct("ReconcilerPorts").finish_non_exhaustive()
1679    }
1680}
1681
1682/// What one reconciliation pass did.
1683///
1684/// `started` and the allocations are reported separately on purpose: an
1685/// allocation is what the pass *decided* under the lock, and `started` is what
1686/// actually came up. They differ when a launch fails or when the lock was held,
1687/// and collapsing them would hide both.
1688#[derive(Debug, Clone, Default)]
1689pub struct ReconcileReport {
1690    /// One entry per policy that got as far as being allocated for.
1691    pub allocations: Vec<Allocation>,
1692    /// Policies skipped because they are monitor-only (D19).
1693    pub monitor_only: Vec<PolicyId>,
1694    /// Policies whose target could not be polled this pass.
1695    pub unreadable: Vec<PolicyId>,
1696    /// Policies whose target GitHub actually answered for this pass.
1697    ///
1698    /// The counterpart to [`Self::unreadable`], and the only honest evidence
1699    /// that this host reached GitHub at all. [`Self::allocations`] is not: a
1700    /// policy this host does not own is allocated for with no demand and
1701    /// without any target being polled, so a pass where every poll failed can
1702    /// still end with allocations in it.
1703    pub targets_read: u16,
1704    /// Runners actually started.
1705    pub started: u16,
1706    /// Pre-acceptance attempts routed back through this pass's ordinary
1707    /// demand/capacity decision.
1708    pub replacement_intents: u16,
1709    /// Terminal attempts whose runtime was removed.
1710    pub cleaned: u16,
1711    /// Of those, the surplus case: registered, got no job, exited on its idle
1712    /// timeout. **Not** a failure.
1713    pub idle_exits: u16,
1714    /// Of those, the ones an operator should look at.
1715    pub failures: u16,
1716    /// Runners this pass was granted but did not start because the allocation
1717    /// lock was held.
1718    ///
1719    /// **Grants, not policies.** It used to be incremented once per
1720    /// `start_runners` call that met a held lock, so a policy that launched two
1721    /// of five and then lost the lock reported `1` while three runners went
1722    /// unstarted -- a number that agreed with neither its own name nor its
1723    /// documentation.
1724    pub deferred: u16,
1725    /// Times the host's attempt set could not be read this pass.
1726    ///
1727    /// Non-zero means the pass decided less than it looks like it decided: a
1728    /// policy whose attempt set was unreadable started nothing and is *not* in
1729    /// [`Self::allocations`], because there was no set to compute an allocation
1730    /// from. It is not the same as the host being idle, which is the whole
1731    /// reason [`RunnerLauncher::attempts`] is fallible.
1732    ///
1733    /// **A count, where [`Self::unreadable`] is a `Vec<PolicyId>`, and that
1734    /// asymmetry is deliberate.** An unreadable *target* is a fact about one
1735    /// policy's GitHub target; an unreadable *attempt set* is a fact about this
1736    /// host's journal, which no policy owns — two of the three paths that reach
1737    /// it (`clean_terminal_attempts` and `scale_down`) have no policy in hand at
1738    /// all. Naming policies here would mean either inventing an owner for a
1739    /// host-wide failure or reporting a partial list, and both read as more
1740    /// precision than there is. The pass is distinguishable from an idle one,
1741    /// which is what the field exists for; the per-policy attribution is not
1742    /// available, and is recorded as missing rather than faked.
1743    pub attempts_unreadable: u16,
1744    /// Terminal attempts whose runtime could not be removed. Retried next pass.
1745    pub clean_failures: u16,
1746    /// The most severe failure across the targets polled, when there was one.
1747    pub failure: Option<RefreshState>,
1748    /// What to display while GitHub is unreachable, including how long the
1749    /// outage has run and therefore whether queued work has already been lost.
1750    pub offline: Option<OfflineState>,
1751    /// When to poll next, and why then.
1752    pub next_poll: NextPoll,
1753    /// Demand requests this pass projected against the shared hourly ceiling.
1754    pub demand_requests: u32,
1755}
1756
1757impl ReconcileReport {
1758    /// Whether this pass actually reached GitHub, which is the only thing that
1759    /// entitles it to write a `last GitHub contact`.
1760    ///
1761    /// # Positive evidence, because the absence of a failure is not evidence
1762    ///
1763    /// The record used to be written whenever [`Self::failure`] was `None`, on
1764    /// the belief that an unauthorized target lands in [`Self::unreadable`]
1765    /// rather than in `failure`. **That belief is wrong.** `unreadable` is
1766    /// pushed only from the `PollOutcome::Failed` arm, `failure` is the maximum
1767    /// over every `Failed` reading, and `RefreshState::Unauthorized` scores 2 —
1768    /// so a non-empty `unreadable` always implies `failure.is_some()`, and
1769    /// guarding on both would have changed nothing at all.
1770    ///
1771    /// The path that really writes a contact record without touching GitHub is
1772    /// a pass that polls **nothing**: every policy draining, owned by another
1773    /// host, or monitor-only. `pollable` is then empty, no reading exists, no
1774    /// failure is computed, and the old guard passed. That is how
1775    /// `service status` can answer `healthy` on a host doing nothing at all.
1776    ///
1777    /// So this asks for evidence rather than for the absence of a complaint. A
1778    /// pass with nothing to ask reaches nobody and records nothing, which is
1779    /// what `never` in `service status` is for.
1780    ///
1781    /// Conservative on purpose: `repositories.scope_for` is a real request that
1782    /// can succeed before a demand poll fails, and it is not counted. Contact
1783    /// that cannot be proven is not claimed.
1784    #[must_use]
1785    pub const fn reached_github(&self) -> bool {
1786        self.targets_read > 0
1787    }
1788}
1789
1790impl Default for NextPoll {
1791    fn default() -> Self {
1792        Self {
1793            delay: PollSchedule::floor(),
1794            pace: PollPace::Nominal,
1795        }
1796    }
1797}
1798
1799impl ReconcileReport {
1800    /// Whether GitHub was unreachable this pass.
1801    #[must_use]
1802    pub fn is_offline(&self) -> bool {
1803        matches!(self.failure, Some(RefreshState::Offline))
1804    }
1805
1806    /// The offline state to display, when this pass was one.
1807    #[must_use]
1808    pub const fn offline_state(&self) -> Option<&OfflineState> {
1809        self.offline.as_ref()
1810    }
1811
1812    /// Attempts this pass created. The idle-host assertion reads this.
1813    #[must_use]
1814    pub const fn starts_nothing(&self) -> bool {
1815        self.started == 0
1816    }
1817}
1818
1819/// What one scale-down request did.
1820#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1821pub struct ScaleDownReport {
1822    /// Terminal attempts whose runtime was removed.
1823    pub removed: u16,
1824    /// Attempts executing a job. **Removed nothing, left `busy`.**
1825    pub refused_busy: u16,
1826    /// Terminal attempts whose runtime could not be removed.
1827    pub clean_failures: u16,
1828    /// Live attempts that are not yet busy. Also removed nothing: capacity is
1829    /// reclaimed only when an attempt reaches a terminal state.
1830    pub retained: u16,
1831    /// The host's attempt set could not be read, so **every other field here is
1832    /// meaningless** rather than zero.
1833    ///
1834    /// This is the same distinction [`ReconcileReport::attempts_unreadable`]
1835    /// draws, and it is here for the same reason: a default
1836    /// [`ScaleDownReport`] and a scale-down that could not see the machine are
1837    /// both all-zeros, and they mean opposite things — "there was nothing to
1838    /// reclaim" against "we do not know what there was". Check
1839    /// [`Self::is_conclusive`] before reading a zero as an answer.
1840    pub attempts_unreadable: bool,
1841}
1842
1843impl ScaleDownReport {
1844    /// Whether the counts here describe the machine at all.
1845    ///
1846    /// `false` means the attempt set could not be read, so every zero is
1847    /// "unknown" rather than "none".
1848    #[must_use]
1849    pub const fn is_conclusive(&self) -> bool {
1850        !self.attempts_unreadable
1851    }
1852}
1853
1854/// The reconciliation loop.
1855///
1856/// One per target, as `f3` runs them; they share a [`RunnerLauncher`] and an
1857/// [`AllocationLock`], which is what keeps the host ceiling true across all of
1858/// them.
1859#[derive(Debug)]
1860pub struct Reconciler {
1861    host: Host,
1862    demand: Arc<dyn DemandSource>,
1863    launcher: Arc<dyn RunnerLauncher>,
1864    lock: Arc<dyn AllocationLock>,
1865    repositories: RepositoryCache,
1866    clock: Arc<dyn Clock>,
1867    jitter: Arc<dyn Jitter>,
1868    events: Arc<dyn EventSink>,
1869    schedule: PollSchedule,
1870}
1871
1872impl Reconciler {
1873    /// Build a reconciler polling at the host's configured interval.
1874    #[must_use]
1875    pub fn new(host: Host, ports: ReconcilerPorts) -> Self {
1876        let interval = host.refresh_interval;
1877        let repositories = RepositoryCache::new(
1878            Arc::clone(&ports.directory),
1879            Arc::clone(&ports.clock),
1880            interval,
1881        );
1882        Self {
1883            host,
1884            demand: ports.demand,
1885            launcher: ports.launcher,
1886            lock: ports.lock,
1887            repositories,
1888            clock: ports.clock,
1889            jitter: ports.jitter,
1890            events: ports.events,
1891            schedule: PollSchedule::new(interval),
1892        }
1893    }
1894
1895    #[must_use]
1896    pub const fn host(&self) -> &Host {
1897        &self.host
1898    }
1899
1900    #[must_use]
1901    pub const fn schedule(&self) -> &PollSchedule {
1902        &self.schedule
1903    }
1904
1905    /// The repository-list cache, so `f1` can report what it has spent.
1906    #[must_use]
1907    pub const fn repositories(&self) -> &RepositoryCache {
1908        &self.repositories
1909    }
1910
1911    /// One reconciliation pass over `policies`.
1912    ///
1913    /// The order of operations is `03-control-flows.md` flow 2, and the two
1914    /// steps most worth naming are the ones that are silent when they are wrong:
1915    ///
1916    /// * **Monitor-only policies are removed before the demand poll**, not
1917    ///   after. D19 says such a policy "is skipped entirely by reconciliation",
1918    ///   and a poll issued on its behalf would spend requests from the shared
1919    ///   ceiling for a policy that can never act on the answer. This is asserted
1920    ///   on [`ScalePolicy::owns_runners`] rather than deduced from
1921    ///   `max_capacity` being absent.
1922    /// * **The attempt set is re-read under the lock, once per runtime.** See
1923    ///   [`RunnerLauncher`] for why it comes from there and nowhere else.
1924    pub async fn reconcile(&mut self, policies: &[ScalePolicy]) -> ReconcileReport {
1925        let mut report = ReconcileReport::default();
1926        // Everything this pass has created, carried across policies so that the
1927        // host-wide total cannot be computed from a set that is missing it. See
1928        // `RunnerLauncher::launch`.
1929        let mut launched: Vec<RunnerAttempt> = Vec::new();
1930
1931        // --- Flow 2.1-2.2: who is even asking, and what did GitHub say -------
1932        let mut pollable: Vec<&ScalePolicy> = Vec::new();
1933        let mut supervision_failed = BTreeSet::new();
1934        for policy in policies {
1935            if !policy.owns_runners() {
1936                report.monitor_only.push(policy.id);
1937                self.events
1938                    .emit(LifecycleEvent::MonitorOnlySkipped { policy: policy.id });
1939                continue;
1940            }
1941            if !policy.is_owned_by(self.host.id) {
1942                // Ownership rule 2 and precedence rule 4. The allocator reports
1943                // both by name below; polling on their behalf would spend
1944                // requests for an answer that cannot be acted on.
1945                continue;
1946            }
1947            match self.launcher.supervise(policy).await {
1948                Ok(intents) => {
1949                    report.replacement_intents = report
1950                        .replacement_intents
1951                        .saturating_add(u16::try_from(intents.len()).unwrap_or(u16::MAX));
1952                }
1953                Err(failure) => {
1954                    supervision_failed.insert(policy.id);
1955                    self.report_unreadable_attempts(&mut report, &failure);
1956                    continue;
1957                }
1958            }
1959            if !policy.may_start_runners() {
1960                continue;
1961            }
1962            pollable.push(policy);
1963        }
1964
1965        let readings = self.poll_targets(&pollable, &mut report).await;
1966
1967        // --- Flow 2.8: terminal attempts, whatever else this pass does -------
1968        //
1969        // Run before the allocation phase so that a report's `cleaned` count
1970        // describes the same instant its allocations do. It does not change the
1971        // arithmetic: a terminal attempt already stopped counting against
1972        // capacity when it became terminal, which is `b1`'s
1973        // `counts_against_capacity`. It touches no live process, so it is also
1974        // safe during an outage — flow 3.3 requires that running runners be
1975        // retained, and nothing here can reach one.
1976        self.clean_terminal_attempts(&mut report).await;
1977
1978        // --- Flow 2.3-2.6: the allocation -----------------------------------
1979        //
1980        // The predicates are re-tested here rather than the reading being looked
1981        // up by target, and that is not redundancy. **Targets are shared.** A
1982        // monitor-only policy watching `acme/app` alongside an autoscale policy
1983        // on the *same* repository finds a reading in the map that the other
1984        // policy paid for, and a lookup-driven loop then serves it: it emits a
1985        // demand observation on its behalf and clamps a number it has no
1986        // business seeing.
1987        //
1988        // Nothing downstream goes wrong when that happens — `may_start_runners`
1989        // is false for a monitor-only policy, so `HostAllocator` refuses it and
1990        // `to_start` is zero. It simply is not *skipped*, and D19's word is
1991        // "entirely".
1992        for policy in policies {
1993            if !policy.owns_runners() {
1994                // Already recorded and reported above, before any demand request
1995                // was issued. It owns no routing labels, takes no part in
1996                // demand, and can never be the reason a runner starts. Asserted
1997                // on the mode rather than deduced from `max_capacity` being
1998                // absent, which is what the specification requires.
1999                continue;
2000            }
2001            if !policy.is_owned_by(self.host.id) || !policy.may_start_runners() {
2002                // Ownership rule 2 and precedence rule 4. Allocated for with no
2003                // demand, so the refusal is reported by name rather than by
2004                // absence.
2005                match self.allocate_only(policy, 0, &launched).await {
2006                    Ok(allocation) => {
2007                        self.emit_allocation(&allocation);
2008                        report.allocations.push(allocation);
2009                    }
2010                    Err(failure) => self.report_unreadable_attempts(&mut report, &failure),
2011                }
2012                continue;
2013            }
2014            if supervision_failed.contains(&policy.id) {
2015                continue;
2016            }
2017            let Some(reading) = readings.get(&policy.target) else {
2018                // Unreachable: every policy reaching here was in `pollable`, and
2019                // `poll_targets` inserts an outcome for each of their targets.
2020                debug_assert!(false, "a pollable policy's target has no reading");
2021                continue;
2022            };
2023            match reading {
2024                PollOutcome::Failed(state) => {
2025                    report.unreadable.push(policy.id);
2026                    self.events.emit(LifecycleEvent::TargetUnreadable {
2027                        policy: policy.id,
2028                        reason: unreadable_reason(state),
2029                    });
2030                }
2031                PollOutcome::Ready(demand) => {
2032                    report.targets_read = report.targets_read.saturating_add(1);
2033                    let tally = demand_for(policy, demand);
2034                    let count = tally.demand();
2035                    self.events.emit(LifecycleEvent::DemandObserved {
2036                        policy: policy.id,
2037                        demand: count,
2038                        not_matched: tally.not_matched,
2039                        unresolvable: u32::try_from(tally.unresolvable.len()).unwrap_or(u32::MAX),
2040                        complete: demand.is_complete(),
2041                    });
2042                    self.start_runners(policy, count, &mut report, &mut launched)
2043                        .await;
2044                }
2045            }
2046        }
2047
2048        // --- Flow 2.1 / 3.3: when to come back ------------------------------
2049        let failure = readings
2050            .values()
2051            .filter_map(PollOutcome::failure)
2052            .max_by_key(|state| severity(state))
2053            .cloned();
2054        let now = self.clock.now();
2055        report.next_poll = self
2056            .schedule
2057            .next_poll(failure.as_ref(), now, self.jitter.as_ref());
2058        report.failure = failure;
2059        // Flow 3.3's fourth obligation: the offline state carries the 24-hour
2060        // bound, and it can only say whether that bound has passed if it is
2061        // given the real elapsed time rather than an estimate from the interval.
2062        if let PollPace::Offline { consecutive } = report.next_poll.pace {
2063            let state = OfflineState::new(consecutive, report.next_poll.delay);
2064            report.offline = Some(match self.schedule.offline_for(now) {
2065                Some(elapsed) => state.since(elapsed),
2066                None => state,
2067            });
2068        }
2069        self.events.emit(LifecycleEvent::PollScheduled {
2070            retry_in_ms: u64::try_from(report.next_poll.delay.as_millis()).unwrap_or(u64::MAX),
2071            pace: report.next_poll.pace,
2072        });
2073
2074        report
2075    }
2076
2077    /// Poll each distinct target once, however many policies share it.
2078    ///
2079    /// Two policies on one repository are one demand request, not two. That is
2080    /// not a micro-optimisation: the budget model in
2081    /// `04-subsystem-contracts.md` prices a *target*, and a loop that spent per
2082    /// policy would quietly exceed the projection `f2` admitted the
2083    /// configuration against.
2084    async fn poll_targets(
2085        &self,
2086        pollable: &[&ScalePolicy],
2087        report: &mut ReconcileReport,
2088    ) -> BTreeMap<ScaleTarget, PollOutcome> {
2089        let targets: BTreeSet<ScaleTarget> = pollable.iter().map(|p| p.target.clone()).collect();
2090
2091        let mut readings = BTreeMap::new();
2092        for target in targets {
2093            let outcome = match self.repositories.scope_for(&target).await {
2094                Ok(scope) => {
2095                    report.demand_requests = report
2096                        .demand_requests
2097                        .saturating_add(demand_requests_per_poll(&scope));
2098                    self.demand.poll(&scope).await
2099                }
2100                // The repository list could not be refreshed, so the scope of
2101                // the poll is unknown. Polling a stale or empty scope would
2102                // report a demand number for a set of repositories nobody
2103                // chose, which is worse than reporting that the target could
2104                // not be read.
2105                Err(error) => PollOutcome::Failed(RefreshState::from_error(&error)),
2106            };
2107            readings.insert(target, outcome);
2108        }
2109        readings
2110    }
2111
2112    /// Compute one policy's allocation without creating anything.
2113    ///
2114    /// # Why this is safe without the lock
2115    ///
2116    /// **Not** because it cannot grant — it can, and
2117    /// [`Reconciler::start_runners`] uses it as a pre-check precisely for the
2118    /// number it returns. That was the original reason and this function
2119    /// outgrew it; the reason now is that it *decides* nothing. Nothing is
2120    /// created here, the headroom it read is re-read under the lock before any
2121    /// runtime exists, and the under-lock allocation may only lower what this
2122    /// one proposed. So there is no read-decide-create sequence here to make
2123    /// atomic, and the worst this can be is optimistic — which the lock then
2124    /// corrects.
2125    ///
2126    /// # Errors
2127    /// Whatever [`RunnerLauncher::attempts`] reported. A failure is never the
2128    /// same answer as an empty set.
2129    async fn allocate_only(
2130        &self,
2131        policy: &ScalePolicy,
2132        demand: u32,
2133        launched: &[RunnerAttempt],
2134    ) -> Result<Allocation, LaunchFailure> {
2135        let attempts = self.host_attempts(launched).await?;
2136        let mut allocator = HostAllocator::from_attempts(&self.host, &attempts);
2137        Ok(allocator.allocate(policy, demand))
2138    }
2139
2140    /// Flow 2.4-2.6: start runners for one policy, one lock hold per runtime.
2141    ///
2142    /// # Two stopping conditions, and both are needed
2143    ///
2144    /// The loop re-reads the attempt set under every hold, so the obvious stop
2145    /// is "the allocator granted nothing". That condition **alone does not
2146    /// terminate**, and the failure is not hypothetical — it was measured.
2147    /// Handing the allocator a set that does not include the runners this loop
2148    /// just started (an empty one, a stale one, or a launcher whose journal
2149    /// write has not landed yet) makes every grant look like the first, and the
2150    /// pass starts runners until something outside it intervenes. With the set
2151    /// dropped entirely, the three-consecutive-polls test below does not report
2152    /// three attempts; it *never returns*.
2153    ///
2154    /// So the grant decided on the first hold is also a **budget**. A later hold
2155    /// may lower it — the host may have filled up meanwhile — and can never
2156    /// raise it, which bounds the pass at the number this policy was actually
2157    /// allocated. That is `c2`'s reasoning for `MAX_PAGES` one layer down: the
2158    /// reconciliation loop is the one place in this product that must not be
2159    /// able to wedge, so the bound is structural rather than a consequence of
2160    /// every input being well behaved.
2161    async fn start_runners(
2162        &self,
2163        policy: &ScalePolicy,
2164        demand: u32,
2165        report: &mut ReconcileReport,
2166        launched: &mut Vec<RunnerAttempt>,
2167    ) {
2168        // A lock-free pre-check, for one reason only: the host-wide lock should
2169        // not be taken by a policy that is going to be granted nothing. On an
2170        // idle host with P policies that was P lock acquisitions per poll --
2171        // free under `InProcessAllocationLock`, a `spawn_blocking` and a
2172        // filesystem lock apiece under `FileAllocationLock`.
2173        //
2174        // It is safe because it can only be optimistic. Anything it grants is
2175        // re-decided under the lock below and may be lowered there; the only
2176        // thing it can get wrong in the other direction is refusing a grant that
2177        // headroom freed a moment later would have allowed, which the next poll
2178        // picks up.
2179        let intent = match self.allocate_only(policy, demand, launched).await {
2180            Ok(intent) => intent,
2181            Err(failure) => {
2182                self.report_unreadable_attempts(report, &failure);
2183                return;
2184            }
2185        };
2186
2187        // The allocation that is *reported* is the one taken under the lock when
2188        // a lock was taken, because that is the one that decided anything. The
2189        // pre-check stands in only when no hold was ever obtained.
2190        let mut decided: Option<Allocation> = None;
2191        let mut budget = intent.to_start;
2192
2193        while budget > 0 {
2194            let guard = match self.lock.acquire().await {
2195                Ok(guard) => guard,
2196                Err(_) => {
2197                    // Grants, not policies: this is what the policy was owed and
2198                    // did not get.
2199                    report.deferred = report.deferred.saturating_add(budget);
2200                    self.events.emit(LifecycleEvent::AllocationDeferred {
2201                        policy: policy.id,
2202                        count: budget,
2203                    });
2204                    break;
2205                }
2206            };
2207
2208            // The read and the decision are both inside the hold, and so is the
2209            // creation below. Two concurrent passes therefore serialise on the
2210            // whole sequence rather than on the decision alone -- reading the
2211            // headroom outside the lock is the shape in which two policies both
2212            // find room for the last slot.
2213            let attempts = match self.host_attempts(launched).await {
2214                Ok(attempts) => attempts,
2215                Err(failure) => {
2216                    drop(guard);
2217                    self.report_unreadable_attempts(report, &failure);
2218                    break;
2219                }
2220            };
2221            let mut allocator = HostAllocator::from_attempts(&self.host, &attempts);
2222            let allocation = allocator.allocate(policy, demand);
2223
2224            if decided.is_none() {
2225                // The under-lock decision may be smaller than the pre-check, and
2226                // never larger: `min` rather than assignment, so a later hold
2227                // cannot raise the bound either.
2228                budget = budget.min(allocation.to_start);
2229                decided = Some(allocation.clone());
2230            }
2231
2232            // Either stop is sufficient on its own in the well-behaved case;
2233            // neither is sufficient when the launcher lags. See the doc comment.
2234            if allocation.starts_nothing() || budget == 0 {
2235                drop(guard);
2236                break;
2237            }
2238
2239            let created = self
2240                .launcher
2241                .launch(LaunchRequest {
2242                    host: &self.host,
2243                    policy,
2244                    allocation_guard: &guard,
2245                })
2246                .await;
2247            drop(guard);
2248
2249            match created {
2250                Ok(attempt) => {
2251                    let id = attempt.id;
2252                    // Carried across policies for the rest of this pass, so the
2253                    // host-wide total cannot be computed from a set that is
2254                    // missing it. See `RunnerLauncher::launch`.
2255                    launched.push(attempt);
2256                    report.started = report.started.saturating_add(1);
2257                    budget -= 1;
2258                    self.events.emit(LifecycleEvent::RunnerStarted {
2259                        policy: policy.id,
2260                        attempt: id,
2261                    });
2262                }
2263                Err(failure) => {
2264                    self.events.emit(LifecycleEvent::RunnerStartFailed {
2265                        policy: policy.id,
2266                        reason: failure_reason_kind(&failure.reason),
2267                    });
2268                    break;
2269                }
2270            }
2271        }
2272
2273        let allocation = decided.unwrap_or(intent);
2274        self.emit_allocation(&allocation);
2275        report.allocations.push(allocation);
2276    }
2277
2278    /// The attempt set the host holds, plus everything this pass has already
2279    /// created.
2280    ///
2281    /// The merge is by [`RunnerAttempt::id`], so a launcher that makes its
2282    /// launches visible before returning -- which
2283    /// [`RunnerLauncher::launch`] asks for -- contributes each attempt once, and
2284    /// one that lags still cannot hide a runner from the host-wide total. The
2285    /// ceiling therefore holds on the strength of this function rather than on
2286    /// the strength of an implementer honouring a comment.
2287    ///
2288    /// # Errors
2289    /// Whatever [`RunnerLauncher::attempts`] reported.
2290    async fn host_attempts(
2291        &self,
2292        launched: &[RunnerAttempt],
2293    ) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
2294        let mut attempts = self.launcher.attempts().await?;
2295
2296        // Each `launch` creates one runtime, so each must answer with an
2297        // identifier no other attempt has. Two entries sharing one here are two
2298        // runtimes the host-wide total below counts once, which is the ceiling
2299        // failing silently -- so a development build stops at the first
2300        // duplicate instead. `RunnerLauncher::launch` states the requirement;
2301        // this is what makes it findable.
2302        debug_assert!(
2303            launched
2304                .iter()
2305                .map(|attempt| attempt.id)
2306                .collect::<BTreeSet<AttemptId>>()
2307                .len()
2308                == launched.len(),
2309            "`RunnerLauncher::launch` returned an AttemptId this pass had already seen; \
2310             the host ceiling is enforced against a set keyed on that identifier, so a \
2311             duplicate is two runtimes counted as one"
2312        );
2313
2314        let known: BTreeSet<AttemptId> = attempts.iter().map(|attempt| attempt.id).collect();
2315        attempts.extend(
2316            launched
2317                .iter()
2318                .filter(|attempt| !known.contains(&attempt.id))
2319                .cloned(),
2320        );
2321        Ok(attempts)
2322    }
2323
2324    /// The attempt set could not be read, so nothing may be decided from it.
2325    ///
2326    /// Counted rather than swallowed for the reason the module documentation
2327    /// gives: an unreadable set and an idle host produce the same *number* and
2328    /// demand opposite actions, so the difference has to survive into the
2329    /// report.
2330    fn report_unreadable_attempts(&self, report: &mut ReconcileReport, failure: &LaunchFailure) {
2331        report.attempts_unreadable = report.attempts_unreadable.saturating_add(1);
2332        // The variant, never a literal and never the detail. A hand-written
2333        // `"attempts_unreadable"` said only what the event's own name already
2334        // said, and threw away the one thing the field is for -- *which* failure
2335        // it was. `FailureReason::Other` carries free text that must not reach
2336        // an event, which is what `failure_reason_kind` is for and what
2337        // `a_cleanup_that_cannot_succeed_...` pins for the sibling path.
2338        self.events.emit(LifecycleEvent::AttemptsUnreadable {
2339            reason: failure_reason_kind(&failure.reason),
2340        });
2341    }
2342
2343    /// Remove the runtimes of attempts that have already concluded.
2344    ///
2345    /// `is_concluded` and not `is_terminal`: `cleaned` is terminal and already
2346    /// done, and `busy` is not terminal at all. That is what makes it impossible
2347    /// for this path to reach a runner executing a job.
2348    async fn clean_terminal_attempts(&self, report: &mut ReconcileReport) {
2349        let attempts = match self.launcher.attempts().await {
2350            Ok(attempts) => attempts,
2351            Err(failure) => {
2352                self.report_unreadable_attempts(report, &failure);
2353                return;
2354            }
2355        };
2356        for attempt in attempts {
2357            if !attempt.state().is_concluded() {
2358                continue;
2359            }
2360            let Some(outcome) = attempt.outcome() else {
2361                continue;
2362            };
2363            let kind = OutcomeKind::of(outcome);
2364            match self.launcher.clean(attempt.id).await {
2365                Ok(()) => {
2366                    report.cleaned = report.cleaned.saturating_add(1);
2367                    if kind.is_failure() {
2368                        report.failures = report.failures.saturating_add(1);
2369                    } else if kind == OutcomeKind::IdleExit {
2370                        // The surplus case. Counted apart from a failure because
2371                        // `g2` renders it apart, and because an operator told
2372                        // that a normal surplus exit is an error goes hunting a
2373                        // fault that does not exist.
2374                        report.idle_exits = report.idle_exits.saturating_add(1);
2375                    }
2376                    self.events.emit(LifecycleEvent::AttemptCleaned {
2377                        policy: attempt.policy_id,
2378                        attempt: attempt.id,
2379                        outcome: kind,
2380                    });
2381                }
2382                // A runtime directory that cannot be removed is retried on every
2383                // poll. Silently, before this arm existed: no event, no counter,
2384                // no report field, so a cleanup that can never succeed was an
2385                // invisible permanent loop. It wedges no capacity -- a terminal
2386                // attempt already stopped counting -- but this module's
2387                // organising principle is the things that go wrong silently, and
2388                // `clean` returns a `Result` precisely so the caller can say
2389                // something.
2390                Err(failure) => {
2391                    report.clean_failures = report.clean_failures.saturating_add(1);
2392                    self.events.emit(LifecycleEvent::AttemptCleanFailed {
2393                        policy: attempt.policy_id,
2394                        attempt: attempt.id,
2395                        reason: failure_reason_kind(&failure.reason),
2396                    });
2397                }
2398            }
2399        }
2400    }
2401
2402    /// Reclaim what can be reclaimed for one policy, and nothing else.
2403    ///
2404    /// **A busy attempt is never removed.** `04-subsystem-contracts.md`:
2405    /// *"`busy` cannot transition to cleanup due to a scale-down request"*.
2406    /// Capacity comes back when an attempt reaches a terminal state and at no
2407    /// other time, so a scale-down against a host full of busy runners removes
2408    /// nothing, changes nothing, and says so.
2409    pub async fn scale_down(&self, policy: &ScalePolicy) -> ScaleDownReport {
2410        let mut report = ScaleDownReport::default();
2411        let attempts = match self.launcher.attempts().await {
2412            Ok(attempts) => attempts,
2413            Err(failure) => {
2414                // The same rule as everywhere else, and this was the one place
2415                // it was still broken: an unreadable set is not an empty one,
2416                // and a bare `default()` here reported all zeros -- byte for
2417                // byte an idle host with nothing to reclaim.
2418                self.events.emit(LifecycleEvent::AttemptsUnreadable {
2419                    reason: failure_reason_kind(&failure.reason),
2420                });
2421                report.attempts_unreadable = true;
2422                return report;
2423            }
2424        };
2425        for attempt in attempts {
2426            if attempt.policy_id != policy.id {
2427                continue;
2428            }
2429            match attempt.state() {
2430                AttemptState::Busy => {
2431                    report.refused_busy = report.refused_busy.saturating_add(1);
2432                    self.events.emit(LifecycleEvent::ScaleDownRefused {
2433                        policy: policy.id,
2434                        attempt: attempt.id,
2435                    });
2436                }
2437                state if state.is_concluded() => {
2438                    let kind = attempt
2439                        .outcome()
2440                        .map_or(OutcomeKind::Failed, OutcomeKind::of);
2441                    match self.launcher.clean(attempt.id).await {
2442                        Ok(()) => {
2443                            report.removed = report.removed.saturating_add(1);
2444                            self.events.emit(LifecycleEvent::AttemptCleaned {
2445                                policy: policy.id,
2446                                attempt: attempt.id,
2447                                outcome: kind,
2448                            });
2449                        }
2450                        Err(failure) => {
2451                            report.clean_failures = report.clean_failures.saturating_add(1);
2452                            self.events.emit(LifecycleEvent::AttemptCleanFailed {
2453                                policy: policy.id,
2454                                attempt: attempt.id,
2455                                reason: failure_reason_kind(&failure.reason),
2456                            });
2457                        }
2458                    }
2459                }
2460                AttemptState::Cleaned => {}
2461                // `allocated`, `jit_received`, `starting`, `idle`: live, holding
2462                // a slot, and not this function's to end.
2463                _ => report.retained = report.retained.saturating_add(1),
2464            }
2465        }
2466        report
2467    }
2468
2469    fn emit_allocation(&self, allocation: &Allocation) {
2470        self.events.emit(LifecycleEvent::Allocated {
2471            policy: allocation.policy_id,
2472            demand: allocation.demand,
2473            desired: allocation.desired,
2474            active_owned: allocation.active_owned,
2475            headroom: allocation.headroom_before,
2476            to_start: allocation.to_start,
2477            limiting: allocation.limiting_factor,
2478        });
2479    }
2480}
2481
2482/// One policy's demand, from the reading its target answered with.
2483///
2484/// A repository target tallies its own repository's queued jobs; an organization
2485/// target tallies every repository its scope covered, because one policy watching
2486/// an organization serves any repository in it.
2487///
2488/// # Why this takes a whole policy rather than a target and a label set
2489///
2490/// Because both halves have to come from the same policy, and a signature that
2491/// took them separately made it possible for them not to. The predecessor took a
2492/// `&ScaleTarget` alone and could not filter at all; the obvious repair was to
2493/// add a `&RoutingLabels` beside it, and at three call sites — two of them in
2494/// tests — nothing would have caught passing one policy's target with another
2495/// policy's labels. It compiles, it runs, and it silently serves the wrong
2496/// repository's queue.
2497///
2498/// # A monitor-only policy has no labels, and cannot reach here
2499///
2500/// [`Reconciler::reconcile`] filters on [`ScalePolicy::owns_runners`] before any
2501/// demand request is issued (D19), so the `None` arm is unreachable rather than
2502/// merely unlikely. It returns an empty tally instead of unwrapping, because a
2503/// panic in the reconciliation loop would take the daemon down over a policy
2504/// that was only ever going to start nothing.
2505fn demand_for(policy: &ScalePolicy, reading: &QueuedDemand) -> DemandTally {
2506    let Some(labels) = policy.routing_labels() else {
2507        debug_assert!(
2508            false,
2509            "a monitor-only policy is skipped before the demand poll (D19)"
2510        );
2511        return DemandTally::default();
2512    };
2513
2514    match &policy.target {
2515        ScaleTarget::Repository(repository) => labels.tally(reading.jobs_for(repository)),
2516        ScaleTarget::Organization(_) => labels.tally(reading.jobs()),
2517    }
2518}
2519
2520/// How urgently one failure should slow the loop down.
2521///
2522/// Ordering matters only for picking the worst of several targets: an outage
2523/// outranks a rate limit because backing off a socket that is not answering is
2524/// the safer error, and both outrank a per-target rejection that says nothing
2525/// about the credential as a whole.
2526const fn severity(state: &RefreshState) -> u8 {
2527    match state {
2528        RefreshState::Offline => 5,
2529        RefreshState::RateLimited(_) => 4,
2530        RefreshState::LockedOut { .. } => 3,
2531        RefreshState::Unauthorized => 2,
2532        RefreshState::Forbidden { .. } | RefreshState::Failed { .. } => 1,
2533        RefreshState::Cancelled | RefreshState::Ready(_) => 0,
2534    }
2535}
2536
2537/// Why one target could not be read, as a fixed, credential-free name.
2538///
2539/// Deliberately not a [`PollPace`]: a pace describes the *schedule*, which is a
2540/// property of the whole pass, and stamping one onto a single target would have
2541/// meant inventing a `consecutive` count for a target that has none. What an
2542/// event needs here is the reason, and `c3`'s [`RefreshState`] already names it.
2543///
2544/// `RefreshState::Failed` carries GitHub's own message and
2545/// `RefreshState::Forbidden` may carry one too. Neither reaches the event: this
2546/// returns the variant, for the reason [`failure_reason_kind`] states.
2547const fn unreadable_reason(state: &RefreshState) -> &'static str {
2548    match state {
2549        RefreshState::Ready(_) => "ready",
2550        RefreshState::Offline => "offline",
2551        RefreshState::RateLimited(_) => "rate_limited",
2552        RefreshState::LockedOut { .. } => "locked_out",
2553        RefreshState::Unauthorized => "unauthorized",
2554        RefreshState::Forbidden { .. } => "forbidden",
2555        RefreshState::Failed { .. } => "failed",
2556        RefreshState::Cancelled => "cancelled",
2557    }
2558}
2559
2560#[cfg(test)]
2561mod tests {
2562    use super::*;
2563
2564    /// The reading that said `healthy` for 28 hours while nothing worked.
2565    ///
2566    /// A daemon every one of whose targets answered `401` kept writing a fresh
2567    /// `last GitHub contact`, because an unauthorized target is `unreadable`
2568    /// rather than a `failure`. Both that record and the `service status` built
2569    /// on it were used as evidence during the investigation, and both were
2570    /// wrong; see `docs/spikes/token-expiry-and-renewal.md`.
2571    #[test]
2572    fn a_pass_that_reached_no_target_does_not_claim_it_reached_github() {
2573        let mut report = ReconcileReport::default();
2574        assert!(
2575            !report.reached_github(),
2576            "a pass that polled nothing -- every policy draining, owned elsewhere, or \
2577             monitor-only -- reached nobody. This is the case the old guard let through, and \
2578             the only one it ever let through."
2579        );
2580
2581        report.unreadable.push(PolicyId::from_u128(1));
2582        assert!(
2583            !report.reached_github(),
2584            "every target this pass tried was unreadable, so there is no contact to record"
2585        );
2586
2587        report.targets_read = 1;
2588        assert!(
2589            report.reached_github(),
2590            "one target answering is contact, whatever else failed alongside it"
2591        );
2592
2593        // `allocations` deliberately does not count: a policy this host does
2594        // not own is allocated for with no demand and without polling anything,
2595        // so a pass where every poll failed can still carry allocations.
2596        let mut unowned = ReconcileReport::default();
2597        unowned.unreadable.push(PolicyId::from_u128(2));
2598        unowned.allocations.push(Allocation {
2599            policy_id: PolicyId::from_u128(2),
2600            demand: 0,
2601            desired: 0,
2602            active_owned: 0,
2603            headroom_before: 0,
2604            to_start: 0,
2605            limiting_factor: LimitingFactor::Demand,
2606        });
2607        assert!(
2608            !unowned.reached_github(),
2609            "an allocation is not evidence that GitHub answered"
2610        );
2611    }
2612
2613    /// The claim the old guard rested on, checked rather than assumed.
2614    ///
2615    /// `report.failure.is_none()` was believed to be compatible with an
2616    /// all-unauthorized pass. It is not: `unreadable` is pushed only from the
2617    /// `Failed` arm and `failure` is the maximum over every `Failed` reading,
2618    /// so guarding on `failure.is_none() && reached_github()` would have been
2619    /// `failure.is_none()` with extra words. This pins the severity that makes
2620    /// it so, because a future `severity(Unauthorized) == 0` would quietly
2621    /// restore the belief.
2622    #[test]
2623    fn an_unauthorized_target_is_a_failure_and_not_merely_unreadable() {
2624        assert!(
2625            severity(&RefreshState::Unauthorized) > 0,
2626            "an unauthorized reading must survive `max_by_key(severity)` into `report.failure`, \
2627             or a pass where every target was refused would report no failure at all"
2628        );
2629    }
2630
2631    use std::sync::atomic::AtomicUsize;
2632
2633    use std::num::NonZeroU16;
2634
2635    use runner_manager_domain::attempt::PersistedAttempt;
2636    use runner_manager_domain::model::{CachePolicy, HostId};
2637    use runner_manager_domain::policy::PolicyMode;
2638    use runner_manager_domain::workspace::WorkspaceKind;
2639    use runner_manager_github::rest::RateLimited;
2640    use runner_manager_testkit::clock::FakeClock;
2641    use runner_manager_testkit::fixtures;
2642    use runner_manager_testkit::github::FakeGithub;
2643
2644    // =======================================================================
2645    // Fakes
2646    // =======================================================================
2647
2648    fn host_with(capacity: u16) -> Host {
2649        fixtures::host().capacity(capacity).build()
2650    }
2651
2652    fn repo(raw: &str) -> OwnerRepo {
2653        OwnerRepo::parse(raw).expect("a valid OWNER/REPO")
2654    }
2655
2656    /// An `active`, enabled autoscale policy on the fixture host.
2657    use runner_manager_domain::policy::RunsOn;
2658
2659    fn policy(id: u128, target: &str, max: u16) -> ScalePolicy {
2660        fixtures::policy()
2661            .id(PolicyId::from_u128(id))
2662            .repository(target)
2663            .autoscale("home", max)
2664            .active()
2665            .build()
2666    }
2667
2668    /// The host label every policy in these tests carries.
2669    ///
2670    /// `policy` above builds through `fixtures::policy().autoscale("home", …)`,
2671    /// which derives `rm-home-win-x64`. A job fixture that did not carry it
2672    /// would be filtered out as another host's work, so the two are tied
2673    /// together here rather than repeated as a literal at each call site.
2674    const HOST_LABEL: &str = "rm-home-win-x64";
2675
2676    /// `n` queued jobs this host's policies match.
2677    ///
2678    /// The ordinary demand fixture. Since the reversal of the run-counting
2679    /// decision the unit `e1` clamps is a job, so a test wanting demand `n` asks
2680    /// for `n` jobs rather than for `n` runs.
2681    fn jobs(n: usize) -> Vec<RunsOn> {
2682        fixtures::queued_jobs(&[HOST_LABEL], n)
2683    }
2684
2685    /// `e3`, faked: an attempt table and a launch counter, no process anywhere.
2686    #[derive(Debug, Default)]
2687    struct FakeLauncher {
2688        attempts: Mutex<Vec<RunnerAttempt>>,
2689        next_id: AtomicU64,
2690        launches: AtomicUsize,
2691        cleaned: Mutex<Vec<AttemptId>>,
2692        /// Yields this many times between reading the attempt set and recording
2693        /// a new one, so an unserialised allocator has a window to be wrong in.
2694        yields_before_recording: usize,
2695        /// Reports success without the attempt ever becoming visible, which is
2696        /// the shape a slow journal write has. Every grant then looks like the
2697        /// first.
2698        forgetful: bool,
2699        fail_next: Mutex<Option<FailureReason>>,
2700        /// Reports that the attempt set cannot be read at all, which is the one
2701        /// answer a caller must never confuse with an idle host.
2702        attempts_fail: Mutex<bool>,
2703        /// Refuses every cleanup, so the silent-retry path has something to be
2704        /// loud about.
2705        clean_fails: bool,
2706        replacements: Mutex<Vec<ReplacementIntent>>,
2707    }
2708
2709    impl FakeLauncher {
2710        fn new() -> Self {
2711            Self::default()
2712        }
2713
2714        fn with_yields(mut self, yields: usize) -> Self {
2715            self.yields_before_recording = yields;
2716            self
2717        }
2718
2719        fn forgetful() -> Self {
2720            Self {
2721                forgetful: true,
2722                ..Self::default()
2723            }
2724        }
2725
2726        fn seeded(self, attempts: Vec<RunnerAttempt>) -> Self {
2727            *self.attempts.lock().unwrap() = attempts;
2728            self
2729        }
2730
2731        fn launches(&self) -> usize {
2732            self.launches.load(Ordering::SeqCst)
2733        }
2734
2735        fn snapshot(&self) -> Vec<RunnerAttempt> {
2736            self.attempts.lock().unwrap().clone()
2737        }
2738
2739        fn live_count(&self) -> usize {
2740            self.snapshot()
2741                .iter()
2742                .filter(|a| a.counts_against_capacity())
2743                .count()
2744        }
2745
2746        fn fail_next(&self, reason: FailureReason) {
2747            *self.fail_next.lock().unwrap() = Some(reason);
2748        }
2749
2750        fn fail_attempts(&self, failing: bool) {
2751            *self.attempts_fail.lock().unwrap() = failing;
2752        }
2753
2754        fn refusing_cleanup(attempts: Vec<RunnerAttempt>) -> Self {
2755            Self {
2756                clean_fails: true,
2757                ..Self::default()
2758            }
2759            .seeded(attempts)
2760        }
2761
2762        fn cleaned(&self) -> Vec<AttemptId> {
2763            self.cleaned.lock().unwrap().clone()
2764        }
2765
2766        fn replacing(self, intent: ReplacementIntent) -> Self {
2767            self.replacements.lock().unwrap().push(intent);
2768            self
2769        }
2770    }
2771
2772    #[async_trait::async_trait]
2773    impl RunnerLauncher for FakeLauncher {
2774        async fn supervise(
2775            &self,
2776            policy: &ScalePolicy,
2777        ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
2778            let mut replacements = self.replacements.lock().unwrap();
2779            let selected: Vec<_> = replacements
2780                .extract_if(.., |intent| intent.policy == policy.id)
2781                .collect();
2782            if !selected.is_empty() {
2783                let retired: BTreeSet<_> = selected
2784                    .iter()
2785                    .map(|intent| intent.previous_attempt)
2786                    .collect();
2787                self.attempts
2788                    .lock()
2789                    .unwrap()
2790                    .retain(|attempt| !retired.contains(&attempt.id));
2791            }
2792            Ok(selected)
2793        }
2794
2795        async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
2796            if *self.attempts_fail.lock().unwrap() {
2797                return Err(LaunchFailure::new(FailureReason::Other(
2798                    "the journal could not be read".into(),
2799                )));
2800            }
2801            Ok(self.snapshot())
2802        }
2803
2804        async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure> {
2805            if let Some(reason) = self.fail_next.lock().unwrap().take() {
2806                return Err(LaunchFailure::new(reason));
2807            }
2808            // The window an unserialised caller would lose the race in.
2809            for _ in 0..self.yields_before_recording {
2810                tokio::task::yield_now().await;
2811            }
2812            let id =
2813                AttemptId::from_u128(u128::from(self.next_id.fetch_add(1, Ordering::SeqCst) + 1));
2814            let created = RunnerAttempt::allocate(
2815                id,
2816                request.policy.id,
2817                "runtime/p/a",
2818                request.host.created_at,
2819            );
2820            self.launches.fetch_add(1, Ordering::SeqCst);
2821            if !self.forgetful {
2822                self.attempts.lock().unwrap().push(created.clone());
2823            }
2824            Ok(created)
2825        }
2826
2827        async fn clean(&self, attempt: AttemptId) -> Result<(), LaunchFailure> {
2828            if self.clean_fails {
2829                return Err(LaunchFailure::new(FailureReason::Other(
2830                    "the runtime directory is locked".into(),
2831                )));
2832            }
2833            self.cleaned.lock().unwrap().push(attempt);
2834            let mut attempts = self.attempts.lock().unwrap();
2835            attempts.retain(|a| a.id != attempt);
2836            Ok(())
2837        }
2838    }
2839
2840    /// A demand source a test programs directly, with no gateway underneath.
2841    #[derive(Debug, Default)]
2842    struct FakeDemand {
2843        outcome: Mutex<Option<PollOutcome>>,
2844        /// Answers programmed for one target, which beat the blanket one.
2845        per_target: Mutex<BTreeMap<ScaleTarget, PollOutcome>>,
2846        scopes: Mutex<Vec<ActivityScope>>,
2847    }
2848
2849    impl FakeDemand {
2850        fn ready(count: u32, repository: &OwnerRepo) -> Self {
2851            let fake = Self::default();
2852            fake.set(PollOutcome::Ready(QueuedDemand::of(
2853                repository.clone(),
2854                jobs(count as usize),
2855            )));
2856            fake
2857        }
2858
2859        fn failing(state: RefreshState) -> Self {
2860            let fake = Self::default();
2861            fake.set(PollOutcome::Failed(state));
2862            fake
2863        }
2864
2865        fn set(&self, outcome: PollOutcome) {
2866            *self.outcome.lock().unwrap() = Some(outcome);
2867        }
2868
2869        /// Program one target's answer, overriding the blanket one.
2870        fn set_for(&self, target: &ScaleTarget, outcome: PollOutcome) {
2871            self.per_target
2872                .lock()
2873                .unwrap()
2874                .insert(target.clone(), outcome);
2875        }
2876
2877        fn polls(&self) -> Vec<ActivityScope> {
2878            self.scopes.lock().unwrap().clone()
2879        }
2880    }
2881
2882    #[async_trait::async_trait]
2883    impl DemandSource for FakeDemand {
2884        async fn poll(&self, scope: &ActivityScope) -> PollOutcome {
2885            self.scopes.lock().unwrap().push(scope.clone());
2886            if let Some(outcome) = self.per_target.lock().unwrap().get(scope.target()) {
2887                return outcome.clone();
2888            }
2889            self.outcome
2890                .lock()
2891                .unwrap()
2892                .clone()
2893                .unwrap_or(PollOutcome::Ready(QueuedDemand::default()))
2894        }
2895    }
2896
2897    #[derive(Debug, Default)]
2898    struct FakeDirectory {
2899        repositories: Vec<OwnerRepo>,
2900        calls: AtomicUsize,
2901    }
2902
2903    impl FakeDirectory {
2904        fn of(repositories: Vec<OwnerRepo>) -> Self {
2905            Self {
2906                repositories,
2907                calls: AtomicUsize::new(0),
2908            }
2909        }
2910
2911        fn calls(&self) -> usize {
2912            self.calls.load(Ordering::SeqCst)
2913        }
2914    }
2915
2916    #[async_trait::async_trait]
2917    impl RepositoryDirectory for FakeDirectory {
2918        async fn repositories(&self, _org: &Org) -> Result<Vec<OwnerRepo>, InventoryError> {
2919            self.calls.fetch_add(1, Ordering::SeqCst);
2920            Ok(self.repositories.clone())
2921        }
2922    }
2923
2924    /// A lock that grants everything and counts how many holders it had at once.
2925    ///
2926    /// The counter is the assertion: "under simulated lock contention" is only
2927    /// meaningful if something measures that the contention was actually
2928    /// serialised.
2929    #[derive(Debug)]
2930    struct CountingLock {
2931        inner: InProcessAllocationLock,
2932        concurrent: Arc<AtomicUsize>,
2933        peak: Arc<AtomicUsize>,
2934        acquisitions: Arc<AtomicUsize>,
2935    }
2936
2937    impl CountingLock {
2938        fn new() -> Self {
2939            Self {
2940                inner: InProcessAllocationLock::new(),
2941                concurrent: Arc::new(AtomicUsize::new(0)),
2942                peak: Arc::new(AtomicUsize::new(0)),
2943                acquisitions: Arc::new(AtomicUsize::new(0)),
2944            }
2945        }
2946
2947        fn peak(&self) -> usize {
2948            self.peak.load(Ordering::SeqCst)
2949        }
2950
2951        fn acquisitions(&self) -> usize {
2952            self.acquisitions.load(Ordering::SeqCst)
2953        }
2954    }
2955
2956    #[derive(Debug)]
2957    struct CountingGuard {
2958        _inner: AllocationGuard,
2959        concurrent: Arc<AtomicUsize>,
2960    }
2961
2962    impl Drop for CountingGuard {
2963        fn drop(&mut self) {
2964            self.concurrent.fetch_sub(1, Ordering::SeqCst);
2965        }
2966    }
2967
2968    #[async_trait::async_trait]
2969    impl AllocationLock for CountingLock {
2970        async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
2971            let inner = self.inner.acquire().await?;
2972            self.acquisitions.fetch_add(1, Ordering::SeqCst);
2973            let now = self.concurrent.fetch_add(1, Ordering::SeqCst) + 1;
2974            self.peak.fetch_max(now, Ordering::SeqCst);
2975            Ok(AllocationGuard::new(CountingGuard {
2976                _inner: inner,
2977                concurrent: Arc::clone(&self.concurrent),
2978            }))
2979        }
2980    }
2981
2982    /// The lock that is not one: what the host looks like with the serialisation
2983    /// removed. Used only by the control half of the contention test.
2984    #[derive(Debug, Default)]
2985    struct NoLock;
2986
2987    #[async_trait::async_trait]
2988    impl AllocationLock for NoLock {
2989        async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
2990            Ok(AllocationGuard::new(()))
2991        }
2992    }
2993
2994    #[tokio::test]
2995    async fn a_wsl_drain_request_fences_the_exact_pre_launch_boundary() {
2996        use runner_manager_platform::paths::AppPaths;
2997        use runner_manager_platform::wsl::fence::{DrainRequest, GuestRecoveryConfig};
2998
2999        let local = tempfile::tempdir().unwrap();
3000        let shared = tempfile::tempdir().unwrap();
3001        let paths = Arc::new(AppPaths::rooted_at(local.path()));
3002        paths.create_all().unwrap();
3003        GuestRecoveryConfig::new(shared.path().to_path_buf())
3004            .write(&paths)
3005            .unwrap();
3006        DrainRequest::new(4, chrono::Utc::now())
3007            .write(shared.path())
3008            .unwrap();
3009        let lock = WslRecoveryAllocationLock::new(paths, Arc::new(NoLock));
3010
3011        assert!(lock.acquire().await.is_err());
3012    }
3013
3014    #[tokio::test]
3015    async fn a_guest_launch_claim_is_released_with_its_allocation_guard() {
3016        use runner_manager_platform::paths::AppPaths;
3017        use runner_manager_platform::wsl::fence::{FENCE_DIRECTORY, GuestRecoveryConfig};
3018
3019        let local = tempfile::tempdir().unwrap();
3020        let shared = tempfile::tempdir().unwrap();
3021        let paths = Arc::new(AppPaths::rooted_at(local.path()));
3022        paths.create_all().unwrap();
3023        GuestRecoveryConfig::new(shared.path().to_path_buf())
3024            .write(&paths)
3025            .unwrap();
3026        let lock = WslRecoveryAllocationLock::new(paths, Arc::new(NoLock));
3027        let guard = lock.acquire().await.unwrap();
3028        assert!(shared.path().join(FENCE_DIRECTORY).exists());
3029        drop(guard);
3030        assert!(!shared.path().join(FENCE_DIRECTORY).exists());
3031    }
3032
3033    /// A lock nobody can take.
3034    #[derive(Debug, Default)]
3035    struct HeldLock;
3036
3037    #[async_trait::async_trait]
3038    impl AllocationLock for HeldLock {
3039        async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
3040            Err(AllocationLockBusy)
3041        }
3042    }
3043
3044    /// Everything one test needs, wired together.
3045    struct Harness {
3046        launcher: Arc<FakeLauncher>,
3047        demand: Arc<FakeDemand>,
3048        events: Arc<EventLog>,
3049        reconciler: Reconciler,
3050    }
3051
3052    impl Harness {
3053        fn build(
3054            host: Host,
3055            launcher: Arc<FakeLauncher>,
3056            demand: Arc<FakeDemand>,
3057            lock: Arc<dyn AllocationLock>,
3058        ) -> Self {
3059            let events = Arc::new(EventLog::new());
3060            let reconciler = Reconciler::new(
3061                host,
3062                ReconcilerPorts {
3063                    demand: Arc::clone(&demand) as Arc<dyn DemandSource>,
3064                    launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
3065                    lock,
3066                    directory: Arc::new(FakeDirectory::default()),
3067                    clock: Arc::new(FakeClock::default()),
3068                    jitter: Arc::new(NoJitter) as Arc<dyn Jitter>,
3069                    events: Arc::clone(&events) as Arc<dyn EventSink>,
3070                },
3071            );
3072            Self {
3073                launcher,
3074                demand,
3075                events,
3076                reconciler,
3077            }
3078        }
3079
3080        fn simple(capacity: u16, demand_count: u32, target: &str) -> Self {
3081            let launcher = Arc::new(FakeLauncher::new());
3082            let demand = Arc::new(FakeDemand::ready(demand_count, &repo(target)));
3083            Self::build(
3084                host_with(capacity),
3085                launcher,
3086                demand,
3087                Arc::new(InProcessAllocationLock::new()),
3088            )
3089        }
3090    }
3091
3092    fn attempt_in(state: AttemptState, id: u128, policy: u128) -> RunnerAttempt {
3093        let outcome = state.is_terminal().then(|| match state {
3094            AttemptState::Failed => {
3095                AttemptOutcome::failed(FailureReason::ProcessExitedUnexpectedly)
3096            }
3097            AttemptState::Orphaned => AttemptOutcome::Orphaned,
3098            _ => AttemptOutcome::CompletedJob,
3099        });
3100        RunnerAttempt::from_persisted(PersistedAttempt {
3101            id: AttemptId::from_u128(id),
3102            policy_id: PolicyId::from_u128(policy),
3103            github_runner_id: None,
3104            state,
3105            outcome,
3106            process_id: None,
3107            runtime_path: "runtime/p/a".into(),
3108            workspace_kind: WorkspaceKind::Ephemeral,
3109            workspace_slot: None,
3110            created_at: fixtures::created_at(),
3111            terminal_at: state.is_terminal().then(fixtures::created_at),
3112            last_state_change_at: fixtures::created_at(),
3113        })
3114        .expect("a state/outcome pair the domain accepts")
3115    }
3116
3117    /// A concluded attempt carrying a specific outcome.
3118    fn concluded(id: u128, policy: u128, outcome: AttemptOutcome) -> RunnerAttempt {
3119        RunnerAttempt::from_persisted(PersistedAttempt {
3120            id: AttemptId::from_u128(id),
3121            policy_id: PolicyId::from_u128(policy),
3122            github_runner_id: None,
3123            state: outcome.terminal_state(),
3124            outcome: Some(outcome),
3125            process_id: None,
3126            runtime_path: "runtime/p/a".into(),
3127            workspace_kind: WorkspaceKind::Ephemeral,
3128            workspace_slot: None,
3129            created_at: fixtures::created_at(),
3130            terminal_at: Some(fixtures::created_at()),
3131            last_state_change_at: fixtures::created_at(),
3132        })
3133        .expect("a state/outcome pair the domain accepts")
3134    }
3135
3136    // =======================================================================
3137    // The in-flight term: the single most likely way this task goes wrong
3138    // =======================================================================
3139
3140    /// `e1`'s Definition of Done, verbatim: *"A job that remains `queued` across
3141    /// three consecutive polls while its attempt is `starting` yields exactly
3142    /// one attempt — the test fails if the in-flight term is dropped from the
3143    /// formula."*
3144    ///
3145    /// `b1` tests the arithmetic underneath this
3146    /// (`capacity::tests::the_same_queued_job_on_two_polls_yields_one_attempt_
3147    /// not_two`). What *this* test covers is the only way `e1` can drop the
3148    /// term without touching `b1` at all: handing the allocator an attempt set
3149    /// that is not the one the host holds.
3150    ///
3151    /// # This was measured, not assumed, and the first measurement was worse
3152    /// # than the failure it was looking for
3153    ///
3154    /// Replacing `self.launcher.attempts().await` in
3155    /// [`Reconciler::start_runners`] with `Vec::new()` compiles and runs. Before
3156    /// that function carried a budget, this test did not go red — it **never
3157    /// returned**: every grant looked like the first, so the pass started
3158    /// runners forever inside poll 1. That is the runaway-runner failure exactly
3159    /// as an operator would meet it, and it is why the budget exists.
3160    ///
3161    /// With the budget in place the same injection fails cleanly and says what
3162    /// happened: `poll 2 … left: 2, right: 1`. Both measurements were run
3163    /// before this assertion was written.
3164    #[tokio::test]
3165    async fn three_polls_of_one_still_queued_run_yield_exactly_one_attempt() {
3166        let mut harness = Harness::simple(4, 1, "acme/app");
3167        let policy = policy(1, "acme/app", 4);
3168
3169        for poll in 1..=3 {
3170            let report = harness
3171                .reconciler
3172                .reconcile(std::slice::from_ref(&policy))
3173                .await;
3174            assert_eq!(
3175                harness.launcher.launches(),
3176                1,
3177                "poll {poll} started another runner for a job already being served; the \
3178                 `- active_owned_runners` term reached `HostAllocator` as a set this host \
3179                 does not hold"
3180            );
3181            assert_eq!(report.allocations.len(), 1);
3182            let allocation = &report.allocations[0];
3183            assert_eq!(allocation.demand, 1, "poll {poll}: still queued at GitHub");
3184            if poll == 1 {
3185                assert_eq!(allocation.to_start, 1);
3186                assert_eq!(report.started, 1);
3187            } else {
3188                assert_eq!(allocation.active_owned, 1, "poll {poll}");
3189                assert_eq!(allocation.to_start, 0, "poll {poll}");
3190                assert_eq!(report.started, 0, "poll {poll}");
3191            }
3192        }
3193        assert_eq!(harness.launcher.live_count(), 1);
3194    }
3195
3196    /// The other half of the measurement above: the loop must terminate even
3197    /// when the attempt set never catches up with it.
3198    ///
3199    /// Dropping the in-flight term made
3200    /// `three_polls_of_one_still_queued_run_yield_exactly_one_attempt` hang
3201    /// rather than fail — the loop had one stopping condition and it was the one
3202    /// the bug removed. A launcher whose journal write has not landed presents
3203    /// exactly the same shape without any bug at all, so the budget in
3204    /// [`Reconciler::start_runners`] bounds the pass structurally. This is what
3205    /// asserts the bound is really there.
3206    #[tokio::test]
3207    async fn a_launcher_whose_attempts_never_appear_cannot_wedge_the_pass() {
3208        let launcher = Arc::new(FakeLauncher::forgetful());
3209        let mut harness = Harness::build(
3210            host_with(64),
3211            Arc::clone(&launcher),
3212            Arc::new(FakeDemand::ready(3, &repo("acme/app"))),
3213            Arc::new(InProcessAllocationLock::new()),
3214        );
3215
3216        let report = harness
3217            .reconciler
3218            .reconcile(&[policy(1, "acme/app", 8)])
3219            .await;
3220
3221        assert_eq!(
3222            report.started, 3,
3223            "the pass is bounded by the grant it was given, not by the attempt set catching \
3224             up with it"
3225        );
3226        assert_eq!(launcher.launches(), 3);
3227        assert!(
3228            launcher.snapshot().is_empty(),
3229            "the launcher never recorded anything, which is the whole point of the fixture"
3230        );
3231    }
3232
3233    /// The host-wide ceiling must hold across policies even when the launcher
3234    /// lags, and the per-policy budget alone does not reach that case.
3235    ///
3236    /// Review found this, with this file's own `forgetful` fixture and one more
3237    /// policy: the budget bounds *each policy's* loop to its own first grant,
3238    /// but policy B's first grant is computed from a set that does not yet
3239    /// contain policy A's launches, so B's bound is itself too large. Two
3240    /// policies on a host of three started **six** runners --
3241    /// `host_capacity=3, started=6, launches=6` -- with the lock held correctly
3242    /// throughout. Serialisation was never the problem; the arithmetic under it
3243    /// was reading a stale set.
3244    #[tokio::test]
3245    async fn two_policies_cannot_exceed_host_capacity_even_when_the_launcher_lags() {
3246        let launcher = Arc::new(FakeLauncher::forgetful());
3247        let demand = Arc::new(FakeDemand::default());
3248        demand.set_for(
3249            &ScaleTarget::repository("acme/left").unwrap(),
3250            PollOutcome::Ready(QueuedDemand::of(repo("acme/left"), jobs(3))),
3251        );
3252        demand.set_for(
3253            &ScaleTarget::repository("acme/right").unwrap(),
3254            PollOutcome::Ready(QueuedDemand::of(repo("acme/right"), jobs(3))),
3255        );
3256        let mut harness = Harness::build(
3257            host_with(3),
3258            Arc::clone(&launcher),
3259            demand,
3260            Arc::new(InProcessAllocationLock::new()),
3261        );
3262
3263        let report = harness
3264            .reconciler
3265            .reconcile(&[policy(1, "acme/left", 3), policy(2, "acme/right", 3)])
3266            .await;
3267
3268        assert_eq!(
3269            report.started, 3,
3270            "host_capacity is 3 and two policies each allowed 3 started {} runners \
3271             between them; the second policy's grant was computed from a set that did \
3272             not yet contain the first policy's launches",
3273            report.started
3274        );
3275        assert_eq!(launcher.launches(), 3);
3276    }
3277
3278    /// Finding 1: an attempt set that cannot be read is not an empty one.
3279    ///
3280    /// `attempts()` used to be infallible, which left `e3` — reading a journal
3281    /// off a disk — a choice between panicking and answering `vec![]`. The
3282    /// second is silent and catastrophic: an empty set is indistinguishable from
3283    /// an idle host, so a transient read failure reads as "nothing is running"
3284    /// and the pass allocates the whole machine for jobs already being served.
3285    ///
3286    /// The contrast is the assertion. Identical host, identical demand,
3287    /// identical policy; the only difference is whether the launcher can answer.
3288    #[tokio::test]
3289    async fn an_unreadable_attempt_set_starts_nothing_and_is_not_read_as_an_idle_host() {
3290        let launcher = Arc::new(FakeLauncher::new());
3291        let mut harness = Harness::build(
3292            host_with(8),
3293            Arc::clone(&launcher),
3294            Arc::new(FakeDemand::ready(4, &repo("acme/app"))),
3295            Arc::new(InProcessAllocationLock::new()),
3296        );
3297        let policy = policy(1, "acme/app", 8);
3298
3299        launcher.fail_attempts(true);
3300        let unreadable = harness
3301            .reconciler
3302            .reconcile(std::slice::from_ref(&policy))
3303            .await;
3304
3305        assert_eq!(
3306            unreadable.started, 0,
3307            "nothing may be decided from a set that was not read"
3308        );
3309        assert_eq!(launcher.launches(), 0);
3310        assert!(unreadable.attempts_unreadable > 0, "and the pass says so");
3311        assert!(
3312            unreadable.allocations.is_empty(),
3313            "no allocation is reported either: there was no set to compute one from, and \
3314             an allocation of zero would claim a decision nobody made"
3315        );
3316        assert!(harness.events.count_of("attempts_unreadable") > 0);
3317
3318        // The same everything, with a launcher that can answer.
3319        launcher.fail_attempts(false);
3320        let readable = harness
3321            .reconciler
3322            .reconcile(std::slice::from_ref(&policy))
3323            .await;
3324        assert_eq!(
3325            readable.started, 4,
3326            "the difference between the two passes is only whether the set could be read"
3327        );
3328        assert_eq!(readable.attempts_unreadable, 0);
3329    }
3330
3331    /// Finding 3: a cleanup that can never succeed was an invisible permanent
3332    /// loop.
3333    ///
3334    /// `if …clean(…).await.is_ok()` had no `else`, so a runtime directory that
3335    /// could not be removed was retried on every poll with no event, no counter
3336    /// and no report field. It wedges no capacity — a terminal attempt already
3337    /// stopped counting — but `clean` returns a `Result` precisely so the caller
3338    /// can say something, and this module's organising principle is the things
3339    /// that go wrong silently.
3340    #[tokio::test]
3341    async fn a_cleanup_that_cannot_succeed_is_reported_rather_than_retried_in_silence() {
3342        let launcher = Arc::new(FakeLauncher::refusing_cleanup(vec![concluded(
3343            1,
3344            1,
3345            AttemptOutcome::ExitedIdleWithoutWork,
3346        )]));
3347        let mut harness = Harness::build(
3348            host_with(4),
3349            Arc::clone(&launcher),
3350            Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
3351            Arc::new(InProcessAllocationLock::new()),
3352        );
3353
3354        let report = harness
3355            .reconciler
3356            .reconcile(&[policy(1, "acme/app", 4)])
3357            .await;
3358
3359        assert_eq!(report.cleaned, 0);
3360        assert_eq!(report.clean_failures, 1);
3361        assert_eq!(harness.events.count_of("attempt_clean_failed"), 1);
3362        assert_eq!(
3363            harness.events.count_of("attempt_cleaned"),
3364            0,
3365            "and it is not reported as cleaned"
3366        );
3367        assert_eq!(
3368            launcher.snapshot().len(),
3369            1,
3370            "the attempt is still there, so the retry is real -- what changed is that it \
3371             is no longer silent"
3372        );
3373
3374        // The reason is the variant, never the detail: the fixture's failure
3375        // carries free text and none of it reaches the event.
3376        let reasons: Vec<&'static str> = harness
3377            .events
3378            .events()
3379            .into_iter()
3380            .filter_map(|event| match event {
3381                LifecycleEvent::AttemptCleanFailed { reason, .. } => Some(reason),
3382                _ => None,
3383            })
3384            .collect();
3385        assert_eq!(reasons, vec!["other"]);
3386    }
3387
3388    /// N2: an unreadable attempt set makes a scale-down inconclusive, not empty.
3389    ///
3390    /// Making `attempts()` fallible closed this everywhere the allocation path
3391    /// touches, and left it open in the one place that returns a different type:
3392    /// `scale_down` answered `ScaleDownReport::default()`, which is all zeros
3393    /// and byte-for-byte identical to an idle host with nothing to reclaim. The
3394    /// two mean opposite things — "there was nothing to remove" against "we
3395    /// cannot see what there was".
3396    ///
3397    /// Measured as the sibling test measures it: identical host, identical
3398    /// attempts, identical policy, and the only difference is whether the
3399    /// launcher can answer.
3400    #[tokio::test]
3401    async fn an_unreadable_attempt_set_makes_scale_down_inconclusive_rather_than_empty() {
3402        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3403            attempt_in(AttemptState::Busy, 1, 1),
3404            concluded(2, 1, AttemptOutcome::CompletedJob),
3405        ]));
3406        let harness = Harness::build(
3407            host_with(4),
3408            Arc::clone(&launcher),
3409            Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
3410            Arc::new(InProcessAllocationLock::new()),
3411        );
3412        let policy = policy(1, "acme/app", 4);
3413
3414        launcher.fail_attempts(true);
3415        let blind = harness.reconciler.scale_down(&policy).await;
3416
3417        assert!(!blind.is_conclusive(), "the machine was never read");
3418        assert_ne!(
3419            blind,
3420            ScaleDownReport::default(),
3421            "a scale-down that could not see the host must not be equal to one that saw \
3422             an idle host; that equality is the whole finding"
3423        );
3424        assert_eq!(blind.removed, 0);
3425        assert_eq!(
3426            blind.refused_busy, 0,
3427            "and this zero means `unknown`, not `none`"
3428        );
3429        assert_eq!(harness.events.count_of("attempts_unreadable"), 1);
3430
3431        // The same everything, with a launcher that can answer.
3432        launcher.fail_attempts(false);
3433        let seeing = harness.reconciler.scale_down(&policy).await;
3434
3435        assert!(seeing.is_conclusive());
3436        assert_eq!(seeing.removed, 1, "the concluded attempt was reclaimed");
3437        assert_eq!(seeing.refused_busy, 1, "and the busy one was left alone");
3438        assert_ne!(
3439            seeing, blind,
3440            "the difference between the two is only whether the set could be read"
3441        );
3442    }
3443
3444    /// Finding 7: the lower arm of the clamp, driven through the reconciler.
3445    ///
3446    /// `demand_below_min_capacity_starts_nothing_in_v1` runs `demand = 0`
3447    /// against `min_capacity = 0`, which is *at* the floor and never raises
3448    /// `desired` — the assertion held for a reason unrelated to the boundary it
3449    /// named. D7 fixes `min` at 0 for v1, but `AutoscaleConfig::new` accepts
3450    /// `min > 0` today, so the path is representable and was undriven.
3451    #[tokio::test]
3452    async fn demand_below_min_capacity_is_raised_to_min_capacity() {
3453        let mut warm = ScalePolicy::new(
3454            PolicyId::from_u128(1),
3455            ScaleTarget::repository("acme/app").unwrap(),
3456            1,
3457            fixtures::HOST_ID,
3458            PolicyMode::autoscale(
3459                fixtures::routing_labels("home"),
3460                2,
3461                NonZeroU16::new(5).expect("non-zero"),
3462            )
3463            .expect("min <= max"),
3464            CachePolicy::default(),
3465        );
3466        warm.activate().expect("pending -> active");
3467
3468        let mut harness = Harness::simple(8, 0, "acme/app");
3469        let report = harness.reconciler.reconcile(&[warm]).await;
3470
3471        assert_eq!(
3472            report.allocations[0].demand, 0,
3473            "GitHub reported no queued runs"
3474        );
3475        assert_eq!(
3476            report.allocations[0].desired, 2,
3477            "min_capacity raised the target above demand"
3478        );
3479        assert_eq!(
3480            report.allocations[0].limiting_factor,
3481            LimitingFactor::MinCapacity
3482        );
3483        assert_eq!(report.started, 2, "and two runners were actually started");
3484        assert_eq!(harness.launcher.live_count(), 2);
3485    }
3486
3487    // =======================================================================
3488    // Capacity, at the boundaries
3489    // =======================================================================
3490
3491    #[tokio::test]
3492    async fn demand_above_max_capacity_is_clamped_to_max_capacity() {
3493        let mut harness = Harness::simple(100, 10, "acme/app");
3494        let report = harness
3495            .reconciler
3496            .reconcile(&[policy(1, "acme/app", 3)])
3497            .await;
3498
3499        assert_eq!(report.allocations[0].demand, 10);
3500        assert_eq!(
3501            report.allocations[0].desired, 3,
3502            "max_capacity beats demand"
3503        );
3504        assert_eq!(report.started, 3);
3505        assert_eq!(
3506            report.allocations[0].limiting_factor,
3507            LimitingFactor::MaxCapacity
3508        );
3509    }
3510
3511    #[tokio::test]
3512    async fn demand_below_min_capacity_starts_nothing_in_v1() {
3513        // D7 fixes `min_capacity` at 0, so "below the floor" is "no demand", and
3514        // the product requirement it satisfies is "no idle runners when unused".
3515        let mut harness = Harness::simple(8, 0, "acme/app");
3516        let report = harness
3517            .reconciler
3518            .reconcile(&[policy(1, "acme/app", 4)])
3519            .await;
3520
3521        assert_eq!(report.allocations[0].desired, 0);
3522        assert_eq!(report.started, 0);
3523        assert!(report.starts_nothing());
3524    }
3525
3526    #[tokio::test]
3527    async fn lifecycle_replacement_intent_is_consumed_by_the_ordinary_allocator() {
3528        let policy = policy(1, "octo/repo", 1);
3529        let previous = attempt_in(AttemptState::Starting, 41, 1);
3530        let intent = ReplacementIntent {
3531            policy: policy.id,
3532            previous_attempt: previous.id,
3533            operation: "exit_before_acceptance_replacement",
3534        };
3535        let launcher = Arc::new(FakeLauncher::new().seeded(vec![previous]).replacing(intent));
3536        let demand = Arc::new(FakeDemand::ready(1, &repo("octo/repo")));
3537        let mut harness = Harness::build(
3538            host_with(1),
3539            Arc::clone(&launcher),
3540            demand,
3541            Arc::new(InProcessAllocationLock::new()),
3542        );
3543
3544        let report = harness.reconciler.reconcile(&[policy]).await;
3545
3546        assert_eq!(report.replacement_intents, 1);
3547        assert_eq!(report.started, 1);
3548        assert_eq!(launcher.launches(), 1);
3549        assert_eq!(launcher.live_count(), 1);
3550    }
3551
3552    #[tokio::test]
3553    async fn zero_host_headroom_starts_nothing_at_maximum_demand() {
3554        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3555            attempt_in(AttemptState::Busy, 1, 1),
3556            attempt_in(AttemptState::Busy, 2, 1),
3557        ]));
3558        let demand = Arc::new(FakeDemand::ready(u32::from(u16::MAX), &repo("acme/app")));
3559        let mut harness = Harness::build(
3560            host_with(2),
3561            launcher,
3562            demand,
3563            Arc::new(InProcessAllocationLock::new()),
3564        );
3565
3566        let report = harness
3567            .reconciler
3568            .reconcile(&[policy(1, "acme/app", 2)])
3569            .await;
3570        assert_eq!(report.started, 0);
3571        assert_eq!(report.allocations[0].headroom_before, 0);
3572        assert_eq!(harness.launcher.launches(), 0);
3573    }
3574
3575    #[tokio::test]
3576    async fn headroom_smaller_than_the_per_policy_allowance_wins() {
3577        // Four slots held by *another* policy on a host of six: this policy is
3578        // allowed five and gets two.
3579        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3580            attempt_in(AttemptState::Busy, 1, 99),
3581            attempt_in(AttemptState::Busy, 2, 99),
3582            attempt_in(AttemptState::Idle, 3, 99),
3583            attempt_in(AttemptState::Starting, 4, 99),
3584        ]));
3585        let demand = Arc::new(FakeDemand::ready(5, &repo("acme/app")));
3586        let mut harness = Harness::build(
3587            host_with(6),
3588            launcher,
3589            demand,
3590            Arc::new(InProcessAllocationLock::new()),
3591        );
3592
3593        let report = harness
3594            .reconciler
3595            .reconcile(&[policy(1, "acme/app", 5)])
3596            .await;
3597        assert_eq!(
3598            report.allocations[0].desired, 5,
3599            "its own ceiling allows five"
3600        );
3601        assert_eq!(report.started, 2, "the host has two slots free");
3602        assert_eq!(
3603            report.allocations[0].limiting_factor,
3604            LimitingFactor::HostCapacity
3605        );
3606        assert_eq!(harness.launcher.live_count(), 6);
3607    }
3608
3609    #[tokio::test]
3610    async fn the_idle_host_assertion_holds() {
3611        // "No demand means zero runner processes and zero attempts out of
3612        // terminal state."
3613        let mut harness = Harness::simple(8, 0, "acme/app");
3614        let report = harness
3615            .reconciler
3616            .reconcile(&[policy(1, "acme/app", 4), policy(2, "acme/app", 4)])
3617            .await;
3618
3619        assert_eq!(report.started, 0);
3620        assert_eq!(harness.launcher.launches(), 0);
3621        assert!(harness.launcher.snapshot().is_empty());
3622        assert_eq!(
3623            harness
3624                .launcher
3625                .snapshot()
3626                .iter()
3627                .filter(|a| !a.is_terminal())
3628                .count(),
3629            0
3630        );
3631    }
3632
3633    // =======================================================================
3634    // D9 under concurrency: the other silent failure
3635    // =======================================================================
3636
3637    /// `e1`'s Definition of Done: *"Two policies on one host with
3638    /// `host_capacity` smaller than the sum of their `max_capacity` values never
3639    /// exceed `host_capacity` under concurrent reconciliation — asserted under
3640    /// simulated lock contention, with no duplicate runners."*
3641    ///
3642    /// The contention is simulated by [`FakeLauncher::with_yields`], which puts
3643    /// executor yield points *between* the launcher reading the attempt set and
3644    /// recording the new one. Without serialisation both tasks read a headroom
3645    /// of three and both spend it.
3646    ///
3647    /// # Watched failing before it was made to pass
3648    ///
3649    /// Granting from this lock without taking the inner mutex — leaving every
3650    /// counter and every yield point exactly as they are — fails this assertion
3651    /// with `left: 4, right: 3`: four runners on a host of three, from two
3652    /// policies each individually inside their own `max_capacity`. The control
3653    /// test below keeps that measurement standing permanently by running the
3654    /// same body against [`NoLock`].
3655    #[tokio::test(flavor = "current_thread")]
3656    async fn two_policies_reconciling_concurrently_never_exceed_host_capacity() {
3657        let lock = Arc::new(CountingLock::new());
3658        let (launches, live) =
3659            two_policies_concurrently(Arc::clone(&lock) as Arc<dyn AllocationLock>).await;
3660
3661        assert_eq!(
3662            launches, 3,
3663            "the sum across policies must never exceed host_capacity, and each policy is \
3664             individually within its own max_capacity of 3"
3665        );
3666        assert_eq!(live, 3, "and no duplicate runner survived the race");
3667        assert_eq!(
3668            lock.peak(),
3669            1,
3670            "the allocation lock had one holder at a time; without that the read of the \
3671             headroom and the creation of the runtime are not atomic"
3672        );
3673        assert!(
3674            (3..=5).contains(&lock.acquisitions()),
3675            "the lock is taken before *each* runtime, not once per pass: three runtimes \
3676             means at least three holds, and at most one further hold per policy to \
3677             discover the host filled up underneath it. It was taken {} times",
3678            lock.acquisitions()
3679        );
3680    }
3681
3682    /// The control for the test above: the same body with the lock removed.
3683    ///
3684    /// It exists so that the assertion above cannot pass vacuously. If a future
3685    /// change makes the unserialised path safe by accident — a launcher that
3686    /// records synchronously, say — this test goes red and says so, rather than
3687    /// the other one silently proving nothing.
3688    #[tokio::test(flavor = "current_thread")]
3689    async fn without_the_allocation_lock_two_policies_oversubscribe_the_host() {
3690        let (launches, _) =
3691            two_policies_concurrently(Arc::new(NoLock) as Arc<dyn AllocationLock>).await;
3692
3693        assert!(
3694            launches > 3,
3695            "with no serialisation both policies must be able to spend the same headroom; \
3696             they started {launches} runners on a host of 3. If this is ever 3, the \
3697             contention window closed and `two_policies_reconciling_concurrently_never_\
3698             exceed_host_capacity` has stopped proving anything"
3699        );
3700    }
3701
3702    /// Two policies, one host of three, each allowed three, reconciled at once.
3703    ///
3704    /// Returns `(launches, live attempts)`.
3705    async fn two_policies_concurrently(lock: Arc<dyn AllocationLock>) -> (usize, usize) {
3706        let launcher = Arc::new(FakeLauncher::new().with_yields(4));
3707        let host = host_with(3);
3708
3709        let mut left = Harness::build(
3710            host.clone(),
3711            Arc::clone(&launcher),
3712            Arc::new(FakeDemand::ready(3, &repo("acme/left"))),
3713            Arc::clone(&lock),
3714        )
3715        .reconciler;
3716        let mut right = Harness::build(
3717            host,
3718            Arc::clone(&launcher),
3719            Arc::new(FakeDemand::ready(3, &repo("acme/right"))),
3720            Arc::clone(&lock),
3721        )
3722        .reconciler;
3723
3724        let a = policy(1, "acme/left", 3);
3725        let b = policy(2, "acme/right", 3);
3726
3727        let left = tokio::spawn(async move { left.reconcile(&[a]).await });
3728        let right = tokio::spawn(async move { right.reconcile(&[b]).await });
3729        let (_, _) = (left.await.unwrap(), right.await.unwrap());
3730
3731        (launcher.launches(), launcher.live_count())
3732    }
3733
3734    // =======================================================================
3735    // D19: monitor-only
3736    // =======================================================================
3737
3738    /// `e1`'s Definition of Done: *"A `MonitorOnly` policy under maximum demand
3739    /// starts zero runners and issues no demand request."*
3740    ///
3741    /// Driven through `c4`'s real gateway fake so that "issued no demand
3742    /// request" is asserted against the thing that would have issued it, rather
3743    /// than against this module's own bookkeeping. `FakeGithub` records every
3744    /// call it is asked to make.
3745    #[tokio::test]
3746    async fn a_monitor_only_policy_under_maximum_demand_starts_nothing_and_polls_nothing() {
3747        let gateway = FakeGithub::new().with_queued_jobs(repo("acme/app"), jobs(10_000));
3748        let gateway = Arc::new(GatewayDemand::new(gateway, CancelToken::new()));
3749        let launcher = Arc::new(FakeLauncher::new());
3750        let events = Arc::new(EventLog::new());
3751
3752        let mut reconciler = Reconciler::new(
3753            host_with(10),
3754            ReconcilerPorts {
3755                demand: Arc::clone(&gateway) as Arc<dyn DemandSource>,
3756                launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
3757                lock: Arc::new(InProcessAllocationLock::new()),
3758                directory: Arc::new(FakeDirectory::default()),
3759                clock: Arc::new(FakeClock::default()),
3760                jitter: Arc::new(NoJitter),
3761                events: Arc::clone(&events) as Arc<dyn EventSink>,
3762            },
3763        );
3764
3765        let monitor = fixtures::policy()
3766            .id(PolicyId::from_u128(1))
3767            .repository("acme/app")
3768            .monitor_only()
3769            .active()
3770            .build();
3771
3772        let report = reconciler.reconcile(&[monitor]).await;
3773
3774        assert_eq!(report.started, 0);
3775        assert_eq!(launcher.launches(), 0);
3776        assert_eq!(report.monitor_only, vec![PolicyId::from_u128(1)]);
3777        assert_eq!(
3778            report.demand_requests, 0,
3779            "a monitor-only policy spends nothing from the shared hourly ceiling"
3780        );
3781        assert!(
3782            gateway.gateway().calls().is_empty(),
3783            "a monitor-only policy issued a demand request: {:?}",
3784            gateway.gateway().calls()
3785        );
3786        assert_eq!(events.count_of("monitor_only_skipped"), 1);
3787        assert_eq!(
3788            events.count_of("demand_observed"),
3789            0,
3790            "and it contributed no demand"
3791        );
3792    }
3793
3794    /// D19 says a monitor-only policy is *"skipped entirely by
3795    /// reconciliation"*, and "entirely" is the load-bearing word once two
3796    /// policies share a target.
3797    ///
3798    /// This defect was found by review rather than by the test above, which
3799    /// cannot see it: there, the monitor-only policy is the *only* policy, so
3800    /// nobody polls its target and the lookup finds nothing. Give it a
3801    /// repository an autoscale policy already polls and the lookup succeeds —
3802    /// and the monitor-only policy was then allocated for and had a demand
3803    /// observation emitted on its behalf. It still started nothing, because
3804    /// `may_start_runners` is false for it and `HostAllocator` refuses it by
3805    /// name, so no ceiling was ever at risk. It simply was not skipped.
3806    ///
3807    /// Removing the `owns_runners` guard from the allocation loop was watched
3808    /// failing this test before it was restored:
3809    /// `a monitor-only policy was allocated for: [… limiting_factor:
3810    /// MonitorOnly]`.
3811    #[tokio::test]
3812    async fn a_monitor_only_policy_sharing_a_target_is_still_skipped_entirely() {
3813        let lock = Arc::new(CountingLock::new());
3814        let launcher = Arc::new(FakeLauncher::new());
3815        let events = Arc::new(EventLog::new());
3816        let mut reconciler = Reconciler::new(
3817            host_with(4),
3818            ReconcilerPorts {
3819                demand: Arc::new(FakeDemand::ready(2, &repo("acme/app"))),
3820                launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
3821                lock: Arc::clone(&lock) as Arc<dyn AllocationLock>,
3822                directory: Arc::new(FakeDirectory::default()),
3823                clock: Arc::new(FakeClock::default()),
3824                jitter: Arc::new(NoJitter),
3825                events: Arc::clone(&events) as Arc<dyn EventSink>,
3826            },
3827        );
3828
3829        let watcher = fixtures::policy()
3830            .id(PolicyId::from_u128(2))
3831            .repository("acme/app")
3832            .monitor_only()
3833            .active()
3834            .build();
3835
3836        let report = reconciler
3837            .reconcile(&[policy(1, "acme/app", 4), watcher])
3838            .await;
3839
3840        assert_eq!(report.started, 2, "the autoscale policy is served normally");
3841        assert_eq!(report.monitor_only, vec![PolicyId::from_u128(2)]);
3842        assert_eq!(
3843            events.count_of("demand_observed"),
3844            1,
3845            "the demand observation belongs to the autoscale policy alone"
3846        );
3847        assert!(
3848            report
3849                .allocations
3850                .iter()
3851                .all(|a| a.policy_id == PolicyId::from_u128(1)),
3852            "a monitor-only policy was allocated for: {:?}",
3853            report.allocations
3854        );
3855        assert_eq!(
3856            lock.acquisitions(),
3857            2,
3858            "one hold per runtime created, and none on behalf of the monitor-only policy. \
3859             It was three before the budget was checked at the top of the loop rather than \
3860             after the re-read, which cost every policy a surplus hold to discover there \
3861             was nothing left to grant"
3862        );
3863    }
3864
3865    #[tokio::test]
3866    async fn the_monitor_only_refusal_is_asserted_on_the_mode_not_on_a_missing_ceiling() {
3867        // The specification requires this to be asserted rather than deduced
3868        // from `max_capacity` being absent. `HostAllocator` reports it by name,
3869        // and this loop reaches that arm through `owns_runners`, which is a
3870        // question about the mode.
3871        let monitor = fixtures::monitor_only_policy();
3872        assert!(!monitor.owns_runners());
3873        assert_eq!(monitor.max_capacity(), None);
3874
3875        let host = host_with(10);
3876        let attempts: Vec<RunnerAttempt> = Vec::new();
3877        let mut allocator = HostAllocator::from_attempts(&host, &attempts);
3878        let allocation = allocator.allocate(&monitor, 10_000);
3879        assert_eq!(allocation.limiting_factor, LimitingFactor::MonitorOnly);
3880        assert_eq!(allocation.to_start, 0);
3881        assert_eq!(
3882            allocator.headroom(),
3883            10,
3884            "and it consumes no headroom, so an autoscale policy on the same host is \
3885             unaffected"
3886        );
3887    }
3888
3889    // =======================================================================
3890    // The surplus runner, and busy protection
3891    // =======================================================================
3892
3893    /// `e1`'s Definition of Done: *"A surplus attempt that receives no job
3894    /// reaches a terminal state recorded as an idle exit, is cleaned, and is not
3895    /// reported as a failure."*
3896    #[tokio::test]
3897    async fn a_surplus_attempt_is_cleaned_as_an_idle_exit_and_not_as_a_failure() {
3898        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3899            concluded(1, 1, AttemptOutcome::ExitedIdleWithoutWork),
3900            concluded(
3901                2,
3902                1,
3903                AttemptOutcome::failed(FailureReason::JitRequestFailed),
3904            ),
3905            concluded(3, 1, AttemptOutcome::CompletedJob),
3906        ]));
3907        let mut harness = Harness::build(
3908            host_with(4),
3909            Arc::clone(&launcher),
3910            Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
3911            Arc::new(InProcessAllocationLock::new()),
3912        );
3913
3914        let report = harness
3915            .reconciler
3916            .reconcile(&[policy(1, "acme/app", 4)])
3917            .await;
3918
3919        assert_eq!(report.cleaned, 3);
3920        assert_eq!(report.idle_exits, 1, "the surplus case, counted apart");
3921        assert_eq!(
3922            report.failures, 1,
3923            "only the failed attempt is a failure; the idle exit and the completed job are \
3924             not"
3925        );
3926        assert_eq!(launcher.cleaned().len(), 3);
3927        assert!(launcher.snapshot().is_empty());
3928
3929        let cleaned: Vec<OutcomeKind> = harness
3930            .events
3931            .events()
3932            .into_iter()
3933            .filter_map(|event| match event {
3934                LifecycleEvent::AttemptCleaned { outcome, .. } => Some(outcome),
3935                _ => None,
3936            })
3937            .collect();
3938        assert!(cleaned.contains(&OutcomeKind::IdleExit));
3939        assert!(
3940            !OutcomeKind::IdleExit.is_failure(),
3941            "an idle exit rendered as a failure sends an operator hunting a fault that does \
3942             not exist"
3943        );
3944    }
3945
3946    /// `e1`'s Definition of Done: *"A scale-down request with a busy attempt
3947    /// removes nothing and leaves the attempt `busy`."*
3948    #[tokio::test]
3949    async fn scale_down_removes_nothing_from_a_busy_attempt() {
3950        let busy = attempt_in(AttemptState::Busy, 1, 1);
3951        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3952            busy.clone(),
3953            attempt_in(AttemptState::Starting, 2, 1),
3954            concluded(3, 1, AttemptOutcome::CompletedJob),
3955        ]));
3956        let harness = Harness::build(
3957            host_with(4),
3958            Arc::clone(&launcher),
3959            Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
3960            Arc::new(InProcessAllocationLock::new()),
3961        );
3962
3963        let report = harness
3964            .reconciler
3965            .scale_down(&policy(1, "acme/app", 4))
3966            .await;
3967
3968        assert_eq!(report.refused_busy, 1);
3969        assert_eq!(
3970            report.retained, 1,
3971            "the `starting` attempt is not ended either"
3972        );
3973        assert_eq!(report.removed, 1, "only the concluded attempt is reclaimed");
3974
3975        let after = launcher.snapshot();
3976        let still_busy = after
3977            .iter()
3978            .find(|a| a.id == AttemptId::from_u128(1))
3979            .expect("the busy attempt is still there");
3980        assert_eq!(
3981            still_busy.state(),
3982            AttemptState::Busy,
3983            "scale-down removed nothing from a runner that is executing a job, and left it \
3984             busy"
3985        );
3986        assert!(!launcher.cleaned().contains(&AttemptId::from_u128(1)));
3987
3988        // And the domain refuses it from the other side too, by name, so a
3989        // future caller that tried anyway would not get a generic transition
3990        // error.
3991        let mut busy = busy;
3992        assert!(matches!(
3993            busy.clean(fixtures::created_at()),
3994            Err(runner_manager_domain::attempt::AttemptError::BusyCannotBeCleaned)
3995        ));
3996        assert_eq!(harness.events.count_of("scale_down_refused"), 1);
3997    }
3998
3999    // =======================================================================
4000    // The schedule
4001    // =======================================================================
4002
4003    #[test]
4004    fn the_default_interval_is_sixty_seconds_and_the_floor_is_thirty() {
4005        assert_eq!(RefreshInterval::DEFAULT_SECS, 60);
4006        assert_eq!(RefreshInterval::MIN_SECS, 30);
4007        assert_eq!(PollSchedule::floor(), Duration::from_secs(30));
4008        assert!(
4009            RefreshInterval::from_secs(29).is_err(),
4010            "the floor is a rate-budget constraint, and a caller must not be able to write \
4011             a shorter interval at all"
4012        );
4013
4014        let mut schedule = PollSchedule::new(RefreshInterval::default());
4015        let next = schedule.next_poll(None, fixtures::created_at(), &NoJitter);
4016        assert_eq!(next.delay, Duration::from_secs(60));
4017        assert_eq!(next.pace, PollPace::Nominal);
4018
4019        let mut floored = PollSchedule::new(RefreshInterval::from_secs(30).unwrap());
4020        assert_eq!(
4021            floored
4022                .next_poll(None, fixtures::created_at(), &NoJitter)
4023                .delay,
4024            Duration::from_secs(30)
4025        );
4026    }
4027
4028    /// `e1`'s Definition of Done: *"The poll interval … increases under a
4029    /// rate-limit signal, and the increase is visible in emitted state rather
4030    /// than silent."*
4031    #[test]
4032    fn a_rate_limit_increases_the_delay_and_names_itself() {
4033        let now = fixtures::created_at();
4034        let mut schedule = PollSchedule::new(RefreshInterval::default());
4035
4036        let limited = RefreshState::RateLimited(RateLimited {
4037            kind: RateLimitKind::Secondary,
4038            retry_after: Some(Duration::from_secs(300)),
4039            remaining: None,
4040            reset_unix_secs: None,
4041        });
4042        let next = schedule.next_poll(Some(&limited), now, &NoJitter);
4043
4044        assert_eq!(next.delay, Duration::from_secs(300));
4045        assert_eq!(
4046            next.pace,
4047            PollPace::RateLimited {
4048                kind: RateLimitKind::Secondary
4049            },
4050            "the increase is reported, never hidden"
4051        );
4052        assert!(next.pace.is_throttled());
4053        assert_eq!(next.pace.as_str(), "rate_limited_secondary");
4054    }
4055
4056    /// Constraint on this task: *"Read `RefreshState::retry_delay` as an
4057    /// absolute floor, not an addend."*
4058    #[test]
4059    fn the_retry_delay_is_an_absolute_floor_and_never_an_addend() {
4060        let now = fixtures::created_at();
4061        let mut schedule = PollSchedule::new(RefreshInterval::default());
4062
4063        let limited = RefreshState::RateLimited(RateLimited {
4064            kind: RateLimitKind::Primary,
4065            retry_after: Some(Duration::from_secs(300)),
4066            remaining: Some(0),
4067            reset_unix_secs: None,
4068        });
4069
4070        // Five successive answers, each carrying the window that is *left*.
4071        // An addend would compound: 360, 660, 960 … and look like a hang.
4072        for _ in 0..5 {
4073            let next = schedule.next_poll(Some(&limited), now, &NoJitter);
4074            assert_eq!(
4075                next.delay,
4076                Duration::from_secs(300),
4077                "the delay is `max(interval, retry_delay)`; `interval + retry_delay` would \
4078                 have compounded on every successive retry"
4079            );
4080        }
4081
4082        // And when GitHub asks for less than the interval, the interval wins:
4083        // the floor is never crossed to catch up.
4084        let brief = RefreshState::RateLimited(RateLimited {
4085            kind: RateLimitKind::Secondary,
4086            retry_after: Some(Duration::from_secs(5)),
4087            remaining: None,
4088            reset_unix_secs: None,
4089        });
4090        let next = schedule.next_poll(Some(&brief), now, &NoJitter);
4091        assert_eq!(
4092            next.delay,
4093            Duration::from_secs(60),
4094            "a short `retry-after` may not drop the loop below its own interval"
4095        );
4096        assert!(next.delay >= PollSchedule::floor());
4097    }
4098
4099    #[test]
4100    fn no_branch_of_the_schedule_can_go_below_the_thirty_second_floor() {
4101        let now = fixtures::created_at();
4102        let states = [
4103            None,
4104            Some(RefreshState::Offline),
4105            Some(RefreshState::RateLimited(RateLimited {
4106                kind: RateLimitKind::Secondary,
4107                retry_after: Some(Duration::from_secs(1)),
4108                remaining: None,
4109                reset_unix_secs: None,
4110            })),
4111            Some(RefreshState::LockedOut {
4112                retry_after: Duration::from_secs(1),
4113            }),
4114            Some(RefreshState::Unauthorized),
4115            Some(RefreshState::Forbidden { message: None }),
4116            Some(RefreshState::Failed {
4117                status: Some(500),
4118                message: "server error".into(),
4119            }),
4120            Some(RefreshState::Cancelled),
4121        ];
4122
4123        for state in &states {
4124            let mut schedule = PollSchedule::new(RefreshInterval::from_secs(30).unwrap());
4125            let next = schedule.next_poll(state.as_ref(), now, &NoJitter);
4126            assert!(
4127                next.delay >= PollSchedule::floor(),
4128                "{state:?} scheduled a poll {}ms away, under the 30-second floor",
4129                next.delay.as_millis()
4130            );
4131        }
4132    }
4133
4134    #[test]
4135    fn an_offline_run_backs_off_with_jitter_and_a_recovery_resets_it() {
4136        let now = fixtures::created_at();
4137        let mut schedule = PollSchedule::new(RefreshInterval::default());
4138
4139        // Doubling, from the nominal interval.
4140        let mut previous = Duration::ZERO;
4141        for consecutive in 1..=6_u32 {
4142            let next = schedule.next_poll(Some(&RefreshState::Offline), now, &NoJitter);
4143            assert_eq!(next.pace, PollPace::Offline { consecutive });
4144            assert!(
4145                next.delay >= previous,
4146                "the back-off must not shrink while the outage continues"
4147            );
4148            assert!(next.delay >= Duration::from_secs(60));
4149            previous = next.delay;
4150        }
4151        assert!(previous <= MAX_OFFLINE_BACKOFF, "and it is capped");
4152
4153        // Jitter widens the delay rather than narrowing it, so a fleet of
4154        // agents does not retry in lockstep.
4155        let mut jittered = PollSchedule::new(RefreshInterval::default());
4156        let none = jittered.next_poll(Some(&RefreshState::Offline), now, &NoJitter);
4157        let mut jittered = PollSchedule::new(RefreshInterval::default());
4158        let full = jittered.next_poll(Some(&RefreshState::Offline), now, &FixedJitter(0.999));
4159        assert!(full.delay > none.delay);
4160        assert!(full.delay <= none.delay.mul_f64(1.0 + JITTER_RATIO));
4161
4162        // Recovery resets the run with no bookkeeping of its own.
4163        assert_eq!(schedule.consecutive_offline(), 6);
4164        let recovered = schedule.next_poll(None, now, &NoJitter);
4165        assert_eq!(recovered.pace, PollPace::Nominal);
4166        assert_eq!(recovered.delay, Duration::from_secs(60));
4167        assert_eq!(schedule.consecutive_offline(), 0);
4168    }
4169
4170    #[test]
4171    fn the_offline_state_states_the_twenty_four_hour_bound() {
4172        assert_eq!(
4173            GITHUB_CANCELS_QUEUED_JOBS_AFTER,
4174            Duration::from_secs(24 * 60 * 60)
4175        );
4176
4177        let brief = OfflineState::new(1, Duration::from_secs(120));
4178        let rendered = brief.to_string();
4179        assert!(rendered.contains("24 hours"), "{rendered}");
4180        assert!(rendered.contains("Retrying in 120s"), "{rendered}");
4181        assert!(!brief.has_outlasted_the_queue());
4182
4183        let long = brief.since(GITHUB_CANCELS_QUEUED_JOBS_AFTER + Duration::from_secs(1));
4184        assert!(long.has_outlasted_the_queue());
4185        assert!(
4186            long.to_string().contains("queued work has been lost"),
4187            "{long}"
4188        );
4189
4190        // "We cannot tell" is not "not yet".
4191        assert!(!OfflineState::new(9, Duration::from_secs(60)).has_outlasted_the_queue());
4192    }
4193
4194    // =======================================================================
4195    // Offline, end to end
4196    // =======================================================================
4197
4198    /// `e1`'s Definition of Done: *"An unreachable GitHub yields `offline`, zero
4199    /// new runners, retained existing processes, and jittered backoff; recovery
4200    /// resumes polling and does not double-count a job that was already being
4201    /// served."*
4202    #[tokio::test]
4203    async fn an_unreachable_github_starts_nothing_retains_everything_and_backs_off() {
4204        let live = vec![
4205            attempt_in(AttemptState::Busy, 1, 1),
4206            attempt_in(AttemptState::Starting, 2, 1),
4207        ];
4208        let launcher = Arc::new(FakeLauncher::new().seeded(live.clone()));
4209        let demand = Arc::new(FakeDemand::failing(RefreshState::Offline));
4210        let mut harness = Harness::build(
4211            host_with(8),
4212            Arc::clone(&launcher),
4213            Arc::clone(&demand),
4214            Arc::new(InProcessAllocationLock::new()),
4215        );
4216        let policy = policy(1, "acme/app", 8);
4217
4218        let report = harness
4219            .reconciler
4220            .reconcile(std::slice::from_ref(&policy))
4221            .await;
4222
4223        assert!(report.is_offline());
4224        assert_eq!(report.started, 0, "no new runner during an outage");
4225        assert_eq!(launcher.launches(), 0);
4226        assert_eq!(
4227            launcher.snapshot(),
4228            live,
4229            "existing runner processes are retained, untouched"
4230        );
4231        assert_eq!(report.unreadable, vec![PolicyId::from_u128(1)]);
4232        assert_eq!(report.next_poll.pace, PollPace::Offline { consecutive: 1 });
4233        assert!(report.next_poll.delay >= Duration::from_secs(60));
4234        let offline = report.offline_state().expect("an offline state to display");
4235        assert!(offline.to_string().contains("24 hours"));
4236
4237        // Recovery: the same job is still queued, and one runner is already
4238        // serving it. Demand is recomputed from the current queued set rather
4239        // than accumulated, so the reconnect starts nothing new.
4240        demand.set(PollOutcome::Ready(QueuedDemand::of(
4241            repo("acme/app"),
4242            jobs(2),
4243        )));
4244        let recovered = harness.reconciler.reconcile(&[policy]).await;
4245
4246        assert!(!recovered.is_offline());
4247        assert_eq!(recovered.next_poll.pace, PollPace::Nominal);
4248        assert_eq!(
4249            recovered.started, 0,
4250            "two queued runs, two attempts already in flight: a reconnect cannot \
4251             double-count work"
4252        );
4253        assert_eq!(recovered.allocations[0].active_owned, 2);
4254        assert_eq!(launcher.live_count(), 2);
4255    }
4256
4257    /// One unreachable target must not idle a whole host.
4258    ///
4259    /// The failure that decides the *schedule* is the most severe across every
4260    /// target polled — backing the whole loop off during an outage is the safe
4261    /// error, and `f3` runs one reconciler per target anyway, so in production
4262    /// the two are usually the same thing. What must not follow from that is
4263    /// refusing to serve a policy whose own target answered perfectly well, and
4264    /// the two are easy to conflate because the offline reading is sitting in
4265    /// the same map.
4266    #[tokio::test]
4267    async fn one_offline_target_does_not_stop_a_reachable_one() {
4268        let mut harness = Harness::simple(8, 0, "acme/app");
4269        harness.demand.set_for(
4270            &ScaleTarget::repository("acme/app").unwrap(),
4271            PollOutcome::Ready(QueuedDemand::of(repo("acme/app"), jobs(2))),
4272        );
4273        harness.demand.set_for(
4274            &ScaleTarget::repository("acme/broken").unwrap(),
4275            PollOutcome::Failed(RefreshState::Offline),
4276        );
4277
4278        let report = harness
4279            .reconciler
4280            .reconcile(&[policy(1, "acme/app", 4), policy(2, "acme/broken", 4)])
4281            .await;
4282
4283        assert_eq!(
4284            report.started, 2,
4285            "the reachable target was served; an unreachable sibling repository must not \
4286             idle the host"
4287        );
4288        assert_eq!(report.unreadable, vec![PolicyId::from_u128(2)]);
4289        assert_eq!(harness.demand.polls().len(), 2, "both targets were polled");
4290
4291        // And the schedule takes the worse of the two.
4292        assert!(report.is_offline());
4293        assert_eq!(report.next_poll.pace, PollPace::Offline { consecutive: 1 });
4294    }
4295
4296    /// The 24-hour bound has to be reachable in production, not only in a unit
4297    /// test of [`OfflineState`].
4298    ///
4299    /// This was a real gap: the reconciler built its offline state from the
4300    /// back-off count alone, so `offline_for` was always `None` and
4301    /// [`OfflineState::has_outlasted_the_queue`] could never be true outside a
4302    /// test that constructed the value by hand. An operator whose agent had been
4303    /// offline for two days would have been told that an outage longer than 24
4304    /// hours *would* lose queued work, in the future tense, having already lost
4305    /// it.
4306    ///
4307    /// The elapsed time is measured from the first poll of the run rather than
4308    /// derived from the interval, because the back-off doubles and the two
4309    /// diverge immediately.
4310    #[tokio::test]
4311    async fn a_day_long_outage_says_that_queued_work_has_already_been_lost() {
4312        let clock = Arc::new(FakeClock::default());
4313        let launcher = Arc::new(FakeLauncher::new());
4314        let demand = Arc::new(FakeDemand::failing(RefreshState::Offline));
4315        let mut reconciler = Reconciler::new(
4316            host_with(4),
4317            ReconcilerPorts {
4318                demand: Arc::clone(&demand) as Arc<dyn DemandSource>,
4319                launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
4320                lock: Arc::new(InProcessAllocationLock::new()),
4321                directory: Arc::new(FakeDirectory::default()),
4322                clock: Arc::clone(&clock) as Arc<dyn Clock>,
4323                jitter: Arc::new(NoJitter),
4324                events: Arc::new(NoEvents),
4325            },
4326        );
4327        let policy = policy(1, "acme/app", 4);
4328
4329        // The outage begins.
4330        let first = reconciler.reconcile(std::slice::from_ref(&policy)).await;
4331        let state = first.offline_state().expect("an offline state");
4332        assert!(!state.has_outlasted_the_queue());
4333        assert!(
4334            state
4335                .to_string()
4336                .contains("an outage longer than that loses"),
4337            "{state}"
4338        );
4339
4340        // A day and a minute later, still unreachable.
4341        clock.advance_secs(24 * 60 * 60 + 60);
4342        let later = reconciler.reconcile(std::slice::from_ref(&policy)).await;
4343        let state = later.offline_state().expect("an offline state");
4344        assert!(state.has_outlasted_the_queue());
4345        assert!(
4346            state.to_string().contains("queued work has been lost"),
4347            "{state}"
4348        );
4349        assert_eq!(launcher.launches(), 0, "and still nothing was started");
4350
4351        // Recovery closes the run, so a *later* outage measures from itself
4352        // rather than from the first one.
4353        demand.set(PollOutcome::Ready(QueuedDemand::of(
4354            repo("acme/app"),
4355            jobs(0),
4356        )));
4357        let recovered = reconciler.reconcile(std::slice::from_ref(&policy)).await;
4358        assert!(recovered.offline_state().is_none());
4359        assert_eq!(reconciler.schedule().offline_for(clock.now()), None);
4360
4361        demand.set(PollOutcome::Failed(RefreshState::Offline));
4362        let again = reconciler.reconcile(std::slice::from_ref(&policy)).await;
4363        assert!(
4364            !again
4365                .offline_state()
4366                .expect("an offline state")
4367                .has_outlasted_the_queue(),
4368            "a new outage must not inherit the age of the one before it"
4369        );
4370    }
4371
4372    /// Finding 5: the adapter, not the lock underneath it.
4373    ///
4374    /// `d1` covers `LockKind::Allocation` including a contended `acquire_at`
4375    /// with a wait. What that does not reach is this adapter: the
4376    /// `spawn_blocking` wrapper, the collapse of both a refused lock and a
4377    /// panicked blocking task into `AllocationLockBusy`, and — the one that
4378    /// would be silent — whether [`AllocationGuard`] really holds the
4379    /// `HostLock`, since dropping it is the only release there is. A guard that
4380    /// dropped the lock on the way out would make every acquisition succeed and
4381    /// the ceiling would hold by luck.
4382    ///
4383    /// The original disclosure said this needed a real filesystem and was
4384    /// therefore expensive. `AppPaths::rooted_at` plus `tempfile` — already a
4385    /// non-dev dependency of this crate — makes it about fifteen lines, so the
4386    /// reason was weaker than stated.
4387    #[tokio::test]
4388    async fn the_file_allocation_lock_excludes_a_second_holder_and_releases_on_drop() {
4389        let root = tempfile::tempdir().expect("a temporary directory");
4390        let paths = Arc::new(runner_manager_platform::paths::AppPaths::rooted_at(
4391            root.path(),
4392        ));
4393        let lock = FileAllocationLock::new(paths).with_wait(Duration::from_millis(50));
4394
4395        let held = lock.acquire().await.expect("an uncontended lock is free");
4396        assert!(
4397            matches!(lock.acquire().await, Err(AllocationLockBusy)),
4398            "a second holder was admitted; on Unix the lock is per open file description \
4399             and on Windows the share mode denies write, so this must be refused even \
4400             from inside the same process"
4401        );
4402
4403        drop(held);
4404        let regained = lock.acquire().await;
4405        assert!(
4406            regained.is_ok(),
4407            "dropping the guard is the only release there is, so a guard that does not \
4408             hold the `HostLock` leaves it held forever"
4409        );
4410    }
4411
4412    #[test]
4413    fn tee_events_reaches_both_sinks() {
4414        // `f3` wires the log sink and `g2`'s buffer at once, and an event that
4415        // reached only one of them would be an activity view missing lines the
4416        // log file has, or the reverse.
4417        let left = Arc::new(EventLog::new());
4418        let right = Arc::new(EventLog::new());
4419        let tee = TeeEvents(
4420            Arc::clone(&left) as Arc<dyn EventSink>,
4421            Arc::clone(&right) as Arc<dyn EventSink>,
4422        );
4423
4424        tee.emit(LifecycleEvent::MonitorOnlySkipped {
4425            policy: PolicyId::from_u128(1),
4426        });
4427
4428        assert_eq!(left.count_of("monitor_only_skipped"), 1);
4429        assert_eq!(right.count_of("monitor_only_skipped"), 1);
4430    }
4431
4432    // =======================================================================
4433    // Budget: the repository list, and the per-target poll
4434    // =======================================================================
4435
4436    #[tokio::test]
4437    async fn the_repository_list_refreshes_far_more_slowly_than_the_demand_poll() {
4438        let clock = Arc::new(FakeClock::default());
4439        let directory = Arc::new(FakeDirectory::of(vec![repo("acme/one"), repo("acme/two")]));
4440        let cache = RepositoryCache::new(
4441            Arc::clone(&directory) as Arc<dyn RepositoryDirectory>,
4442            Arc::clone(&clock) as Arc<dyn Clock>,
4443            RefreshInterval::default(),
4444        );
4445        let target = ScaleTarget::organization("acme").unwrap();
4446
4447        assert_eq!(
4448            cache.ttl(),
4449            Duration::from_secs(60 * u64::from(REPOSITORY_LIST_REFRESH_MULTIPLE))
4450        );
4451
4452        // Every poll inside the window reuses the list.
4453        for _ in 0..REPOSITORY_LIST_REFRESH_MULTIPLE {
4454            let scope = cache.scope_for(&target).await.unwrap();
4455            assert_eq!(scope.repositories().len(), 2);
4456            clock.advance_secs(60);
4457        }
4458        assert_eq!(
4459            directory.calls(),
4460            1,
4461            "re-listing an organization at demand-poll frequency is what exhausts the \
4462             shared request budget"
4463        );
4464        assert_eq!(cache.lookups(), 1);
4465
4466        // Past it, exactly one more.
4467        cache.scope_for(&target).await.unwrap();
4468        assert_eq!(directory.calls(), 2);
4469    }
4470
4471    #[tokio::test]
4472    async fn a_repository_target_never_consults_the_directory() {
4473        let directory = Arc::new(FakeDirectory::of(vec![repo("acme/other")]));
4474        let cache = RepositoryCache::new(
4475            Arc::clone(&directory) as Arc<dyn RepositoryDirectory>,
4476            Arc::new(FakeClock::default()) as Arc<dyn Clock>,
4477            RefreshInterval::default(),
4478        );
4479        let target = ScaleTarget::repository("acme/app").unwrap();
4480
4481        let scope = cache.scope_for(&target).await.unwrap();
4482        assert_eq!(scope.repositories(), &[repo("acme/app")]);
4483        assert_eq!(directory.calls(), 0);
4484    }
4485
4486    #[tokio::test]
4487    async fn two_policies_on_one_target_cost_one_demand_poll_not_two() {
4488        // `04-subsystem-contracts.md` prices a *target*. A loop that spent per
4489        // policy would exceed the projection `f2` admitted the configuration
4490        // against, silently.
4491        let mut harness = Harness::simple(8, 4, "acme/app");
4492        let report = harness
4493            .reconciler
4494            .reconcile(&[policy(1, "acme/app", 2), policy(2, "acme/app", 2)])
4495            .await;
4496
4497        assert_eq!(harness.demand.polls().len(), 1);
4498        assert_eq!(
4499            report.demand_requests,
4500            runner_manager_github::demand::DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL,
4501            "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"
4502        );
4503        assert_eq!(report.started, 4, "and both policies still get their share");
4504    }
4505
4506    // =======================================================================
4507    // Failure paths
4508    // =======================================================================
4509
4510    #[tokio::test]
4511    async fn a_failed_launch_stops_the_run_and_is_reported_without_free_text() {
4512        let launcher = Arc::new(FakeLauncher::new());
4513        launcher.fail_next(FailureReason::Other("token ghp_0123456789abcdef".into()));
4514        let mut harness = Harness::build(
4515            host_with(4),
4516            Arc::clone(&launcher),
4517            Arc::new(FakeDemand::ready(3, &repo("acme/app"))),
4518            Arc::new(InProcessAllocationLock::new()),
4519        );
4520
4521        let report = harness
4522            .reconciler
4523            .reconcile(&[policy(1, "acme/app", 4)])
4524            .await;
4525        assert_eq!(report.started, 0);
4526        assert_eq!(report.allocations[0].to_start, 3, "the decision stands");
4527
4528        let failures: Vec<&'static str> = harness
4529            .events
4530            .events()
4531            .into_iter()
4532            .filter_map(|event| match event {
4533                LifecycleEvent::RunnerStartFailed { reason, .. } => Some(reason),
4534                _ => None,
4535            })
4536            .collect();
4537        assert_eq!(failures, vec!["other"]);
4538        assert!(
4539            !failures[0].contains("ghp_"),
4540            "an event carried a `FailureReason::Other` detail verbatim"
4541        );
4542    }
4543
4544    #[tokio::test]
4545    async fn a_held_allocation_lock_starts_nothing_and_says_so() {
4546        let launcher = Arc::new(FakeLauncher::new());
4547        let mut harness = Harness::build(
4548            host_with(4),
4549            Arc::clone(&launcher),
4550            Arc::new(FakeDemand::ready(3, &repo("acme/app"))),
4551            Arc::new(HeldLock),
4552        );
4553
4554        let report = harness
4555            .reconciler
4556            .reconcile(&[policy(1, "acme/app", 4)])
4557            .await;
4558        assert_eq!(report.started, 0);
4559        assert_eq!(
4560            report.deferred, 3,
4561            "three runners were granted and none was created; `deferred` counts grants, \
4562             not policies -- it reported `1` when a policy that launched two of five and \
4563             then lost the lock had left three unstarted"
4564        );
4565        assert_eq!(launcher.launches(), 0);
4566        assert_eq!(harness.events.count_of("allocation_deferred"), 1);
4567        assert!(
4568            harness
4569                .events
4570                .events()
4571                .iter()
4572                .any(|event| matches!(event, LifecycleEvent::AllocationDeferred { count: 3, .. })),
4573            "the event carries the same number the report does"
4574        );
4575        assert_eq!(
4576            report.allocations.len(),
4577            1,
4578            "the intent is still reported, so an operator staring at a queue sees why \
4579             nothing started"
4580        );
4581    }
4582
4583    #[tokio::test]
4584    async fn a_foreign_or_draining_policy_is_reported_by_name_and_polls_nothing() {
4585        let mut harness = Harness::simple(8, 5, "acme/app");
4586
4587        let foreign = fixtures::policy()
4588            .id(PolicyId::from_u128(1))
4589            .repository("acme/app")
4590            .host(HostId::from_u128(0xdead))
4591            .autoscale("office", 4)
4592            .active()
4593            .build();
4594        let mut draining = policy(2, "acme/app", 4);
4595        draining.request_disable().unwrap();
4596
4597        let report = harness.reconciler.reconcile(&[foreign, draining]).await;
4598
4599        assert_eq!(report.started, 0);
4600        assert_eq!(
4601            harness.demand.polls().len(),
4602            0,
4603            "neither can act on an answer"
4604        );
4605        let factors: Vec<LimitingFactor> = report
4606            .allocations
4607            .iter()
4608            .map(|a| a.limiting_factor)
4609            .collect();
4610        assert!(factors.contains(&LimitingFactor::ForeignHost));
4611        assert!(factors.contains(&LimitingFactor::NotReconciling));
4612    }
4613
4614    #[tokio::test]
4615    async fn an_unreadable_repository_list_makes_the_target_unreadable_not_empty() {
4616        // Polling a scope nobody chose would report a demand number for the
4617        // wrong set of repositories, which is worse than reporting nothing.
4618        #[derive(Debug)]
4619        struct BrokenDirectory;
4620
4621        #[async_trait::async_trait]
4622        impl RepositoryDirectory for BrokenDirectory {
4623            async fn repositories(&self, _org: &Org) -> Result<Vec<OwnerRepo>, InventoryError> {
4624                Err(InventoryError::Cancelled)
4625            }
4626        }
4627
4628        let launcher = Arc::new(FakeLauncher::new());
4629        let events = Arc::new(EventLog::new());
4630        let mut reconciler = Reconciler::new(
4631            host_with(4),
4632            ReconcilerPorts {
4633                demand: Arc::new(FakeDemand::default()),
4634                launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
4635                lock: Arc::new(InProcessAllocationLock::new()),
4636                directory: Arc::new(BrokenDirectory),
4637                clock: Arc::new(FakeClock::default()),
4638                jitter: Arc::new(NoJitter),
4639                events: Arc::clone(&events) as Arc<dyn EventSink>,
4640            },
4641        );
4642
4643        let org_policy = fixtures::policy()
4644            .id(PolicyId::from_u128(1))
4645            .organization("acme")
4646            .autoscale("home", 4)
4647            .active()
4648            .build();
4649
4650        let report = reconciler.reconcile(&[org_policy]).await;
4651        assert_eq!(report.started, 0);
4652        assert_eq!(report.unreadable, vec![PolicyId::from_u128(1)]);
4653        assert_eq!(events.count_of("target_unreadable"), 1);
4654    }
4655
4656    // =======================================================================
4657    // What the events may carry
4658    // =======================================================================
4659
4660    /// One value of every [`LifecycleEvent`] variant.
4661    ///
4662    /// Hand-written, and what keeps it honest is the wildcard-free `match` in
4663    /// [`LifecycleEvent::name`]: adding a variant stops that compiling and puts
4664    /// the author here. The same residual `b1` records for `FailureReason::ALL`
4665    /// applies — an author who writes the `name` arm and forgets this list gets
4666    /// a green suite with the variant unscanned.
4667    fn every_event() -> Vec<LifecycleEvent> {
4668        let policy = PolicyId::from_u128(0xabcd_ef01);
4669        let attempt = AttemptId::from_u128(0x1234_5678);
4670        vec![
4671            LifecycleEvent::DemandObserved {
4672                policy,
4673                demand: u32::MAX,
4674                not_matched: u32::MAX,
4675                unresolvable: u32::MAX,
4676                complete: false,
4677            },
4678            LifecycleEvent::TargetUnreadable {
4679                policy,
4680                reason: unreadable_reason(&RefreshState::Failed {
4681                    status: Some(500),
4682                    message: "Authorization: Bearer ghp_0123456789abcdefghijklmnopqrstuvwxyz"
4683                        .into(),
4684                }),
4685            },
4686            LifecycleEvent::Allocated {
4687                policy,
4688                demand: u32::MAX,
4689                desired: u16::MAX,
4690                active_owned: 7,
4691                headroom: 9,
4692                to_start: 2,
4693                limiting: LimitingFactor::HostCapacity,
4694            },
4695            LifecycleEvent::MonitorOnlySkipped { policy },
4696            LifecycleEvent::RunnerStarted { policy, attempt },
4697            LifecycleEvent::RunnerStartFailed {
4698                policy,
4699                reason: failure_reason_kind(&FailureReason::Other(
4700                    "Authorization: Bearer ghp_0123456789abcdefghijklmnopqrstuvwxyz".into(),
4701                )),
4702            },
4703            LifecycleEvent::AllocationDeferred { policy, count: 4 },
4704            LifecycleEvent::AttemptsUnreadable {
4705                reason: failure_reason_kind(&FailureReason::Other(
4706                    "x-api-key: ghp_0123456789abcdefghijklmnopqrstuvwxyz".into(),
4707                )),
4708            },
4709            LifecycleEvent::AttemptCleanFailed {
4710                policy,
4711                attempt,
4712                reason: failure_reason_kind(&FailureReason::ProcessExitedUnexpectedly),
4713            },
4714            LifecycleEvent::AttemptCleaned {
4715                policy,
4716                attempt,
4717                outcome: OutcomeKind::IdleExit,
4718            },
4719            LifecycleEvent::ScaleDownRefused { policy, attempt },
4720            LifecycleEvent::PollScheduled {
4721                retry_in_ms: 900_000,
4722                pace: PollPace::RateLimited {
4723                    kind: RateLimitKind::Primary,
4724                },
4725            },
4726        ]
4727    }
4728
4729    /// `e1`'s Definition of Done: *"No emitted event contains a token, a JIT
4730    /// blob, or a credential header."*
4731    ///
4732    /// Asserted by rendering every variant and putting the result through `d1`'s
4733    /// own scrubber: if any of it looked like a credential to the redactor that
4734    /// guards the log file, the round trip would not be the identity. The
4735    /// positive control at the bottom is what stops that assertion passing
4736    /// because the scrubber is asleep.
4737    #[test]
4738    fn no_emitted_event_can_carry_a_credential() {
4739        use runner_manager_platform::logging::redact;
4740
4741        for event in every_event() {
4742            let displayed = event.to_string();
4743            assert_eq!(
4744                redact(&displayed),
4745                displayed,
4746                "`{}` renders something `d1`'s sink would have to redact",
4747                event.name()
4748            );
4749
4750            let debugged = format!("{event:?}");
4751            assert_eq!(
4752                redact(&debugged),
4753                debugged,
4754                "`{}`'s Debug renders something `d1`'s sink would have to redact",
4755                event.name()
4756            );
4757        }
4758
4759        // The control: the scrubber is awake, and would have caught a credential
4760        // had one been there.
4761        let secret = "Authorization: Bearer ghp_0123456789abcdefghijklmnopqrstuvwxyz";
4762        assert_ne!(
4763            redact(secret),
4764            secret,
4765            "the scan above proves nothing if `redact` no longer recognises a credential"
4766        );
4767    }
4768
4769    #[test]
4770    fn every_field_name_this_sink_emits_is_one_d1_allows() {
4771        use runner_manager_platform::logging::is_field_allowed;
4772
4773        // The names `TracingEvents` writes. Kept beside the sink rather than
4774        // derived from it, because a derived list would move with the code and
4775        // assert nothing.
4776        for field in [
4777            "event",
4778            "policy_id",
4779            "attempt_id",
4780            "attempt_state",
4781            "demand",
4782            "desired",
4783            "capacity",
4784            "headroom",
4785            "count",
4786            "reason",
4787            "outcome",
4788            "mode",
4789            "lock",
4790            "retry_in_ms",
4791            "state",
4792        ] {
4793            assert!(
4794                is_field_allowed(field),
4795                "`{field}` is not on `d1`'s allow-list, so this sink would emit \
4796                 `[redacted]` in its place and the line would lose its meaning"
4797            );
4798        }
4799    }
4800
4801    #[test]
4802    fn every_failure_reason_has_a_credential_free_kind() {
4803        for reason in FailureReason::ALL {
4804            let kind = failure_reason_kind(&reason);
4805            assert!(!kind.is_empty());
4806            assert!(
4807                kind.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
4808                "`{kind}` is not a fixed identifier"
4809            );
4810        }
4811        assert_eq!(
4812            failure_reason_kind(&FailureReason::Other("ghp_secret".into())),
4813            "other",
4814            "the detail of an `Other` reason never reaches an event"
4815        );
4816    }
4817
4818    // =======================================================================
4819    // The two tripwires
4820    // =======================================================================
4821
4822    /// One source file's production half, with comment lines dropped.
4823    ///
4824    /// Both exclusions are `c4`'s, and load-bearing for the same reasons. The
4825    /// **test module** goes because the tests in it legitimately name the shapes
4826    /// they forbid — this module's own positive control is a literal
4827    /// `async fn acquire_jobs`, which would accuse the file of the thing it is
4828    /// proving it does not do. The **comments** go because this module's
4829    /// documentation explains the seam at length and has to name what does not
4830    /// exist in order to say why; a scan that forbade the explanation is a scan
4831    /// that gets the explanation deleted.
4832    fn production_half_of(source: &str) -> String {
4833        let production = source
4834            .split_once("\n#[cfg(test)]")
4835            .map_or(source, |(production, _)| production);
4836        production
4837            .lines()
4838            .filter(|line| !line.trim_start().starts_with("//"))
4839            .collect::<Vec<_>>()
4840            .join("\n")
4841    }
4842
4843    /// This file's own production half.
4844    fn this_file_above_its_tests_without_prose() -> String {
4845        production_half_of(include_str!("reconcile.rs"))
4846    }
4847
4848    /// The one normalisation both halves of the scan use.
4849    ///
4850    /// # This is a second copy of `crates/github/src/demand.rs`, deliberately
4851    ///
4852    /// `production_half_of`, this function, [`FORBIDDEN`] and
4853    /// `forbidden_shape_in` together duplicate `demand.rs:1530-1619`. Sharing
4854    /// them would mean putting them in `crates/testkit`, which `e1` does not
4855    /// own, so the copy was the only option available to this task.
4856    ///
4857    /// **It is worth consolidating later, and here is the specific hazard.**
4858    /// The last defect in `c4`'s copy was two spellings of "the same"
4859    /// normalisation drifting apart — the haystack lower-cased and the needle
4860    /// not — which made three of its seven assertions vacuously true from the
4861    /// day they were written. Two copies is the same hazard one level up. The
4862    /// mitigation inside *this* copy is that one function serves both the scan
4863    /// and its positive control, so a normaliser that stops matching fails the
4864    /// control loudly rather than passing the scan silently; what that cannot
4865    /// catch is this copy and `c4`'s diverging from each other.
4866    fn normalise_for_scan(text: &str) -> String {
4867        text.to_ascii_lowercase().replace(['_', ' '], "")
4868    }
4869
4870    /// The Actions-service call this design has no equivalent of, plus the
4871    /// shapes an implementer would invent in its place.
4872    ///
4873    /// Spelled in halves so that no needle ever appears whole in the text being
4874    /// scanned, and keyed to `fn`/`struct` so that the prose above may keep
4875    /// explaining why there is no reservation. `c4` records both trades at
4876    /// length; this list is its counterpart one layer up. Note that the
4877    /// allocation lock's own `fn acquire` is deliberately *not* matched: the
4878    /// needle is `acquire`-a-**job**, and a lock is not one.
4879    const FORBIDDEN: &[&str] = &[
4880        concat!("fn ", "acquire", "_job"),
4881        concat!("fn ", "claim", "_job"),
4882        concat!("fn ", "lease", "_job"),
4883        concat!("fn ", "reserve", "_job"),
4884        concat!("fn ", "ack", "nowledge"),
4885        concat!("struct ", "Job", "Lease"),
4886        concat!("struct ", "Job", "Claim"),
4887        concat!("struct ", "Job", "Reservation"),
4888    ];
4889
4890    fn forbidden_shape_in(source: &str) -> Option<&'static str> {
4891        let haystack = normalise_for_scan(source);
4892        FORBIDDEN
4893            .iter()
4894            .copied()
4895            .find(|forbidden| haystack.contains(&normalise_for_scan(forbidden)))
4896    }
4897
4898    /// `e1`'s Definition of Done: *"No reservation, claim, lease, or acquisition
4899    /// call exists in the crate; a test or review note records that this is
4900    /// deliberate rather than missing."*
4901    ///
4902    /// **Deliberate, not missing.** The scale-set model let a listener call
4903    /// `AcquireJobs` to claim an assignment before scaling; the REST path has no
4904    /// equivalent, so demand is advisory and two hosts serving the same labels
4905    /// can both start a runner for one queued run. Adding a local reservation
4906    /// table would not remove that — the other host cannot see it — it would
4907    /// only hide the surplus case from the tests that measure it. The three
4908    /// controls that actually bound it are host-scoped routing labels,
4909    /// `max_capacity`, and `host_capacity`, and the last two are enforced in
4910    /// this file.
4911    ///
4912    /// The scan is a tripwire on the obvious shape rather than a proof: a
4913    /// reservation reached through a trait method or a differently-named helper
4914    /// would walk past it. Review is the primary control, exactly as `c4` states
4915    /// for its own copy.
4916    ///
4917    /// # It scans the crate, because the bullet says "in the crate"
4918    ///
4919    /// It used to scan this file alone while quoting a crate-wide claim, which
4920    /// left `lifecycle.rs` — `e3`, the launcher, and by far the likeliest place
4921    /// for someone to "fix" the surplus-runner case with a local lease — covered
4922    /// by nothing. Reading another owner's file is not editing it, so ownership
4923    /// was never the obstacle.
4924    ///
4925    /// The walk below is `c4`'s, and it **recurses** for the reason `c4`
4926    /// records: a module directory (`src/reconcile/mod.rs`) arrives as an entry
4927    /// that does not end in `.rs`, so a flat filter drops it and takes every
4928    /// file underneath with it, leaving the scan passing over files it covers
4929    /// by nothing at all. The listed-versus-on-disk assertion is what stops
4930    /// `SOURCES` going stale the moment `e2` or `e3` adds a module.
4931    #[test]
4932    fn nothing_in_this_crate_reserves_or_claims_a_job() {
4933        const SOURCES: &[(&str, &str)] = &[
4934            ("lib.rs", include_str!("lib.rs")),
4935            ("lifecycle.rs", include_str!("lifecycle.rs")),
4936            ("package.rs", include_str!("package.rs")),
4937            ("reconcile.rs", include_str!("reconcile.rs")),
4938        ];
4939
4940        fn walk(directory: &std::path::Path, prefix: &str, found: &mut Vec<String>) {
4941            for entry in std::fs::read_dir(directory).expect("the crate's own src/ is readable") {
4942                let entry = entry.expect("a readable directory entry");
4943                let name = entry.file_name().to_string_lossy().into_owned();
4944                // `/`-joined, which is what `include_str!` takes on every
4945                // platform, so the two sides compare directly.
4946                let joined = if prefix.is_empty() {
4947                    name.clone()
4948                } else {
4949                    format!("{prefix}/{name}")
4950                };
4951                if entry.path().is_dir() {
4952                    walk(&entry.path(), &joined, found);
4953                } else if name.ends_with(".rs") {
4954                    found.push(joined);
4955                }
4956            }
4957        }
4958
4959        let mut listed: Vec<&str> = SOURCES.iter().map(|(name, _)| *name).collect();
4960        listed.sort_unstable();
4961        let mut on_disk = Vec::new();
4962        walk(
4963            std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")),
4964            "",
4965            &mut on_disk,
4966        );
4967        on_disk.sort_unstable();
4968        assert_eq!(
4969            listed, on_disk,
4970            "a source file was added or removed; this scan claims to cover the whole crate \
4971             and a stale list makes that claim false"
4972        );
4973
4974        for (name, source) in SOURCES {
4975            assert_eq!(
4976                forbidden_shape_in(&production_half_of(source)),
4977                None,
4978                "{name} names a forbidden shape: there is no `AcquireJobs` equivalent over \
4979                 REST, and a local lease coordinates this host with itself and with nothing \
4980                 else. If an owner decision restored one, that decision belongs in this \
4981                 module's documentation and in this test before it belongs in the code"
4982            );
4983        }
4984
4985        // The control: the scan can see a shape when there is one, through the
4986        // same matcher the loop above uses.
4987        assert!(
4988            forbidden_shape_in("async fn acquire_jobs(&self) -> Vec<Job> { todo!() }").is_some(),
4989            "the scan above proves nothing if the needles no longer match"
4990        );
4991    }
4992
4993    /// This module **applies** `b1`'s label predicate and implements none of it.
4994    ///
4995    /// The counterpart to `c4`'s scan over `crates/github/src/demand.rs`, and it
4996    /// checks the opposite thing, because the two modules sit on opposite sides
4997    /// of the same seam. `c4` builds a `RunsOn` per queued job and must name no
4998    /// `RoutingLabels`; this module holds the policy whose labels decide, so it
4999    /// must call `RoutingLabels::tally` and must not re-derive what that call
5000    /// answers.
5001    ///
5002    /// So the scan is in two halves:
5003    ///
5004    /// * **Present.** `DemandTally` has to appear, because [`demand_for`]
5005    ///   returns one. A production half that named it nowhere would mean the
5006    ///   filtering had been dropped and every queued job in a watched repository
5007    ///   was driving this policy toward `max_capacity` again.
5008    /// * **Absent.** The vocabulary of a *second* implementation. `b1` names the
5009    ///   three outcomes of matching one job; this module consumes the aggregate
5010    ///   and never a single job's verdict, so naming `RunsOnMatch` or
5011    ///   `UnresolvableRunsOn` here means a `match` on an outcome that
5012    ///   `RoutingLabels::tally` has already decided — which is how two copies of
5013    ///   a predicate start.
5014    ///
5015    /// Like the needles in `nothing_in_this_module_reserves_or_claims_a_job`,
5016    /// this is a tripwire on the obvious shape rather than a proof: a hand-rolled
5017    /// comparison of raw label strings that never names a `policy` type would
5018    /// walk past it. Stated rather than implied, for the same reason it is
5019    /// stated there.
5020    #[test]
5021    fn the_label_predicate_is_b1s_and_this_module_only_applies_it() {
5022        let production = this_file_above_its_tests_without_prose();
5023
5024        assert!(
5025            production.contains("DemandTally"),
5026            "the reconciliation loop must tally queued jobs against this policy's routing \
5027             labels. A production half that named `DemandTally` nowhere would mean the \
5028             label filtering had been removed, and a repository whose jobs target \
5029             `ubuntu-latest` would drive its policy toward `max_capacity` again"
5030        );
5031
5032        for second_implementation in ["RunsOnMatch", "UnresolvableRunsOn"] {
5033            assert!(
5034                !production.contains(second_implementation),
5035                "the reconciliation loop names `{second_implementation}`, which is the \
5036                 vocabulary of deciding one job's `runs-on` -- and `RoutingLabels::tally` \
5037                 has already decided it. This module applies the predicate and does not \
5038                 re-implement it; if an owner decision changed that, it belongs in this \
5039                 module's documentation and in this test before it belongs in the code"
5040            );
5041        }
5042    }
5043
5044    /// The demand this module clamps is the *matched* count, and a job this host
5045    /// cannot serve is not demand.
5046    ///
5047    /// The behaviour the whole reversal was for, asserted end to end through
5048    /// `demand_for` rather than through `b1`'s predicate in isolation: a policy
5049    /// carrying this host's labels, a reading holding some of its jobs and some
5050    /// of somebody else's, and the three counts kept apart.
5051    #[test]
5052    fn demand_is_the_queued_jobs_this_policy_can_actually_serve() {
5053        let policy = policy(1, "acme/app", 10);
5054        let reading = QueuedDemand::of(
5055            repo("acme/app"),
5056            [
5057                fixtures::queued_job(&[HOST_LABEL]),
5058                fixtures::queued_job(&[HOST_LABEL]),
5059                fixtures::queued_job(&["ubuntu-latest"]),
5060                fixtures::unresolvable_job(),
5061            ],
5062        );
5063
5064        let tally = demand_for(&policy, &reading);
5065
5066        assert_eq!(
5067            tally.demand(),
5068            2,
5069            "only the jobs whose required labels this policy carries are demand"
5070        );
5071        assert_eq!(
5072            tally.not_matched, 1,
5073            "a `ubuntu-latest` job is somebody else's work; counting it would start a \
5074             runner that idles until it times out"
5075        );
5076        assert_eq!(
5077            tally.unresolvable.len(),
5078            1,
5079            "an unresolvable `runs-on` is never demand and never discarded"
5080        );
5081    }
5082
5083    /// A repository target reads its own repository; an organization target
5084    /// reads the whole scope.
5085    #[test]
5086    fn an_organization_policy_tallies_every_repository_its_scope_covers() {
5087        let mut per_repository = BTreeMap::new();
5088        per_repository.insert(repo("acme/left"), fixtures::queued_jobs(&[HOST_LABEL], 3));
5089        per_repository.insert(repo("acme/right"), fixtures::queued_jobs(&[HOST_LABEL], 4));
5090        let reading = QueuedDemand::new(per_repository);
5091
5092        let repository_policy = policy(1, "acme/left", 10);
5093        assert_eq!(
5094            demand_for(&repository_policy, &reading).demand(),
5095            3,
5096            "a repository target reads its own repository's queue and not the aggregate"
5097        );
5098
5099        let org_policy = fixtures::policy()
5100            .id(PolicyId::from_u128(2))
5101            .organization("acme")
5102            .autoscale("home", 10)
5103            .active()
5104            .build();
5105        assert_eq!(
5106            demand_for(&org_policy, &reading).demand(),
5107            7,
5108            "an organization policy serves any repository in its scope, so its demand is \
5109             the whole aggregate's"
5110        );
5111    }
5112
5113    #[test]
5114    fn the_accepted_over_count_is_bounded_by_the_two_ceilings_and_nothing_else() {
5115        // The owner decision accepts that a repository whose jobs only target
5116        // `ubuntu-latest` still drives its policy toward `max_capacity`. What
5117        // stops that being unbounded is exactly what stops any other demand
5118        // being unbounded, which is asserted here rather than assumed.
5119        let host = host_with(2);
5120        let policy = policy(1, "acme/app", 5);
5121        let attempts: Vec<RunnerAttempt> = Vec::new();
5122        let mut allocator = HostAllocator::from_attempts(&host, &attempts);
5123
5124        let allocation = allocator.allocate(&policy, u32::MAX);
5125        assert_eq!(allocation.desired, 5, "max_capacity beats reported demand");
5126        assert_eq!(allocation.to_start, 2, "host_capacity beats max_capacity");
5127        assert_eq!(allocation.limiting_factor, LimitingFactor::HostCapacity);
5128    }
5129}