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