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// ---------------------------------------------------------------------------
1129// Lifecycle events
1130// ---------------------------------------------------------------------------
1131
1132/// Which terminal thing happened, as a closed vocabulary.
1133///
1134/// The distinction `g2` renders: an idle exit is the accepted surplus case and
1135/// **not** a failure, and showing it as one sends an operator hunting a fault
1136/// that does not exist.
1137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1138pub enum OutcomeKind {
1139    CompletedJob,
1140    IdleExit,
1141    Failed,
1142    Orphaned,
1143}
1144
1145impl OutcomeKind {
1146    #[must_use]
1147    pub const fn of(outcome: &AttemptOutcome) -> Self {
1148        match outcome {
1149            AttemptOutcome::CompletedJob => Self::CompletedJob,
1150            AttemptOutcome::ExitedIdleWithoutWork => Self::IdleExit,
1151            AttemptOutcome::Failed { .. } => Self::Failed,
1152            AttemptOutcome::Orphaned => Self::Orphaned,
1153        }
1154    }
1155
1156    #[must_use]
1157    pub const fn is_failure(&self) -> bool {
1158        matches!(self, Self::Failed | Self::Orphaned)
1159    }
1160
1161    #[must_use]
1162    pub const fn as_str(&self) -> &'static str {
1163        match self {
1164            Self::CompletedJob => "completed_job",
1165            Self::IdleExit => "exited_idle_without_work",
1166            Self::Failed => "failed",
1167            Self::Orphaned => "orphaned",
1168        }
1169    }
1170}
1171
1172impl fmt::Display for OutcomeKind {
1173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1174        f.write_str(self.as_str())
1175    }
1176}
1177
1178/// A [`FailureReason`]'s variant name, with no detail.
1179///
1180/// [`FailureReason::Other`] carries a `String` that `e3` fills in, and an event
1181/// is not the place for it: `07-security.md`'s log scan runs over everything
1182/// this loop emits, and free text is the one shape that can carry a credential
1183/// past a field allow-list. The operator-facing detail reaches the journal
1184/// through `b2` and the screen through `g2`; what reaches an *event* is the
1185/// variant.
1186#[must_use]
1187pub const fn failure_reason_kind(reason: &FailureReason) -> &'static str {
1188    match reason {
1189        FailureReason::JitRequestFailed => "jit_request_failed",
1190        FailureReason::JitExpired => "jit_expired",
1191        FailureReason::RunnerPackageUnverified => "runner_package_unverified",
1192        FailureReason::RunnerVersionRejected => "runner_version_rejected",
1193        FailureReason::ProcessStartFailed => "process_start_failed",
1194        FailureReason::ProcessExitedUnexpectedly => "process_exited_unexpectedly",
1195        FailureReason::RegistrationTimedOut => "registration_timed_out",
1196        FailureReason::TerminatedAfterRegistrationTimeout => {
1197            "terminated_after_registration_timeout"
1198        }
1199        FailureReason::Other(_) => "other",
1200    }
1201}
1202
1203/// What `g2`'s activity view and the local log sink see.
1204///
1205/// **Every field is an identifier, a count, a duration, or a `&'static str`
1206/// drawn from a closed set.** There is no `String` anywhere in this enum, which
1207/// is what makes "no emitted event contains a token, a JIT blob, or a credential
1208/// header" a property of the type rather than a discipline each call site has to
1209/// keep. `tests::no_emitted_event_can_carry_a_credential` renders every variant
1210/// through `d1`'s scrubber and asserts nothing changes, with a positive control
1211/// so the assertion cannot pass vacuously.
1212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1213pub enum LifecycleEvent {
1214    /// A demand poll answered for one target.
1215    DemandObserved {
1216        policy: PolicyId,
1217        /// Queued jobs this policy's routing labels match. The number clamped.
1218        demand: u32,
1219        /// Queued jobs whose required labels this policy does not carry.
1220        ///
1221        /// Never demand. Reported because the difference between this and
1222        /// `demand` is the whole value of the label filtering, and an operator
1223        /// wondering why a busy repository started no runners is owed it.
1224        not_matched: u32,
1225        /// Queued jobs whose `runs-on` could not be resolved statically.
1226        ///
1227        /// `b1` requires these be "reported as unresolvable rather than silently
1228        /// counted or silently dropped": counting one would start a runner for a
1229        /// job that may not be ours, and dropping it would hide a workflow this
1230        /// host can never serve. A count rather than the reasons themselves
1231        /// because this type is `Copy`, and `c4` logs the reasons where it
1232        /// builds them.
1233        unresolvable: u32,
1234        /// `false` when the count is a floor rather than a total.
1235        complete: bool,
1236    },
1237    /// A target could not be polled, so its policies start nothing this pass.
1238    TargetUnreadable {
1239        policy: PolicyId,
1240        reason: &'static str,
1241    },
1242    /// One policy's share of the pass.
1243    Allocated {
1244        policy: PolicyId,
1245        demand: u32,
1246        desired: u16,
1247        active_owned: u16,
1248        headroom: u16,
1249        to_start: u16,
1250        limiting: LimitingFactor,
1251    },
1252    /// A monitor-only policy was skipped entirely, before any demand request
1253    /// was issued for it (D19).
1254    MonitorOnlySkipped { policy: PolicyId },
1255    /// One runtime was created and one runner started.
1256    RunnerStarted {
1257        policy: PolicyId,
1258        attempt: AttemptId,
1259    },
1260    /// One runner could not be started.
1261    RunnerStartFailed {
1262        policy: PolicyId,
1263        reason: &'static str,
1264    },
1265    /// The allocation lock was not free, so `count` runners this policy was
1266    /// granted were not created this pass.
1267    AllocationDeferred { policy: PolicyId, count: u16 },
1268    /// The host's attempt set could not be read at all.
1269    ///
1270    /// Distinct from an empty set on purpose, and the whole reason
1271    /// [`RunnerLauncher::attempts`] is fallible: the two produce the same
1272    /// *number* and demand opposite actions.
1273    AttemptsUnreadable { reason: &'static str },
1274    /// A terminal attempt's runtime was removed.
1275    AttemptCleaned {
1276        policy: PolicyId,
1277        attempt: AttemptId,
1278        outcome: OutcomeKind,
1279    },
1280    /// A terminal attempt's runtime could not be removed. It will be retried on
1281    /// the next pass, and this is what keeps that retry from being silent.
1282    AttemptCleanFailed {
1283        policy: PolicyId,
1284        attempt: AttemptId,
1285        reason: &'static str,
1286    },
1287    /// Scale-down declined to remove a runner that is executing a job.
1288    ScaleDownRefused {
1289        policy: PolicyId,
1290        attempt: AttemptId,
1291    },
1292    /// When the next poll is, and why then.
1293    PollScheduled { retry_in_ms: u64, pace: PollPace },
1294}
1295
1296impl LifecycleEvent {
1297    /// A fixed name, for the `event` field `d1`'s sink allows verbatim.
1298    #[must_use]
1299    pub const fn name(&self) -> &'static str {
1300        match self {
1301            Self::DemandObserved { .. } => "demand_observed",
1302            Self::TargetUnreadable { .. } => "target_unreadable",
1303            Self::Allocated { .. } => "allocated",
1304            Self::MonitorOnlySkipped { .. } => "monitor_only_skipped",
1305            Self::RunnerStarted { .. } => "runner_started",
1306            Self::RunnerStartFailed { .. } => "runner_start_failed",
1307            Self::AllocationDeferred { .. } => "allocation_deferred",
1308            Self::AttemptsUnreadable { .. } => "attempts_unreadable",
1309            Self::AttemptCleaned { .. } => "attempt_cleaned",
1310            Self::AttemptCleanFailed { .. } => "attempt_clean_failed",
1311            Self::ScaleDownRefused { .. } => "scale_down_refused",
1312            Self::PollScheduled { .. } => "poll_scheduled",
1313        }
1314    }
1315
1316    /// Which policy this event is about.
1317    #[must_use]
1318    pub const fn policy(&self) -> Option<PolicyId> {
1319        match self {
1320            Self::DemandObserved { policy, .. }
1321            | Self::TargetUnreadable { policy, .. }
1322            | Self::Allocated { policy, .. }
1323            | Self::MonitorOnlySkipped { policy }
1324            | Self::RunnerStarted { policy, .. }
1325            | Self::RunnerStartFailed { policy, .. }
1326            | Self::AllocationDeferred { policy, .. }
1327            | Self::AttemptCleaned { policy, .. }
1328            | Self::AttemptCleanFailed { policy, .. }
1329            | Self::ScaleDownRefused { policy, .. } => Some(*policy),
1330            Self::PollScheduled { .. } | Self::AttemptsUnreadable { .. } => None,
1331        }
1332    }
1333}
1334
1335impl fmt::Display for LifecycleEvent {
1336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1337        match self {
1338            Self::DemandObserved {
1339                policy,
1340                demand,
1341                not_matched,
1342                unresolvable,
1343                complete,
1344            } => write!(
1345                f,
1346                "policy {policy}: {demand} queued jobs for this host{}{}{}",
1347                if *not_matched == 0 {
1348                    String::new()
1349                } else {
1350                    format!(", {not_matched} for other labels")
1351                },
1352                if *unresolvable == 0 {
1353                    String::new()
1354                } else {
1355                    format!(", {unresolvable} with an unresolvable `runs-on`")
1356                },
1357                if *complete {
1358                    ""
1359                } else {
1360                    " (a floor, not a total)"
1361                }
1362            ),
1363            Self::TargetUnreadable { policy, reason } => {
1364                write!(f, "policy {policy}: target unreadable ({reason})")
1365            }
1366            Self::Allocated {
1367                policy,
1368                demand,
1369                desired,
1370                active_owned,
1371                headroom,
1372                to_start,
1373                limiting,
1374            } => write!(
1375                f,
1376                "policy {policy}: demand {demand}, desired {desired}, {active_owned} in \
1377                 flight, {headroom} free on this host, starting {to_start} ({limiting})"
1378            ),
1379            Self::MonitorOnlySkipped { policy } => {
1380                write!(f, "policy {policy}: monitor-only, skipped")
1381            }
1382            Self::RunnerStarted { policy, attempt } => {
1383                write!(f, "policy {policy}: started attempt {attempt}")
1384            }
1385            Self::RunnerStartFailed { policy, reason } => {
1386                write!(f, "policy {policy}: could not start a runner ({reason})")
1387            }
1388            Self::AllocationDeferred { policy, count } => write!(
1389                f,
1390                "policy {policy}: the allocation lock was held; {count} granted runners \
1391                 were not created"
1392            ),
1393            Self::AttemptsUnreadable { reason } => write!(
1394                f,
1395                "the host's attempt set could not be read ({reason}); nothing was started, \
1396                 and this is not the same as the host being idle"
1397            ),
1398            Self::AttemptCleaned {
1399                policy,
1400                attempt,
1401                outcome,
1402            } => write!(f, "policy {policy}: cleaned attempt {attempt} ({outcome})"),
1403            Self::AttemptCleanFailed {
1404                policy,
1405                attempt,
1406                reason,
1407            } => write!(
1408                f,
1409                "policy {policy}: attempt {attempt} could not be cleaned ({reason}); it \
1410                 will be retried"
1411            ),
1412            Self::ScaleDownRefused { policy, attempt } => write!(
1413                f,
1414                "policy {policy}: attempt {attempt} is executing a job and was not removed"
1415            ),
1416            Self::PollScheduled { retry_in_ms, pace } => {
1417                write!(f, "next poll in {retry_in_ms}ms ({pace})")
1418            }
1419        }
1420    }
1421}
1422
1423/// Where lifecycle events go.
1424pub trait EventSink: fmt::Debug + Send + Sync {
1425    fn emit(&self, event: LifecycleEvent);
1426}
1427
1428/// Discards everything. For callers that only want the report.
1429#[derive(Debug, Clone, Copy, Default)]
1430pub struct NoEvents;
1431
1432impl EventSink for NoEvents {
1433    fn emit(&self, _event: LifecycleEvent) {}
1434}
1435
1436/// The local log sink, through `d1`'s redacting layer.
1437///
1438/// Every field name below is on
1439/// [`runner_manager_platform::logging::ALLOWED_FIELDS`]; anything else would be
1440/// replaced with `[redacted]` and the line would lose its meaning rather than
1441/// its safety. `tests::every_field_name_this_sink_emits_is_one_d1_allows` keeps
1442/// that true.
1443#[derive(Debug, Clone, Copy, Default)]
1444pub struct TracingEvents;
1445
1446impl EventSink for TracingEvents {
1447    fn emit(&self, event: LifecycleEvent) {
1448        let name = event.name();
1449        match event {
1450            LifecycleEvent::DemandObserved {
1451                policy,
1452                demand,
1453                not_matched,
1454                unresolvable,
1455                complete,
1456            } => {
1457                tracing::info!(
1458                    event = name,
1459                    policy_id = %policy,
1460                    demand,
1461                    not_matched,
1462                    unresolvable,
1463                    count = u64::from(complete),
1464                );
1465                // There is deliberately no `warn!` here for the "demand is zero
1466                // but jobs were not matched" shape, though it is the one this
1467                // change introduced: before demand was filtered, a repository
1468                // with work in it always produced some, and now a policy whose
1469                // labels do not cover its jobs produces none.
1470                //
1471                // The reason is that the shape is indistinguishable from a
1472                // healthy one. A repository served by a Windows host and a macOS
1473                // host has the other host's jobs queued in it constantly, so
1474                // each agent would warn on every poll about work that is being
1475                // served correctly by the other machine. Telling the two apart
1476                // needs to know whether this policy has *ever* matched anything,
1477                // which is state across polls that this loop does not keep.
1478                //
1479                // What an operator gets instead is the `not_matched` count, on
1480                // this event and in its `Display`, which `g2` renders. "0 queued
1481                // jobs for this host, 5 for other labels" is the diagnosis; a
1482                // warning that fired on every healthy minute would be the kind
1483                // nobody reads.
1484            }
1485            LifecycleEvent::TargetUnreadable { policy, reason } => {
1486                tracing::warn!(event = name, policy_id = %policy, reason);
1487            }
1488            LifecycleEvent::Allocated {
1489                policy,
1490                demand,
1491                desired,
1492                active_owned,
1493                headroom,
1494                to_start,
1495                limiting,
1496            } => tracing::info!(
1497                event = name,
1498                policy_id = %policy,
1499                demand,
1500                desired,
1501                capacity = active_owned,
1502                headroom,
1503                count = to_start,
1504                reason = %limiting,
1505            ),
1506            LifecycleEvent::MonitorOnlySkipped { policy } => {
1507                tracing::debug!(event = name, policy_id = %policy, mode = "monitor_only");
1508            }
1509            LifecycleEvent::RunnerStarted { policy, attempt } => {
1510                tracing::info!(event = name, policy_id = %policy, attempt_id = %attempt);
1511            }
1512            LifecycleEvent::RunnerStartFailed { policy, reason } => {
1513                tracing::warn!(event = name, policy_id = %policy, reason);
1514            }
1515            LifecycleEvent::AllocationDeferred { policy, count } => {
1516                tracing::debug!(event = name, policy_id = %policy, lock = "allocation", count);
1517            }
1518            LifecycleEvent::AttemptsUnreadable { reason } => {
1519                tracing::warn!(event = name, reason);
1520            }
1521            LifecycleEvent::AttemptCleaned {
1522                policy,
1523                attempt,
1524                outcome,
1525            } => tracing::info!(
1526                event = name,
1527                policy_id = %policy,
1528                attempt_id = %attempt,
1529                outcome = outcome.as_str(),
1530            ),
1531            LifecycleEvent::AttemptCleanFailed {
1532                policy,
1533                attempt,
1534                reason,
1535            } => tracing::warn!(
1536                event = name,
1537                policy_id = %policy,
1538                attempt_id = %attempt,
1539                reason,
1540            ),
1541            LifecycleEvent::ScaleDownRefused { policy, attempt } => tracing::info!(
1542                event = name,
1543                policy_id = %policy,
1544                attempt_id = %attempt,
1545                attempt_state = "busy",
1546            ),
1547            LifecycleEvent::PollScheduled { retry_in_ms, pace } => {
1548                tracing::info!(event = name, retry_in_ms, state = pace.as_str());
1549            }
1550        }
1551    }
1552}
1553
1554/// Keeps every event, in order.
1555///
1556/// `g2`'s activity view is a reader of this, and so is every test below.
1557#[derive(Debug, Default)]
1558pub struct EventLog {
1559    events: Mutex<Vec<LifecycleEvent>>,
1560}
1561
1562impl EventLog {
1563    #[must_use]
1564    pub fn new() -> Self {
1565        Self::default()
1566    }
1567
1568    #[must_use]
1569    pub fn events(&self) -> Vec<LifecycleEvent> {
1570        self.events.lock().map(|e| e.clone()).unwrap_or_default()
1571    }
1572
1573    /// How many events of one name were emitted.
1574    #[must_use]
1575    pub fn count_of(&self, name: &str) -> usize {
1576        self.events()
1577            .iter()
1578            .filter(|event| event.name() == name)
1579            .count()
1580    }
1581}
1582
1583impl EventSink for EventLog {
1584    fn emit(&self, event: LifecycleEvent) {
1585        if let Ok(mut events) = self.events.lock() {
1586            events.push(event);
1587        }
1588    }
1589}
1590
1591/// Both sinks at once: the log sink for the operator's file, the buffer for
1592/// `g2`'s screen.
1593#[derive(Debug)]
1594pub struct TeeEvents(pub Arc<dyn EventSink>, pub Arc<dyn EventSink>);
1595
1596impl EventSink for TeeEvents {
1597    fn emit(&self, event: LifecycleEvent) {
1598        self.0.emit(event);
1599        self.1.emit(event);
1600    }
1601}
1602
1603// ---------------------------------------------------------------------------
1604// The reconciler
1605// ---------------------------------------------------------------------------
1606
1607/// Everything one reconciler needs, written down at the call site.
1608///
1609/// A struct rather than seven positional arguments, for the reason `b1` gives at
1610/// `PersistedAttempt`: several of these are `Arc<dyn …>` and transposing two of
1611/// them type-checks. Construct it with a struct literal so every port is named.
1612pub struct ReconcilerPorts {
1613    pub demand: Arc<dyn DemandSource>,
1614    pub launcher: Arc<dyn RunnerLauncher>,
1615    pub lock: Arc<dyn AllocationLock>,
1616    pub directory: Arc<dyn RepositoryDirectory>,
1617    pub clock: Arc<dyn Clock>,
1618    pub jitter: Arc<dyn Jitter>,
1619    pub events: Arc<dyn EventSink>,
1620}
1621
1622impl fmt::Debug for ReconcilerPorts {
1623    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1624        f.debug_struct("ReconcilerPorts").finish_non_exhaustive()
1625    }
1626}
1627
1628/// What one reconciliation pass did.
1629///
1630/// `started` and the allocations are reported separately on purpose: an
1631/// allocation is what the pass *decided* under the lock, and `started` is what
1632/// actually came up. They differ when a launch fails or when the lock was held,
1633/// and collapsing them would hide both.
1634#[derive(Debug, Clone, Default)]
1635pub struct ReconcileReport {
1636    /// One entry per policy that got as far as being allocated for.
1637    pub allocations: Vec<Allocation>,
1638    /// Policies skipped because they are monitor-only (D19).
1639    pub monitor_only: Vec<PolicyId>,
1640    /// Policies whose target could not be polled this pass.
1641    pub unreadable: Vec<PolicyId>,
1642    /// Policies whose target GitHub actually answered for this pass.
1643    ///
1644    /// The counterpart to [`Self::unreadable`], and the only honest evidence
1645    /// that this host reached GitHub at all. [`Self::allocations`] is not: a
1646    /// policy this host does not own is allocated for with no demand and
1647    /// without any target being polled, so a pass where every poll failed can
1648    /// still end with allocations in it.
1649    pub targets_read: u16,
1650    /// Runners actually started.
1651    pub started: u16,
1652    /// Pre-acceptance attempts routed back through this pass's ordinary
1653    /// demand/capacity decision.
1654    pub replacement_intents: u16,
1655    /// Terminal attempts whose runtime was removed.
1656    pub cleaned: u16,
1657    /// Of those, the surplus case: registered, got no job, exited on its idle
1658    /// timeout. **Not** a failure.
1659    pub idle_exits: u16,
1660    /// Of those, the ones an operator should look at.
1661    pub failures: u16,
1662    /// Runners this pass was granted but did not start because the allocation
1663    /// lock was held.
1664    ///
1665    /// **Grants, not policies.** It used to be incremented once per
1666    /// `start_runners` call that met a held lock, so a policy that launched two
1667    /// of five and then lost the lock reported `1` while three runners went
1668    /// unstarted -- a number that agreed with neither its own name nor its
1669    /// documentation.
1670    pub deferred: u16,
1671    /// Times the host's attempt set could not be read this pass.
1672    ///
1673    /// Non-zero means the pass decided less than it looks like it decided: a
1674    /// policy whose attempt set was unreadable started nothing and is *not* in
1675    /// [`Self::allocations`], because there was no set to compute an allocation
1676    /// from. It is not the same as the host being idle, which is the whole
1677    /// reason [`RunnerLauncher::attempts`] is fallible.
1678    ///
1679    /// **A count, where [`Self::unreadable`] is a `Vec<PolicyId>`, and that
1680    /// asymmetry is deliberate.** An unreadable *target* is a fact about one
1681    /// policy's GitHub target; an unreadable *attempt set* is a fact about this
1682    /// host's journal, which no policy owns — two of the three paths that reach
1683    /// it (`clean_terminal_attempts` and `scale_down`) have no policy in hand at
1684    /// all. Naming policies here would mean either inventing an owner for a
1685    /// host-wide failure or reporting a partial list, and both read as more
1686    /// precision than there is. The pass is distinguishable from an idle one,
1687    /// which is what the field exists for; the per-policy attribution is not
1688    /// available, and is recorded as missing rather than faked.
1689    pub attempts_unreadable: u16,
1690    /// Terminal attempts whose runtime could not be removed. Retried next pass.
1691    pub clean_failures: u16,
1692    /// The most severe failure across the targets polled, when there was one.
1693    pub failure: Option<RefreshState>,
1694    /// What to display while GitHub is unreachable, including how long the
1695    /// outage has run and therefore whether queued work has already been lost.
1696    pub offline: Option<OfflineState>,
1697    /// When to poll next, and why then.
1698    pub next_poll: NextPoll,
1699    /// Demand requests this pass projected against the shared hourly ceiling.
1700    pub demand_requests: u32,
1701}
1702
1703impl ReconcileReport {
1704    /// Whether this pass actually reached GitHub, which is the only thing that
1705    /// entitles it to write a `last GitHub contact`.
1706    ///
1707    /// # Positive evidence, because the absence of a failure is not evidence
1708    ///
1709    /// The record used to be written whenever [`Self::failure`] was `None`, on
1710    /// the belief that an unauthorized target lands in [`Self::unreadable`]
1711    /// rather than in `failure`. **That belief is wrong.** `unreadable` is
1712    /// pushed only from the `PollOutcome::Failed` arm, `failure` is the maximum
1713    /// over every `Failed` reading, and `RefreshState::Unauthorized` scores 2 —
1714    /// so a non-empty `unreadable` always implies `failure.is_some()`, and
1715    /// guarding on both would have changed nothing at all.
1716    ///
1717    /// The path that really writes a contact record without touching GitHub is
1718    /// a pass that polls **nothing**: every policy draining, owned by another
1719    /// host, or monitor-only. `pollable` is then empty, no reading exists, no
1720    /// failure is computed, and the old guard passed. That is how
1721    /// `service status` can answer `healthy` on a host doing nothing at all.
1722    ///
1723    /// So this asks for evidence rather than for the absence of a complaint. A
1724    /// pass with nothing to ask reaches nobody and records nothing, which is
1725    /// what `never` in `service status` is for.
1726    ///
1727    /// Conservative on purpose: `repositories.scope_for` is a real request that
1728    /// can succeed before a demand poll fails, and it is not counted. Contact
1729    /// that cannot be proven is not claimed.
1730    #[must_use]
1731    pub const fn reached_github(&self) -> bool {
1732        self.targets_read > 0
1733    }
1734}
1735
1736impl Default for NextPoll {
1737    fn default() -> Self {
1738        Self {
1739            delay: PollSchedule::floor(),
1740            pace: PollPace::Nominal,
1741        }
1742    }
1743}
1744
1745impl ReconcileReport {
1746    /// Whether GitHub was unreachable this pass.
1747    #[must_use]
1748    pub fn is_offline(&self) -> bool {
1749        matches!(self.failure, Some(RefreshState::Offline))
1750    }
1751
1752    /// The offline state to display, when this pass was one.
1753    #[must_use]
1754    pub const fn offline_state(&self) -> Option<&OfflineState> {
1755        self.offline.as_ref()
1756    }
1757
1758    /// Attempts this pass created. The idle-host assertion reads this.
1759    #[must_use]
1760    pub const fn starts_nothing(&self) -> bool {
1761        self.started == 0
1762    }
1763}
1764
1765/// What one scale-down request did.
1766#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1767pub struct ScaleDownReport {
1768    /// Terminal attempts whose runtime was removed.
1769    pub removed: u16,
1770    /// Attempts executing a job. **Removed nothing, left `busy`.**
1771    pub refused_busy: u16,
1772    /// Terminal attempts whose runtime could not be removed.
1773    pub clean_failures: u16,
1774    /// Live attempts that are not yet busy. Also removed nothing: capacity is
1775    /// reclaimed only when an attempt reaches a terminal state.
1776    pub retained: u16,
1777    /// The host's attempt set could not be read, so **every other field here is
1778    /// meaningless** rather than zero.
1779    ///
1780    /// This is the same distinction [`ReconcileReport::attempts_unreadable`]
1781    /// draws, and it is here for the same reason: a default
1782    /// [`ScaleDownReport`] and a scale-down that could not see the machine are
1783    /// both all-zeros, and they mean opposite things — "there was nothing to
1784    /// reclaim" against "we do not know what there was". Check
1785    /// [`Self::is_conclusive`] before reading a zero as an answer.
1786    pub attempts_unreadable: bool,
1787}
1788
1789impl ScaleDownReport {
1790    /// Whether the counts here describe the machine at all.
1791    ///
1792    /// `false` means the attempt set could not be read, so every zero is
1793    /// "unknown" rather than "none".
1794    #[must_use]
1795    pub const fn is_conclusive(&self) -> bool {
1796        !self.attempts_unreadable
1797    }
1798}
1799
1800/// The reconciliation loop.
1801///
1802/// One per target, as `f3` runs them; they share a [`RunnerLauncher`] and an
1803/// [`AllocationLock`], which is what keeps the host ceiling true across all of
1804/// them.
1805#[derive(Debug)]
1806pub struct Reconciler {
1807    host: Host,
1808    demand: Arc<dyn DemandSource>,
1809    launcher: Arc<dyn RunnerLauncher>,
1810    lock: Arc<dyn AllocationLock>,
1811    repositories: RepositoryCache,
1812    clock: Arc<dyn Clock>,
1813    jitter: Arc<dyn Jitter>,
1814    events: Arc<dyn EventSink>,
1815    schedule: PollSchedule,
1816}
1817
1818impl Reconciler {
1819    /// Build a reconciler polling at the host's configured interval.
1820    #[must_use]
1821    pub fn new(host: Host, ports: ReconcilerPorts) -> Self {
1822        let interval = host.refresh_interval;
1823        let repositories = RepositoryCache::new(
1824            Arc::clone(&ports.directory),
1825            Arc::clone(&ports.clock),
1826            interval,
1827        );
1828        Self {
1829            host,
1830            demand: ports.demand,
1831            launcher: ports.launcher,
1832            lock: ports.lock,
1833            repositories,
1834            clock: ports.clock,
1835            jitter: ports.jitter,
1836            events: ports.events,
1837            schedule: PollSchedule::new(interval),
1838        }
1839    }
1840
1841    #[must_use]
1842    pub const fn host(&self) -> &Host {
1843        &self.host
1844    }
1845
1846    #[must_use]
1847    pub const fn schedule(&self) -> &PollSchedule {
1848        &self.schedule
1849    }
1850
1851    /// The repository-list cache, so `f1` can report what it has spent.
1852    #[must_use]
1853    pub const fn repositories(&self) -> &RepositoryCache {
1854        &self.repositories
1855    }
1856
1857    /// One reconciliation pass over `policies`.
1858    ///
1859    /// The order of operations is `03-control-flows.md` flow 2, and the two
1860    /// steps most worth naming are the ones that are silent when they are wrong:
1861    ///
1862    /// * **Monitor-only policies are removed before the demand poll**, not
1863    ///   after. D19 says such a policy "is skipped entirely by reconciliation",
1864    ///   and a poll issued on its behalf would spend requests from the shared
1865    ///   ceiling for a policy that can never act on the answer. This is asserted
1866    ///   on [`ScalePolicy::owns_runners`] rather than deduced from
1867    ///   `max_capacity` being absent.
1868    /// * **The attempt set is re-read under the lock, once per runtime.** See
1869    ///   [`RunnerLauncher`] for why it comes from there and nowhere else.
1870    pub async fn reconcile(&mut self, policies: &[ScalePolicy]) -> ReconcileReport {
1871        let mut report = ReconcileReport::default();
1872        // Everything this pass has created, carried across policies so that the
1873        // host-wide total cannot be computed from a set that is missing it. See
1874        // `RunnerLauncher::launch`.
1875        let mut launched: Vec<RunnerAttempt> = Vec::new();
1876
1877        // --- Flow 2.1-2.2: who is even asking, and what did GitHub say -------
1878        let mut pollable: Vec<&ScalePolicy> = Vec::new();
1879        let mut supervision_failed = BTreeSet::new();
1880        for policy in policies {
1881            if !policy.owns_runners() {
1882                report.monitor_only.push(policy.id);
1883                self.events
1884                    .emit(LifecycleEvent::MonitorOnlySkipped { policy: policy.id });
1885                continue;
1886            }
1887            if !policy.is_owned_by(self.host.id) {
1888                // Ownership rule 2 and precedence rule 4. The allocator reports
1889                // both by name below; polling on their behalf would spend
1890                // requests for an answer that cannot be acted on.
1891                continue;
1892            }
1893            match self.launcher.supervise(policy).await {
1894                Ok(intents) => {
1895                    report.replacement_intents = report
1896                        .replacement_intents
1897                        .saturating_add(u16::try_from(intents.len()).unwrap_or(u16::MAX));
1898                }
1899                Err(failure) => {
1900                    supervision_failed.insert(policy.id);
1901                    self.report_unreadable_attempts(&mut report, &failure);
1902                    continue;
1903                }
1904            }
1905            if !policy.may_start_runners() {
1906                continue;
1907            }
1908            pollable.push(policy);
1909        }
1910
1911        let readings = self.poll_targets(&pollable, &mut report).await;
1912
1913        // --- Flow 2.8: terminal attempts, whatever else this pass does -------
1914        //
1915        // Run before the allocation phase so that a report's `cleaned` count
1916        // describes the same instant its allocations do. It does not change the
1917        // arithmetic: a terminal attempt already stopped counting against
1918        // capacity when it became terminal, which is `b1`'s
1919        // `counts_against_capacity`. It touches no live process, so it is also
1920        // safe during an outage — flow 3.3 requires that running runners be
1921        // retained, and nothing here can reach one.
1922        self.clean_terminal_attempts(&mut report).await;
1923
1924        // --- Flow 2.3-2.6: the allocation -----------------------------------
1925        //
1926        // The predicates are re-tested here rather than the reading being looked
1927        // up by target, and that is not redundancy. **Targets are shared.** A
1928        // monitor-only policy watching `acme/app` alongside an autoscale policy
1929        // on the *same* repository finds a reading in the map that the other
1930        // policy paid for, and a lookup-driven loop then serves it: it emits a
1931        // demand observation on its behalf and clamps a number it has no
1932        // business seeing.
1933        //
1934        // Nothing downstream goes wrong when that happens — `may_start_runners`
1935        // is false for a monitor-only policy, so `HostAllocator` refuses it and
1936        // `to_start` is zero. It simply is not *skipped*, and D19's word is
1937        // "entirely".
1938        for policy in policies {
1939            if !policy.owns_runners() {
1940                // Already recorded and reported above, before any demand request
1941                // was issued. It owns no routing labels, takes no part in
1942                // demand, and can never be the reason a runner starts. Asserted
1943                // on the mode rather than deduced from `max_capacity` being
1944                // absent, which is what the specification requires.
1945                continue;
1946            }
1947            if !policy.is_owned_by(self.host.id) || !policy.may_start_runners() {
1948                // Ownership rule 2 and precedence rule 4. Allocated for with no
1949                // demand, so the refusal is reported by name rather than by
1950                // absence.
1951                match self.allocate_only(policy, 0, &launched).await {
1952                    Ok(allocation) => {
1953                        self.emit_allocation(&allocation);
1954                        report.allocations.push(allocation);
1955                    }
1956                    Err(failure) => self.report_unreadable_attempts(&mut report, &failure),
1957                }
1958                continue;
1959            }
1960            if supervision_failed.contains(&policy.id) {
1961                continue;
1962            }
1963            let Some(reading) = readings.get(&policy.target) else {
1964                // Unreachable: every policy reaching here was in `pollable`, and
1965                // `poll_targets` inserts an outcome for each of their targets.
1966                debug_assert!(false, "a pollable policy's target has no reading");
1967                continue;
1968            };
1969            match reading {
1970                PollOutcome::Failed(state) => {
1971                    report.unreadable.push(policy.id);
1972                    self.events.emit(LifecycleEvent::TargetUnreadable {
1973                        policy: policy.id,
1974                        reason: unreadable_reason(state),
1975                    });
1976                }
1977                PollOutcome::Ready(demand) => {
1978                    report.targets_read = report.targets_read.saturating_add(1);
1979                    let tally = demand_for(policy, demand);
1980                    let count = tally.demand();
1981                    self.events.emit(LifecycleEvent::DemandObserved {
1982                        policy: policy.id,
1983                        demand: count,
1984                        not_matched: tally.not_matched,
1985                        unresolvable: u32::try_from(tally.unresolvable.len()).unwrap_or(u32::MAX),
1986                        complete: demand.is_complete(),
1987                    });
1988                    self.start_runners(policy, count, &mut report, &mut launched)
1989                        .await;
1990                }
1991            }
1992        }
1993
1994        // --- Flow 2.1 / 3.3: when to come back ------------------------------
1995        let failure = readings
1996            .values()
1997            .filter_map(PollOutcome::failure)
1998            .max_by_key(|state| severity(state))
1999            .cloned();
2000        let now = self.clock.now();
2001        report.next_poll = self
2002            .schedule
2003            .next_poll(failure.as_ref(), now, self.jitter.as_ref());
2004        report.failure = failure;
2005        // Flow 3.3's fourth obligation: the offline state carries the 24-hour
2006        // bound, and it can only say whether that bound has passed if it is
2007        // given the real elapsed time rather than an estimate from the interval.
2008        if let PollPace::Offline { consecutive } = report.next_poll.pace {
2009            let state = OfflineState::new(consecutive, report.next_poll.delay);
2010            report.offline = Some(match self.schedule.offline_for(now) {
2011                Some(elapsed) => state.since(elapsed),
2012                None => state,
2013            });
2014        }
2015        self.events.emit(LifecycleEvent::PollScheduled {
2016            retry_in_ms: u64::try_from(report.next_poll.delay.as_millis()).unwrap_or(u64::MAX),
2017            pace: report.next_poll.pace,
2018        });
2019
2020        report
2021    }
2022
2023    /// Poll each distinct target once, however many policies share it.
2024    ///
2025    /// Two policies on one repository are one demand request, not two. That is
2026    /// not a micro-optimisation: the budget model in
2027    /// `04-subsystem-contracts.md` prices a *target*, and a loop that spent per
2028    /// policy would quietly exceed the projection `f2` admitted the
2029    /// configuration against.
2030    async fn poll_targets(
2031        &self,
2032        pollable: &[&ScalePolicy],
2033        report: &mut ReconcileReport,
2034    ) -> BTreeMap<ScaleTarget, PollOutcome> {
2035        let targets: BTreeSet<ScaleTarget> = pollable.iter().map(|p| p.target.clone()).collect();
2036
2037        let mut readings = BTreeMap::new();
2038        for target in targets {
2039            let outcome = match self.repositories.scope_for(&target).await {
2040                Ok(scope) => {
2041                    report.demand_requests = report
2042                        .demand_requests
2043                        .saturating_add(demand_requests_per_poll(&scope));
2044                    self.demand.poll(&scope).await
2045                }
2046                // The repository list could not be refreshed, so the scope of
2047                // the poll is unknown. Polling a stale or empty scope would
2048                // report a demand number for a set of repositories nobody
2049                // chose, which is worse than reporting that the target could
2050                // not be read.
2051                Err(error) => PollOutcome::Failed(RefreshState::from_error(&error)),
2052            };
2053            readings.insert(target, outcome);
2054        }
2055        readings
2056    }
2057
2058    /// Compute one policy's allocation without creating anything.
2059    ///
2060    /// # Why this is safe without the lock
2061    ///
2062    /// **Not** because it cannot grant — it can, and
2063    /// [`Reconciler::start_runners`] uses it as a pre-check precisely for the
2064    /// number it returns. That was the original reason and this function
2065    /// outgrew it; the reason now is that it *decides* nothing. Nothing is
2066    /// created here, the headroom it read is re-read under the lock before any
2067    /// runtime exists, and the under-lock allocation may only lower what this
2068    /// one proposed. So there is no read-decide-create sequence here to make
2069    /// atomic, and the worst this can be is optimistic — which the lock then
2070    /// corrects.
2071    ///
2072    /// # Errors
2073    /// Whatever [`RunnerLauncher::attempts`] reported. A failure is never the
2074    /// same answer as an empty set.
2075    async fn allocate_only(
2076        &self,
2077        policy: &ScalePolicy,
2078        demand: u32,
2079        launched: &[RunnerAttempt],
2080    ) -> Result<Allocation, LaunchFailure> {
2081        let attempts = self.host_attempts(launched).await?;
2082        let mut allocator = HostAllocator::from_attempts(&self.host, &attempts);
2083        Ok(allocator.allocate(policy, demand))
2084    }
2085
2086    /// Flow 2.4-2.6: start runners for one policy, one lock hold per runtime.
2087    ///
2088    /// # Two stopping conditions, and both are needed
2089    ///
2090    /// The loop re-reads the attempt set under every hold, so the obvious stop
2091    /// is "the allocator granted nothing". That condition **alone does not
2092    /// terminate**, and the failure is not hypothetical — it was measured.
2093    /// Handing the allocator a set that does not include the runners this loop
2094    /// just started (an empty one, a stale one, or a launcher whose journal
2095    /// write has not landed yet) makes every grant look like the first, and the
2096    /// pass starts runners until something outside it intervenes. With the set
2097    /// dropped entirely, the three-consecutive-polls test below does not report
2098    /// three attempts; it *never returns*.
2099    ///
2100    /// So the grant decided on the first hold is also a **budget**. A later hold
2101    /// may lower it — the host may have filled up meanwhile — and can never
2102    /// raise it, which bounds the pass at the number this policy was actually
2103    /// allocated. That is `c2`'s reasoning for `MAX_PAGES` one layer down: the
2104    /// reconciliation loop is the one place in this product that must not be
2105    /// able to wedge, so the bound is structural rather than a consequence of
2106    /// every input being well behaved.
2107    async fn start_runners(
2108        &self,
2109        policy: &ScalePolicy,
2110        demand: u32,
2111        report: &mut ReconcileReport,
2112        launched: &mut Vec<RunnerAttempt>,
2113    ) {
2114        // A lock-free pre-check, for one reason only: the host-wide lock should
2115        // not be taken by a policy that is going to be granted nothing. On an
2116        // idle host with P policies that was P lock acquisitions per poll --
2117        // free under `InProcessAllocationLock`, a `spawn_blocking` and a
2118        // filesystem lock apiece under `FileAllocationLock`.
2119        //
2120        // It is safe because it can only be optimistic. Anything it grants is
2121        // re-decided under the lock below and may be lowered there; the only
2122        // thing it can get wrong in the other direction is refusing a grant that
2123        // headroom freed a moment later would have allowed, which the next poll
2124        // picks up.
2125        let intent = match self.allocate_only(policy, demand, launched).await {
2126            Ok(intent) => intent,
2127            Err(failure) => {
2128                self.report_unreadable_attempts(report, &failure);
2129                return;
2130            }
2131        };
2132
2133        // The allocation that is *reported* is the one taken under the lock when
2134        // a lock was taken, because that is the one that decided anything. The
2135        // pre-check stands in only when no hold was ever obtained.
2136        let mut decided: Option<Allocation> = None;
2137        let mut budget = intent.to_start;
2138
2139        while budget > 0 {
2140            let guard = match self.lock.acquire().await {
2141                Ok(guard) => guard,
2142                Err(_) => {
2143                    // Grants, not policies: this is what the policy was owed and
2144                    // did not get.
2145                    report.deferred = report.deferred.saturating_add(budget);
2146                    self.events.emit(LifecycleEvent::AllocationDeferred {
2147                        policy: policy.id,
2148                        count: budget,
2149                    });
2150                    break;
2151                }
2152            };
2153
2154            // The read and the decision are both inside the hold, and so is the
2155            // creation below. Two concurrent passes therefore serialise on the
2156            // whole sequence rather than on the decision alone -- reading the
2157            // headroom outside the lock is the shape in which two policies both
2158            // find room for the last slot.
2159            let attempts = match self.host_attempts(launched).await {
2160                Ok(attempts) => attempts,
2161                Err(failure) => {
2162                    drop(guard);
2163                    self.report_unreadable_attempts(report, &failure);
2164                    break;
2165                }
2166            };
2167            let mut allocator = HostAllocator::from_attempts(&self.host, &attempts);
2168            let allocation = allocator.allocate(policy, demand);
2169
2170            if decided.is_none() {
2171                // The under-lock decision may be smaller than the pre-check, and
2172                // never larger: `min` rather than assignment, so a later hold
2173                // cannot raise the bound either.
2174                budget = budget.min(allocation.to_start);
2175                decided = Some(allocation.clone());
2176            }
2177
2178            // Either stop is sufficient on its own in the well-behaved case;
2179            // neither is sufficient when the launcher lags. See the doc comment.
2180            if allocation.starts_nothing() || budget == 0 {
2181                drop(guard);
2182                break;
2183            }
2184
2185            let created = self
2186                .launcher
2187                .launch(LaunchRequest {
2188                    host: &self.host,
2189                    policy,
2190                    allocation_guard: &guard,
2191                })
2192                .await;
2193            drop(guard);
2194
2195            match created {
2196                Ok(attempt) => {
2197                    let id = attempt.id;
2198                    // Carried across policies for the rest of this pass, so the
2199                    // host-wide total cannot be computed from a set that is
2200                    // missing it. See `RunnerLauncher::launch`.
2201                    launched.push(attempt);
2202                    report.started = report.started.saturating_add(1);
2203                    budget -= 1;
2204                    self.events.emit(LifecycleEvent::RunnerStarted {
2205                        policy: policy.id,
2206                        attempt: id,
2207                    });
2208                }
2209                Err(failure) => {
2210                    self.events.emit(LifecycleEvent::RunnerStartFailed {
2211                        policy: policy.id,
2212                        reason: failure_reason_kind(&failure.reason),
2213                    });
2214                    break;
2215                }
2216            }
2217        }
2218
2219        let allocation = decided.unwrap_or(intent);
2220        self.emit_allocation(&allocation);
2221        report.allocations.push(allocation);
2222    }
2223
2224    /// The attempt set the host holds, plus everything this pass has already
2225    /// created.
2226    ///
2227    /// The merge is by [`RunnerAttempt::id`], so a launcher that makes its
2228    /// launches visible before returning -- which
2229    /// [`RunnerLauncher::launch`] asks for -- contributes each attempt once, and
2230    /// one that lags still cannot hide a runner from the host-wide total. The
2231    /// ceiling therefore holds on the strength of this function rather than on
2232    /// the strength of an implementer honouring a comment.
2233    ///
2234    /// # Errors
2235    /// Whatever [`RunnerLauncher::attempts`] reported.
2236    async fn host_attempts(
2237        &self,
2238        launched: &[RunnerAttempt],
2239    ) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
2240        let mut attempts = self.launcher.attempts().await?;
2241
2242        // Each `launch` creates one runtime, so each must answer with an
2243        // identifier no other attempt has. Two entries sharing one here are two
2244        // runtimes the host-wide total below counts once, which is the ceiling
2245        // failing silently -- so a development build stops at the first
2246        // duplicate instead. `RunnerLauncher::launch` states the requirement;
2247        // this is what makes it findable.
2248        debug_assert!(
2249            launched
2250                .iter()
2251                .map(|attempt| attempt.id)
2252                .collect::<BTreeSet<AttemptId>>()
2253                .len()
2254                == launched.len(),
2255            "`RunnerLauncher::launch` returned an AttemptId this pass had already seen; \
2256             the host ceiling is enforced against a set keyed on that identifier, so a \
2257             duplicate is two runtimes counted as one"
2258        );
2259
2260        let known: BTreeSet<AttemptId> = attempts.iter().map(|attempt| attempt.id).collect();
2261        attempts.extend(
2262            launched
2263                .iter()
2264                .filter(|attempt| !known.contains(&attempt.id))
2265                .cloned(),
2266        );
2267        Ok(attempts)
2268    }
2269
2270    /// The attempt set could not be read, so nothing may be decided from it.
2271    ///
2272    /// Counted rather than swallowed for the reason the module documentation
2273    /// gives: an unreadable set and an idle host produce the same *number* and
2274    /// demand opposite actions, so the difference has to survive into the
2275    /// report.
2276    fn report_unreadable_attempts(&self, report: &mut ReconcileReport, failure: &LaunchFailure) {
2277        report.attempts_unreadable = report.attempts_unreadable.saturating_add(1);
2278        // The variant, never a literal and never the detail. A hand-written
2279        // `"attempts_unreadable"` said only what the event's own name already
2280        // said, and threw away the one thing the field is for -- *which* failure
2281        // it was. `FailureReason::Other` carries free text that must not reach
2282        // an event, which is what `failure_reason_kind` is for and what
2283        // `a_cleanup_that_cannot_succeed_...` pins for the sibling path.
2284        self.events.emit(LifecycleEvent::AttemptsUnreadable {
2285            reason: failure_reason_kind(&failure.reason),
2286        });
2287    }
2288
2289    /// Remove the runtimes of attempts that have already concluded.
2290    ///
2291    /// `is_concluded` and not `is_terminal`: `cleaned` is terminal and already
2292    /// done, and `busy` is not terminal at all. That is what makes it impossible
2293    /// for this path to reach a runner executing a job.
2294    async fn clean_terminal_attempts(&self, report: &mut ReconcileReport) {
2295        let attempts = match self.launcher.attempts().await {
2296            Ok(attempts) => attempts,
2297            Err(failure) => {
2298                self.report_unreadable_attempts(report, &failure);
2299                return;
2300            }
2301        };
2302        for attempt in attempts {
2303            if !attempt.state().is_concluded() {
2304                continue;
2305            }
2306            let Some(outcome) = attempt.outcome() else {
2307                continue;
2308            };
2309            let kind = OutcomeKind::of(outcome);
2310            match self.launcher.clean(attempt.id).await {
2311                Ok(()) => {
2312                    report.cleaned = report.cleaned.saturating_add(1);
2313                    if kind.is_failure() {
2314                        report.failures = report.failures.saturating_add(1);
2315                    } else if kind == OutcomeKind::IdleExit {
2316                        // The surplus case. Counted apart from a failure because
2317                        // `g2` renders it apart, and because an operator told
2318                        // that a normal surplus exit is an error goes hunting a
2319                        // fault that does not exist.
2320                        report.idle_exits = report.idle_exits.saturating_add(1);
2321                    }
2322                    self.events.emit(LifecycleEvent::AttemptCleaned {
2323                        policy: attempt.policy_id,
2324                        attempt: attempt.id,
2325                        outcome: kind,
2326                    });
2327                }
2328                // A runtime directory that cannot be removed is retried on every
2329                // poll. Silently, before this arm existed: no event, no counter,
2330                // no report field, so a cleanup that can never succeed was an
2331                // invisible permanent loop. It wedges no capacity -- a terminal
2332                // attempt already stopped counting -- but this module's
2333                // organising principle is the things that go wrong silently, and
2334                // `clean` returns a `Result` precisely so the caller can say
2335                // something.
2336                Err(failure) => {
2337                    report.clean_failures = report.clean_failures.saturating_add(1);
2338                    self.events.emit(LifecycleEvent::AttemptCleanFailed {
2339                        policy: attempt.policy_id,
2340                        attempt: attempt.id,
2341                        reason: failure_reason_kind(&failure.reason),
2342                    });
2343                }
2344            }
2345        }
2346    }
2347
2348    /// Reclaim what can be reclaimed for one policy, and nothing else.
2349    ///
2350    /// **A busy attempt is never removed.** `04-subsystem-contracts.md`:
2351    /// *"`busy` cannot transition to cleanup due to a scale-down request"*.
2352    /// Capacity comes back when an attempt reaches a terminal state and at no
2353    /// other time, so a scale-down against a host full of busy runners removes
2354    /// nothing, changes nothing, and says so.
2355    pub async fn scale_down(&self, policy: &ScalePolicy) -> ScaleDownReport {
2356        let mut report = ScaleDownReport::default();
2357        let attempts = match self.launcher.attempts().await {
2358            Ok(attempts) => attempts,
2359            Err(failure) => {
2360                // The same rule as everywhere else, and this was the one place
2361                // it was still broken: an unreadable set is not an empty one,
2362                // and a bare `default()` here reported all zeros -- byte for
2363                // byte an idle host with nothing to reclaim.
2364                self.events.emit(LifecycleEvent::AttemptsUnreadable {
2365                    reason: failure_reason_kind(&failure.reason),
2366                });
2367                report.attempts_unreadable = true;
2368                return report;
2369            }
2370        };
2371        for attempt in attempts {
2372            if attempt.policy_id != policy.id {
2373                continue;
2374            }
2375            match attempt.state() {
2376                AttemptState::Busy => {
2377                    report.refused_busy = report.refused_busy.saturating_add(1);
2378                    self.events.emit(LifecycleEvent::ScaleDownRefused {
2379                        policy: policy.id,
2380                        attempt: attempt.id,
2381                    });
2382                }
2383                state if state.is_concluded() => {
2384                    let kind = attempt
2385                        .outcome()
2386                        .map_or(OutcomeKind::Failed, OutcomeKind::of);
2387                    match self.launcher.clean(attempt.id).await {
2388                        Ok(()) => {
2389                            report.removed = report.removed.saturating_add(1);
2390                            self.events.emit(LifecycleEvent::AttemptCleaned {
2391                                policy: policy.id,
2392                                attempt: attempt.id,
2393                                outcome: kind,
2394                            });
2395                        }
2396                        Err(failure) => {
2397                            report.clean_failures = report.clean_failures.saturating_add(1);
2398                            self.events.emit(LifecycleEvent::AttemptCleanFailed {
2399                                policy: policy.id,
2400                                attempt: attempt.id,
2401                                reason: failure_reason_kind(&failure.reason),
2402                            });
2403                        }
2404                    }
2405                }
2406                AttemptState::Cleaned => {}
2407                // `allocated`, `jit_received`, `starting`, `idle`: live, holding
2408                // a slot, and not this function's to end.
2409                _ => report.retained = report.retained.saturating_add(1),
2410            }
2411        }
2412        report
2413    }
2414
2415    fn emit_allocation(&self, allocation: &Allocation) {
2416        self.events.emit(LifecycleEvent::Allocated {
2417            policy: allocation.policy_id,
2418            demand: allocation.demand,
2419            desired: allocation.desired,
2420            active_owned: allocation.active_owned,
2421            headroom: allocation.headroom_before,
2422            to_start: allocation.to_start,
2423            limiting: allocation.limiting_factor,
2424        });
2425    }
2426}
2427
2428/// One policy's demand, from the reading its target answered with.
2429///
2430/// A repository target tallies its own repository's queued jobs; an organization
2431/// target tallies every repository its scope covered, because one policy watching
2432/// an organization serves any repository in it.
2433///
2434/// # Why this takes a whole policy rather than a target and a label set
2435///
2436/// Because both halves have to come from the same policy, and a signature that
2437/// took them separately made it possible for them not to. The predecessor took a
2438/// `&ScaleTarget` alone and could not filter at all; the obvious repair was to
2439/// add a `&RoutingLabels` beside it, and at three call sites — two of them in
2440/// tests — nothing would have caught passing one policy's target with another
2441/// policy's labels. It compiles, it runs, and it silently serves the wrong
2442/// repository's queue.
2443///
2444/// # A monitor-only policy has no labels, and cannot reach here
2445///
2446/// [`Reconciler::reconcile`] filters on [`ScalePolicy::owns_runners`] before any
2447/// demand request is issued (D19), so the `None` arm is unreachable rather than
2448/// merely unlikely. It returns an empty tally instead of unwrapping, because a
2449/// panic in the reconciliation loop would take the daemon down over a policy
2450/// that was only ever going to start nothing.
2451fn demand_for(policy: &ScalePolicy, reading: &QueuedDemand) -> DemandTally {
2452    let Some(labels) = policy.routing_labels() else {
2453        debug_assert!(
2454            false,
2455            "a monitor-only policy is skipped before the demand poll (D19)"
2456        );
2457        return DemandTally::default();
2458    };
2459
2460    match &policy.target {
2461        ScaleTarget::Repository(repository) => labels.tally(reading.jobs_for(repository)),
2462        ScaleTarget::Organization(_) => labels.tally(reading.jobs()),
2463    }
2464}
2465
2466/// How urgently one failure should slow the loop down.
2467///
2468/// Ordering matters only for picking the worst of several targets: an outage
2469/// outranks a rate limit because backing off a socket that is not answering is
2470/// the safer error, and both outrank a per-target rejection that says nothing
2471/// about the credential as a whole.
2472const fn severity(state: &RefreshState) -> u8 {
2473    match state {
2474        RefreshState::Offline => 5,
2475        RefreshState::RateLimited(_) => 4,
2476        RefreshState::LockedOut { .. } => 3,
2477        RefreshState::Unauthorized => 2,
2478        RefreshState::Forbidden { .. } | RefreshState::Failed { .. } => 1,
2479        RefreshState::Cancelled | RefreshState::Ready(_) => 0,
2480    }
2481}
2482
2483/// Why one target could not be read, as a fixed, credential-free name.
2484///
2485/// Deliberately not a [`PollPace`]: a pace describes the *schedule*, which is a
2486/// property of the whole pass, and stamping one onto a single target would have
2487/// meant inventing a `consecutive` count for a target that has none. What an
2488/// event needs here is the reason, and `c3`'s [`RefreshState`] already names it.
2489///
2490/// `RefreshState::Failed` carries GitHub's own message and
2491/// `RefreshState::Forbidden` may carry one too. Neither reaches the event: this
2492/// returns the variant, for the reason [`failure_reason_kind`] states.
2493const fn unreadable_reason(state: &RefreshState) -> &'static str {
2494    match state {
2495        RefreshState::Ready(_) => "ready",
2496        RefreshState::Offline => "offline",
2497        RefreshState::RateLimited(_) => "rate_limited",
2498        RefreshState::LockedOut { .. } => "locked_out",
2499        RefreshState::Unauthorized => "unauthorized",
2500        RefreshState::Forbidden { .. } => "forbidden",
2501        RefreshState::Failed { .. } => "failed",
2502        RefreshState::Cancelled => "cancelled",
2503    }
2504}
2505
2506#[cfg(test)]
2507mod tests {
2508    use super::*;
2509
2510    /// The reading that said `healthy` for 28 hours while nothing worked.
2511    ///
2512    /// A daemon every one of whose targets answered `401` kept writing a fresh
2513    /// `last GitHub contact`, because an unauthorized target is `unreadable`
2514    /// rather than a `failure`. Both that record and the `service status` built
2515    /// on it were used as evidence during the investigation, and both were
2516    /// wrong; see `docs/spikes/token-expiry-and-renewal.md`.
2517    #[test]
2518    fn a_pass_that_reached_no_target_does_not_claim_it_reached_github() {
2519        let mut report = ReconcileReport::default();
2520        assert!(
2521            !report.reached_github(),
2522            "a pass that polled nothing -- every policy draining, owned elsewhere, or \
2523             monitor-only -- reached nobody. This is the case the old guard let through, and \
2524             the only one it ever let through."
2525        );
2526
2527        report.unreadable.push(PolicyId::from_u128(1));
2528        assert!(
2529            !report.reached_github(),
2530            "every target this pass tried was unreadable, so there is no contact to record"
2531        );
2532
2533        report.targets_read = 1;
2534        assert!(
2535            report.reached_github(),
2536            "one target answering is contact, whatever else failed alongside it"
2537        );
2538
2539        // `allocations` deliberately does not count: a policy this host does
2540        // not own is allocated for with no demand and without polling anything,
2541        // so a pass where every poll failed can still carry allocations.
2542        let mut unowned = ReconcileReport::default();
2543        unowned.unreadable.push(PolicyId::from_u128(2));
2544        unowned.allocations.push(Allocation {
2545            policy_id: PolicyId::from_u128(2),
2546            demand: 0,
2547            desired: 0,
2548            active_owned: 0,
2549            headroom_before: 0,
2550            to_start: 0,
2551            limiting_factor: LimitingFactor::Demand,
2552        });
2553        assert!(
2554            !unowned.reached_github(),
2555            "an allocation is not evidence that GitHub answered"
2556        );
2557    }
2558
2559    /// The claim the old guard rested on, checked rather than assumed.
2560    ///
2561    /// `report.failure.is_none()` was believed to be compatible with an
2562    /// all-unauthorized pass. It is not: `unreadable` is pushed only from the
2563    /// `Failed` arm and `failure` is the maximum over every `Failed` reading,
2564    /// so guarding on `failure.is_none() && reached_github()` would have been
2565    /// `failure.is_none()` with extra words. This pins the severity that makes
2566    /// it so, because a future `severity(Unauthorized) == 0` would quietly
2567    /// restore the belief.
2568    #[test]
2569    fn an_unauthorized_target_is_a_failure_and_not_merely_unreadable() {
2570        assert!(
2571            severity(&RefreshState::Unauthorized) > 0,
2572            "an unauthorized reading must survive `max_by_key(severity)` into `report.failure`, \
2573             or a pass where every target was refused would report no failure at all"
2574        );
2575    }
2576
2577    use std::sync::atomic::AtomicUsize;
2578
2579    use std::num::NonZeroU16;
2580
2581    use runner_manager_domain::attempt::PersistedAttempt;
2582    use runner_manager_domain::model::{CachePolicy, HostId};
2583    use runner_manager_domain::policy::PolicyMode;
2584    use runner_manager_domain::workspace::WorkspaceKind;
2585    use runner_manager_github::rest::RateLimited;
2586    use runner_manager_testkit::clock::FakeClock;
2587    use runner_manager_testkit::fixtures;
2588    use runner_manager_testkit::github::FakeGithub;
2589
2590    // =======================================================================
2591    // Fakes
2592    // =======================================================================
2593
2594    fn host_with(capacity: u16) -> Host {
2595        fixtures::host().capacity(capacity).build()
2596    }
2597
2598    fn repo(raw: &str) -> OwnerRepo {
2599        OwnerRepo::parse(raw).expect("a valid OWNER/REPO")
2600    }
2601
2602    /// An `active`, enabled autoscale policy on the fixture host.
2603    use runner_manager_domain::policy::RunsOn;
2604
2605    fn policy(id: u128, target: &str, max: u16) -> ScalePolicy {
2606        fixtures::policy()
2607            .id(PolicyId::from_u128(id))
2608            .repository(target)
2609            .autoscale("home", max)
2610            .active()
2611            .build()
2612    }
2613
2614    /// The host label every policy in these tests carries.
2615    ///
2616    /// `policy` above builds through `fixtures::policy().autoscale("home", …)`,
2617    /// which derives `rm-home-win-x64`. A job fixture that did not carry it
2618    /// would be filtered out as another host's work, so the two are tied
2619    /// together here rather than repeated as a literal at each call site.
2620    const HOST_LABEL: &str = "rm-home-win-x64";
2621
2622    /// `n` queued jobs this host's policies match.
2623    ///
2624    /// The ordinary demand fixture. Since the reversal of the run-counting
2625    /// decision the unit `e1` clamps is a job, so a test wanting demand `n` asks
2626    /// for `n` jobs rather than for `n` runs.
2627    fn jobs(n: usize) -> Vec<RunsOn> {
2628        fixtures::queued_jobs(&[HOST_LABEL], n)
2629    }
2630
2631    /// `e3`, faked: an attempt table and a launch counter, no process anywhere.
2632    #[derive(Debug, Default)]
2633    struct FakeLauncher {
2634        attempts: Mutex<Vec<RunnerAttempt>>,
2635        next_id: AtomicU64,
2636        launches: AtomicUsize,
2637        cleaned: Mutex<Vec<AttemptId>>,
2638        /// Yields this many times between reading the attempt set and recording
2639        /// a new one, so an unserialised allocator has a window to be wrong in.
2640        yields_before_recording: usize,
2641        /// Reports success without the attempt ever becoming visible, which is
2642        /// the shape a slow journal write has. Every grant then looks like the
2643        /// first.
2644        forgetful: bool,
2645        fail_next: Mutex<Option<FailureReason>>,
2646        /// Reports that the attempt set cannot be read at all, which is the one
2647        /// answer a caller must never confuse with an idle host.
2648        attempts_fail: Mutex<bool>,
2649        /// Refuses every cleanup, so the silent-retry path has something to be
2650        /// loud about.
2651        clean_fails: bool,
2652        replacements: Mutex<Vec<ReplacementIntent>>,
2653    }
2654
2655    impl FakeLauncher {
2656        fn new() -> Self {
2657            Self::default()
2658        }
2659
2660        fn with_yields(mut self, yields: usize) -> Self {
2661            self.yields_before_recording = yields;
2662            self
2663        }
2664
2665        fn forgetful() -> Self {
2666            Self {
2667                forgetful: true,
2668                ..Self::default()
2669            }
2670        }
2671
2672        fn seeded(self, attempts: Vec<RunnerAttempt>) -> Self {
2673            *self.attempts.lock().unwrap() = attempts;
2674            self
2675        }
2676
2677        fn launches(&self) -> usize {
2678            self.launches.load(Ordering::SeqCst)
2679        }
2680
2681        fn snapshot(&self) -> Vec<RunnerAttempt> {
2682            self.attempts.lock().unwrap().clone()
2683        }
2684
2685        fn live_count(&self) -> usize {
2686            self.snapshot()
2687                .iter()
2688                .filter(|a| a.counts_against_capacity())
2689                .count()
2690        }
2691
2692        fn fail_next(&self, reason: FailureReason) {
2693            *self.fail_next.lock().unwrap() = Some(reason);
2694        }
2695
2696        fn fail_attempts(&self, failing: bool) {
2697            *self.attempts_fail.lock().unwrap() = failing;
2698        }
2699
2700        fn refusing_cleanup(attempts: Vec<RunnerAttempt>) -> Self {
2701            Self {
2702                clean_fails: true,
2703                ..Self::default()
2704            }
2705            .seeded(attempts)
2706        }
2707
2708        fn cleaned(&self) -> Vec<AttemptId> {
2709            self.cleaned.lock().unwrap().clone()
2710        }
2711
2712        fn replacing(self, intent: ReplacementIntent) -> Self {
2713            self.replacements.lock().unwrap().push(intent);
2714            self
2715        }
2716    }
2717
2718    #[async_trait::async_trait]
2719    impl RunnerLauncher for FakeLauncher {
2720        async fn supervise(
2721            &self,
2722            policy: &ScalePolicy,
2723        ) -> Result<Vec<ReplacementIntent>, LaunchFailure> {
2724            let mut replacements = self.replacements.lock().unwrap();
2725            let selected: Vec<_> = replacements
2726                .extract_if(.., |intent| intent.policy == policy.id)
2727                .collect();
2728            if !selected.is_empty() {
2729                let retired: BTreeSet<_> = selected
2730                    .iter()
2731                    .map(|intent| intent.previous_attempt)
2732                    .collect();
2733                self.attempts
2734                    .lock()
2735                    .unwrap()
2736                    .retain(|attempt| !retired.contains(&attempt.id));
2737            }
2738            Ok(selected)
2739        }
2740
2741        async fn attempts(&self) -> Result<Vec<RunnerAttempt>, LaunchFailure> {
2742            if *self.attempts_fail.lock().unwrap() {
2743                return Err(LaunchFailure::new(FailureReason::Other(
2744                    "the journal could not be read".into(),
2745                )));
2746            }
2747            Ok(self.snapshot())
2748        }
2749
2750        async fn launch(&self, request: LaunchRequest<'_>) -> Result<RunnerAttempt, LaunchFailure> {
2751            if let Some(reason) = self.fail_next.lock().unwrap().take() {
2752                return Err(LaunchFailure::new(reason));
2753            }
2754            // The window an unserialised caller would lose the race in.
2755            for _ in 0..self.yields_before_recording {
2756                tokio::task::yield_now().await;
2757            }
2758            let id =
2759                AttemptId::from_u128(u128::from(self.next_id.fetch_add(1, Ordering::SeqCst) + 1));
2760            let created = RunnerAttempt::allocate(
2761                id,
2762                request.policy.id,
2763                "runtime/p/a",
2764                request.host.created_at,
2765            );
2766            self.launches.fetch_add(1, Ordering::SeqCst);
2767            if !self.forgetful {
2768                self.attempts.lock().unwrap().push(created.clone());
2769            }
2770            Ok(created)
2771        }
2772
2773        async fn clean(&self, attempt: AttemptId) -> Result<(), LaunchFailure> {
2774            if self.clean_fails {
2775                return Err(LaunchFailure::new(FailureReason::Other(
2776                    "the runtime directory is locked".into(),
2777                )));
2778            }
2779            self.cleaned.lock().unwrap().push(attempt);
2780            let mut attempts = self.attempts.lock().unwrap();
2781            attempts.retain(|a| a.id != attempt);
2782            Ok(())
2783        }
2784    }
2785
2786    /// A demand source a test programs directly, with no gateway underneath.
2787    #[derive(Debug, Default)]
2788    struct FakeDemand {
2789        outcome: Mutex<Option<PollOutcome>>,
2790        /// Answers programmed for one target, which beat the blanket one.
2791        per_target: Mutex<BTreeMap<ScaleTarget, PollOutcome>>,
2792        scopes: Mutex<Vec<ActivityScope>>,
2793    }
2794
2795    impl FakeDemand {
2796        fn ready(count: u32, repository: &OwnerRepo) -> Self {
2797            let fake = Self::default();
2798            fake.set(PollOutcome::Ready(QueuedDemand::of(
2799                repository.clone(),
2800                jobs(count as usize),
2801            )));
2802            fake
2803        }
2804
2805        fn failing(state: RefreshState) -> Self {
2806            let fake = Self::default();
2807            fake.set(PollOutcome::Failed(state));
2808            fake
2809        }
2810
2811        fn set(&self, outcome: PollOutcome) {
2812            *self.outcome.lock().unwrap() = Some(outcome);
2813        }
2814
2815        /// Program one target's answer, overriding the blanket one.
2816        fn set_for(&self, target: &ScaleTarget, outcome: PollOutcome) {
2817            self.per_target
2818                .lock()
2819                .unwrap()
2820                .insert(target.clone(), outcome);
2821        }
2822
2823        fn polls(&self) -> Vec<ActivityScope> {
2824            self.scopes.lock().unwrap().clone()
2825        }
2826    }
2827
2828    #[async_trait::async_trait]
2829    impl DemandSource for FakeDemand {
2830        async fn poll(&self, scope: &ActivityScope) -> PollOutcome {
2831            self.scopes.lock().unwrap().push(scope.clone());
2832            if let Some(outcome) = self.per_target.lock().unwrap().get(scope.target()) {
2833                return outcome.clone();
2834            }
2835            self.outcome
2836                .lock()
2837                .unwrap()
2838                .clone()
2839                .unwrap_or(PollOutcome::Ready(QueuedDemand::default()))
2840        }
2841    }
2842
2843    #[derive(Debug, Default)]
2844    struct FakeDirectory {
2845        repositories: Vec<OwnerRepo>,
2846        calls: AtomicUsize,
2847    }
2848
2849    impl FakeDirectory {
2850        fn of(repositories: Vec<OwnerRepo>) -> Self {
2851            Self {
2852                repositories,
2853                calls: AtomicUsize::new(0),
2854            }
2855        }
2856
2857        fn calls(&self) -> usize {
2858            self.calls.load(Ordering::SeqCst)
2859        }
2860    }
2861
2862    #[async_trait::async_trait]
2863    impl RepositoryDirectory for FakeDirectory {
2864        async fn repositories(&self, _org: &Org) -> Result<Vec<OwnerRepo>, InventoryError> {
2865            self.calls.fetch_add(1, Ordering::SeqCst);
2866            Ok(self.repositories.clone())
2867        }
2868    }
2869
2870    /// A lock that grants everything and counts how many holders it had at once.
2871    ///
2872    /// The counter is the assertion: "under simulated lock contention" is only
2873    /// meaningful if something measures that the contention was actually
2874    /// serialised.
2875    #[derive(Debug)]
2876    struct CountingLock {
2877        inner: InProcessAllocationLock,
2878        concurrent: Arc<AtomicUsize>,
2879        peak: Arc<AtomicUsize>,
2880        acquisitions: Arc<AtomicUsize>,
2881    }
2882
2883    impl CountingLock {
2884        fn new() -> Self {
2885            Self {
2886                inner: InProcessAllocationLock::new(),
2887                concurrent: Arc::new(AtomicUsize::new(0)),
2888                peak: Arc::new(AtomicUsize::new(0)),
2889                acquisitions: Arc::new(AtomicUsize::new(0)),
2890            }
2891        }
2892
2893        fn peak(&self) -> usize {
2894            self.peak.load(Ordering::SeqCst)
2895        }
2896
2897        fn acquisitions(&self) -> usize {
2898            self.acquisitions.load(Ordering::SeqCst)
2899        }
2900    }
2901
2902    #[derive(Debug)]
2903    struct CountingGuard {
2904        _inner: AllocationGuard,
2905        concurrent: Arc<AtomicUsize>,
2906    }
2907
2908    impl Drop for CountingGuard {
2909        fn drop(&mut self) {
2910            self.concurrent.fetch_sub(1, Ordering::SeqCst);
2911        }
2912    }
2913
2914    #[async_trait::async_trait]
2915    impl AllocationLock for CountingLock {
2916        async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
2917            let inner = self.inner.acquire().await?;
2918            self.acquisitions.fetch_add(1, Ordering::SeqCst);
2919            let now = self.concurrent.fetch_add(1, Ordering::SeqCst) + 1;
2920            self.peak.fetch_max(now, Ordering::SeqCst);
2921            Ok(AllocationGuard::new(CountingGuard {
2922                _inner: inner,
2923                concurrent: Arc::clone(&self.concurrent),
2924            }))
2925        }
2926    }
2927
2928    /// The lock that is not one: what the host looks like with the serialisation
2929    /// removed. Used only by the control half of the contention test.
2930    #[derive(Debug, Default)]
2931    struct NoLock;
2932
2933    #[async_trait::async_trait]
2934    impl AllocationLock for NoLock {
2935        async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
2936            Ok(AllocationGuard::new(()))
2937        }
2938    }
2939
2940    /// A lock nobody can take.
2941    #[derive(Debug, Default)]
2942    struct HeldLock;
2943
2944    #[async_trait::async_trait]
2945    impl AllocationLock for HeldLock {
2946        async fn acquire(&self) -> Result<AllocationGuard, AllocationLockBusy> {
2947            Err(AllocationLockBusy)
2948        }
2949    }
2950
2951    /// Everything one test needs, wired together.
2952    struct Harness {
2953        launcher: Arc<FakeLauncher>,
2954        demand: Arc<FakeDemand>,
2955        events: Arc<EventLog>,
2956        reconciler: Reconciler,
2957    }
2958
2959    impl Harness {
2960        fn build(
2961            host: Host,
2962            launcher: Arc<FakeLauncher>,
2963            demand: Arc<FakeDemand>,
2964            lock: Arc<dyn AllocationLock>,
2965        ) -> Self {
2966            let events = Arc::new(EventLog::new());
2967            let reconciler = Reconciler::new(
2968                host,
2969                ReconcilerPorts {
2970                    demand: Arc::clone(&demand) as Arc<dyn DemandSource>,
2971                    launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
2972                    lock,
2973                    directory: Arc::new(FakeDirectory::default()),
2974                    clock: Arc::new(FakeClock::default()),
2975                    jitter: Arc::new(NoJitter) as Arc<dyn Jitter>,
2976                    events: Arc::clone(&events) as Arc<dyn EventSink>,
2977                },
2978            );
2979            Self {
2980                launcher,
2981                demand,
2982                events,
2983                reconciler,
2984            }
2985        }
2986
2987        fn simple(capacity: u16, demand_count: u32, target: &str) -> Self {
2988            let launcher = Arc::new(FakeLauncher::new());
2989            let demand = Arc::new(FakeDemand::ready(demand_count, &repo(target)));
2990            Self::build(
2991                host_with(capacity),
2992                launcher,
2993                demand,
2994                Arc::new(InProcessAllocationLock::new()),
2995            )
2996        }
2997    }
2998
2999    fn attempt_in(state: AttemptState, id: u128, policy: u128) -> RunnerAttempt {
3000        let outcome = state.is_terminal().then(|| match state {
3001            AttemptState::Failed => {
3002                AttemptOutcome::failed(FailureReason::ProcessExitedUnexpectedly)
3003            }
3004            AttemptState::Orphaned => AttemptOutcome::Orphaned,
3005            _ => AttemptOutcome::CompletedJob,
3006        });
3007        RunnerAttempt::from_persisted(PersistedAttempt {
3008            id: AttemptId::from_u128(id),
3009            policy_id: PolicyId::from_u128(policy),
3010            github_runner_id: None,
3011            state,
3012            outcome,
3013            process_id: None,
3014            runtime_path: "runtime/p/a".into(),
3015            workspace_kind: WorkspaceKind::Ephemeral,
3016            workspace_slot: None,
3017            created_at: fixtures::created_at(),
3018            terminal_at: state.is_terminal().then(fixtures::created_at),
3019            last_state_change_at: fixtures::created_at(),
3020        })
3021        .expect("a state/outcome pair the domain accepts")
3022    }
3023
3024    /// A concluded attempt carrying a specific outcome.
3025    fn concluded(id: u128, policy: u128, outcome: AttemptOutcome) -> RunnerAttempt {
3026        RunnerAttempt::from_persisted(PersistedAttempt {
3027            id: AttemptId::from_u128(id),
3028            policy_id: PolicyId::from_u128(policy),
3029            github_runner_id: None,
3030            state: outcome.terminal_state(),
3031            outcome: Some(outcome),
3032            process_id: None,
3033            runtime_path: "runtime/p/a".into(),
3034            workspace_kind: WorkspaceKind::Ephemeral,
3035            workspace_slot: None,
3036            created_at: fixtures::created_at(),
3037            terminal_at: Some(fixtures::created_at()),
3038            last_state_change_at: fixtures::created_at(),
3039        })
3040        .expect("a state/outcome pair the domain accepts")
3041    }
3042
3043    // =======================================================================
3044    // The in-flight term: the single most likely way this task goes wrong
3045    // =======================================================================
3046
3047    /// `e1`'s Definition of Done, verbatim: *"A job that remains `queued` across
3048    /// three consecutive polls while its attempt is `starting` yields exactly
3049    /// one attempt — the test fails if the in-flight term is dropped from the
3050    /// formula."*
3051    ///
3052    /// `b1` tests the arithmetic underneath this
3053    /// (`capacity::tests::the_same_queued_job_on_two_polls_yields_one_attempt_
3054    /// not_two`). What *this* test covers is the only way `e1` can drop the
3055    /// term without touching `b1` at all: handing the allocator an attempt set
3056    /// that is not the one the host holds.
3057    ///
3058    /// # This was measured, not assumed, and the first measurement was worse
3059    /// # than the failure it was looking for
3060    ///
3061    /// Replacing `self.launcher.attempts().await` in
3062    /// [`Reconciler::start_runners`] with `Vec::new()` compiles and runs. Before
3063    /// that function carried a budget, this test did not go red — it **never
3064    /// returned**: every grant looked like the first, so the pass started
3065    /// runners forever inside poll 1. That is the runaway-runner failure exactly
3066    /// as an operator would meet it, and it is why the budget exists.
3067    ///
3068    /// With the budget in place the same injection fails cleanly and says what
3069    /// happened: `poll 2 … left: 2, right: 1`. Both measurements were run
3070    /// before this assertion was written.
3071    #[tokio::test]
3072    async fn three_polls_of_one_still_queued_run_yield_exactly_one_attempt() {
3073        let mut harness = Harness::simple(4, 1, "acme/app");
3074        let policy = policy(1, "acme/app", 4);
3075
3076        for poll in 1..=3 {
3077            let report = harness
3078                .reconciler
3079                .reconcile(std::slice::from_ref(&policy))
3080                .await;
3081            assert_eq!(
3082                harness.launcher.launches(),
3083                1,
3084                "poll {poll} started another runner for a job already being served; the \
3085                 `- active_owned_runners` term reached `HostAllocator` as a set this host \
3086                 does not hold"
3087            );
3088            assert_eq!(report.allocations.len(), 1);
3089            let allocation = &report.allocations[0];
3090            assert_eq!(allocation.demand, 1, "poll {poll}: still queued at GitHub");
3091            if poll == 1 {
3092                assert_eq!(allocation.to_start, 1);
3093                assert_eq!(report.started, 1);
3094            } else {
3095                assert_eq!(allocation.active_owned, 1, "poll {poll}");
3096                assert_eq!(allocation.to_start, 0, "poll {poll}");
3097                assert_eq!(report.started, 0, "poll {poll}");
3098            }
3099        }
3100        assert_eq!(harness.launcher.live_count(), 1);
3101    }
3102
3103    /// The other half of the measurement above: the loop must terminate even
3104    /// when the attempt set never catches up with it.
3105    ///
3106    /// Dropping the in-flight term made
3107    /// `three_polls_of_one_still_queued_run_yield_exactly_one_attempt` hang
3108    /// rather than fail — the loop had one stopping condition and it was the one
3109    /// the bug removed. A launcher whose journal write has not landed presents
3110    /// exactly the same shape without any bug at all, so the budget in
3111    /// [`Reconciler::start_runners`] bounds the pass structurally. This is what
3112    /// asserts the bound is really there.
3113    #[tokio::test]
3114    async fn a_launcher_whose_attempts_never_appear_cannot_wedge_the_pass() {
3115        let launcher = Arc::new(FakeLauncher::forgetful());
3116        let mut harness = Harness::build(
3117            host_with(64),
3118            Arc::clone(&launcher),
3119            Arc::new(FakeDemand::ready(3, &repo("acme/app"))),
3120            Arc::new(InProcessAllocationLock::new()),
3121        );
3122
3123        let report = harness
3124            .reconciler
3125            .reconcile(&[policy(1, "acme/app", 8)])
3126            .await;
3127
3128        assert_eq!(
3129            report.started, 3,
3130            "the pass is bounded by the grant it was given, not by the attempt set catching \
3131             up with it"
3132        );
3133        assert_eq!(launcher.launches(), 3);
3134        assert!(
3135            launcher.snapshot().is_empty(),
3136            "the launcher never recorded anything, which is the whole point of the fixture"
3137        );
3138    }
3139
3140    /// The host-wide ceiling must hold across policies even when the launcher
3141    /// lags, and the per-policy budget alone does not reach that case.
3142    ///
3143    /// Review found this, with this file's own `forgetful` fixture and one more
3144    /// policy: the budget bounds *each policy's* loop to its own first grant,
3145    /// but policy B's first grant is computed from a set that does not yet
3146    /// contain policy A's launches, so B's bound is itself too large. Two
3147    /// policies on a host of three started **six** runners --
3148    /// `host_capacity=3, started=6, launches=6` -- with the lock held correctly
3149    /// throughout. Serialisation was never the problem; the arithmetic under it
3150    /// was reading a stale set.
3151    #[tokio::test]
3152    async fn two_policies_cannot_exceed_host_capacity_even_when_the_launcher_lags() {
3153        let launcher = Arc::new(FakeLauncher::forgetful());
3154        let demand = Arc::new(FakeDemand::default());
3155        demand.set_for(
3156            &ScaleTarget::repository("acme/left").unwrap(),
3157            PollOutcome::Ready(QueuedDemand::of(repo("acme/left"), jobs(3))),
3158        );
3159        demand.set_for(
3160            &ScaleTarget::repository("acme/right").unwrap(),
3161            PollOutcome::Ready(QueuedDemand::of(repo("acme/right"), jobs(3))),
3162        );
3163        let mut harness = Harness::build(
3164            host_with(3),
3165            Arc::clone(&launcher),
3166            demand,
3167            Arc::new(InProcessAllocationLock::new()),
3168        );
3169
3170        let report = harness
3171            .reconciler
3172            .reconcile(&[policy(1, "acme/left", 3), policy(2, "acme/right", 3)])
3173            .await;
3174
3175        assert_eq!(
3176            report.started, 3,
3177            "host_capacity is 3 and two policies each allowed 3 started {} runners \
3178             between them; the second policy's grant was computed from a set that did \
3179             not yet contain the first policy's launches",
3180            report.started
3181        );
3182        assert_eq!(launcher.launches(), 3);
3183    }
3184
3185    /// Finding 1: an attempt set that cannot be read is not an empty one.
3186    ///
3187    /// `attempts()` used to be infallible, which left `e3` — reading a journal
3188    /// off a disk — a choice between panicking and answering `vec![]`. The
3189    /// second is silent and catastrophic: an empty set is indistinguishable from
3190    /// an idle host, so a transient read failure reads as "nothing is running"
3191    /// and the pass allocates the whole machine for jobs already being served.
3192    ///
3193    /// The contrast is the assertion. Identical host, identical demand,
3194    /// identical policy; the only difference is whether the launcher can answer.
3195    #[tokio::test]
3196    async fn an_unreadable_attempt_set_starts_nothing_and_is_not_read_as_an_idle_host() {
3197        let launcher = Arc::new(FakeLauncher::new());
3198        let mut harness = Harness::build(
3199            host_with(8),
3200            Arc::clone(&launcher),
3201            Arc::new(FakeDemand::ready(4, &repo("acme/app"))),
3202            Arc::new(InProcessAllocationLock::new()),
3203        );
3204        let policy = policy(1, "acme/app", 8);
3205
3206        launcher.fail_attempts(true);
3207        let unreadable = harness
3208            .reconciler
3209            .reconcile(std::slice::from_ref(&policy))
3210            .await;
3211
3212        assert_eq!(
3213            unreadable.started, 0,
3214            "nothing may be decided from a set that was not read"
3215        );
3216        assert_eq!(launcher.launches(), 0);
3217        assert!(unreadable.attempts_unreadable > 0, "and the pass says so");
3218        assert!(
3219            unreadable.allocations.is_empty(),
3220            "no allocation is reported either: there was no set to compute one from, and \
3221             an allocation of zero would claim a decision nobody made"
3222        );
3223        assert!(harness.events.count_of("attempts_unreadable") > 0);
3224
3225        // The same everything, with a launcher that can answer.
3226        launcher.fail_attempts(false);
3227        let readable = harness
3228            .reconciler
3229            .reconcile(std::slice::from_ref(&policy))
3230            .await;
3231        assert_eq!(
3232            readable.started, 4,
3233            "the difference between the two passes is only whether the set could be read"
3234        );
3235        assert_eq!(readable.attempts_unreadable, 0);
3236    }
3237
3238    /// Finding 3: a cleanup that can never succeed was an invisible permanent
3239    /// loop.
3240    ///
3241    /// `if …clean(…).await.is_ok()` had no `else`, so a runtime directory that
3242    /// could not be removed was retried on every poll with no event, no counter
3243    /// and no report field. It wedges no capacity — a terminal attempt already
3244    /// stopped counting — but `clean` returns a `Result` precisely so the caller
3245    /// can say something, and this module's organising principle is the things
3246    /// that go wrong silently.
3247    #[tokio::test]
3248    async fn a_cleanup_that_cannot_succeed_is_reported_rather_than_retried_in_silence() {
3249        let launcher = Arc::new(FakeLauncher::refusing_cleanup(vec![concluded(
3250            1,
3251            1,
3252            AttemptOutcome::ExitedIdleWithoutWork,
3253        )]));
3254        let mut harness = Harness::build(
3255            host_with(4),
3256            Arc::clone(&launcher),
3257            Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
3258            Arc::new(InProcessAllocationLock::new()),
3259        );
3260
3261        let report = harness
3262            .reconciler
3263            .reconcile(&[policy(1, "acme/app", 4)])
3264            .await;
3265
3266        assert_eq!(report.cleaned, 0);
3267        assert_eq!(report.clean_failures, 1);
3268        assert_eq!(harness.events.count_of("attempt_clean_failed"), 1);
3269        assert_eq!(
3270            harness.events.count_of("attempt_cleaned"),
3271            0,
3272            "and it is not reported as cleaned"
3273        );
3274        assert_eq!(
3275            launcher.snapshot().len(),
3276            1,
3277            "the attempt is still there, so the retry is real -- what changed is that it \
3278             is no longer silent"
3279        );
3280
3281        // The reason is the variant, never the detail: the fixture's failure
3282        // carries free text and none of it reaches the event.
3283        let reasons: Vec<&'static str> = harness
3284            .events
3285            .events()
3286            .into_iter()
3287            .filter_map(|event| match event {
3288                LifecycleEvent::AttemptCleanFailed { reason, .. } => Some(reason),
3289                _ => None,
3290            })
3291            .collect();
3292        assert_eq!(reasons, vec!["other"]);
3293    }
3294
3295    /// N2: an unreadable attempt set makes a scale-down inconclusive, not empty.
3296    ///
3297    /// Making `attempts()` fallible closed this everywhere the allocation path
3298    /// touches, and left it open in the one place that returns a different type:
3299    /// `scale_down` answered `ScaleDownReport::default()`, which is all zeros
3300    /// and byte-for-byte identical to an idle host with nothing to reclaim. The
3301    /// two mean opposite things — "there was nothing to remove" against "we
3302    /// cannot see what there was".
3303    ///
3304    /// Measured as the sibling test measures it: identical host, identical
3305    /// attempts, identical policy, and the only difference is whether the
3306    /// launcher can answer.
3307    #[tokio::test]
3308    async fn an_unreadable_attempt_set_makes_scale_down_inconclusive_rather_than_empty() {
3309        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3310            attempt_in(AttemptState::Busy, 1, 1),
3311            concluded(2, 1, AttemptOutcome::CompletedJob),
3312        ]));
3313        let harness = Harness::build(
3314            host_with(4),
3315            Arc::clone(&launcher),
3316            Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
3317            Arc::new(InProcessAllocationLock::new()),
3318        );
3319        let policy = policy(1, "acme/app", 4);
3320
3321        launcher.fail_attempts(true);
3322        let blind = harness.reconciler.scale_down(&policy).await;
3323
3324        assert!(!blind.is_conclusive(), "the machine was never read");
3325        assert_ne!(
3326            blind,
3327            ScaleDownReport::default(),
3328            "a scale-down that could not see the host must not be equal to one that saw \
3329             an idle host; that equality is the whole finding"
3330        );
3331        assert_eq!(blind.removed, 0);
3332        assert_eq!(
3333            blind.refused_busy, 0,
3334            "and this zero means `unknown`, not `none`"
3335        );
3336        assert_eq!(harness.events.count_of("attempts_unreadable"), 1);
3337
3338        // The same everything, with a launcher that can answer.
3339        launcher.fail_attempts(false);
3340        let seeing = harness.reconciler.scale_down(&policy).await;
3341
3342        assert!(seeing.is_conclusive());
3343        assert_eq!(seeing.removed, 1, "the concluded attempt was reclaimed");
3344        assert_eq!(seeing.refused_busy, 1, "and the busy one was left alone");
3345        assert_ne!(
3346            seeing, blind,
3347            "the difference between the two is only whether the set could be read"
3348        );
3349    }
3350
3351    /// Finding 7: the lower arm of the clamp, driven through the reconciler.
3352    ///
3353    /// `demand_below_min_capacity_starts_nothing_in_v1` runs `demand = 0`
3354    /// against `min_capacity = 0`, which is *at* the floor and never raises
3355    /// `desired` — the assertion held for a reason unrelated to the boundary it
3356    /// named. D7 fixes `min` at 0 for v1, but `AutoscaleConfig::new` accepts
3357    /// `min > 0` today, so the path is representable and was undriven.
3358    #[tokio::test]
3359    async fn demand_below_min_capacity_is_raised_to_min_capacity() {
3360        let mut warm = ScalePolicy::new(
3361            PolicyId::from_u128(1),
3362            ScaleTarget::repository("acme/app").unwrap(),
3363            1,
3364            fixtures::HOST_ID,
3365            PolicyMode::autoscale(
3366                fixtures::routing_labels("home"),
3367                2,
3368                NonZeroU16::new(5).expect("non-zero"),
3369            )
3370            .expect("min <= max"),
3371            CachePolicy::default(),
3372        );
3373        warm.activate().expect("pending -> active");
3374
3375        let mut harness = Harness::simple(8, 0, "acme/app");
3376        let report = harness.reconciler.reconcile(&[warm]).await;
3377
3378        assert_eq!(
3379            report.allocations[0].demand, 0,
3380            "GitHub reported no queued runs"
3381        );
3382        assert_eq!(
3383            report.allocations[0].desired, 2,
3384            "min_capacity raised the target above demand"
3385        );
3386        assert_eq!(
3387            report.allocations[0].limiting_factor,
3388            LimitingFactor::MinCapacity
3389        );
3390        assert_eq!(report.started, 2, "and two runners were actually started");
3391        assert_eq!(harness.launcher.live_count(), 2);
3392    }
3393
3394    // =======================================================================
3395    // Capacity, at the boundaries
3396    // =======================================================================
3397
3398    #[tokio::test]
3399    async fn demand_above_max_capacity_is_clamped_to_max_capacity() {
3400        let mut harness = Harness::simple(100, 10, "acme/app");
3401        let report = harness
3402            .reconciler
3403            .reconcile(&[policy(1, "acme/app", 3)])
3404            .await;
3405
3406        assert_eq!(report.allocations[0].demand, 10);
3407        assert_eq!(
3408            report.allocations[0].desired, 3,
3409            "max_capacity beats demand"
3410        );
3411        assert_eq!(report.started, 3);
3412        assert_eq!(
3413            report.allocations[0].limiting_factor,
3414            LimitingFactor::MaxCapacity
3415        );
3416    }
3417
3418    #[tokio::test]
3419    async fn demand_below_min_capacity_starts_nothing_in_v1() {
3420        // D7 fixes `min_capacity` at 0, so "below the floor" is "no demand", and
3421        // the product requirement it satisfies is "no idle runners when unused".
3422        let mut harness = Harness::simple(8, 0, "acme/app");
3423        let report = harness
3424            .reconciler
3425            .reconcile(&[policy(1, "acme/app", 4)])
3426            .await;
3427
3428        assert_eq!(report.allocations[0].desired, 0);
3429        assert_eq!(report.started, 0);
3430        assert!(report.starts_nothing());
3431    }
3432
3433    #[tokio::test]
3434    async fn lifecycle_replacement_intent_is_consumed_by_the_ordinary_allocator() {
3435        let policy = policy(1, "octo/repo", 1);
3436        let previous = attempt_in(AttemptState::Starting, 41, 1);
3437        let intent = ReplacementIntent {
3438            policy: policy.id,
3439            previous_attempt: previous.id,
3440            operation: "exit_before_acceptance_replacement",
3441        };
3442        let launcher = Arc::new(FakeLauncher::new().seeded(vec![previous]).replacing(intent));
3443        let demand = Arc::new(FakeDemand::ready(1, &repo("octo/repo")));
3444        let mut harness = Harness::build(
3445            host_with(1),
3446            Arc::clone(&launcher),
3447            demand,
3448            Arc::new(InProcessAllocationLock::new()),
3449        );
3450
3451        let report = harness.reconciler.reconcile(&[policy]).await;
3452
3453        assert_eq!(report.replacement_intents, 1);
3454        assert_eq!(report.started, 1);
3455        assert_eq!(launcher.launches(), 1);
3456        assert_eq!(launcher.live_count(), 1);
3457    }
3458
3459    #[tokio::test]
3460    async fn zero_host_headroom_starts_nothing_at_maximum_demand() {
3461        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3462            attempt_in(AttemptState::Busy, 1, 1),
3463            attempt_in(AttemptState::Busy, 2, 1),
3464        ]));
3465        let demand = Arc::new(FakeDemand::ready(u32::from(u16::MAX), &repo("acme/app")));
3466        let mut harness = Harness::build(
3467            host_with(2),
3468            launcher,
3469            demand,
3470            Arc::new(InProcessAllocationLock::new()),
3471        );
3472
3473        let report = harness
3474            .reconciler
3475            .reconcile(&[policy(1, "acme/app", 2)])
3476            .await;
3477        assert_eq!(report.started, 0);
3478        assert_eq!(report.allocations[0].headroom_before, 0);
3479        assert_eq!(harness.launcher.launches(), 0);
3480    }
3481
3482    #[tokio::test]
3483    async fn headroom_smaller_than_the_per_policy_allowance_wins() {
3484        // Four slots held by *another* policy on a host of six: this policy is
3485        // allowed five and gets two.
3486        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3487            attempt_in(AttemptState::Busy, 1, 99),
3488            attempt_in(AttemptState::Busy, 2, 99),
3489            attempt_in(AttemptState::Idle, 3, 99),
3490            attempt_in(AttemptState::Starting, 4, 99),
3491        ]));
3492        let demand = Arc::new(FakeDemand::ready(5, &repo("acme/app")));
3493        let mut harness = Harness::build(
3494            host_with(6),
3495            launcher,
3496            demand,
3497            Arc::new(InProcessAllocationLock::new()),
3498        );
3499
3500        let report = harness
3501            .reconciler
3502            .reconcile(&[policy(1, "acme/app", 5)])
3503            .await;
3504        assert_eq!(
3505            report.allocations[0].desired, 5,
3506            "its own ceiling allows five"
3507        );
3508        assert_eq!(report.started, 2, "the host has two slots free");
3509        assert_eq!(
3510            report.allocations[0].limiting_factor,
3511            LimitingFactor::HostCapacity
3512        );
3513        assert_eq!(harness.launcher.live_count(), 6);
3514    }
3515
3516    #[tokio::test]
3517    async fn the_idle_host_assertion_holds() {
3518        // "No demand means zero runner processes and zero attempts out of
3519        // terminal state."
3520        let mut harness = Harness::simple(8, 0, "acme/app");
3521        let report = harness
3522            .reconciler
3523            .reconcile(&[policy(1, "acme/app", 4), policy(2, "acme/app", 4)])
3524            .await;
3525
3526        assert_eq!(report.started, 0);
3527        assert_eq!(harness.launcher.launches(), 0);
3528        assert!(harness.launcher.snapshot().is_empty());
3529        assert_eq!(
3530            harness
3531                .launcher
3532                .snapshot()
3533                .iter()
3534                .filter(|a| !a.is_terminal())
3535                .count(),
3536            0
3537        );
3538    }
3539
3540    // =======================================================================
3541    // D9 under concurrency: the other silent failure
3542    // =======================================================================
3543
3544    /// `e1`'s Definition of Done: *"Two policies on one host with
3545    /// `host_capacity` smaller than the sum of their `max_capacity` values never
3546    /// exceed `host_capacity` under concurrent reconciliation — asserted under
3547    /// simulated lock contention, with no duplicate runners."*
3548    ///
3549    /// The contention is simulated by [`FakeLauncher::with_yields`], which puts
3550    /// executor yield points *between* the launcher reading the attempt set and
3551    /// recording the new one. Without serialisation both tasks read a headroom
3552    /// of three and both spend it.
3553    ///
3554    /// # Watched failing before it was made to pass
3555    ///
3556    /// Granting from this lock without taking the inner mutex — leaving every
3557    /// counter and every yield point exactly as they are — fails this assertion
3558    /// with `left: 4, right: 3`: four runners on a host of three, from two
3559    /// policies each individually inside their own `max_capacity`. The control
3560    /// test below keeps that measurement standing permanently by running the
3561    /// same body against [`NoLock`].
3562    #[tokio::test(flavor = "current_thread")]
3563    async fn two_policies_reconciling_concurrently_never_exceed_host_capacity() {
3564        let lock = Arc::new(CountingLock::new());
3565        let (launches, live) =
3566            two_policies_concurrently(Arc::clone(&lock) as Arc<dyn AllocationLock>).await;
3567
3568        assert_eq!(
3569            launches, 3,
3570            "the sum across policies must never exceed host_capacity, and each policy is \
3571             individually within its own max_capacity of 3"
3572        );
3573        assert_eq!(live, 3, "and no duplicate runner survived the race");
3574        assert_eq!(
3575            lock.peak(),
3576            1,
3577            "the allocation lock had one holder at a time; without that the read of the \
3578             headroom and the creation of the runtime are not atomic"
3579        );
3580        assert!(
3581            (3..=5).contains(&lock.acquisitions()),
3582            "the lock is taken before *each* runtime, not once per pass: three runtimes \
3583             means at least three holds, and at most one further hold per policy to \
3584             discover the host filled up underneath it. It was taken {} times",
3585            lock.acquisitions()
3586        );
3587    }
3588
3589    /// The control for the test above: the same body with the lock removed.
3590    ///
3591    /// It exists so that the assertion above cannot pass vacuously. If a future
3592    /// change makes the unserialised path safe by accident — a launcher that
3593    /// records synchronously, say — this test goes red and says so, rather than
3594    /// the other one silently proving nothing.
3595    #[tokio::test(flavor = "current_thread")]
3596    async fn without_the_allocation_lock_two_policies_oversubscribe_the_host() {
3597        let (launches, _) =
3598            two_policies_concurrently(Arc::new(NoLock) as Arc<dyn AllocationLock>).await;
3599
3600        assert!(
3601            launches > 3,
3602            "with no serialisation both policies must be able to spend the same headroom; \
3603             they started {launches} runners on a host of 3. If this is ever 3, the \
3604             contention window closed and `two_policies_reconciling_concurrently_never_\
3605             exceed_host_capacity` has stopped proving anything"
3606        );
3607    }
3608
3609    /// Two policies, one host of three, each allowed three, reconciled at once.
3610    ///
3611    /// Returns `(launches, live attempts)`.
3612    async fn two_policies_concurrently(lock: Arc<dyn AllocationLock>) -> (usize, usize) {
3613        let launcher = Arc::new(FakeLauncher::new().with_yields(4));
3614        let host = host_with(3);
3615
3616        let mut left = Harness::build(
3617            host.clone(),
3618            Arc::clone(&launcher),
3619            Arc::new(FakeDemand::ready(3, &repo("acme/left"))),
3620            Arc::clone(&lock),
3621        )
3622        .reconciler;
3623        let mut right = Harness::build(
3624            host,
3625            Arc::clone(&launcher),
3626            Arc::new(FakeDemand::ready(3, &repo("acme/right"))),
3627            Arc::clone(&lock),
3628        )
3629        .reconciler;
3630
3631        let a = policy(1, "acme/left", 3);
3632        let b = policy(2, "acme/right", 3);
3633
3634        let left = tokio::spawn(async move { left.reconcile(&[a]).await });
3635        let right = tokio::spawn(async move { right.reconcile(&[b]).await });
3636        let (_, _) = (left.await.unwrap(), right.await.unwrap());
3637
3638        (launcher.launches(), launcher.live_count())
3639    }
3640
3641    // =======================================================================
3642    // D19: monitor-only
3643    // =======================================================================
3644
3645    /// `e1`'s Definition of Done: *"A `MonitorOnly` policy under maximum demand
3646    /// starts zero runners and issues no demand request."*
3647    ///
3648    /// Driven through `c4`'s real gateway fake so that "issued no demand
3649    /// request" is asserted against the thing that would have issued it, rather
3650    /// than against this module's own bookkeeping. `FakeGithub` records every
3651    /// call it is asked to make.
3652    #[tokio::test]
3653    async fn a_monitor_only_policy_under_maximum_demand_starts_nothing_and_polls_nothing() {
3654        let gateway = FakeGithub::new().with_queued_jobs(repo("acme/app"), jobs(10_000));
3655        let gateway = Arc::new(GatewayDemand::new(gateway, CancelToken::new()));
3656        let launcher = Arc::new(FakeLauncher::new());
3657        let events = Arc::new(EventLog::new());
3658
3659        let mut reconciler = Reconciler::new(
3660            host_with(10),
3661            ReconcilerPorts {
3662                demand: Arc::clone(&gateway) as Arc<dyn DemandSource>,
3663                launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
3664                lock: Arc::new(InProcessAllocationLock::new()),
3665                directory: Arc::new(FakeDirectory::default()),
3666                clock: Arc::new(FakeClock::default()),
3667                jitter: Arc::new(NoJitter),
3668                events: Arc::clone(&events) as Arc<dyn EventSink>,
3669            },
3670        );
3671
3672        let monitor = fixtures::policy()
3673            .id(PolicyId::from_u128(1))
3674            .repository("acme/app")
3675            .monitor_only()
3676            .active()
3677            .build();
3678
3679        let report = reconciler.reconcile(&[monitor]).await;
3680
3681        assert_eq!(report.started, 0);
3682        assert_eq!(launcher.launches(), 0);
3683        assert_eq!(report.monitor_only, vec![PolicyId::from_u128(1)]);
3684        assert_eq!(
3685            report.demand_requests, 0,
3686            "a monitor-only policy spends nothing from the shared hourly ceiling"
3687        );
3688        assert!(
3689            gateway.gateway().calls().is_empty(),
3690            "a monitor-only policy issued a demand request: {:?}",
3691            gateway.gateway().calls()
3692        );
3693        assert_eq!(events.count_of("monitor_only_skipped"), 1);
3694        assert_eq!(
3695            events.count_of("demand_observed"),
3696            0,
3697            "and it contributed no demand"
3698        );
3699    }
3700
3701    /// D19 says a monitor-only policy is *"skipped entirely by
3702    /// reconciliation"*, and "entirely" is the load-bearing word once two
3703    /// policies share a target.
3704    ///
3705    /// This defect was found by review rather than by the test above, which
3706    /// cannot see it: there, the monitor-only policy is the *only* policy, so
3707    /// nobody polls its target and the lookup finds nothing. Give it a
3708    /// repository an autoscale policy already polls and the lookup succeeds —
3709    /// and the monitor-only policy was then allocated for and had a demand
3710    /// observation emitted on its behalf. It still started nothing, because
3711    /// `may_start_runners` is false for it and `HostAllocator` refuses it by
3712    /// name, so no ceiling was ever at risk. It simply was not skipped.
3713    ///
3714    /// Removing the `owns_runners` guard from the allocation loop was watched
3715    /// failing this test before it was restored:
3716    /// `a monitor-only policy was allocated for: [… limiting_factor:
3717    /// MonitorOnly]`.
3718    #[tokio::test]
3719    async fn a_monitor_only_policy_sharing_a_target_is_still_skipped_entirely() {
3720        let lock = Arc::new(CountingLock::new());
3721        let launcher = Arc::new(FakeLauncher::new());
3722        let events = Arc::new(EventLog::new());
3723        let mut reconciler = Reconciler::new(
3724            host_with(4),
3725            ReconcilerPorts {
3726                demand: Arc::new(FakeDemand::ready(2, &repo("acme/app"))),
3727                launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
3728                lock: Arc::clone(&lock) as Arc<dyn AllocationLock>,
3729                directory: Arc::new(FakeDirectory::default()),
3730                clock: Arc::new(FakeClock::default()),
3731                jitter: Arc::new(NoJitter),
3732                events: Arc::clone(&events) as Arc<dyn EventSink>,
3733            },
3734        );
3735
3736        let watcher = fixtures::policy()
3737            .id(PolicyId::from_u128(2))
3738            .repository("acme/app")
3739            .monitor_only()
3740            .active()
3741            .build();
3742
3743        let report = reconciler
3744            .reconcile(&[policy(1, "acme/app", 4), watcher])
3745            .await;
3746
3747        assert_eq!(report.started, 2, "the autoscale policy is served normally");
3748        assert_eq!(report.monitor_only, vec![PolicyId::from_u128(2)]);
3749        assert_eq!(
3750            events.count_of("demand_observed"),
3751            1,
3752            "the demand observation belongs to the autoscale policy alone"
3753        );
3754        assert!(
3755            report
3756                .allocations
3757                .iter()
3758                .all(|a| a.policy_id == PolicyId::from_u128(1)),
3759            "a monitor-only policy was allocated for: {:?}",
3760            report.allocations
3761        );
3762        assert_eq!(
3763            lock.acquisitions(),
3764            2,
3765            "one hold per runtime created, and none on behalf of the monitor-only policy. \
3766             It was three before the budget was checked at the top of the loop rather than \
3767             after the re-read, which cost every policy a surplus hold to discover there \
3768             was nothing left to grant"
3769        );
3770    }
3771
3772    #[tokio::test]
3773    async fn the_monitor_only_refusal_is_asserted_on_the_mode_not_on_a_missing_ceiling() {
3774        // The specification requires this to be asserted rather than deduced
3775        // from `max_capacity` being absent. `HostAllocator` reports it by name,
3776        // and this loop reaches that arm through `owns_runners`, which is a
3777        // question about the mode.
3778        let monitor = fixtures::monitor_only_policy();
3779        assert!(!monitor.owns_runners());
3780        assert_eq!(monitor.max_capacity(), None);
3781
3782        let host = host_with(10);
3783        let attempts: Vec<RunnerAttempt> = Vec::new();
3784        let mut allocator = HostAllocator::from_attempts(&host, &attempts);
3785        let allocation = allocator.allocate(&monitor, 10_000);
3786        assert_eq!(allocation.limiting_factor, LimitingFactor::MonitorOnly);
3787        assert_eq!(allocation.to_start, 0);
3788        assert_eq!(
3789            allocator.headroom(),
3790            10,
3791            "and it consumes no headroom, so an autoscale policy on the same host is \
3792             unaffected"
3793        );
3794    }
3795
3796    // =======================================================================
3797    // The surplus runner, and busy protection
3798    // =======================================================================
3799
3800    /// `e1`'s Definition of Done: *"A surplus attempt that receives no job
3801    /// reaches a terminal state recorded as an idle exit, is cleaned, and is not
3802    /// reported as a failure."*
3803    #[tokio::test]
3804    async fn a_surplus_attempt_is_cleaned_as_an_idle_exit_and_not_as_a_failure() {
3805        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3806            concluded(1, 1, AttemptOutcome::ExitedIdleWithoutWork),
3807            concluded(
3808                2,
3809                1,
3810                AttemptOutcome::failed(FailureReason::JitRequestFailed),
3811            ),
3812            concluded(3, 1, AttemptOutcome::CompletedJob),
3813        ]));
3814        let mut harness = Harness::build(
3815            host_with(4),
3816            Arc::clone(&launcher),
3817            Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
3818            Arc::new(InProcessAllocationLock::new()),
3819        );
3820
3821        let report = harness
3822            .reconciler
3823            .reconcile(&[policy(1, "acme/app", 4)])
3824            .await;
3825
3826        assert_eq!(report.cleaned, 3);
3827        assert_eq!(report.idle_exits, 1, "the surplus case, counted apart");
3828        assert_eq!(
3829            report.failures, 1,
3830            "only the failed attempt is a failure; the idle exit and the completed job are \
3831             not"
3832        );
3833        assert_eq!(launcher.cleaned().len(), 3);
3834        assert!(launcher.snapshot().is_empty());
3835
3836        let cleaned: Vec<OutcomeKind> = harness
3837            .events
3838            .events()
3839            .into_iter()
3840            .filter_map(|event| match event {
3841                LifecycleEvent::AttemptCleaned { outcome, .. } => Some(outcome),
3842                _ => None,
3843            })
3844            .collect();
3845        assert!(cleaned.contains(&OutcomeKind::IdleExit));
3846        assert!(
3847            !OutcomeKind::IdleExit.is_failure(),
3848            "an idle exit rendered as a failure sends an operator hunting a fault that does \
3849             not exist"
3850        );
3851    }
3852
3853    /// `e1`'s Definition of Done: *"A scale-down request with a busy attempt
3854    /// removes nothing and leaves the attempt `busy`."*
3855    #[tokio::test]
3856    async fn scale_down_removes_nothing_from_a_busy_attempt() {
3857        let busy = attempt_in(AttemptState::Busy, 1, 1);
3858        let launcher = Arc::new(FakeLauncher::new().seeded(vec![
3859            busy.clone(),
3860            attempt_in(AttemptState::Starting, 2, 1),
3861            concluded(3, 1, AttemptOutcome::CompletedJob),
3862        ]));
3863        let harness = Harness::build(
3864            host_with(4),
3865            Arc::clone(&launcher),
3866            Arc::new(FakeDemand::ready(0, &repo("acme/app"))),
3867            Arc::new(InProcessAllocationLock::new()),
3868        );
3869
3870        let report = harness
3871            .reconciler
3872            .scale_down(&policy(1, "acme/app", 4))
3873            .await;
3874
3875        assert_eq!(report.refused_busy, 1);
3876        assert_eq!(
3877            report.retained, 1,
3878            "the `starting` attempt is not ended either"
3879        );
3880        assert_eq!(report.removed, 1, "only the concluded attempt is reclaimed");
3881
3882        let after = launcher.snapshot();
3883        let still_busy = after
3884            .iter()
3885            .find(|a| a.id == AttemptId::from_u128(1))
3886            .expect("the busy attempt is still there");
3887        assert_eq!(
3888            still_busy.state(),
3889            AttemptState::Busy,
3890            "scale-down removed nothing from a runner that is executing a job, and left it \
3891             busy"
3892        );
3893        assert!(!launcher.cleaned().contains(&AttemptId::from_u128(1)));
3894
3895        // And the domain refuses it from the other side too, by name, so a
3896        // future caller that tried anyway would not get a generic transition
3897        // error.
3898        let mut busy = busy;
3899        assert!(matches!(
3900            busy.clean(fixtures::created_at()),
3901            Err(runner_manager_domain::attempt::AttemptError::BusyCannotBeCleaned)
3902        ));
3903        assert_eq!(harness.events.count_of("scale_down_refused"), 1);
3904    }
3905
3906    // =======================================================================
3907    // The schedule
3908    // =======================================================================
3909
3910    #[test]
3911    fn the_default_interval_is_sixty_seconds_and_the_floor_is_thirty() {
3912        assert_eq!(RefreshInterval::DEFAULT_SECS, 60);
3913        assert_eq!(RefreshInterval::MIN_SECS, 30);
3914        assert_eq!(PollSchedule::floor(), Duration::from_secs(30));
3915        assert!(
3916            RefreshInterval::from_secs(29).is_err(),
3917            "the floor is a rate-budget constraint, and a caller must not be able to write \
3918             a shorter interval at all"
3919        );
3920
3921        let mut schedule = PollSchedule::new(RefreshInterval::default());
3922        let next = schedule.next_poll(None, fixtures::created_at(), &NoJitter);
3923        assert_eq!(next.delay, Duration::from_secs(60));
3924        assert_eq!(next.pace, PollPace::Nominal);
3925
3926        let mut floored = PollSchedule::new(RefreshInterval::from_secs(30).unwrap());
3927        assert_eq!(
3928            floored
3929                .next_poll(None, fixtures::created_at(), &NoJitter)
3930                .delay,
3931            Duration::from_secs(30)
3932        );
3933    }
3934
3935    /// `e1`'s Definition of Done: *"The poll interval … increases under a
3936    /// rate-limit signal, and the increase is visible in emitted state rather
3937    /// than silent."*
3938    #[test]
3939    fn a_rate_limit_increases_the_delay_and_names_itself() {
3940        let now = fixtures::created_at();
3941        let mut schedule = PollSchedule::new(RefreshInterval::default());
3942
3943        let limited = RefreshState::RateLimited(RateLimited {
3944            kind: RateLimitKind::Secondary,
3945            retry_after: Some(Duration::from_secs(300)),
3946            remaining: None,
3947            reset_unix_secs: None,
3948        });
3949        let next = schedule.next_poll(Some(&limited), now, &NoJitter);
3950
3951        assert_eq!(next.delay, Duration::from_secs(300));
3952        assert_eq!(
3953            next.pace,
3954            PollPace::RateLimited {
3955                kind: RateLimitKind::Secondary
3956            },
3957            "the increase is reported, never hidden"
3958        );
3959        assert!(next.pace.is_throttled());
3960        assert_eq!(next.pace.as_str(), "rate_limited_secondary");
3961    }
3962
3963    /// Constraint on this task: *"Read `RefreshState::retry_delay` as an
3964    /// absolute floor, not an addend."*
3965    #[test]
3966    fn the_retry_delay_is_an_absolute_floor_and_never_an_addend() {
3967        let now = fixtures::created_at();
3968        let mut schedule = PollSchedule::new(RefreshInterval::default());
3969
3970        let limited = RefreshState::RateLimited(RateLimited {
3971            kind: RateLimitKind::Primary,
3972            retry_after: Some(Duration::from_secs(300)),
3973            remaining: Some(0),
3974            reset_unix_secs: None,
3975        });
3976
3977        // Five successive answers, each carrying the window that is *left*.
3978        // An addend would compound: 360, 660, 960 … and look like a hang.
3979        for _ in 0..5 {
3980            let next = schedule.next_poll(Some(&limited), now, &NoJitter);
3981            assert_eq!(
3982                next.delay,
3983                Duration::from_secs(300),
3984                "the delay is `max(interval, retry_delay)`; `interval + retry_delay` would \
3985                 have compounded on every successive retry"
3986            );
3987        }
3988
3989        // And when GitHub asks for less than the interval, the interval wins:
3990        // the floor is never crossed to catch up.
3991        let brief = RefreshState::RateLimited(RateLimited {
3992            kind: RateLimitKind::Secondary,
3993            retry_after: Some(Duration::from_secs(5)),
3994            remaining: None,
3995            reset_unix_secs: None,
3996        });
3997        let next = schedule.next_poll(Some(&brief), now, &NoJitter);
3998        assert_eq!(
3999            next.delay,
4000            Duration::from_secs(60),
4001            "a short `retry-after` may not drop the loop below its own interval"
4002        );
4003        assert!(next.delay >= PollSchedule::floor());
4004    }
4005
4006    #[test]
4007    fn no_branch_of_the_schedule_can_go_below_the_thirty_second_floor() {
4008        let now = fixtures::created_at();
4009        let states = [
4010            None,
4011            Some(RefreshState::Offline),
4012            Some(RefreshState::RateLimited(RateLimited {
4013                kind: RateLimitKind::Secondary,
4014                retry_after: Some(Duration::from_secs(1)),
4015                remaining: None,
4016                reset_unix_secs: None,
4017            })),
4018            Some(RefreshState::LockedOut {
4019                retry_after: Duration::from_secs(1),
4020            }),
4021            Some(RefreshState::Unauthorized),
4022            Some(RefreshState::Forbidden { message: None }),
4023            Some(RefreshState::Failed {
4024                status: Some(500),
4025                message: "server error".into(),
4026            }),
4027            Some(RefreshState::Cancelled),
4028        ];
4029
4030        for state in &states {
4031            let mut schedule = PollSchedule::new(RefreshInterval::from_secs(30).unwrap());
4032            let next = schedule.next_poll(state.as_ref(), now, &NoJitter);
4033            assert!(
4034                next.delay >= PollSchedule::floor(),
4035                "{state:?} scheduled a poll {}ms away, under the 30-second floor",
4036                next.delay.as_millis()
4037            );
4038        }
4039    }
4040
4041    #[test]
4042    fn an_offline_run_backs_off_with_jitter_and_a_recovery_resets_it() {
4043        let now = fixtures::created_at();
4044        let mut schedule = PollSchedule::new(RefreshInterval::default());
4045
4046        // Doubling, from the nominal interval.
4047        let mut previous = Duration::ZERO;
4048        for consecutive in 1..=6_u32 {
4049            let next = schedule.next_poll(Some(&RefreshState::Offline), now, &NoJitter);
4050            assert_eq!(next.pace, PollPace::Offline { consecutive });
4051            assert!(
4052                next.delay >= previous,
4053                "the back-off must not shrink while the outage continues"
4054            );
4055            assert!(next.delay >= Duration::from_secs(60));
4056            previous = next.delay;
4057        }
4058        assert!(previous <= MAX_OFFLINE_BACKOFF, "and it is capped");
4059
4060        // Jitter widens the delay rather than narrowing it, so a fleet of
4061        // agents does not retry in lockstep.
4062        let mut jittered = PollSchedule::new(RefreshInterval::default());
4063        let none = jittered.next_poll(Some(&RefreshState::Offline), now, &NoJitter);
4064        let mut jittered = PollSchedule::new(RefreshInterval::default());
4065        let full = jittered.next_poll(Some(&RefreshState::Offline), now, &FixedJitter(0.999));
4066        assert!(full.delay > none.delay);
4067        assert!(full.delay <= none.delay.mul_f64(1.0 + JITTER_RATIO));
4068
4069        // Recovery resets the run with no bookkeeping of its own.
4070        assert_eq!(schedule.consecutive_offline(), 6);
4071        let recovered = schedule.next_poll(None, now, &NoJitter);
4072        assert_eq!(recovered.pace, PollPace::Nominal);
4073        assert_eq!(recovered.delay, Duration::from_secs(60));
4074        assert_eq!(schedule.consecutive_offline(), 0);
4075    }
4076
4077    #[test]
4078    fn the_offline_state_states_the_twenty_four_hour_bound() {
4079        assert_eq!(
4080            GITHUB_CANCELS_QUEUED_JOBS_AFTER,
4081            Duration::from_secs(24 * 60 * 60)
4082        );
4083
4084        let brief = OfflineState::new(1, Duration::from_secs(120));
4085        let rendered = brief.to_string();
4086        assert!(rendered.contains("24 hours"), "{rendered}");
4087        assert!(rendered.contains("Retrying in 120s"), "{rendered}");
4088        assert!(!brief.has_outlasted_the_queue());
4089
4090        let long = brief.since(GITHUB_CANCELS_QUEUED_JOBS_AFTER + Duration::from_secs(1));
4091        assert!(long.has_outlasted_the_queue());
4092        assert!(
4093            long.to_string().contains("queued work has been lost"),
4094            "{long}"
4095        );
4096
4097        // "We cannot tell" is not "not yet".
4098        assert!(!OfflineState::new(9, Duration::from_secs(60)).has_outlasted_the_queue());
4099    }
4100
4101    // =======================================================================
4102    // Offline, end to end
4103    // =======================================================================
4104
4105    /// `e1`'s Definition of Done: *"An unreachable GitHub yields `offline`, zero
4106    /// new runners, retained existing processes, and jittered backoff; recovery
4107    /// resumes polling and does not double-count a job that was already being
4108    /// served."*
4109    #[tokio::test]
4110    async fn an_unreachable_github_starts_nothing_retains_everything_and_backs_off() {
4111        let live = vec![
4112            attempt_in(AttemptState::Busy, 1, 1),
4113            attempt_in(AttemptState::Starting, 2, 1),
4114        ];
4115        let launcher = Arc::new(FakeLauncher::new().seeded(live.clone()));
4116        let demand = Arc::new(FakeDemand::failing(RefreshState::Offline));
4117        let mut harness = Harness::build(
4118            host_with(8),
4119            Arc::clone(&launcher),
4120            Arc::clone(&demand),
4121            Arc::new(InProcessAllocationLock::new()),
4122        );
4123        let policy = policy(1, "acme/app", 8);
4124
4125        let report = harness
4126            .reconciler
4127            .reconcile(std::slice::from_ref(&policy))
4128            .await;
4129
4130        assert!(report.is_offline());
4131        assert_eq!(report.started, 0, "no new runner during an outage");
4132        assert_eq!(launcher.launches(), 0);
4133        assert_eq!(
4134            launcher.snapshot(),
4135            live,
4136            "existing runner processes are retained, untouched"
4137        );
4138        assert_eq!(report.unreadable, vec![PolicyId::from_u128(1)]);
4139        assert_eq!(report.next_poll.pace, PollPace::Offline { consecutive: 1 });
4140        assert!(report.next_poll.delay >= Duration::from_secs(60));
4141        let offline = report.offline_state().expect("an offline state to display");
4142        assert!(offline.to_string().contains("24 hours"));
4143
4144        // Recovery: the same job is still queued, and one runner is already
4145        // serving it. Demand is recomputed from the current queued set rather
4146        // than accumulated, so the reconnect starts nothing new.
4147        demand.set(PollOutcome::Ready(QueuedDemand::of(
4148            repo("acme/app"),
4149            jobs(2),
4150        )));
4151        let recovered = harness.reconciler.reconcile(&[policy]).await;
4152
4153        assert!(!recovered.is_offline());
4154        assert_eq!(recovered.next_poll.pace, PollPace::Nominal);
4155        assert_eq!(
4156            recovered.started, 0,
4157            "two queued runs, two attempts already in flight: a reconnect cannot \
4158             double-count work"
4159        );
4160        assert_eq!(recovered.allocations[0].active_owned, 2);
4161        assert_eq!(launcher.live_count(), 2);
4162    }
4163
4164    /// One unreachable target must not idle a whole host.
4165    ///
4166    /// The failure that decides the *schedule* is the most severe across every
4167    /// target polled — backing the whole loop off during an outage is the safe
4168    /// error, and `f3` runs one reconciler per target anyway, so in production
4169    /// the two are usually the same thing. What must not follow from that is
4170    /// refusing to serve a policy whose own target answered perfectly well, and
4171    /// the two are easy to conflate because the offline reading is sitting in
4172    /// the same map.
4173    #[tokio::test]
4174    async fn one_offline_target_does_not_stop_a_reachable_one() {
4175        let mut harness = Harness::simple(8, 0, "acme/app");
4176        harness.demand.set_for(
4177            &ScaleTarget::repository("acme/app").unwrap(),
4178            PollOutcome::Ready(QueuedDemand::of(repo("acme/app"), jobs(2))),
4179        );
4180        harness.demand.set_for(
4181            &ScaleTarget::repository("acme/broken").unwrap(),
4182            PollOutcome::Failed(RefreshState::Offline),
4183        );
4184
4185        let report = harness
4186            .reconciler
4187            .reconcile(&[policy(1, "acme/app", 4), policy(2, "acme/broken", 4)])
4188            .await;
4189
4190        assert_eq!(
4191            report.started, 2,
4192            "the reachable target was served; an unreachable sibling repository must not \
4193             idle the host"
4194        );
4195        assert_eq!(report.unreadable, vec![PolicyId::from_u128(2)]);
4196        assert_eq!(harness.demand.polls().len(), 2, "both targets were polled");
4197
4198        // And the schedule takes the worse of the two.
4199        assert!(report.is_offline());
4200        assert_eq!(report.next_poll.pace, PollPace::Offline { consecutive: 1 });
4201    }
4202
4203    /// The 24-hour bound has to be reachable in production, not only in a unit
4204    /// test of [`OfflineState`].
4205    ///
4206    /// This was a real gap: the reconciler built its offline state from the
4207    /// back-off count alone, so `offline_for` was always `None` and
4208    /// [`OfflineState::has_outlasted_the_queue`] could never be true outside a
4209    /// test that constructed the value by hand. An operator whose agent had been
4210    /// offline for two days would have been told that an outage longer than 24
4211    /// hours *would* lose queued work, in the future tense, having already lost
4212    /// it.
4213    ///
4214    /// The elapsed time is measured from the first poll of the run rather than
4215    /// derived from the interval, because the back-off doubles and the two
4216    /// diverge immediately.
4217    #[tokio::test]
4218    async fn a_day_long_outage_says_that_queued_work_has_already_been_lost() {
4219        let clock = Arc::new(FakeClock::default());
4220        let launcher = Arc::new(FakeLauncher::new());
4221        let demand = Arc::new(FakeDemand::failing(RefreshState::Offline));
4222        let mut reconciler = Reconciler::new(
4223            host_with(4),
4224            ReconcilerPorts {
4225                demand: Arc::clone(&demand) as Arc<dyn DemandSource>,
4226                launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
4227                lock: Arc::new(InProcessAllocationLock::new()),
4228                directory: Arc::new(FakeDirectory::default()),
4229                clock: Arc::clone(&clock) as Arc<dyn Clock>,
4230                jitter: Arc::new(NoJitter),
4231                events: Arc::new(NoEvents),
4232            },
4233        );
4234        let policy = policy(1, "acme/app", 4);
4235
4236        // The outage begins.
4237        let first = reconciler.reconcile(std::slice::from_ref(&policy)).await;
4238        let state = first.offline_state().expect("an offline state");
4239        assert!(!state.has_outlasted_the_queue());
4240        assert!(
4241            state
4242                .to_string()
4243                .contains("an outage longer than that loses"),
4244            "{state}"
4245        );
4246
4247        // A day and a minute later, still unreachable.
4248        clock.advance_secs(24 * 60 * 60 + 60);
4249        let later = reconciler.reconcile(std::slice::from_ref(&policy)).await;
4250        let state = later.offline_state().expect("an offline state");
4251        assert!(state.has_outlasted_the_queue());
4252        assert!(
4253            state.to_string().contains("queued work has been lost"),
4254            "{state}"
4255        );
4256        assert_eq!(launcher.launches(), 0, "and still nothing was started");
4257
4258        // Recovery closes the run, so a *later* outage measures from itself
4259        // rather than from the first one.
4260        demand.set(PollOutcome::Ready(QueuedDemand::of(
4261            repo("acme/app"),
4262            jobs(0),
4263        )));
4264        let recovered = reconciler.reconcile(std::slice::from_ref(&policy)).await;
4265        assert!(recovered.offline_state().is_none());
4266        assert_eq!(reconciler.schedule().offline_for(clock.now()), None);
4267
4268        demand.set(PollOutcome::Failed(RefreshState::Offline));
4269        let again = reconciler.reconcile(std::slice::from_ref(&policy)).await;
4270        assert!(
4271            !again
4272                .offline_state()
4273                .expect("an offline state")
4274                .has_outlasted_the_queue(),
4275            "a new outage must not inherit the age of the one before it"
4276        );
4277    }
4278
4279    /// Finding 5: the adapter, not the lock underneath it.
4280    ///
4281    /// `d1` covers `LockKind::Allocation` including a contended `acquire_at`
4282    /// with a wait. What that does not reach is this adapter: the
4283    /// `spawn_blocking` wrapper, the collapse of both a refused lock and a
4284    /// panicked blocking task into `AllocationLockBusy`, and — the one that
4285    /// would be silent — whether [`AllocationGuard`] really holds the
4286    /// `HostLock`, since dropping it is the only release there is. A guard that
4287    /// dropped the lock on the way out would make every acquisition succeed and
4288    /// the ceiling would hold by luck.
4289    ///
4290    /// The original disclosure said this needed a real filesystem and was
4291    /// therefore expensive. `AppPaths::rooted_at` plus `tempfile` — already a
4292    /// non-dev dependency of this crate — makes it about fifteen lines, so the
4293    /// reason was weaker than stated.
4294    #[tokio::test]
4295    async fn the_file_allocation_lock_excludes_a_second_holder_and_releases_on_drop() {
4296        let root = tempfile::tempdir().expect("a temporary directory");
4297        let paths = Arc::new(runner_manager_platform::paths::AppPaths::rooted_at(
4298            root.path(),
4299        ));
4300        let lock = FileAllocationLock::new(paths).with_wait(Duration::from_millis(50));
4301
4302        let held = lock.acquire().await.expect("an uncontended lock is free");
4303        assert!(
4304            matches!(lock.acquire().await, Err(AllocationLockBusy)),
4305            "a second holder was admitted; on Unix the lock is per open file description \
4306             and on Windows the share mode denies write, so this must be refused even \
4307             from inside the same process"
4308        );
4309
4310        drop(held);
4311        let regained = lock.acquire().await;
4312        assert!(
4313            regained.is_ok(),
4314            "dropping the guard is the only release there is, so a guard that does not \
4315             hold the `HostLock` leaves it held forever"
4316        );
4317    }
4318
4319    #[test]
4320    fn tee_events_reaches_both_sinks() {
4321        // `f3` wires the log sink and `g2`'s buffer at once, and an event that
4322        // reached only one of them would be an activity view missing lines the
4323        // log file has, or the reverse.
4324        let left = Arc::new(EventLog::new());
4325        let right = Arc::new(EventLog::new());
4326        let tee = TeeEvents(
4327            Arc::clone(&left) as Arc<dyn EventSink>,
4328            Arc::clone(&right) as Arc<dyn EventSink>,
4329        );
4330
4331        tee.emit(LifecycleEvent::MonitorOnlySkipped {
4332            policy: PolicyId::from_u128(1),
4333        });
4334
4335        assert_eq!(left.count_of("monitor_only_skipped"), 1);
4336        assert_eq!(right.count_of("monitor_only_skipped"), 1);
4337    }
4338
4339    // =======================================================================
4340    // Budget: the repository list, and the per-target poll
4341    // =======================================================================
4342
4343    #[tokio::test]
4344    async fn the_repository_list_refreshes_far_more_slowly_than_the_demand_poll() {
4345        let clock = Arc::new(FakeClock::default());
4346        let directory = Arc::new(FakeDirectory::of(vec![repo("acme/one"), repo("acme/two")]));
4347        let cache = RepositoryCache::new(
4348            Arc::clone(&directory) as Arc<dyn RepositoryDirectory>,
4349            Arc::clone(&clock) as Arc<dyn Clock>,
4350            RefreshInterval::default(),
4351        );
4352        let target = ScaleTarget::organization("acme").unwrap();
4353
4354        assert_eq!(
4355            cache.ttl(),
4356            Duration::from_secs(60 * u64::from(REPOSITORY_LIST_REFRESH_MULTIPLE))
4357        );
4358
4359        // Every poll inside the window reuses the list.
4360        for _ in 0..REPOSITORY_LIST_REFRESH_MULTIPLE {
4361            let scope = cache.scope_for(&target).await.unwrap();
4362            assert_eq!(scope.repositories().len(), 2);
4363            clock.advance_secs(60);
4364        }
4365        assert_eq!(
4366            directory.calls(),
4367            1,
4368            "re-listing an organization at demand-poll frequency is what exhausts the \
4369             shared request budget"
4370        );
4371        assert_eq!(cache.lookups(), 1);
4372
4373        // Past it, exactly one more.
4374        cache.scope_for(&target).await.unwrap();
4375        assert_eq!(directory.calls(), 2);
4376    }
4377
4378    #[tokio::test]
4379    async fn a_repository_target_never_consults_the_directory() {
4380        let directory = Arc::new(FakeDirectory::of(vec![repo("acme/other")]));
4381        let cache = RepositoryCache::new(
4382            Arc::clone(&directory) as Arc<dyn RepositoryDirectory>,
4383            Arc::new(FakeClock::default()) as Arc<dyn Clock>,
4384            RefreshInterval::default(),
4385        );
4386        let target = ScaleTarget::repository("acme/app").unwrap();
4387
4388        let scope = cache.scope_for(&target).await.unwrap();
4389        assert_eq!(scope.repositories(), &[repo("acme/app")]);
4390        assert_eq!(directory.calls(), 0);
4391    }
4392
4393    #[tokio::test]
4394    async fn two_policies_on_one_target_cost_one_demand_poll_not_two() {
4395        // `04-subsystem-contracts.md` prices a *target*. A loop that spent per
4396        // policy would exceed the projection `f2` admitted the configuration
4397        // against, silently.
4398        let mut harness = Harness::simple(8, 4, "acme/app");
4399        let report = harness
4400            .reconciler
4401            .reconcile(&[policy(1, "acme/app", 2), policy(2, "acme/app", 2)])
4402            .await;
4403
4404        assert_eq!(harness.demand.polls().len(), 1);
4405        assert_eq!(
4406            report.demand_requests,
4407            runner_manager_github::demand::DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL,
4408            "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"
4409        );
4410        assert_eq!(report.started, 4, "and both policies still get their share");
4411    }
4412
4413    // =======================================================================
4414    // Failure paths
4415    // =======================================================================
4416
4417    #[tokio::test]
4418    async fn a_failed_launch_stops_the_run_and_is_reported_without_free_text() {
4419        let launcher = Arc::new(FakeLauncher::new());
4420        launcher.fail_next(FailureReason::Other("token ghp_0123456789abcdef".into()));
4421        let mut harness = Harness::build(
4422            host_with(4),
4423            Arc::clone(&launcher),
4424            Arc::new(FakeDemand::ready(3, &repo("acme/app"))),
4425            Arc::new(InProcessAllocationLock::new()),
4426        );
4427
4428        let report = harness
4429            .reconciler
4430            .reconcile(&[policy(1, "acme/app", 4)])
4431            .await;
4432        assert_eq!(report.started, 0);
4433        assert_eq!(report.allocations[0].to_start, 3, "the decision stands");
4434
4435        let failures: Vec<&'static str> = harness
4436            .events
4437            .events()
4438            .into_iter()
4439            .filter_map(|event| match event {
4440                LifecycleEvent::RunnerStartFailed { reason, .. } => Some(reason),
4441                _ => None,
4442            })
4443            .collect();
4444        assert_eq!(failures, vec!["other"]);
4445        assert!(
4446            !failures[0].contains("ghp_"),
4447            "an event carried a `FailureReason::Other` detail verbatim"
4448        );
4449    }
4450
4451    #[tokio::test]
4452    async fn a_held_allocation_lock_starts_nothing_and_says_so() {
4453        let launcher = Arc::new(FakeLauncher::new());
4454        let mut harness = Harness::build(
4455            host_with(4),
4456            Arc::clone(&launcher),
4457            Arc::new(FakeDemand::ready(3, &repo("acme/app"))),
4458            Arc::new(HeldLock),
4459        );
4460
4461        let report = harness
4462            .reconciler
4463            .reconcile(&[policy(1, "acme/app", 4)])
4464            .await;
4465        assert_eq!(report.started, 0);
4466        assert_eq!(
4467            report.deferred, 3,
4468            "three runners were granted and none was created; `deferred` counts grants, \
4469             not policies -- it reported `1` when a policy that launched two of five and \
4470             then lost the lock had left three unstarted"
4471        );
4472        assert_eq!(launcher.launches(), 0);
4473        assert_eq!(harness.events.count_of("allocation_deferred"), 1);
4474        assert!(
4475            harness
4476                .events
4477                .events()
4478                .iter()
4479                .any(|event| matches!(event, LifecycleEvent::AllocationDeferred { count: 3, .. })),
4480            "the event carries the same number the report does"
4481        );
4482        assert_eq!(
4483            report.allocations.len(),
4484            1,
4485            "the intent is still reported, so an operator staring at a queue sees why \
4486             nothing started"
4487        );
4488    }
4489
4490    #[tokio::test]
4491    async fn a_foreign_or_draining_policy_is_reported_by_name_and_polls_nothing() {
4492        let mut harness = Harness::simple(8, 5, "acme/app");
4493
4494        let foreign = fixtures::policy()
4495            .id(PolicyId::from_u128(1))
4496            .repository("acme/app")
4497            .host(HostId::from_u128(0xdead))
4498            .autoscale("office", 4)
4499            .active()
4500            .build();
4501        let mut draining = policy(2, "acme/app", 4);
4502        draining.request_disable().unwrap();
4503
4504        let report = harness.reconciler.reconcile(&[foreign, draining]).await;
4505
4506        assert_eq!(report.started, 0);
4507        assert_eq!(
4508            harness.demand.polls().len(),
4509            0,
4510            "neither can act on an answer"
4511        );
4512        let factors: Vec<LimitingFactor> = report
4513            .allocations
4514            .iter()
4515            .map(|a| a.limiting_factor)
4516            .collect();
4517        assert!(factors.contains(&LimitingFactor::ForeignHost));
4518        assert!(factors.contains(&LimitingFactor::NotReconciling));
4519    }
4520
4521    #[tokio::test]
4522    async fn an_unreadable_repository_list_makes_the_target_unreadable_not_empty() {
4523        // Polling a scope nobody chose would report a demand number for the
4524        // wrong set of repositories, which is worse than reporting nothing.
4525        #[derive(Debug)]
4526        struct BrokenDirectory;
4527
4528        #[async_trait::async_trait]
4529        impl RepositoryDirectory for BrokenDirectory {
4530            async fn repositories(&self, _org: &Org) -> Result<Vec<OwnerRepo>, InventoryError> {
4531                Err(InventoryError::Cancelled)
4532            }
4533        }
4534
4535        let launcher = Arc::new(FakeLauncher::new());
4536        let events = Arc::new(EventLog::new());
4537        let mut reconciler = Reconciler::new(
4538            host_with(4),
4539            ReconcilerPorts {
4540                demand: Arc::new(FakeDemand::default()),
4541                launcher: Arc::clone(&launcher) as Arc<dyn RunnerLauncher>,
4542                lock: Arc::new(InProcessAllocationLock::new()),
4543                directory: Arc::new(BrokenDirectory),
4544                clock: Arc::new(FakeClock::default()),
4545                jitter: Arc::new(NoJitter),
4546                events: Arc::clone(&events) as Arc<dyn EventSink>,
4547            },
4548        );
4549
4550        let org_policy = fixtures::policy()
4551            .id(PolicyId::from_u128(1))
4552            .organization("acme")
4553            .autoscale("home", 4)
4554            .active()
4555            .build();
4556
4557        let report = reconciler.reconcile(&[org_policy]).await;
4558        assert_eq!(report.started, 0);
4559        assert_eq!(report.unreadable, vec![PolicyId::from_u128(1)]);
4560        assert_eq!(events.count_of("target_unreadable"), 1);
4561    }
4562
4563    // =======================================================================
4564    // What the events may carry
4565    // =======================================================================
4566
4567    /// One value of every [`LifecycleEvent`] variant.
4568    ///
4569    /// Hand-written, and what keeps it honest is the wildcard-free `match` in
4570    /// [`LifecycleEvent::name`]: adding a variant stops that compiling and puts
4571    /// the author here. The same residual `b1` records for `FailureReason::ALL`
4572    /// applies — an author who writes the `name` arm and forgets this list gets
4573    /// a green suite with the variant unscanned.
4574    fn every_event() -> Vec<LifecycleEvent> {
4575        let policy = PolicyId::from_u128(0xabcd_ef01);
4576        let attempt = AttemptId::from_u128(0x1234_5678);
4577        vec![
4578            LifecycleEvent::DemandObserved {
4579                policy,
4580                demand: u32::MAX,
4581                not_matched: u32::MAX,
4582                unresolvable: u32::MAX,
4583                complete: false,
4584            },
4585            LifecycleEvent::TargetUnreadable {
4586                policy,
4587                reason: unreadable_reason(&RefreshState::Failed {
4588                    status: Some(500),
4589                    message: "Authorization: Bearer ghp_0123456789abcdefghijklmnopqrstuvwxyz"
4590                        .into(),
4591                }),
4592            },
4593            LifecycleEvent::Allocated {
4594                policy,
4595                demand: u32::MAX,
4596                desired: u16::MAX,
4597                active_owned: 7,
4598                headroom: 9,
4599                to_start: 2,
4600                limiting: LimitingFactor::HostCapacity,
4601            },
4602            LifecycleEvent::MonitorOnlySkipped { policy },
4603            LifecycleEvent::RunnerStarted { policy, attempt },
4604            LifecycleEvent::RunnerStartFailed {
4605                policy,
4606                reason: failure_reason_kind(&FailureReason::Other(
4607                    "Authorization: Bearer ghp_0123456789abcdefghijklmnopqrstuvwxyz".into(),
4608                )),
4609            },
4610            LifecycleEvent::AllocationDeferred { policy, count: 4 },
4611            LifecycleEvent::AttemptsUnreadable {
4612                reason: failure_reason_kind(&FailureReason::Other(
4613                    "x-api-key: ghp_0123456789abcdefghijklmnopqrstuvwxyz".into(),
4614                )),
4615            },
4616            LifecycleEvent::AttemptCleanFailed {
4617                policy,
4618                attempt,
4619                reason: failure_reason_kind(&FailureReason::ProcessExitedUnexpectedly),
4620            },
4621            LifecycleEvent::AttemptCleaned {
4622                policy,
4623                attempt,
4624                outcome: OutcomeKind::IdleExit,
4625            },
4626            LifecycleEvent::ScaleDownRefused { policy, attempt },
4627            LifecycleEvent::PollScheduled {
4628                retry_in_ms: 900_000,
4629                pace: PollPace::RateLimited {
4630                    kind: RateLimitKind::Primary,
4631                },
4632            },
4633        ]
4634    }
4635
4636    /// `e1`'s Definition of Done: *"No emitted event contains a token, a JIT
4637    /// blob, or a credential header."*
4638    ///
4639    /// Asserted by rendering every variant and putting the result through `d1`'s
4640    /// own scrubber: if any of it looked like a credential to the redactor that
4641    /// guards the log file, the round trip would not be the identity. The
4642    /// positive control at the bottom is what stops that assertion passing
4643    /// because the scrubber is asleep.
4644    #[test]
4645    fn no_emitted_event_can_carry_a_credential() {
4646        use runner_manager_platform::logging::redact;
4647
4648        for event in every_event() {
4649            let displayed = event.to_string();
4650            assert_eq!(
4651                redact(&displayed),
4652                displayed,
4653                "`{}` renders something `d1`'s sink would have to redact",
4654                event.name()
4655            );
4656
4657            let debugged = format!("{event:?}");
4658            assert_eq!(
4659                redact(&debugged),
4660                debugged,
4661                "`{}`'s Debug renders something `d1`'s sink would have to redact",
4662                event.name()
4663            );
4664        }
4665
4666        // The control: the scrubber is awake, and would have caught a credential
4667        // had one been there.
4668        let secret = "Authorization: Bearer ghp_0123456789abcdefghijklmnopqrstuvwxyz";
4669        assert_ne!(
4670            redact(secret),
4671            secret,
4672            "the scan above proves nothing if `redact` no longer recognises a credential"
4673        );
4674    }
4675
4676    #[test]
4677    fn every_field_name_this_sink_emits_is_one_d1_allows() {
4678        use runner_manager_platform::logging::is_field_allowed;
4679
4680        // The names `TracingEvents` writes. Kept beside the sink rather than
4681        // derived from it, because a derived list would move with the code and
4682        // assert nothing.
4683        for field in [
4684            "event",
4685            "policy_id",
4686            "attempt_id",
4687            "attempt_state",
4688            "demand",
4689            "desired",
4690            "capacity",
4691            "headroom",
4692            "count",
4693            "reason",
4694            "outcome",
4695            "mode",
4696            "lock",
4697            "retry_in_ms",
4698            "state",
4699        ] {
4700            assert!(
4701                is_field_allowed(field),
4702                "`{field}` is not on `d1`'s allow-list, so this sink would emit \
4703                 `[redacted]` in its place and the line would lose its meaning"
4704            );
4705        }
4706    }
4707
4708    #[test]
4709    fn every_failure_reason_has_a_credential_free_kind() {
4710        for reason in FailureReason::ALL {
4711            let kind = failure_reason_kind(&reason);
4712            assert!(!kind.is_empty());
4713            assert!(
4714                kind.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
4715                "`{kind}` is not a fixed identifier"
4716            );
4717        }
4718        assert_eq!(
4719            failure_reason_kind(&FailureReason::Other("ghp_secret".into())),
4720            "other",
4721            "the detail of an `Other` reason never reaches an event"
4722        );
4723    }
4724
4725    // =======================================================================
4726    // The two tripwires
4727    // =======================================================================
4728
4729    /// One source file's production half, with comment lines dropped.
4730    ///
4731    /// Both exclusions are `c4`'s, and load-bearing for the same reasons. The
4732    /// **test module** goes because the tests in it legitimately name the shapes
4733    /// they forbid — this module's own positive control is a literal
4734    /// `async fn acquire_jobs`, which would accuse the file of the thing it is
4735    /// proving it does not do. The **comments** go because this module's
4736    /// documentation explains the seam at length and has to name what does not
4737    /// exist in order to say why; a scan that forbade the explanation is a scan
4738    /// that gets the explanation deleted.
4739    fn production_half_of(source: &str) -> String {
4740        let production = source
4741            .split_once("\n#[cfg(test)]")
4742            .map_or(source, |(production, _)| production);
4743        production
4744            .lines()
4745            .filter(|line| !line.trim_start().starts_with("//"))
4746            .collect::<Vec<_>>()
4747            .join("\n")
4748    }
4749
4750    /// This file's own production half.
4751    fn this_file_above_its_tests_without_prose() -> String {
4752        production_half_of(include_str!("reconcile.rs"))
4753    }
4754
4755    /// The one normalisation both halves of the scan use.
4756    ///
4757    /// # This is a second copy of `crates/github/src/demand.rs`, deliberately
4758    ///
4759    /// `production_half_of`, this function, [`FORBIDDEN`] and
4760    /// `forbidden_shape_in` together duplicate `demand.rs:1530-1619`. Sharing
4761    /// them would mean putting them in `crates/testkit`, which `e1` does not
4762    /// own, so the copy was the only option available to this task.
4763    ///
4764    /// **It is worth consolidating later, and here is the specific hazard.**
4765    /// The last defect in `c4`'s copy was two spellings of "the same"
4766    /// normalisation drifting apart — the haystack lower-cased and the needle
4767    /// not — which made three of its seven assertions vacuously true from the
4768    /// day they were written. Two copies is the same hazard one level up. The
4769    /// mitigation inside *this* copy is that one function serves both the scan
4770    /// and its positive control, so a normaliser that stops matching fails the
4771    /// control loudly rather than passing the scan silently; what that cannot
4772    /// catch is this copy and `c4`'s diverging from each other.
4773    fn normalise_for_scan(text: &str) -> String {
4774        text.to_ascii_lowercase().replace(['_', ' '], "")
4775    }
4776
4777    /// The Actions-service call this design has no equivalent of, plus the
4778    /// shapes an implementer would invent in its place.
4779    ///
4780    /// Spelled in halves so that no needle ever appears whole in the text being
4781    /// scanned, and keyed to `fn`/`struct` so that the prose above may keep
4782    /// explaining why there is no reservation. `c4` records both trades at
4783    /// length; this list is its counterpart one layer up. Note that the
4784    /// allocation lock's own `fn acquire` is deliberately *not* matched: the
4785    /// needle is `acquire`-a-**job**, and a lock is not one.
4786    const FORBIDDEN: &[&str] = &[
4787        concat!("fn ", "acquire", "_job"),
4788        concat!("fn ", "claim", "_job"),
4789        concat!("fn ", "lease", "_job"),
4790        concat!("fn ", "reserve", "_job"),
4791        concat!("fn ", "ack", "nowledge"),
4792        concat!("struct ", "Job", "Lease"),
4793        concat!("struct ", "Job", "Claim"),
4794        concat!("struct ", "Job", "Reservation"),
4795    ];
4796
4797    fn forbidden_shape_in(source: &str) -> Option<&'static str> {
4798        let haystack = normalise_for_scan(source);
4799        FORBIDDEN
4800            .iter()
4801            .copied()
4802            .find(|forbidden| haystack.contains(&normalise_for_scan(forbidden)))
4803    }
4804
4805    /// `e1`'s Definition of Done: *"No reservation, claim, lease, or acquisition
4806    /// call exists in the crate; a test or review note records that this is
4807    /// deliberate rather than missing."*
4808    ///
4809    /// **Deliberate, not missing.** The scale-set model let a listener call
4810    /// `AcquireJobs` to claim an assignment before scaling; the REST path has no
4811    /// equivalent, so demand is advisory and two hosts serving the same labels
4812    /// can both start a runner for one queued run. Adding a local reservation
4813    /// table would not remove that — the other host cannot see it — it would
4814    /// only hide the surplus case from the tests that measure it. The three
4815    /// controls that actually bound it are host-scoped routing labels,
4816    /// `max_capacity`, and `host_capacity`, and the last two are enforced in
4817    /// this file.
4818    ///
4819    /// The scan is a tripwire on the obvious shape rather than a proof: a
4820    /// reservation reached through a trait method or a differently-named helper
4821    /// would walk past it. Review is the primary control, exactly as `c4` states
4822    /// for its own copy.
4823    ///
4824    /// # It scans the crate, because the bullet says "in the crate"
4825    ///
4826    /// It used to scan this file alone while quoting a crate-wide claim, which
4827    /// left `lifecycle.rs` — `e3`, the launcher, and by far the likeliest place
4828    /// for someone to "fix" the surplus-runner case with a local lease — covered
4829    /// by nothing. Reading another owner's file is not editing it, so ownership
4830    /// was never the obstacle.
4831    ///
4832    /// The walk below is `c4`'s, and it **recurses** for the reason `c4`
4833    /// records: a module directory (`src/reconcile/mod.rs`) arrives as an entry
4834    /// that does not end in `.rs`, so a flat filter drops it and takes every
4835    /// file underneath with it, leaving the scan passing over files it covers
4836    /// by nothing at all. The listed-versus-on-disk assertion is what stops
4837    /// `SOURCES` going stale the moment `e2` or `e3` adds a module.
4838    #[test]
4839    fn nothing_in_this_crate_reserves_or_claims_a_job() {
4840        const SOURCES: &[(&str, &str)] = &[
4841            ("lib.rs", include_str!("lib.rs")),
4842            ("lifecycle.rs", include_str!("lifecycle.rs")),
4843            ("package.rs", include_str!("package.rs")),
4844            ("reconcile.rs", include_str!("reconcile.rs")),
4845        ];
4846
4847        fn walk(directory: &std::path::Path, prefix: &str, found: &mut Vec<String>) {
4848            for entry in std::fs::read_dir(directory).expect("the crate's own src/ is readable") {
4849                let entry = entry.expect("a readable directory entry");
4850                let name = entry.file_name().to_string_lossy().into_owned();
4851                // `/`-joined, which is what `include_str!` takes on every
4852                // platform, so the two sides compare directly.
4853                let joined = if prefix.is_empty() {
4854                    name.clone()
4855                } else {
4856                    format!("{prefix}/{name}")
4857                };
4858                if entry.path().is_dir() {
4859                    walk(&entry.path(), &joined, found);
4860                } else if name.ends_with(".rs") {
4861                    found.push(joined);
4862                }
4863            }
4864        }
4865
4866        let mut listed: Vec<&str> = SOURCES.iter().map(|(name, _)| *name).collect();
4867        listed.sort_unstable();
4868        let mut on_disk = Vec::new();
4869        walk(
4870            std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")),
4871            "",
4872            &mut on_disk,
4873        );
4874        on_disk.sort_unstable();
4875        assert_eq!(
4876            listed, on_disk,
4877            "a source file was added or removed; this scan claims to cover the whole crate \
4878             and a stale list makes that claim false"
4879        );
4880
4881        for (name, source) in SOURCES {
4882            assert_eq!(
4883                forbidden_shape_in(&production_half_of(source)),
4884                None,
4885                "{name} names a forbidden shape: there is no `AcquireJobs` equivalent over \
4886                 REST, and a local lease coordinates this host with itself and with nothing \
4887                 else. If an owner decision restored one, that decision belongs in this \
4888                 module's documentation and in this test before it belongs in the code"
4889            );
4890        }
4891
4892        // The control: the scan can see a shape when there is one, through the
4893        // same matcher the loop above uses.
4894        assert!(
4895            forbidden_shape_in("async fn acquire_jobs(&self) -> Vec<Job> { todo!() }").is_some(),
4896            "the scan above proves nothing if the needles no longer match"
4897        );
4898    }
4899
4900    /// This module **applies** `b1`'s label predicate and implements none of it.
4901    ///
4902    /// The counterpart to `c4`'s scan over `crates/github/src/demand.rs`, and it
4903    /// checks the opposite thing, because the two modules sit on opposite sides
4904    /// of the same seam. `c4` builds a `RunsOn` per queued job and must name no
4905    /// `RoutingLabels`; this module holds the policy whose labels decide, so it
4906    /// must call `RoutingLabels::tally` and must not re-derive what that call
4907    /// answers.
4908    ///
4909    /// So the scan is in two halves:
4910    ///
4911    /// * **Present.** `DemandTally` has to appear, because [`demand_for`]
4912    ///   returns one. A production half that named it nowhere would mean the
4913    ///   filtering had been dropped and every queued job in a watched repository
4914    ///   was driving this policy toward `max_capacity` again.
4915    /// * **Absent.** The vocabulary of a *second* implementation. `b1` names the
4916    ///   three outcomes of matching one job; this module consumes the aggregate
4917    ///   and never a single job's verdict, so naming `RunsOnMatch` or
4918    ///   `UnresolvableRunsOn` here means a `match` on an outcome that
4919    ///   `RoutingLabels::tally` has already decided — which is how two copies of
4920    ///   a predicate start.
4921    ///
4922    /// Like the needles in `nothing_in_this_module_reserves_or_claims_a_job`,
4923    /// this is a tripwire on the obvious shape rather than a proof: a hand-rolled
4924    /// comparison of raw label strings that never names a `policy` type would
4925    /// walk past it. Stated rather than implied, for the same reason it is
4926    /// stated there.
4927    #[test]
4928    fn the_label_predicate_is_b1s_and_this_module_only_applies_it() {
4929        let production = this_file_above_its_tests_without_prose();
4930
4931        assert!(
4932            production.contains("DemandTally"),
4933            "the reconciliation loop must tally queued jobs against this policy's routing \
4934             labels. A production half that named `DemandTally` nowhere would mean the \
4935             label filtering had been removed, and a repository whose jobs target \
4936             `ubuntu-latest` would drive its policy toward `max_capacity` again"
4937        );
4938
4939        for second_implementation in ["RunsOnMatch", "UnresolvableRunsOn"] {
4940            assert!(
4941                !production.contains(second_implementation),
4942                "the reconciliation loop names `{second_implementation}`, which is the \
4943                 vocabulary of deciding one job's `runs-on` -- and `RoutingLabels::tally` \
4944                 has already decided it. This module applies the predicate and does not \
4945                 re-implement it; if an owner decision changed that, it belongs in this \
4946                 module's documentation and in this test before it belongs in the code"
4947            );
4948        }
4949    }
4950
4951    /// The demand this module clamps is the *matched* count, and a job this host
4952    /// cannot serve is not demand.
4953    ///
4954    /// The behaviour the whole reversal was for, asserted end to end through
4955    /// `demand_for` rather than through `b1`'s predicate in isolation: a policy
4956    /// carrying this host's labels, a reading holding some of its jobs and some
4957    /// of somebody else's, and the three counts kept apart.
4958    #[test]
4959    fn demand_is_the_queued_jobs_this_policy_can_actually_serve() {
4960        let policy = policy(1, "acme/app", 10);
4961        let reading = QueuedDemand::of(
4962            repo("acme/app"),
4963            [
4964                fixtures::queued_job(&[HOST_LABEL]),
4965                fixtures::queued_job(&[HOST_LABEL]),
4966                fixtures::queued_job(&["ubuntu-latest"]),
4967                fixtures::unresolvable_job(),
4968            ],
4969        );
4970
4971        let tally = demand_for(&policy, &reading);
4972
4973        assert_eq!(
4974            tally.demand(),
4975            2,
4976            "only the jobs whose required labels this policy carries are demand"
4977        );
4978        assert_eq!(
4979            tally.not_matched, 1,
4980            "a `ubuntu-latest` job is somebody else's work; counting it would start a \
4981             runner that idles until it times out"
4982        );
4983        assert_eq!(
4984            tally.unresolvable.len(),
4985            1,
4986            "an unresolvable `runs-on` is never demand and never discarded"
4987        );
4988    }
4989
4990    /// A repository target reads its own repository; an organization target
4991    /// reads the whole scope.
4992    #[test]
4993    fn an_organization_policy_tallies_every_repository_its_scope_covers() {
4994        let mut per_repository = BTreeMap::new();
4995        per_repository.insert(repo("acme/left"), fixtures::queued_jobs(&[HOST_LABEL], 3));
4996        per_repository.insert(repo("acme/right"), fixtures::queued_jobs(&[HOST_LABEL], 4));
4997        let reading = QueuedDemand::new(per_repository);
4998
4999        let repository_policy = policy(1, "acme/left", 10);
5000        assert_eq!(
5001            demand_for(&repository_policy, &reading).demand(),
5002            3,
5003            "a repository target reads its own repository's queue and not the aggregate"
5004        );
5005
5006        let org_policy = fixtures::policy()
5007            .id(PolicyId::from_u128(2))
5008            .organization("acme")
5009            .autoscale("home", 10)
5010            .active()
5011            .build();
5012        assert_eq!(
5013            demand_for(&org_policy, &reading).demand(),
5014            7,
5015            "an organization policy serves any repository in its scope, so its demand is \
5016             the whole aggregate's"
5017        );
5018    }
5019
5020    #[test]
5021    fn the_accepted_over_count_is_bounded_by_the_two_ceilings_and_nothing_else() {
5022        // The owner decision accepts that a repository whose jobs only target
5023        // `ubuntu-latest` still drives its policy toward `max_capacity`. What
5024        // stops that being unbounded is exactly what stops any other demand
5025        // being unbounded, which is asserted here rather than assumed.
5026        let host = host_with(2);
5027        let policy = policy(1, "acme/app", 5);
5028        let attempts: Vec<RunnerAttempt> = Vec::new();
5029        let mut allocator = HostAllocator::from_attempts(&host, &attempts);
5030
5031        let allocation = allocator.allocate(&policy, u32::MAX);
5032        assert_eq!(allocation.desired, 5, "max_capacity beats reported demand");
5033        assert_eq!(allocation.to_start, 2, "host_capacity beats max_capacity");
5034        assert_eq!(allocation.limiting_factor, LimitingFactor::HostCapacity);
5035    }
5036}