Skip to main content

runner_manager_github/
demand.rs

1// owner: c4-demand-and-jit-gateway
2
3//! How much work is waiting for a runner that does not exist yet.
4//!
5//! Demand is the number `e1` feeds to `clamp(demand, min_capacity,
6//! max_capacity)`, so it is the number that decides how many runner processes
7//! this host starts. Everything in this module exists to make that number
8//! honest — and, where it cannot be, to make it *say* so rather than look
9//! precise.
10//!
11//! ```text
12//! GET /repos/{owner}/{repo}/actions/runs?status=queued&per_page=100
13//! GET /repos/{owner}/{repo}/actions/runs?status=in_progress&per_page=100
14//!   -> 200 { "total_count": N, "workflow_runs": [ { "id": … }, … ] }
15//! GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs?filter=latest&per_page=100
16//!   -> 200 { "total_count": M, "jobs": [ { "status": …, "labels": […] }, … ] }
17//! ```
18//!
19//! # The counting unit is a **job**, and this reverses an earlier decision
20//!
21//! This is the single most important thing to know about this module, and it is
22//! an owner decision that **replaced the opposite owner decision**. The history
23//! is kept here rather than deleted, because the reasoning that produced the old
24//! answer is still sound in the abstract and a later reader who only sees the
25//! new code will otherwise re-derive it and revert this.
26//!
27//! **What the previous decision said.** `d18b-run-count-filtering.md` probed the
28//! runs endpoint against live GitHub and established that its `total_count`
29//! counts **workflow runs matching the query**. Counting runs costs exactly one
30//! request per repository, a fixed figure the budget model
31//! ([`crate::rest::TargetCost`], [`crate::rest::BudgetProjection`]) could price
32//! and `f2`'s `add` refusals could be computed from. Resolving each queued run's
33//! jobs costs one extra request *per run*, a variable cost scaling with queue
34//! depth. The owner chose the fixed cost, accepted the resulting under-count,
35//! and this module said at length: *do not "fix" this, and do not add a per-run
36//! job listing*.
37//!
38//! **Why it was reversed.** A workflow run holds many jobs — a matrix, or a
39//! `jobs:` map with several independent entries — and **each job needs its own
40//! runner**. Under the run count, a single queued run holding eight jobs read as
41//! demand `1`, `e1` started **one** runner, that runner took one job, and the
42//! remaining seven queued behind it. The next poll saw the same run still
43//! queued, still read `1`, and started one more. So a host configured for ten
44//! concurrent runners served an eight-job matrix **serially, roughly one at a
45//! time**, with the queue depth on GitHub growing while the machine sat idle.
46//! The under-count was not a rounding error in the demand signal; on the
47//! workflow shape people actually write, it was the difference between the
48//! product's headline feature working and not working. That is a worse outcome
49//! than a variable request cost, so the trade was re-made the other way.
50//!
51//! **What that means for a later reader.** The per-run job listing below is
52//! deliberate and load-bearing. Removing it to restore a fixed per-repository
53//! cost re-creates the serial-matrix defect described above. If a future owner
54//! decision reverses this again, it belongs in this documentation and in
55//! `tests::the_runs_on_predicate_is_b1s_and_this_module_only_feeds_it` before it
56//! belongs in the code.
57//!
58//! # Both run statuses are polled, and the second one is not redundant
59//!
60//! `status=queued` alone is the obvious query and it is not sufficient. A run's
61//! status is a property of the *run*, and a run holding both a running job and a
62//! queued one has to report one value for both. Live observation on a repository
63//! using this product caught a run of five jobs — two completed, one
64//! `in_progress`, two `queued` — reporting `status: "queued"`, so `queued` does
65//! take precedence over `in_progress` while any job is still waiting.
66//!
67//! That observation is what makes `status=queued` the *primary* signal, and it
68//! is not what makes it sufficient. The case it does not cover is a job that
69//! becomes queued **later**: `needs:` holds a job back until its dependency
70//! finishes, and whether GitHub flips the run's status back to `queued` at that
71//! moment is a claim about a state machine this project has not observed. A
72//! `needs:`-gated job is an ordinary workflow shape, and missing one entirely
73//! would be the same class of defect this module was just rewritten to fix.
74//!
75//! So `status=in_progress` is polled too, as a **safety net rather than a second
76//! primary signal**, and it is budgeted like one: it is read after the queued
77//! runs and gets the smaller of the two run caps
78//! ([`MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL`] against
79//! [`MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL`]). A run appears in at most one of
80//! the two lists — the queries are disjoint by construction — and only jobs
81//! whose own `status` is `queued` are counted, so an in-progress run whose jobs
82//! have all been dispatched contributes nothing but the request that discovered
83//! that.
84//!
85//! `completed` and `waiting` runs are not polled. A completed run has no
86//! dispatchable job left, and a `waiting` run is held by a deployment gate or a
87//! concurrency group rather than by the absence of a runner — starting one for
88//! it would produce a runner that idles until its timeout.
89//!
90//! # Routing labels ARE applied now, and the predicate is still `b1`'s
91//!
92//! The previous decision's second accepted cost was that **no routing-label
93//! filtering happened at all**: a run carries no `runs-on`, labels live on jobs,
94//! and this module fetched no jobs. Every queued run in a watched repository
95//! counted, including runs whose jobs targeted `ubuntu-latest` or another host's
96//! `rm-<host>-…` label, and each runner started that way idled until it timed
97//! out.
98//!
99//! Fetching the jobs supplies the input that was missing, so that cost is paid
100//! back by the same change. **This module still owns no predicate.** It reads
101//! each job's `labels` array, builds a [`RunsOn`] from it, and hands that to the
102//! caller. `b1` owns the matching
103//! ([`runner_manager_domain::policy::RoutingLabels::matches`] and its `tally`),
104//! `e1` owns applying it per policy, and
105//! `tests::the_runs_on_predicate_is_b1s_and_this_module_only_feeds_it` scans
106//! this file's own source to pin that no second implementation grows here.
107//!
108//! The filtering is deliberately **not** done in this module even though it now
109//! has the input, and the reason is `e1`'s: one target can be watched by more
110//! than one policy, each with its own routing labels, and `e1` polls a target
111//! once for all of them. A gateway that filtered would have to be told whose
112//! labels to filter by, which would make the poll per-policy and multiply its
113//! request cost by the number of policies sharing the target. So the gateway
114//! returns the jobs and each policy tallies them.
115//!
116//! # What is still approximate, stated plainly rather than left to be discovered
117//!
118//! * **A job listing is a snapshot.** A job that leaves the queue between the
119//!   run list and the job list is counted; one that arrives after is not. The
120//!   next poll corrects both, and `e1`'s per-policy `active_owned` term stops a
121//!   job already being served from being served twice.
122//! * **The run caps make a large queue a floor.** Past
123//!   [`MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL`] the count is a *floor* rather
124//!   than a total, reported through [`QueuedDemand::is_truncated`]. Scaling up
125//!   from a floor is safe and successive polls converge; concluding "idle" from
126//!   one is not, which is why the floor is expressible at all.
127//! * **`runs-on` is not always resolvable.** `runs-on: ${{ matrix.runner }}` can
128//!   only be evaluated by GitHub. `b1` reports those as
129//!   [`runner_manager_domain::policy::UnresolvableRunsOn`] and they are neither
130//!   counted as demand nor silently dropped.
131//!
132//! # There is no job reservation, and nothing here may pretend otherwise
133//!
134//! The scale-set model's `AcquireJobs` has no REST equivalent
135//! (`d17-user-to-server-scale-set-chain.md`), so demand is **advisory**: another
136//! host may take a job this host has already started a runner for
137//! (`01-current-architecture.md`, edge case 6).
138//!
139//! **Do not add a claim, a lease, a local reservation table, or an
140//! acknowledgement call to compensate.** No such call exists in this crate, and
141//! `b1`'s, `e1`'s and this task's specifications all say so independently
142//! because implementers keep reaching for one. The bounding controls are the
143//! host-scoped labels in `b1` and the two capacity ceilings in `e1`; a local
144//! lease would coordinate this host with itself and with nothing else, which is
145//! the one thing the problem does not need.
146
147use std::{
148    collections::{BTreeMap, BTreeSet},
149    fmt,
150    sync::{
151        Arc, Mutex,
152        atomic::{AtomicU64, Ordering},
153    },
154    time::Duration,
155};
156
157use runner_manager_domain::{
158    model::{Clock, OwnerRepo, TargetScope, Timestamp},
159    policy::RunsOn,
160};
161use serde::Deserialize;
162
163use crate::{
164    ApiRequest, AuthenticatedClient, GithubError,
165    conditional::{ConditionalCache, Fetched},
166    rest::{
167        ActivityScope, CancelToken, DEFAULT_RATE_LIMIT_BACKOFF, InventoryError,
168        MAX_RATE_LIMIT_BACKOFF, PER_PAGE, RateLimitKind, RateLimited, TargetCost,
169        UnavailableRepository,
170    },
171    traffic::RateLimitSnapshot,
172};
173
174// ---------------------------------------------------------------------------
175// Constants
176// ---------------------------------------------------------------------------
177
178/// The `status` filter that selects runs with a job that may still be waiting.
179///
180/// Stated as a constant rather than inlined because it is the whole difference
181/// between this module and `c3`'s activity count, and a one-word typo here
182/// produces a plausible-looking number rather than an error.
183pub const QUEUED_RUN_STATUS: &str = "queued";
184
185/// The `status` filter for the safety-net pass over runs already under way.
186///
187/// Not a second primary signal. The module documentation states what it covers
188/// that [`QUEUED_RUN_STATUS`] does not — a `needs:`-gated job entering the queue
189/// after its run has already started — and why the difference is not something
190/// this project has observed its way out of needing.
191pub const IN_PROGRESS_RUN_STATUS: &str = "in_progress";
192
193/// The job `status` that means "waiting for a runner that does not exist yet".
194///
195/// This is the value the whole module reduces to. A job in any other state
196/// either has a runner or has finished with one, and counting it would start a
197/// runner for work already being done — the same mistake as reading `c3`'s
198/// in-progress count as demand, one level down.
199pub const QUEUED_JOB_STATUS: &str = "queued";
200
201/// The `filter` for the jobs endpoint: the latest attempt of each job only.
202///
203/// The default is `latest`, and it is sent explicitly because the alternative,
204/// `all`, returns every attempt of every re-run. Under `all` a job re-run three
205/// times contributes three entries, and the two that are historical would be
206/// counted as present demand.
207pub const LATEST_JOBS_FILTER: &str = "latest";
208
209/// Requests one demand poll costs, **per repository**, in steady state.
210///
211/// Four: the two run listings ([`QUEUED_RUN_STATUS`] and
212/// [`IN_PROGRESS_RUN_STATUS`]), plus a job listing for each of the couple of
213/// runs a repository has under way at any moment.
214///
215/// # Why this is a projection and not a measurement, and what bounds it
216///
217/// Under the previous owner decision this constant was `1` and it was exact: one
218/// request per repository, always, because `total_count` on the runs query
219/// answered the whole question. Counting jobs makes the cost depend on how many
220/// runs are active, which is a number no constant can know. So this is the
221/// steady-state figure the budget model prices, in the same spirit as
222/// [`crate::rest::ACTIVITY_REQUESTS_PER_REPOSITORY_PER_REFRESH`], which is also
223/// a best case with a documented worse one.
224///
225/// The **worst** case is `2 + MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL +
226/// MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL`, which is what
227/// [`max_demand_requests_per_repository_per_poll`] returns, and it is bounded by
228/// construction rather than by hope: the two caps are hard, and a repository
229/// that reaches them says so through [`QueuedDemand::is_truncated`] rather than
230/// spending more. [`crate::rest::BUDGET_SHARE_DIVISOR`] absorbs the gap between
231/// the two figures — the projection is compared against half the documented
232/// ceiling precisely so that the half nobody models has somewhere to go.
233///
234/// A repository is only at the worst case while it genuinely has that many runs
235/// in flight, which is also exactly when spending requests to scale correctly is
236/// worth more than saving them.
237pub const DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL: u32 = 4;
238
239/// The most `status=queued` runs one repository's job listing may resolve per
240/// poll.
241///
242/// The primary signal gets the larger cap. Past it the reported count is a
243/// **floor** rather than a total, which is safe in the direction that matters:
244/// `e1` clamps demand to `max_capacity` and the host ceiling anyway, so a
245/// repository with more than this many queued runs is one whose real demand
246/// exceeds any realistic host's capacity — the allocation is already pinned at
247/// the ceiling and a larger number would not change it. Successive polls resolve
248/// the rest as the earlier runs drain.
249pub const MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL: usize = 6;
250
251/// The most `status=in_progress` runs one repository's job listing may resolve
252/// per poll.
253///
254/// Smaller than [`MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL`] on purpose: this
255/// pass exists to catch a `needs:`-gated job whose run has already started, and
256/// on the overwhelmingly common shape it finds nothing and costs one request per
257/// run to discover that. Giving the safety net the same budget as the primary
258/// signal would double the worst case to buy a rarer case.
259pub const MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL: usize = 4;
260
261/// The most pages of jobs one run's listing may walk.
262///
263/// A run's job count is bounded by GitHub's own matrix limit of 256, so two
264/// pages at [`PER_PAGE`] cover every legal run with room to spare. The third is
265/// there because a `Link: rel="next"` chain that does not terminate is a
266/// runaway, and this walk is charged against a budget.
267pub const MAX_JOB_PAGES_PER_RUN: usize = 3;
268
269/// The ceiling on what one repository's demand poll may spend.
270///
271/// Stated as a function rather than a constant because it is the sum of three
272/// constants and a reader checking the budget arithmetic should not have to
273/// re-add them — and because `f1` and `f2` render the worst case beside the
274/// projection.
275#[must_use]
276pub const fn max_demand_requests_per_repository_per_poll() -> u32 {
277    // The two run listings, then one job listing per run each cap admits.
278    2 + (MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL as u32)
279        + (MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL as u32)
280}
281
282// A poll that costs nothing is a poll that issued no request, and a budget line
283// of zero would let `f2` admit an unbounded number of targets.
284const _: () = assert!(
285    DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL > 0,
286    "a demand poll costs at least the requests that fetched the run lists"
287);
288
289// The projection has to sit inside the bound, or the bound is not a bound. This
290// is a compile-time check rather than a test because the two numbers drifting
291// apart is the defect itself rather than a symptom of one: a projection above
292// the ceiling would have `f2` refuse configurations that cannot occur, and the
293// arithmetic that produced it would look deliberate.
294const _: () = assert!(
295    DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL <= max_demand_requests_per_repository_per_poll(),
296    "the projected demand cost must fit inside the worst case the caps allow"
297);
298
299// The projection must also cover the two run listings, which every poll issues
300// unconditionally. A projection below that floor would under-price even a
301// completely idle repository, which is the one case the model must get exactly
302// right: it is what `f1`'s printed ceiling and `f2`'s `add` refusals are
303// computed from.
304const _: () = assert!(
305    DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL >= 2,
306    "every poll issues both run listings, so the projection cannot be below two"
307);
308
309// The safety net must not outgrow the signal it is backing up. If these ever
310// invert, the cheaper `in_progress` pass would be resolving more runs than the
311// `queued` pass that actually carries the demand.
312const _: () = assert!(
313    MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL <= MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL,
314    "the in-progress safety net may not be given a larger budget than the primary signal"
315);
316
317/// How far GitHub's `total_count` may exceed the single page it arrived with
318/// before the disagreement stops being a race and starts being evidence.
319///
320/// `c3` states the reasoning in full at its own `MAX_BENIGN_TOTAL_COUNT_SKEW`,
321/// which is private to `crates/github/src/rest.rs`; the value is repeated rather
322/// than shared because this task does not own that file. The short form:
323///
324/// * A run leaving the queue between GitHub computing `total_count` and
325///   serialising the page makes `total` exceed `listed` by a handful. That race
326///   is documented and legitimate, and a debug build pointed at live GitHub is
327///   the build most likely to meet it.
328/// * The defect being hunted — `total_count` carrying the repository's
329///   *unfiltered* lifetime total — is gross: thousands over a page of three.
330///
331/// # This is now a consistency check rather than a load-bearing one
332///
333/// Under the previous owner decision `total_count` **was** the demand number,
334/// and being wrong about it started the wrong number of runners. It no longer
335/// reaches `clamp()`: demand is counted from the jobs, and `total_count` is read
336/// only to notice that a repository has more runs than the caps will resolve.
337/// So the check stays — it is free, and `c3` reads the same envelope for a
338/// dashboard number — but it is a `warn!` and no longer a `debug_assert!`.
339/// Panicking a development build over a field the decision no longer depends on
340/// would be a tripwire that cries wolf, and those get deleted.
341const MAX_BENIGN_TOTAL_COUNT_SKEW: u64 = 16;
342
343// A zero skew is `total == listed` again, which fires on a run leaving the queue
344// mid-serialisation. At compile time rather than in a test because a test
345// deriving its fixture from this constant moves with it and stays green at zero.
346const _: () = assert!(
347    MAX_BENIGN_TOTAL_COUNT_SKEW > 0,
348    "a zero skew re-creates the check that trips on a run leaving the queue mid-serialisation"
349);
350
351// ---------------------------------------------------------------------------
352// The demand reading
353// ---------------------------------------------------------------------------
354
355/// Queued **jobs**, per repository, each carrying the `runs-on` it requires.
356///
357/// **This is a count of jobs, not of runs, and it is not filtered by any
358/// policy's routing labels — but it carries everything needed to filter it.**
359/// Both facts are the module documentation's subject and are repeated on the
360/// type because this is what a caller holds.
361///
362/// The unfiltered totals ([`QueuedDemand::total`],
363/// [`QueuedDemand::for_repository`]) are the raw queue depth, which is what `g2`
364/// renders for an operator: "what is waiting in this repository", independent of
365/// which host could serve it. The number `e1` clamps is **not** either of those.
366/// It comes from tallying [`QueuedDemand::jobs_for`] against one policy's
367/// routing labels, and the difference between the two is exactly the jobs this
368/// host cannot serve.
369///
370/// # A count can be short in two different ways, and both have to say so
371///
372/// A repository can fail to answer at all ([`QueuedDemand::unavailable`]), and a
373/// repository can answer with a number that is only a **floor**
374/// ([`QueuedDemand::truncated`]) — more runs were active than
375/// [`MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL`] and
376/// [`MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL`] allow resolving, or one
377/// run's job listing walked to [`MAX_JOB_PAGES_PER_RUN`].
378/// [`QueuedDemand::is_complete`] is `false` for either.
379///
380/// The shape mirrors [`crate::rest::ActivityCount`] deliberately, down to the
381/// method names, because `g2` renders the two side by side and a caller that has
382/// learned one should not have to learn the other. They stay separate types for
383/// the reason `c3` keeps the busy-runner count and the in-progress count apart:
384/// a type that can hold either number is a type that will eventually add them.
385#[derive(Debug, Clone, PartialEq, Eq, Default)]
386pub struct QueuedDemand {
387    per_repository: BTreeMap<OwnerRepo, Vec<RunsOn>>,
388    unavailable: Vec<UnavailableRepository>,
389    /// Repositories whose count is a floor rather than a total.
390    truncated: BTreeSet<OwnerRepo>,
391    /// Repositories with runs under way whose listings **changed** since the
392    /// previous poll. See [`QueuedDemand::is_quiet`].
393    busy: BTreeSet<OwnerRepo>,
394    /// The account's hourly quota as GitHub reported it during this poll.
395    rate_limit: Option<RateLimitSnapshot>,
396}
397
398impl QueuedDemand {
399    #[must_use]
400    pub fn new(per_repository: BTreeMap<OwnerRepo, Vec<RunsOn>>) -> Self {
401        Self {
402            per_repository,
403            unavailable: Vec::new(),
404            truncated: BTreeSet::new(),
405            busy: BTreeSet::new(),
406            rate_limit: None,
407        }
408    }
409
410    /// One repository's queued jobs, for the repository-target case and for
411    /// tests.
412    #[must_use]
413    pub fn of(repository: OwnerRepo, jobs: impl IntoIterator<Item = RunsOn>) -> Self {
414        Self::new(BTreeMap::from([(
415            repository,
416            jobs.into_iter().collect::<Vec<_>>(),
417        )]))
418    }
419
420    /// Record that `repository`'s count is a floor rather than a total.
421    #[must_use]
422    pub fn with_truncated(mut self, repository: OwnerRepo) -> Self {
423        self.truncated.insert(repository);
424        self
425    }
426
427    /// Record that `repository` has runs under way whose listings changed.
428    #[must_use]
429    pub fn with_busy(mut self, repository: OwnerRepo) -> Self {
430        self.busy.insert(repository);
431        self
432    }
433
434    /// Attach the hourly-quota reading GitHub sent during this poll.
435    #[must_use]
436    pub const fn with_rate_limit(mut self, rate_limit: Option<RateLimitSnapshot>) -> Self {
437        self.rate_limit = rate_limit;
438        self
439    }
440
441    /// Whether nothing is happening in any repository this poll read.
442    ///
443    /// A repository is quiet when it had **no run under way**, or when every
444    /// listing it took to find out was answered `304 Not Modified`. The second
445    /// half matters: a run stuck in the queue for a label no host serves stays
446    /// in the listing for hours, and treating that as activity would hold the
447    /// whole target at the slower active interval for no reason, when its
448    /// listings cost nothing while they do not change.
449    ///
450    /// `e1` polls a quiet target at the host's *idle* interval. That is the
451    /// moment latency matters most, because work arrives after idle, and the
452    /// moment polling is free, because every answer is a `304`.
453    #[must_use]
454    pub fn is_quiet(&self) -> bool {
455        // An unavailable repository is not quiet either: its failing listing
456        // is not cached, so every poll of it is a charged request, and an
457        // idle interval would multiply that by six.
458        self.busy.is_empty() && self.unavailable.is_empty()
459    }
460
461    /// The account's hourly quota as GitHub reported it during this poll.
462    ///
463    /// Every response carries it, a `304` included, and it describes every
464    /// client signed in as the same user, so it is what `e1` slows down on.
465    #[must_use]
466    pub const fn rate_limit(&self) -> Option<&RateLimitSnapshot> {
467        self.rate_limit.as_ref()
468    }
469
470    /// Record that `repository` could not be read at all, and why.
471    ///
472    /// Deliberately **not** the same as a count of zero: nothing was learned
473    /// about it, and a zero would render a possibly-busy repository as idle.
474    #[must_use]
475    pub fn with_unavailable(mut self, repository: OwnerRepo, reason: impl Into<String>) -> Self {
476        self.unavailable.push(UnavailableRepository {
477            repository,
478            reason: reason.into(),
479        });
480        self
481    }
482
483    /// Queued jobs across every repository that answered, **unfiltered**.
484    ///
485    /// The raw queue depth, not the demand any one policy should serve. See the
486    /// type documentation for the distinction, which is the whole reason
487    /// [`QueuedDemand::jobs`] exists beside this.
488    ///
489    /// Saturating rather than wrapping: a total wider than a `u32` is not a
490    /// number to wrap around zero, and `u32::MAX` runners is refused by the
491    /// capacity ceilings long before it means anything.
492    #[must_use]
493    pub fn total(&self) -> u32 {
494        self.per_repository.values().fold(0_u32, |sum, jobs| {
495            sum.saturating_add(u32::try_from(jobs.len()).unwrap_or(u32::MAX))
496        })
497    }
498
499    #[must_use]
500    pub fn per_repository(&self) -> &BTreeMap<OwnerRepo, Vec<RunsOn>> {
501        &self.per_repository
502    }
503
504    /// One repository's unfiltered count, or `None` when it did not answer.
505    #[must_use]
506    pub fn for_repository(&self, repository: &OwnerRepo) -> Option<u32> {
507        self.per_repository
508            .get(repository)
509            .map(|jobs| u32::try_from(jobs.len()).unwrap_or(u32::MAX))
510    }
511
512    /// One repository's queued jobs, as the `runs-on` each requires.
513    ///
514    /// This is the input `b1`'s predicate was written for and never had. An
515    /// empty slice for a repository that answered means it really is idle; a
516    /// repository that did not answer is in [`QueuedDemand::unavailable`]
517    /// instead, and the two must not be conflated.
518    #[must_use]
519    pub fn jobs_for(&self, repository: &OwnerRepo) -> &[RunsOn] {
520        self.per_repository
521            .get(repository)
522            .map_or(&[], Vec::as_slice)
523    }
524
525    /// Every queued job across every repository that answered.
526    ///
527    /// What an organization target tallies, for the reason a repository target
528    /// tallies [`QueuedDemand::jobs_for`]: one policy watching an organization
529    /// serves any repository in it, so its demand is the whole scope's.
530    pub fn jobs(&self) -> impl Iterator<Item = &RunsOn> {
531        self.per_repository.values().flat_map(Vec::as_slice)
532    }
533
534    #[must_use]
535    pub fn unavailable(&self) -> &[UnavailableRepository] {
536        &self.unavailable
537    }
538
539    #[must_use]
540    pub fn truncated(&self) -> &BTreeSet<OwnerRepo> {
541        &self.truncated
542    }
543
544    #[must_use]
545    pub fn is_truncated(&self, repository: &OwnerRepo) -> bool {
546        self.truncated.contains(repository)
547    }
548
549    /// Whether every repository in scope answered with an exact count.
550    ///
551    /// `false` means the total is a **floor**. Scaling *up* from a floor is
552    /// safe; concluding "idle" from one is not, which is the mistake this exists
553    /// to make expressible.
554    #[must_use]
555    pub fn is_complete(&self) -> bool {
556        self.unavailable.is_empty() && self.truncated.is_empty()
557    }
558}
559
560/// Requests one demand poll over `scope` costs, in steady state.
561///
562/// Grows with the repository count, because there is no organization-wide
563/// workflow-runs endpoint and an organization therefore pays per repository the
564/// App is installed on. That growth *is* the product constraint after D4: every
565/// added repository multiplies this policy's share of the shared hourly ceiling.
566#[must_use]
567pub fn demand_requests_per_poll(scope: &ActivityScope) -> u32 {
568    u32::try_from(scope.repositories().len())
569        .unwrap_or(u32::MAX)
570        .saturating_mul(DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL)
571}
572
573/// The most requests one demand poll over `scope` may spend.
574///
575/// The companion to [`demand_requests_per_poll`], and the number a reader should
576/// be shown when they ask why a busy hour cost more than the projection. See
577/// [`DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL`] for why the model prices the
578/// steady state and bounds the peak rather than trying to price the peak.
579#[must_use]
580pub fn max_demand_requests_per_poll(scope: &ActivityScope) -> u32 {
581    u32::try_from(scope.repositories().len())
582        .unwrap_or(u32::MAX)
583        .saturating_mul(max_demand_requests_per_repository_per_poll())
584}
585
586/// `scope`'s budget cost with this module's demand figure substituted for
587/// `c3`'s estimate.
588///
589/// This is the reporting seam `c4`'s specification requires — "report the
590/// per-poll request count to `c3`'s budget model rather than estimating it
591/// there" — and [`TargetCost::with_demand_requests_per_repository`] is where
592/// `c3` left it open. Callers that project a budget (`f1`'s `host show`, `f2`'s
593/// `repo add` and `org add`, `g3`'s settings) should build their
594/// [`TargetCost`] through this function rather than through
595/// [`TargetCost::from_activity_scope`] directly.
596#[must_use]
597pub fn target_cost(scope: &ActivityScope) -> TargetCost {
598    TargetCost::from_activity_scope(scope)
599        .with_demand_requests_per_repository(DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL)
600}
601
602// ---------------------------------------------------------------------------
603// The gateway
604// ---------------------------------------------------------------------------
605
606/// The demand read model.
607///
608/// A trait for [`crate::rest::InventoryGateway`]'s reason: `e1` and `g2` are
609/// tested against `runner_manager_testkit::github::FakeGithub` with no network
610/// and no `wiremock` in their dependency graphs. [`RestDemand`] is the one
611/// implementation that talks to GitHub.
612///
613/// # Why the scope type is `c3`'s `ActivityScope` and not a new one
614///
615/// The name says "activity" and this is demand, so the reuse is worth
616/// justifying rather than leaving to look like an oversight.
617///
618/// [`ActivityScope`] is not a description of the in-progress count; it is the
619/// answer to "which repositories does one per-repository workflow-runs
620/// aggregate cover", and demand asks that question with exactly the same
621/// answer. Both hit `/repos/{o}/{r}/actions/runs`, both have no
622/// organization-wide form, and both take the repository list from the same
623/// caller-held set — `c3` documents that the list "has to come from the caller,
624/// \[because\] `f1` and `e1` already hold it, from
625/// [`crate::AuthenticatedClient::discover_installations`], and re-discovering it
626/// on every refresh would cost more requests than the count itself".
627///
628/// A `DemandScope` beside it would be that type with a different name, and the
629/// cost of the duplicate is concrete rather than aesthetic: `e1` polls both read
630/// models in one refresh, and two scope types are two chances for them to
631/// disagree about which repositories are in scope — which would make the demand
632/// total and the activity total describe different sets while being rendered
633/// side by side. What is *not* shared is the cost function:
634/// [`ActivityScope::requests_per_refresh`] prices the activity count, and
635/// [`demand_requests_per_poll`] prices this one, because those really are two
636/// different numbers.
637#[async_trait::async_trait]
638pub trait DemandGateway: fmt::Debug + Send + Sync {
639    /// Queued workflow runs across `scope`.
640    ///
641    /// # Errors
642    /// Every variant of [`InventoryError`].
643    async fn queued_demand(
644        &self,
645        scope: &ActivityScope,
646        cancel: &CancelToken,
647    ) -> Result<QueuedDemand, InventoryError>;
648
649    /// The instant a reading is stamped with.
650    fn now(&self) -> Timestamp;
651}
652
653/// One gateway shared by every target loop on a host. Sharing is what lets
654/// [`RestDemand`] read a repository once for every target that covers it, and
655/// silence every loop at once inside a rate-limit quiet period.
656#[async_trait::async_trait]
657impl<T: DemandGateway + ?Sized> DemandGateway for Arc<T> {
658    async fn queued_demand(
659        &self,
660        scope: &ActivityScope,
661        cancel: &CancelToken,
662    ) -> Result<QueuedDemand, InventoryError> {
663        (**self).queued_demand(scope, cancel).await
664    }
665
666    fn now(&self) -> Timestamp {
667        (**self).now()
668    }
669}
670
671/// [`DemandGateway`] over `api.github.com`.
672///
673/// Holds no credential of its own: authentication is entirely
674/// [`AuthenticatedClient`]'s, and this type only ever hands it an
675/// [`ApiRequest`].
676///
677/// # Why this is not a method on `c3`'s `RestInventory`
678///
679/// It would be the better shape, and it is not available. `RestInventory::get`
680/// — the one place cancellation, request accounting and the rate-limit gate meet
681/// — is private to `crates/github/src/rest.rs`, and a sibling module cannot
682/// reach a private item. Making it `pub(crate)` is an edit to `c3`'s file, which
683/// this task does not own, so the choice was between duplicating `c3`'s whole
684/// rate-limit *policy* here and consuming what `c3` already exports. This
685/// consumes.
686///
687/// # What "consuming `c3`'s rate-limit policy" means precisely
688///
689/// [`RateLimited::detect`] is `c3`'s decision procedure for whether a failure is
690/// a rate limit and which of GitHub's two it is, including the part that keeps a
691/// permissions `403` landing on an exhausted quota from being misreported as
692/// one. It is public, and this module calls it rather than re-deciding.
693///
694/// What this module deliberately does **not** copy is `c3`'s in-gateway
695/// *back-off latch*, the window during which `RestInventory` opens no socket at
696/// all. A second latch would be a second, quietly divergent copy of a policy
697/// that only works if there is one of it. The scheduling floor is
698/// [`crate::rest::RefreshState::retry_delay`], which `c3` documents as "the
699/// **absolute floor** on when `e1` may try again" — an `e1` honouring it stops
700/// demand polling for the same window, from the layer that owns the schedule.
701///
702/// The residual gap is stated rather than hidden: a rate limit whose *first*
703/// evidence arrives on a demand request does not silence `RestInventory`, and
704/// vice versa. Both report [`InventoryError::RateLimited`] to `e1`, which is the
705/// layer that can act on either.
706pub struct RestDemand {
707    client: Arc<AuthenticatedClient>,
708    clock: Arc<dyn Clock>,
709    requests_issued: AtomicU64,
710    /// Every listing's `ETag` and body, so a repeat poll can be answered `304`.
711    conditional: ConditionalCache,
712    /// One repository's reading, shared between every target that covers it.
713    shared: SharedReadings,
714    /// The host-wide quiet period after GitHub said "rate limited".
715    hold: Mutex<Option<RateLimitHold>>,
716    stats: PollCounters,
717}
718
719/// A repository's reading, handed to every target that asks for it within a
720/// window.
721///
722/// # Why: one poll per repository, not one per target
723///
724/// The daemon runs one loop per target, and two targets can cover the same
725/// repository: an organization target and a repository target inside it.
726/// Each loop used to poll for itself. With one `RestDemand` shared by every
727/// loop on the host and a window here, a repository is read **once** per
728/// window however many targets, policies and profiles want it, and the others
729/// are handed that reading.
730///
731/// A zero window, the default, shares nothing: every call reads GitHub. That
732/// is what a single-target caller and the tests of the reading itself want.
733struct SharedReadings {
734    /// The window, in milliseconds. Atomic so the daemon can change it when
735    /// the host's idle interval changes, without stopping a loop.
736    window_ms: AtomicU64,
737    /// Pruned of readings older than [`HOLD_MEMORY`] on every insert.
738    readings: Mutex<BTreeMap<OwnerRepo, (Timestamp, RepositoryDemand)>>,
739    /// One gate per repository, so two loops asking at once make one request
740    /// between them.
741    gates: Mutex<BTreeMap<OwnerRepo, Arc<tokio::sync::Mutex<()>>>>,
742}
743
744/// How long an ended rate-limit hold is still remembered as part of the same
745/// episode, and how long an unused shared reading is kept.
746const HOLD_MEMORY: Duration = Duration::from_secs(60 * 60);
747
748/// The rate-limit quiet period, host-wide.
749#[derive(Debug, Clone, Copy)]
750struct RateLimitHold {
751    until: Timestamp,
752    limit: RateLimited,
753    /// Secondary limits in a row. GitHub: "If your request continues to fail
754    /// due to a secondary rate limit, wait for an exponentially increasing
755    /// amount of time between retries."
756    consecutive_secondary: u32,
757}
758
759#[derive(Debug, Default)]
760struct PollCounters {
761    reads: AtomicU64,
762    unchanged_reads: AtomicU64,
763    shared_reads: AtomicU64,
764    suppressed: AtomicU64,
765}
766
767/// What [`RestDemand`] has done, for `status` and `doctor`.
768#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
769pub struct DemandStats {
770    /// Repository readings fetched from GitHub.
771    pub reads: u64,
772    /// Of those, readings where every listing came back `304`.
773    pub unchanged_reads: u64,
774    /// Readings handed to another target instead of being fetched again.
775    pub shared_reads: u64,
776    /// Polls answered "rate limited" without a request, inside the host-wide
777    /// quiet period.
778    pub suppressed: u64,
779}
780
781impl fmt::Debug for RestDemand {
782    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
783        // Hand-written for the reason `AuthenticatedClient`'s own `Debug`
784        // records: nothing here may render a credential, and a derive on a type
785        // holding a client is how that is lost.
786        f.debug_struct("RestDemand")
787            .field(
788                "requests_issued",
789                &self.requests_issued.load(Ordering::Relaxed),
790            )
791            .finish_non_exhaustive()
792    }
793}
794
795impl RestDemand {
796    #[must_use]
797    pub fn new(client: Arc<AuthenticatedClient>, clock: Arc<dyn Clock>) -> Self {
798        Self {
799            conditional: ConditionalCache::new(Arc::clone(&clock)),
800            client,
801            clock,
802            requests_issued: AtomicU64::new(0),
803            shared: SharedReadings {
804                window_ms: AtomicU64::new(0),
805                readings: Mutex::new(BTreeMap::new()),
806                gates: Mutex::new(BTreeMap::new()),
807            },
808            hold: Mutex::new(None),
809            stats: PollCounters::default(),
810        }
811    }
812
813    /// Hand a repository's reading to every target that asks within `window`
814    /// of it being fetched. See [`SharedReadings`].
815    ///
816    /// The daemon passes its idle interval: a repository is then read at most
817    /// once per idle interval, and a target sharing it sees a reading no older
818    /// than that.
819    #[must_use]
820    pub fn with_shared_readings(self, window: Duration) -> Self {
821        self.set_shared_window(window);
822        self
823    }
824
825    /// Change the sharing window while running.
826    pub fn set_shared_window(&self, window: Duration) {
827        self.shared.window_ms.store(
828            u64::try_from(window.as_millis()).unwrap_or(u64::MAX),
829            Ordering::SeqCst,
830        );
831    }
832
833    /// Drops `repository`'s shared reading, so the next target to ask for it
834    /// reads GitHub instead of being handed a reading from before.
835    ///
836    /// For a coordinator's wake: GitHub just said this repository's queue
837    /// changed, so a reading shared from a few seconds ago is known stale.
838    /// Nothing else is bypassed — the conditional cache still makes an
839    /// unchanged listing a free `304`, and the rate-limit quiet period still
840    /// withholds every request inside it.
841    pub fn forget_shared_reading(&self, repository: &OwnerRepo) {
842        self.shared
843            .readings
844            .lock()
845            .unwrap_or_else(std::sync::PoisonError::into_inner)
846            .remove(repository);
847    }
848
849    /// The window readings are shared for.
850    fn shared_window(&self) -> Duration {
851        Duration::from_millis(self.shared.window_ms.load(Ordering::SeqCst))
852    }
853
854    /// What this gateway has done.
855    #[must_use]
856    pub fn stats(&self) -> DemandStats {
857        DemandStats {
858            reads: self.stats.reads.load(Ordering::SeqCst),
859            unchanged_reads: self.stats.unchanged_reads.load(Ordering::SeqCst),
860            shared_reads: self.stats.shared_reads.load(Ordering::SeqCst),
861            suppressed: self.stats.suppressed.load(Ordering::SeqCst),
862        }
863    }
864
865    /// The client every request goes through, for its traffic counters.
866    #[must_use]
867    pub const fn client(&self) -> &Arc<AuthenticatedClient> {
868        &self.client
869    }
870
871    /// The rate limit still being waited out, with the time left on it.
872    fn held(&self, now: Timestamp) -> Option<RateLimited> {
873        let hold = (*self
874            .hold
875            .lock()
876            .unwrap_or_else(std::sync::PoisonError::into_inner))?;
877        let left = hold
878            .until
879            .signed_duration_since(now)
880            .to_std()
881            .ok()?
882            // A clock that jumped backwards must not stretch the hold past
883            // the longest one this gateway ever sets.
884            .min(MAX_RATE_LIMIT_BACKOFF);
885        if left.is_zero() {
886            return None;
887        }
888        Some(RateLimited {
889            retry_after: Some(left),
890            ..hold.limit
891        })
892    }
893
894    /// Start, or lengthen, the host-wide quiet period for `limit`, and say
895    /// how long it is.
896    ///
897    /// # Why a quiet period here, when `e1` already waits
898    ///
899    /// `e1`'s schedule waits per loop, and the daemon runs one loop per
900    /// target. A secondary limit hit by one target's poll used to leave every
901    /// other target's loop polling on its own schedule, which is exactly the
902    /// "continuing to make requests while you are rate limited" GitHub warns
903    /// "may result in the banning of your integration"
904    /// (<https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api#handle-rate-limit-errors-appropriately>).
905    /// Every loop shares this gateway, so a quiet period here silences them
906    /// all.
907    ///
908    /// The wait is GitHub's own: `retry-after` when sent, else until
909    /// `x-ratelimit-reset` for the primary limit, else one minute. A secondary
910    /// limit that recurs doubles it each time, up to
911    /// [`MAX_RATE_LIMIT_BACKOFF`], which is GitHub's "exponentially increasing
912    /// amount of time between retries".
913    fn hold_for(&self, limit: RateLimited, now: Timestamp) -> RateLimited {
914        let mut hold = self
915            .hold
916            .lock()
917            .unwrap_or_else(std::sync::PoisonError::into_inner);
918        // A hold that ended long ago is not part of this episode: a secondary
919        // limit days after the last one starts from one minute again, even if
920        // nothing but errors came back in between.
921        let previous = (*hold).filter(|previous| {
922            now.signed_duration_since(previous.until)
923                < chrono::TimeDelta::from_std(HOLD_MEMORY).unwrap_or(chrono::TimeDelta::MAX)
924        });
925        // The doubling counts EPISODES, not answers. Every target loop shares
926        // this gateway, so one secondary limit can come back on several
927        // requests that were in flight together; each of those is the same
928        // limit, and only an answer arriving after the previous hold ended is
929        // GitHub saying "still limited".
930        let live = previous.filter(|previous| previous.until > now);
931        let consecutive_secondary = match (limit.kind, previous, live) {
932            (RateLimitKind::Primary, _, _) => 0,
933            (RateLimitKind::Secondary, _, Some(live)) => live.consecutive_secondary.max(1),
934            (RateLimitKind::Secondary, Some(previous), None) => {
935                previous.consecutive_secondary.saturating_add(1)
936            }
937            (RateLimitKind::Secondary, None, None) => 1,
938        };
939        let mut wait = limit.delay_from(now);
940        if consecutive_secondary > 1 {
941            let doubled = DEFAULT_RATE_LIMIT_BACKOFF
942                .saturating_mul(1_u32 << (consecutive_secondary - 1).min(10));
943            wait = wait.max(doubled).min(MAX_RATE_LIMIT_BACKOFF);
944        }
945        let mut until = now
946            .checked_add_signed(chrono::TimeDelta::from_std(wait).unwrap_or(chrono::TimeDelta::MAX))
947            .unwrap_or(now);
948        // A later answer never SHORTENS a hold in force: a primary limit with
949        // a near reset must not reopen traffic a secondary limit closed.
950        if let Some(live) = live
951            && live.until > until
952        {
953            until = live.until;
954            wait = until.signed_duration_since(now).to_std().unwrap_or(wait);
955        }
956        *hold = Some(RateLimitHold {
957            until,
958            limit,
959            consecutive_secondary: consecutive_secondary
960                .max(live.map_or(0, |live| live.consecutive_secondary)),
961        });
962        RateLimited {
963            retry_after: Some(wait),
964            ..limit
965        }
966    }
967
968    /// A request went through: the next secondary limit starts the doubling
969    /// again from one minute.
970    fn clear_hold(&self) {
971        let mut hold = self
972            .hold
973            .lock()
974            .unwrap_or_else(std::sync::PoisonError::into_inner);
975        if hold.is_some_and(|h| h.until <= self.clock.now()) {
976            *hold = None;
977        }
978    }
979
980    /// How many HTTP requests this gateway has issued.
981    ///
982    /// [`demand_requests_per_poll`] projects a cost and this measures it. A
983    /// projection nothing measures is a table in a document, which is why `c3`
984    /// exposes the same counter and why the tests below assert one against the
985    /// other.
986    #[must_use]
987    pub fn requests_issued(&self) -> u64 {
988        self.requests_issued.load(Ordering::SeqCst)
989    }
990
991    /// One request, with cancellation applied and a rate limit recognised.
992    ///
993    /// Cancellation is consulted twice for `c3`'s reason, and the two are not
994    /// redundant: [`CancelToken::check`] stops a multi-page walk *between*
995    /// pages, and [`CancelToken::run`] stops one already blocked on a socket.
996    ///
997    /// Every request is **conditional** once its listing has been seen: see
998    /// [`crate::conditional`]. And none is sent at all inside the host-wide
999    /// rate-limit quiet period; see [`Self::hold_for`].
1000    async fn get(
1001        &self,
1002        request: &ApiRequest,
1003        cancel: &CancelToken,
1004    ) -> Result<Fetched, InventoryError> {
1005        cancel.check()?;
1006        if let Some(limit) = self.held(self.clock.now()) {
1007            self.stats.suppressed.fetch_add(1, Ordering::SeqCst);
1008            return Err(InventoryError::RateLimited(limit));
1009        }
1010
1011        let result = cancel
1012            .run(async {
1013                // Counted inside the future, so the count is of requests
1014                // actually attempted: `run`'s biased `select!` answers
1015                // `Cancelled` without polling this block when the token is
1016                // already flipped, and no socket is opened.
1017                self.requests_issued.fetch_add(1, Ordering::SeqCst);
1018                self.conditional
1019                    .send(&self.client, request)
1020                    .await
1021                    .map_err(InventoryError::from)
1022            })
1023            .await;
1024        match result {
1025            Ok(fetched) => {
1026                self.clear_hold();
1027                Ok(fetched)
1028            }
1029            Err(InventoryError::Github(error)) => Err(self.classify(error)),
1030            Err(other) => Err(other),
1031        }
1032    }
1033
1034    /// Turn a failure into a rate limit when GitHub's own evidence says it is
1035    /// one, using `c3`'s decision procedure rather than a second one, and
1036    /// start the host-wide quiet period for it.
1037    fn classify(&self, error: GithubError) -> InventoryError {
1038        let Some(limit) = RateLimited::detect(&error) else {
1039            return InventoryError::Github(error);
1040        };
1041        let held = self.hold_for(limit, self.clock.now());
1042        tracing::warn!(
1043            kind = %limit.kind,
1044            remaining = limit.remaining,
1045            quiet_secs = held.retry_after.map_or(0, |wait| wait.as_secs()),
1046            "GitHub is rate limiting this credential; demand for this poll is unknown, not zero, \
1047             and no demand request leaves this host until the quiet period ends"
1048        );
1049        InventoryError::RateLimited(held)
1050    }
1051
1052    /// Queued **jobs** for one repository, each with the `runs-on` it requires.
1053    ///
1054    /// Two run listings, then one job listing per run either cap admits. See
1055    /// [`DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL`] for what that costs in steady
1056    /// state and [`max_demand_requests_per_repository_per_poll`] for the bound.
1057    ///
1058    /// # The order of the two passes is load-bearing
1059    ///
1060    /// Queued runs are resolved first and in-progress runs second, because the
1061    /// caps are spent in that order and the first pass carries the signal. A
1062    /// repository busy enough to exhaust the queued cap gets no in-progress pass
1063    /// at all, which is the right trade: its count is already a floor above any
1064    /// realistic host ceiling, and one more `needs:`-gated job cannot change the
1065    /// allocation.
1066    ///
1067    /// # Why a run is resolved at most once, though the two queries are disjoint
1068    ///
1069    /// They are disjoint *at any one instant*, and these are two requests with
1070    /// time between them. A run that is `queued` when the first is answered and
1071    /// `in_progress` when the second is — which is precisely what happens when
1072    /// its last waiting job gets picked up, so it is the common transition
1073    /// rather than an exotic one — appears in **both** lists. Listing its jobs
1074    /// twice would count every queued job it still holds twice, and demand that
1075    /// double-counts starts runners for work that does not exist.
1076    ///
1077    /// The seen set is what stops that. It is deliberately not an argument that
1078    /// the race is too narrow to matter: the window is one HTTP round trip
1079    /// against a poll that repeats every sixty seconds forever, and the failure
1080    /// it produces is silent inflation rather than an error.
1081    async fn repository_queued(
1082        &self,
1083        repository: &OwnerRepo,
1084        cancel: &CancelToken,
1085    ) -> Result<RepositoryDemand, InventoryError> {
1086        let mut jobs: Vec<RunsOn> = Vec::new();
1087        let mut exact = true;
1088        let mut changed = false;
1089        let mut resolved: BTreeSet<u64> = BTreeSet::new();
1090
1091        for (status, cap) in [
1092            (QUEUED_RUN_STATUS, MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL),
1093            (
1094                IN_PROGRESS_RUN_STATUS,
1095                MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL,
1096            ),
1097        ] {
1098            let listing = self.active_runs(repository, status, cap, cancel).await?;
1099            exact &= listing.complete;
1100            changed |= listing.changed;
1101
1102            for run_id in listing.run_ids {
1103                // A run that changed status between the two listings is in both.
1104                // Resolving it twice would double every queued job it holds.
1105                if !resolved.insert(run_id) {
1106                    continue;
1107                }
1108                let run = self.queued_jobs_of_run(repository, run_id, cancel).await?;
1109                exact &= run.complete;
1110                changed |= run.changed;
1111                jobs.extend(run.jobs);
1112            }
1113        }
1114
1115        self.stats.reads.fetch_add(1, Ordering::SeqCst);
1116        if !changed {
1117            self.stats.unchanged_reads.fetch_add(1, Ordering::SeqCst);
1118        }
1119        Ok(RepositoryDemand {
1120            jobs,
1121            exact,
1122            busy: changed && !resolved.is_empty(),
1123        })
1124    }
1125
1126    /// One repository's reading, from the shared window when another target
1127    /// fetched it recently enough, from GitHub otherwise.
1128    async fn repository_reading(
1129        &self,
1130        repository: &OwnerRepo,
1131        cancel: &CancelToken,
1132    ) -> Result<RepositoryDemand, InventoryError> {
1133        let window = self.shared_window();
1134        if window.is_zero() {
1135            return self.repository_queued(repository, cancel).await;
1136        }
1137        let gate = Arc::clone(
1138            self.shared
1139                .gates
1140                .lock()
1141                .unwrap_or_else(std::sync::PoisonError::into_inner)
1142                .entry(repository.clone())
1143                .or_default(),
1144        );
1145        // Held across the fetch, so a second loop asking for this repository
1146        // meanwhile waits for this reading instead of making its own request.
1147        let _gate = cancel.run(async { Ok(gate.lock().await) }).await?;
1148        let now = self.clock.now();
1149        let fresh = self
1150            .shared
1151            .readings
1152            .lock()
1153            .unwrap_or_else(std::sync::PoisonError::into_inner)
1154            .get(repository)
1155            .filter(|(at, _)| {
1156                now.signed_duration_since(*at)
1157                    .to_std()
1158                    .is_ok_and(|age| age < window)
1159            })
1160            .map(|(_, reading)| reading.clone());
1161        if let Some(reading) = fresh {
1162            self.stats.shared_reads.fetch_add(1, Ordering::SeqCst);
1163            return Ok(reading);
1164        }
1165        let reading = self.repository_queued(repository, cancel).await?;
1166        let mut readings = self
1167            .shared
1168            .readings
1169            .lock()
1170            .unwrap_or_else(std::sync::PoisonError::into_inner);
1171        readings.insert(repository.clone(), (now, reading.clone()));
1172        // A repository that left an organization's list stops being asked
1173        // for; its reading goes once nobody could use it.
1174        readings.retain(|_, (at, _)| {
1175            now.signed_duration_since(*at)
1176                .to_std()
1177                .is_ok_and(|age| age < HOLD_MEMORY)
1178        });
1179        Ok(reading)
1180    }
1181
1182    /// The ids of one repository's runs in `status`, up to `cap`.
1183    ///
1184    /// **One request, never a page walk.** Both caps are far below [`PER_PAGE`],
1185    /// so the first page always carries more run ids than this may use, and a
1186    /// second page could only contain runs that are already past the cap. That
1187    /// is the whole reason the caps are stated in *runs* rather than in pages:
1188    /// it turns the run listing back into the fixed one-request cost the
1189    /// previous owner decision valued, and spends the variable cost only where
1190    /// it buys the job-level count.
1191    async fn active_runs(
1192        &self,
1193        repository: &OwnerRepo,
1194        status: &str,
1195        cap: usize,
1196        cancel: &CancelToken,
1197    ) -> Result<RunListing, InventoryError> {
1198        let request = ApiRequest::get(format!(
1199            "/repos/{}/{}/actions/runs",
1200            repository.owner(),
1201            repository.repo()
1202        ))
1203        .query("status", status)
1204        .query("per_page", PER_PAGE);
1205
1206        let Fetched {
1207            response,
1208            not_modified,
1209        } = self.get(&request, cancel).await?;
1210        let has_next_page = response.next_page().is_some();
1211        let page: QueuedRunsPage = response.json()?;
1212
1213        let listed = page.workflow_runs.len();
1214        if let Some(total) = page.total_count
1215            && !has_next_page
1216            && total != listed as u64
1217        {
1218            // Free, and no longer load-bearing: see `MAX_BENIGN_TOTAL_COUNT_SKEW`
1219            // for why this is a log line and not the `debug_assert!` it was
1220            // while `total_count` *was* the demand number. The two levels draw
1221            // the same distinction that constant does. A handful over is the
1222            // documented race of a run leaving the queue mid-serialisation,
1223            // which this module's own documentation calls legitimate — warning
1224            // on it every poll is how an operator learns to ignore the warning.
1225            // Thousands over is the unfiltered lifetime total, which is a real
1226            // finding about the API.
1227            if total > (listed as u64).saturating_add(MAX_BENIGN_TOTAL_COUNT_SKEW) {
1228                tracing::warn!(
1229                    repository = %repository,
1230                    status,
1231                    total_count = total,
1232                    listed,
1233                    "GitHub's `total_count` is far larger than the single page it sent for \
1234                     a filtered query, so it is not the filtered count. Demand is counted \
1235                     from the jobs and does not depend on this field, but `c3` reads the \
1236                     same envelope for a dashboard number and does"
1237                );
1238            } else {
1239                tracing::debug!(
1240                    repository = %repository,
1241                    status,
1242                    total_count = total,
1243                    listed,
1244                    "GitHub's `total_count` disagrees slightly with the page it arrived \
1245                     with; this is the documented race of a run leaving the queue while \
1246                     the response was being built"
1247                );
1248            }
1249        }
1250
1251        let run_ids: Vec<u64> = page
1252            .workflow_runs
1253            .iter()
1254            .take(cap)
1255            .map(|run| run.id)
1256            .collect();
1257
1258        Ok(RunListing {
1259            // More runs exist than this pass will resolve, so the job count it
1260            // produces is a floor. Both conditions matter: `listed > cap` is the
1261            // ordinary case, and `has_next_page` catches a repository whose
1262            // first page was itself short of the whole filtered set.
1263            complete: listed <= cap && !has_next_page,
1264            run_ids,
1265            changed: !not_modified,
1266        })
1267    }
1268
1269    /// One run's jobs that are still waiting for a runner.
1270    ///
1271    /// Jobs in any other state are dropped here rather than downstream, because
1272    /// "queued" is what makes a job demand and a caller holding a mixed list
1273    /// would have to re-derive that. The `runs-on` is rebuilt from the job's
1274    /// `labels` array — which is the array form, so [`RunsOn::from_job_labels`]
1275    /// is the constructor `b1` provides for exactly this.
1276    async fn queued_jobs_of_run(
1277        &self,
1278        repository: &OwnerRepo,
1279        run_id: u64,
1280        cancel: &CancelToken,
1281    ) -> Result<RunJobs, InventoryError> {
1282        let mut request = Some(
1283            ApiRequest::get(format!(
1284                "/repos/{}/{}/actions/runs/{run_id}/jobs",
1285                repository.owner(),
1286                repository.repo()
1287            ))
1288            .query("filter", LATEST_JOBS_FILTER)
1289            .query("per_page", PER_PAGE),
1290        );
1291
1292        let mut jobs = Vec::new();
1293        let mut pages = 0_usize;
1294        let mut changed = false;
1295
1296        while let Some(next) = request.take() {
1297            if pages >= MAX_JOB_PAGES_PER_RUN {
1298                tracing::warn!(
1299                    repository = %repository,
1300                    run_id,
1301                    pages,
1302                    "stopped listing one run's jobs at the page budget; the queued-job \
1303                     count for this repository is a floor, not a total"
1304                );
1305                return Ok(RunJobs {
1306                    jobs,
1307                    complete: false,
1308                    changed,
1309                });
1310            }
1311
1312            let Fetched {
1313                response,
1314                not_modified,
1315            } = self.get(&next, cancel).await?;
1316            changed |= !not_modified;
1317            let following = response
1318                .next_page()
1319                .map(|url| ApiRequest::get(url.as_str()));
1320            let page: RunJobsPage = response.json()?;
1321            pages += 1;
1322
1323            jobs.extend(
1324                page.jobs
1325                    .into_iter()
1326                    .filter(|job| job.status == QUEUED_JOB_STATUS)
1327                    .map(|job| RunsOn::from_job_labels(job.labels)),
1328            );
1329
1330            request = following;
1331        }
1332
1333        Ok(RunJobs {
1334            jobs,
1335            complete: true,
1336            changed,
1337        })
1338    }
1339}
1340
1341/// Whether a per-repository failure should be recorded and stepped over, or
1342/// should abort the whole aggregate.
1343///
1344/// The same line `c3` draws in its private `is_repository_local_failure`, and
1345/// repeated here rather than shared because that function lives in a file this
1346/// task does not own. The line is between a fact about *that repository* — a
1347/// `404` for one deleted or renamed, a plain `403` for one with Actions disabled
1348/// — and a fact about the credential or the connection, which stepping over
1349/// would turn into a total short by an unknown amount while looking complete.
1350///
1351/// It applies to an aggregate only. Stepping over the only repository in scope
1352/// would turn a permissions failure into demand `0`, and `e1` would then read
1353/// "nothing queued" for a target it cannot see at all — so the caller checks
1354/// [`TargetScope`] first.
1355fn is_repository_local_failure(error: &InventoryError) -> bool {
1356    match error {
1357        InventoryError::Github(GithubError::Forbidden { .. }) => true,
1358        InventoryError::Github(GithubError::Status { status, .. }) => *status == 404,
1359        _ => false,
1360    }
1361}
1362
1363#[async_trait::async_trait]
1364impl DemandGateway for RestDemand {
1365    async fn queued_demand(
1366        &self,
1367        scope: &ActivityScope,
1368        cancel: &CancelToken,
1369    ) -> Result<QueuedDemand, InventoryError> {
1370        let mut demand = QueuedDemand::default();
1371        // Only an aggregate steps over a bad repository; see
1372        // `is_repository_local_failure`.
1373        let aggregating = scope.target().scope() == TargetScope::Organization;
1374        self.conditional.evict_idle();
1375
1376        for repository in scope.repositories() {
1377            match self.repository_reading(repository, cancel).await {
1378                Ok(reading) => {
1379                    if reading.busy {
1380                        demand.busy.insert(repository.clone());
1381                    }
1382                    demand
1383                        .per_repository
1384                        .insert(repository.clone(), reading.jobs);
1385                    if !reading.exact {
1386                        // A floor travels with the aggregate rather than being
1387                        // flattened into it: one truncated repository makes the
1388                        // total a floor too, and nothing downstream has another
1389                        // way to know.
1390                        demand.truncated.insert(repository.clone());
1391                    }
1392                }
1393                Err(error) if aggregating && is_repository_local_failure(&error) => {
1394                    tracing::warn!(
1395                        repository = %repository,
1396                        error = %error,
1397                        "a repository in this organization could not be polled for demand; \
1398                         the aggregate reports it as unavailable rather than as zero"
1399                    );
1400                    demand.unavailable.push(UnavailableRepository {
1401                        repository: repository.clone(),
1402                        reason: error.to_string(),
1403                    });
1404                }
1405                Err(error) => return Err(error),
1406            }
1407        }
1408
1409        demand.rate_limit = self.client.traffic().latest_rate_limit();
1410        Ok(demand)
1411    }
1412
1413    fn now(&self) -> Timestamp {
1414        self.clock.now()
1415    }
1416}
1417
1418// ---------------------------------------------------------------------------
1419// Wire shapes
1420// ---------------------------------------------------------------------------
1421
1422/// One repository's queued jobs, and whether that set is the whole truth.
1423#[derive(Debug, Clone, PartialEq, Eq)]
1424struct RepositoryDemand {
1425    /// The `runs-on` of every job still waiting for a runner.
1426    jobs: Vec<RunsOn>,
1427    /// `false` when `jobs` is a **floor**: a run cap or a job page budget
1428    /// stopped the walk before the whole queue had been seen.
1429    exact: bool,
1430    /// Runs were under way and at least one listing changed since the last
1431    /// poll. See [`QueuedDemand::is_quiet`].
1432    busy: bool,
1433}
1434
1435/// One run listing's ids, and whether the cap left any behind.
1436#[derive(Debug, Clone, PartialEq, Eq)]
1437struct RunListing {
1438    run_ids: Vec<u64>,
1439    complete: bool,
1440    /// `false` when GitHub answered `304`.
1441    changed: bool,
1442}
1443
1444/// One run's queued jobs, and whether the page budget saw all of them.
1445#[derive(Debug, Clone, PartialEq, Eq)]
1446struct RunJobs {
1447    jobs: Vec<RunsOn>,
1448    complete: bool,
1449    /// `false` when every page was answered `304`.
1450    changed: bool,
1451}
1452
1453/// One page of `GET …/actions/runs?status=…`.
1454///
1455/// Only the `id` is read, and it is read because the job listing needs it. That
1456/// is the field the previous owner decision deliberately did not have — the
1457/// module documentation used to point at `jobs_url` and ask nobody to follow it
1458/// — and reversing that decision is what put it here.
1459#[derive(Debug, Deserialize)]
1460struct QueuedRunsPage {
1461    total_count: Option<u64>,
1462    #[serde(default)]
1463    workflow_runs: Vec<QueuedRun>,
1464}
1465
1466/// One workflow run, reduced to the identifier its jobs are fetched by.
1467#[derive(Debug, Deserialize)]
1468struct QueuedRun {
1469    id: u64,
1470}
1471
1472/// One page of `GET …/actions/runs/{run_id}/jobs`.
1473#[derive(Debug, Deserialize)]
1474struct RunJobsPage {
1475    #[serde(default)]
1476    jobs: Vec<RunJob>,
1477}
1478
1479/// One job of a run: whether it is still waiting, and what it needs.
1480///
1481/// `labels` is GitHub's flat array form of `runs-on`, which is why
1482/// [`RunsOn::from_job_labels`] exists on `b1`'s side. It defaults to empty
1483/// rather than being required, because a job with no labels is a real answer —
1484/// `b1` reports it as [`runner_manager_domain::policy::UnresolvableRunsOn`] —
1485/// and a missing field should not fail the whole repository's poll.
1486#[derive(Debug, Deserialize)]
1487struct RunJob {
1488    #[serde(default)]
1489    status: String,
1490    #[serde(default)]
1491    labels: Vec<String>,
1492}
1493
1494// The unit tests below are inline rather than in a `src/demand/tests.rs`, and
1495// that is a constraint rather than a preference: `lib.rs`'s
1496// `the_confidential_credential_scan_covers_every_source_file` walks `src/`
1497// recursively and requires every `.rs` file under it to appear in
1498// `CRATE_SOURCES` — a list in `lib.rs`, which `c2` owns. A second file in this
1499// directory would fail that pin, and the only fix would be editing another
1500// task's file.
1501#[cfg(test)]
1502mod tests {
1503    use super::*;
1504    use crate::testing::{FIXTURE_TOKEN, TestClock};
1505    use crate::{Endpoints, UserAccessToken};
1506    use runner_manager_domain::{
1507        model::{Arch, HostLabel, Label, Org, Os},
1508        policy::{RoutingLabels, RunsOn, RunsOnMatch, UnresolvableRunsOn},
1509    };
1510    use secrecy::SecretString;
1511    use serde_json::json;
1512    use wiremock::{
1513        Mock, MockServer, ResponseTemplate,
1514        matchers::{method, path, query_param},
1515    };
1516
1517    fn repo() -> OwnerRepo {
1518        OwnerRepo::parse("octo/dashboard").expect("a valid owner/repo")
1519    }
1520
1521    fn other_repo() -> OwnerRepo {
1522        OwnerRepo::parse("octo/api").expect("a valid owner/repo")
1523    }
1524
1525    fn third_repo() -> OwnerRepo {
1526        OwnerRepo::parse("octo/tools").expect("a valid owner/repo")
1527    }
1528
1529    fn org_scope(repositories: impl IntoIterator<Item = OwnerRepo>) -> ActivityScope {
1530        ActivityScope::organization(
1531            Org::new("octo-org").expect("a valid organization login"),
1532            repositories,
1533        )
1534    }
1535
1536    fn gateway(server: &MockServer) -> RestDemand {
1537        let endpoints = Endpoints::for_test_server(&server.uri()).expect("a test server base");
1538        let token = UserAccessToken::from_stored(SecretString::from(FIXTURE_TOKEN));
1539        let client = AuthenticatedClient::new(endpoints, token, Arc::new(TestClock::default()))
1540            .expect("a client over the test server");
1541        RestDemand::new(Arc::new(client), Arc::new(TestClock::default()))
1542    }
1543
1544    // -- fixtures -----------------------------------------------------------
1545
1546    /// A run list carrying `ids`, and a `total_count` that agrees with it.
1547    fn runs_body(ids: &[u64]) -> serde_json::Value {
1548        json!({
1549            "total_count": ids.len(),
1550            "workflow_runs": ids.iter().map(|id| json!({ "id": id })).collect::<Vec<_>>()
1551        })
1552    }
1553
1554    /// An empty run list, which is what an idle repository answers.
1555    fn no_runs() -> serde_json::Value {
1556        runs_body(&[])
1557    }
1558
1559    /// A jobs page: `queued` jobs carrying `labels`, then `running` that do not
1560    /// count.
1561    fn jobs_body(labels: &[&str], queued: usize, running: usize) -> serde_json::Value {
1562        let mut jobs = Vec::new();
1563        for _ in 0..queued {
1564            jobs.push(json!({ "status": "queued", "labels": labels }));
1565        }
1566        for _ in 0..running {
1567            jobs.push(json!({ "status": "in_progress", "labels": labels }));
1568        }
1569        json!({ "total_count": jobs.len(), "jobs": jobs })
1570    }
1571
1572    fn runs_path(repository: &OwnerRepo) -> String {
1573        format!(
1574            "/repos/{}/{}/actions/runs",
1575            repository.owner(),
1576            repository.repo()
1577        )
1578    }
1579
1580    fn jobs_path(repository: &OwnerRepo, run_id: u64) -> String {
1581        format!("{}/{run_id}/jobs", runs_path(repository))
1582    }
1583
1584    /// Mount one repository's run list for one status filter.
1585    async fn mount_runs(
1586        server: &MockServer,
1587        repository: &OwnerRepo,
1588        status: &str,
1589        body: serde_json::Value,
1590    ) {
1591        Mock::given(method("GET"))
1592            .and(path(runs_path(repository)))
1593            .and(query_param("status", status))
1594            .respond_with(ResponseTemplate::new(200).set_body_json(body))
1595            .mount(server)
1596            .await;
1597    }
1598
1599    /// Mount one run's job list.
1600    async fn mount_jobs(
1601        server: &MockServer,
1602        repository: &OwnerRepo,
1603        run_id: u64,
1604        body: serde_json::Value,
1605    ) {
1606        Mock::given(method("GET"))
1607            .and(path(jobs_path(repository, run_id)))
1608            .respond_with(ResponseTemplate::new(200).set_body_json(body))
1609            .mount(server)
1610            .await;
1611    }
1612
1613    /// The ordinary shape: one queued run of `queued` + `running` jobs, and an
1614    /// empty in-progress list.
1615    async fn mount_one_queued_run(
1616        server: &MockServer,
1617        repository: &OwnerRepo,
1618        labels: &[&str],
1619        queued: usize,
1620        running: usize,
1621    ) {
1622        mount_runs(server, repository, QUEUED_RUN_STATUS, runs_body(&[100])).await;
1623        mount_runs(server, repository, IN_PROGRESS_RUN_STATUS, no_runs()).await;
1624        mount_jobs(server, repository, 100, jobs_body(labels, queued, running)).await;
1625    }
1626
1627    /// A repository with nothing waiting: two run listings, no job listings.
1628    async fn mount_idle(server: &MockServer, repository: &OwnerRepo) {
1629        mount_runs(server, repository, QUEUED_RUN_STATUS, no_runs()).await;
1630        mount_runs(server, repository, IN_PROGRESS_RUN_STATUS, no_runs()).await;
1631    }
1632
1633    /// The routing labels of a realistic policy on this host.
1634    ///
1635    /// Deliberately **not** a bare [`RoutingLabels::derive`]. That produces the
1636    /// derived host label alone, and a job written `runs-on: [self-hosted,
1637    /// windows]` — the shape people actually write — requires labels a bare
1638    /// derived set does not carry, so it would not match. An operator adds those
1639    /// with `repo add --label`, and a fixture that skipped them would test the
1640    /// filtering against a policy nobody configures.
1641    fn host_labels() -> RoutingLabels {
1642        RoutingLabels::from_parts(
1643            Label::new("rm-home-win-x64").expect("a valid label"),
1644            [
1645                Label::new("self-hosted").expect("a valid label"),
1646                Label::new("windows").expect("a valid label"),
1647            ],
1648        )
1649    }
1650
1651    // -- the count itself ---------------------------------------------------
1652
1653    /// The defect this module was rewritten for, as an executable statement.
1654    ///
1655    /// One queued run holding eight matrix jobs. Under the previous owner
1656    /// decision this repository reported demand `1`, `e1` started one runner,
1657    /// and the other seven jobs waited for a machine that was sitting idle. It
1658    /// must now report `8`.
1659    #[tokio::test]
1660    async fn a_matrix_run_of_eight_jobs_is_eight_units_of_demand_and_not_one() {
1661        let server = MockServer::start().await;
1662        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 8, 0).await;
1663        let gateway = gateway(&server);
1664
1665        let demand = gateway
1666            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1667            .await
1668            .expect("a queued-job count");
1669
1670        assert_eq!(
1671            demand.total(),
1672            8,
1673            "eight jobs in one run are eight runners' worth of work; reading the run \
1674             count here is the defect that forced the owner decision back"
1675        );
1676        assert_eq!(demand.for_repository(&repo()), Some(8));
1677        assert!(demand.is_complete());
1678        assert_eq!(
1679            gateway.requests_issued(),
1680            3,
1681            "two run listings and one job listing for the single active run"
1682        );
1683    }
1684
1685    /// A job that already has a runner is not demand.
1686    ///
1687    /// The run-level mistake one level down: `status=in_progress` work already
1688    /// has a runner, and counting it would start a second for the same job.
1689    #[tokio::test]
1690    async fn only_jobs_still_queued_are_counted() {
1691        let server = MockServer::start().await;
1692        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 3, 5).await;
1693        let gateway = gateway(&server);
1694
1695        let demand = gateway
1696            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1697            .await
1698            .expect("a queued-job count");
1699
1700        assert_eq!(
1701            demand.total(),
1702            3,
1703            "five of the eight jobs already have a runner and are not waiting for one"
1704        );
1705    }
1706
1707    /// The labels travel with the job, which is the input `b1`'s predicate never
1708    /// had.
1709    #[tokio::test]
1710    async fn each_queued_job_carries_the_runs_on_it_requires() {
1711        let server = MockServer::start().await;
1712        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&[100, 101])).await;
1713        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
1714        mount_jobs(
1715            &server,
1716            &repo(),
1717            100,
1718            jobs_body(&["rm-home-win-x64", "self-hosted", "windows"], 2, 0),
1719        )
1720        .await;
1721        mount_jobs(&server, &repo(), 101, jobs_body(&["ubuntu-latest"], 4, 0)).await;
1722        let gateway = gateway(&server);
1723
1724        let demand = gateway
1725            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1726            .await
1727            .expect("a queued-job count");
1728
1729        assert_eq!(
1730            demand.total(),
1731            6,
1732            "the unfiltered depth is every queued job"
1733        );
1734
1735        // And the number `e1` clamps, which is the unfiltered depth put through
1736        // `b1`'s predicate. This gateway does not compute it; it supplies it.
1737        let tally = host_labels().tally(demand.jobs_for(&repo()));
1738        assert_eq!(
1739            tally.demand(),
1740            2,
1741            "the four `ubuntu-latest` jobs are somebody else's work; before the job \
1742             listing existed all six would have driven this policy toward max_capacity"
1743        );
1744        assert_eq!(tally.not_matched, 4);
1745    }
1746
1747    /// The two run statuses are both on the wire, and the job filter with them.
1748    ///
1749    /// The queries are one word apart and answer different questions, so a
1750    /// gateway that sent the wrong one would return a plausible number. The
1751    /// mocks match on the exact status, so sending anything else 404s here
1752    /// rather than passing.
1753    #[tokio::test]
1754    async fn both_run_statuses_are_polled_and_the_jobs_request_asks_for_the_latest_attempt() {
1755        let server = MockServer::start().await;
1756        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 1, 0).await;
1757        let gateway = gateway(&server);
1758
1759        gateway
1760            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1761            .await
1762            .expect("both filters are mounted");
1763
1764        let requests = server.received_requests().await.expect("recorded requests");
1765        assert_eq!(requests.len(), 3);
1766
1767        let queries: Vec<String> = requests
1768            .iter()
1769            .map(|r| r.url.query().unwrap_or_default().to_string())
1770            .collect();
1771
1772        assert!(
1773            queries.iter().any(|q| q.contains("status=queued")),
1774            "the primary signal is the queued run list; sent {queries:?}"
1775        );
1776        assert!(
1777            queries.iter().any(|q| q.contains("status=in_progress")),
1778            "the safety net catches a `needs:`-gated job whose run has already \
1779             started; sent {queries:?}"
1780        );
1781        assert!(
1782            queries
1783                .iter()
1784                .any(|q| q.contains(&format!("filter={LATEST_JOBS_FILTER}"))),
1785            "`filter=all` would count every attempt of a re-run job as present \
1786             demand; sent {queries:?}"
1787        );
1788        assert!(
1789            queries
1790                .iter()
1791                .all(|q| q.contains(&format!("per_page={PER_PAGE}"))),
1792            "asking for fewer than GitHub's maximum multiplies the request count \
1793             against the budget this module projects; sent {queries:?}"
1794        );
1795    }
1796
1797    /// The queued run list is read before the in-progress one.
1798    ///
1799    /// The order is what spends the caps on the signal rather than on the safety
1800    /// net, and it is the kind of thing that is only true until somebody
1801    /// reorders a literal.
1802    #[tokio::test]
1803    async fn the_queued_run_list_is_read_before_the_in_progress_one() {
1804        let server = MockServer::start().await;
1805        mount_idle(&server, &repo()).await;
1806        let gateway = gateway(&server);
1807
1808        gateway
1809            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1810            .await
1811            .expect("an idle repository still answers");
1812
1813        let requests = server.received_requests().await.expect("recorded requests");
1814        let queries: Vec<String> = requests
1815            .iter()
1816            .map(|r| r.url.query().unwrap_or_default().to_string())
1817            .collect();
1818        assert_eq!(queries.len(), 2, "an idle repository lists no run's jobs");
1819        assert!(
1820            queries[0].contains("status=queued"),
1821            "the primary signal is read first; sent {queries:?}"
1822        );
1823        assert!(
1824            queries[1].contains("status=in_progress"),
1825            "the safety net is read second; sent {queries:?}"
1826        );
1827    }
1828
1829    /// An idle repository costs the two listings and nothing more.
1830    ///
1831    /// The steady-state figure the budget model prices, asserted against what
1832    /// the gateway really spends rather than left as a claim in a doc comment.
1833    #[tokio::test]
1834    async fn an_idle_repository_costs_only_the_two_run_listings() {
1835        let server = MockServer::start().await;
1836        mount_idle(&server, &repo()).await;
1837        let gateway = gateway(&server);
1838
1839        let demand = gateway
1840            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1841            .await
1842            .expect("an idle repository answers zero rather than failing");
1843
1844        assert_eq!(demand.total(), 0);
1845        assert!(
1846            demand.is_complete(),
1847            "zero from a repository that answered is a measurement, not a floor"
1848        );
1849        assert_eq!(gateway.requests_issued(), 2);
1850        assert!(
1851            gateway.requests_issued() <= u64::from(DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL),
1852            "the idle case must sit inside the projection, which is the number `f2`'s \
1853             refusals are computed from"
1854        );
1855    }
1856
1857    /// A run whose jobs have all been dispatched is found and costs one request.
1858    ///
1859    /// The safety net's ordinary outcome, and the reason it is capped lower than
1860    /// the primary signal: on the common shape it finds nothing.
1861    #[tokio::test]
1862    async fn an_in_progress_run_with_no_queued_job_contributes_only_its_request() {
1863        let server = MockServer::start().await;
1864        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, no_runs()).await;
1865        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, runs_body(&[200])).await;
1866        mount_jobs(&server, &repo(), 200, jobs_body(&["rm-home-win-x64"], 0, 4)).await;
1867        let gateway = gateway(&server);
1868
1869        let demand = gateway
1870            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1871            .await
1872            .expect("a queued-job count");
1873
1874        assert_eq!(demand.total(), 0);
1875        assert!(demand.is_complete());
1876        assert_eq!(gateway.requests_issued(), 3);
1877    }
1878
1879    /// A run caught mid-transition appears in both listings and is counted once.
1880    ///
1881    /// The two GitHub queries are disjoint at any one instant and these are two
1882    /// requests with time between them. A run whose last waiting job is picked
1883    /// up between them is `queued` for the first and `in_progress` for the
1884    /// second — the ordinary transition, not an exotic one — so it comes back in
1885    /// both lists. Counting its jobs twice would inflate demand silently, which
1886    /// is the failure mode with no error to notice.
1887    #[tokio::test]
1888    async fn a_run_in_both_listings_is_resolved_once_and_not_counted_twice() {
1889        let server = MockServer::start().await;
1890        // The same run id in both lists, which is what the race produces.
1891        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&[100])).await;
1892        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, runs_body(&[100])).await;
1893        mount_jobs(&server, &repo(), 100, jobs_body(&["rm-home-win-x64"], 3, 0)).await;
1894        let gateway = gateway(&server);
1895
1896        let demand = gateway
1897            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1898            .await
1899            .expect("a queued-job count");
1900
1901        assert_eq!(
1902            demand.total(),
1903            3,
1904            "the run holds three queued jobs, and appearing in both listings does not              make it six"
1905        );
1906        assert_eq!(
1907            gateway.requests_issued(),
1908            3,
1909            "and the duplicate costs no second job listing either"
1910        );
1911    }
1912
1913    /// A `needs:`-gated job whose run has already started is still demand.
1914    ///
1915    /// This is the whole reason the in-progress pass exists. Live sampling of a
1916    /// repository using this product never caught GitHub reporting a run as
1917    /// `in_progress` while one of its jobs was queued — 44 samples, 25 of them
1918    /// with a queued job — so the primary signal covers everything that was
1919    /// observed. It does not cover a job that becomes queued *after* its run
1920    /// started, which is what `needs:` produces and what this pins.
1921    #[tokio::test]
1922    async fn a_job_that_enters_the_queue_after_its_run_started_is_still_found() {
1923        let server = MockServer::start().await;
1924        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, no_runs()).await;
1925        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, runs_body(&[200])).await;
1926        // One job running, one released by `needs:` and now waiting.
1927        mount_jobs(&server, &repo(), 200, jobs_body(&["rm-home-win-x64"], 1, 1)).await;
1928        let gateway = gateway(&server);
1929
1930        let demand = gateway
1931            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1932            .await
1933            .expect("a queued-job count");
1934
1935        assert_eq!(
1936            demand.total(),
1937            1,
1938            "polling only `status=queued` runs would report zero here and the \
1939             `needs:`-gated job would wait for a machine that is idle"
1940        );
1941    }
1942
1943    // -- the wire contract, against payloads GitHub really sent -------------
1944
1945    /// The deserializers are pinned against **real** GitHub responses, not only
1946    /// against fixtures written to match them.
1947    ///
1948    /// Every other test here builds its own JSON, so all of them would keep
1949    /// passing if this module's idea of the wire format were wrong in the same
1950    /// way the fixtures are. That is the one failure a mock server cannot catch,
1951    /// and it is the failure this change was most exposed to: the previous owner
1952    /// decision deliberately read *nothing* out of a run and had no job
1953    /// endpoint at all, so `workflow_runs[].id`, `jobs[].status` and
1954    /// `jobs[].labels` are all fields this crate had never parsed before.
1955    ///
1956    /// The payloads below are verbatim excerpts captured from
1957    /// `api.github.com` on 2026-09-05 against a repository using this product,
1958    /// trimmed only by replacing the `steps` array — which is long, which this
1959    /// module does not read, and whose presence is itself part of what is being
1960    /// asserted, since a job object carries twenty-odd fields that must all be
1961    /// ignored without error.
1962    #[test]
1963    fn the_wire_shapes_parse_a_payload_github_really_sent() {
1964        // GET /repos/{o}/{r}/actions/runs/33938794901/jobs?filter=latest&per_page=100
1965        let jobs: RunJobsPage = serde_json::from_value(json!({
1966          "total_count": 5,
1967          "jobs": [
1968            {
1969              "id": 101_231_925_899_i64,
1970              "run_id": 33_938_794_901_i64,
1971              "workflow_name": "tests",
1972              "head_branch": "worktree-p1-lock-and-worktree-set",
1973              "run_url": "https://api.github.com/repos/o/r/actions/runs/33938794901",
1974              "run_attempt": 1,
1975              "node_id": "CR_kwDOS_wnss8AAAAXkeSaiw",
1976              "head_sha": "e78bc5d1865693aba030d83a2c627dd5515edf45",
1977              "url": "https://api.github.com/repos/o/r/actions/jobs/101231925899",
1978              "html_url": "https://github.com/o/r/actions/runs/33938794901/job/101231925899",
1979              "status": "completed",
1980              "conclusion": "success",
1981              "created_at": "2026-09-05T02:20:30Z",
1982              "started_at": "2026-09-05T02:26:03Z",
1983              "completed_at": "2026-09-05T02:28:44Z",
1984              "name": "scripts-tests",
1985              "steps": [],
1986              "check_run_url": "https://api.github.com/repos/o/r/check-runs/101231925899",
1987              "labels": ["self-hosted", "windows"],
1988              "runner_id": 725,
1989              "runner_name": "runner-manager-4bd32f05-088f-4b13-a59c-6900b9142aa1",
1990              "runner_group_id": 1,
1991              "runner_group_name": "Default"
1992            },
1993            {
1994              "id": 101_231_925_900_i64,
1995              "run_id": 33_938_794_901_i64,
1996              "status": "queued",
1997              "conclusion": serde_json::Value::Null,
1998              "started_at": serde_json::Value::Null,
1999              "completed_at": serde_json::Value::Null,
2000              "name": "pipeline-tests",
2001              "steps": [],
2002              "labels": ["self-hosted", "windows"],
2003              "runner_id": serde_json::Value::Null,
2004              "runner_name": "",
2005              "runner_group_name": ""
2006            },
2007            {
2008              "id": 101_231_925_901_i64,
2009              "status": "queued",
2010              "name": "scripts-tests-macos",
2011              "labels": ["self-hosted", "macOS", "rm-macmini-osx-arm64"]
2012            }
2013          ]
2014        }))
2015        .expect("the jobs page GitHub really sends must deserialize");
2016
2017        assert_eq!(
2018            jobs.jobs.len(),
2019            3,
2020            "every job is read, whatever else it carries"
2021        );
2022
2023        // What the gateway does with it: keep the queued ones, and turn each
2024        // one's `labels` array into the `RunsOn` `b1` matches.
2025        let queued: Vec<RunsOn> = jobs
2026            .jobs
2027            .into_iter()
2028            .filter(|job| job.status == QUEUED_JOB_STATUS)
2029            .map(|job| RunsOn::from_job_labels(job.labels))
2030            .collect();
2031
2032        assert_eq!(
2033            queued,
2034            vec![
2035                RunsOn::Many(vec!["self-hosted".into(), "windows".into()]),
2036                RunsOn::Many(vec![
2037                    "self-hosted".into(),
2038                    "macOS".into(),
2039                    "rm-macmini-osx-arm64".into()
2040                ]),
2041            ],
2042            "the completed job is dropped and the two queued ones keep their labels"
2043        );
2044
2045        // The Windows job requires a subset of this policy's labels, even
2046        // without its selector. The macOS job still requires missing labels.
2047        let tally = host_labels().tally(&queued);
2048        assert_eq!(tally.demand(), 1);
2049        assert_eq!(tally.not_matched, 1);
2050
2051        // GET /repos/{o}/{r}/actions/runs?status=queued&per_page=100, as an idle
2052        // repository answers it. `total_count` and an empty array, which is the
2053        // shape that must read as "nothing waiting" rather than as a failure.
2054        let idle: QueuedRunsPage = serde_json::from_value(json!({
2055            "total_count": 0,
2056            "workflow_runs": []
2057        }))
2058        .expect("an idle run listing must deserialize");
2059        assert_eq!(idle.total_count, Some(0));
2060        assert!(idle.workflow_runs.is_empty());
2061
2062        // And a busy one. A run object carries far more than the id, and the id
2063        // is the only field this module reads out of it.
2064        let busy: QueuedRunsPage = serde_json::from_value(json!({
2065            "total_count": 1,
2066            "workflow_runs": [{
2067                "id": 33_938_794_901_i64,
2068                "name": "tests",
2069                "node_id": "WFR_kwLOS_wnss8AAAAH6oSPFQ",
2070                "head_branch": "main",
2071                "head_sha": "e78bc5d1865693aba030d83a2c627dd5515edf45",
2072                "path": ".github/workflows/tests.yml",
2073                "run_number": 412,
2074                "event": "push",
2075                "status": "queued",
2076                "conclusion": serde_json::Value::Null,
2077                "workflow_id": 213_842_591_i64,
2078                "url": "https://api.github.com/repos/o/r/actions/runs/33938794901",
2079                "created_at": "2026-09-05T02:20:30Z",
2080                "updated_at": "2026-09-05T02:20:31Z"
2081            }]
2082        }))
2083        .expect("a busy run listing must deserialize");
2084        assert_eq!(
2085            busy.workflow_runs
2086                .iter()
2087                .map(|run| run.id)
2088                .collect::<Vec<_>>(),
2089            vec![33_938_794_901],
2090            "the run id is what the job listing is fetched by, and it is a u64: \
2091             GitHub's run ids passed 2^32 long ago, so a u32 here would have \
2092             wrapped on every real repository"
2093        );
2094    }
2095
2096    // -- the caps -----------------------------------------------------------
2097
2098    /// More queued runs than the cap resolves makes the answer a floor.
2099    #[tokio::test]
2100    async fn more_queued_runs_than_the_cap_report_a_floor_rather_than_a_total() {
2101        let server = MockServer::start().await;
2102        let ids: Vec<u64> = (0..(MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL as u64 + 4))
2103            .map(|i| 100 + i)
2104            .collect();
2105        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&ids)).await;
2106        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
2107        for id in &ids {
2108            mount_jobs(&server, &repo(), *id, jobs_body(&["rm-home-win-x64"], 1, 0)).await;
2109        }
2110        let gateway = gateway(&server);
2111
2112        let demand = gateway
2113            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2114            .await
2115            .expect("a bounded poll still answers");
2116
2117        assert_eq!(
2118            demand.total() as usize,
2119            MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL,
2120            "one job resolved per run the cap admits"
2121        );
2122        assert!(
2123            !demand.is_complete(),
2124            "a count clipped by the run cap is a floor and must say so; concluding \
2125             `idle` from one would be the mistake the flag exists to prevent"
2126        );
2127        assert!(demand.is_truncated(&repo()));
2128    }
2129
2130    /// The caps bound what one repository can spend, whatever GitHub sends.
2131    ///
2132    /// The projection is a steady-state figure and the worst case is what keeps
2133    /// it honest, so the worst case has to be a real ceiling rather than an
2134    /// estimate. A repository with a hundred active runs must not spend a
2135    /// hundred requests.
2136    #[tokio::test]
2137    async fn a_repository_cannot_spend_more_than_the_documented_worst_case() {
2138        let server = MockServer::start().await;
2139        let queued: Vec<u64> = (0..40).map(|i| 100 + i).collect();
2140        let running: Vec<u64> = (0..40).map(|i| 500 + i).collect();
2141        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&queued)).await;
2142        mount_runs(
2143            &server,
2144            &repo(),
2145            IN_PROGRESS_RUN_STATUS,
2146            runs_body(&running),
2147        )
2148        .await;
2149        for id in queued.iter().chain(running.iter()) {
2150            mount_jobs(&server, &repo(), *id, jobs_body(&["rm-home-win-x64"], 2, 0)).await;
2151        }
2152        let gateway = gateway(&server);
2153
2154        let demand = gateway
2155            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2156            .await
2157            .expect("a bounded poll still answers");
2158
2159        assert_eq!(
2160            gateway.requests_issued(),
2161            u64::from(max_demand_requests_per_repository_per_poll()),
2162            "the measured ceiling must equal the projected one, or the bound is a \
2163             sentence in a doc comment"
2164        );
2165        assert_eq!(
2166            demand.total(),
2167            2 * (MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL
2168                + MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL) as u32
2169        );
2170        assert!(!demand.is_complete());
2171    }
2172
2173    /// The queued pass is served before the in-progress one when both are over
2174    /// their caps.
2175    #[tokio::test]
2176    async fn the_primary_signal_is_resolved_before_the_safety_net() {
2177        let server = MockServer::start().await;
2178        let queued: Vec<u64> = (0..40).map(|i| 100 + i).collect();
2179        let running: Vec<u64> = (0..40).map(|i| 500 + i).collect();
2180        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&queued)).await;
2181        mount_runs(
2182            &server,
2183            &repo(),
2184            IN_PROGRESS_RUN_STATUS,
2185            runs_body(&running),
2186        )
2187        .await;
2188        // Queued runs hold this host's work; in-progress runs hold another
2189        // host's. If the caps were spent in the other order the demand would be
2190        // made of the wrong jobs.
2191        for id in &queued {
2192            mount_jobs(&server, &repo(), *id, jobs_body(&["rm-home-win-x64"], 1, 0)).await;
2193        }
2194        for id in &running {
2195            mount_jobs(&server, &repo(), *id, jobs_body(&["ubuntu-latest"], 1, 0)).await;
2196        }
2197        let gateway = gateway(&server);
2198
2199        let demand = gateway
2200            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2201            .await
2202            .expect("a bounded poll still answers");
2203
2204        let tally = host_labels().tally(demand.jobs_for(&repo()));
2205        assert_eq!(
2206            tally.demand() as usize,
2207            MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL,
2208            "the queued cap is spent in full on the primary signal"
2209        );
2210        assert_eq!(
2211            tally.not_matched as usize, MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL,
2212            "and the safety net gets its own smaller cap, not a share of the first"
2213        );
2214    }
2215
2216    /// One run's job listing follows pages, and stops at its budget.
2217    #[tokio::test]
2218    async fn a_runs_job_listing_walks_pages_and_stops_at_its_budget() {
2219        let server = MockServer::start().await;
2220        let base = server.uri();
2221        let path_100 = jobs_path(&repo(), 100);
2222
2223        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&[100])).await;
2224        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
2225        // Every page points at another, forever.
2226        Mock::given(method("GET"))
2227            .and(path(path_100.clone()))
2228            .respond_with(
2229                ResponseTemplate::new(200)
2230                    .set_body_json(jobs_body(&["rm-home-win-x64"], 100, 0))
2231                    .insert_header(
2232                        "link",
2233                        format!("<{base}{path_100}?page=9>; rel=\"next\"").as_str(),
2234                    ),
2235            )
2236            .mount(&server)
2237            .await;
2238        let gateway = gateway(&server);
2239
2240        let demand = gateway
2241            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2242            .await
2243            .expect("a bounded walk still answers");
2244
2245        assert_eq!(
2246            gateway.requests_issued() as usize,
2247            2 + MAX_JOB_PAGES_PER_RUN,
2248            "an endless `Link` chain must stop at the job page budget rather than \
2249             spending the hourly ceiling on one run"
2250        );
2251        assert_eq!(demand.total() as usize, 100 * MAX_JOB_PAGES_PER_RUN);
2252        assert!(
2253            !demand.is_complete(),
2254            "a count clipped by the page bound is a floor and must say so"
2255        );
2256        assert!(demand.is_truncated(&repo()));
2257    }
2258
2259    // -- the `total_count` tripwire ----------------------------------------
2260
2261    /// The zero-cost check that `total_count` is the *filtered* count.
2262    ///
2263    /// A repository with 3 queued runs out of 5,000 lifetime runs would answer
2264    /// `len() == 3`, no `Link`, and `total_count == 5000`. The demand number no
2265    /// longer comes from that field, so the contradiction is a `warn!` rather
2266    /// than a `debug_assert!` — but it still means GitHub is not answering the
2267    /// question this module asked, and it is free to notice.
2268    #[tokio::test]
2269    async fn a_total_count_that_disagrees_with_its_only_page_does_not_derail_the_count() {
2270        let server = MockServer::start().await;
2271        mount_runs(
2272            &server,
2273            &repo(),
2274            QUEUED_RUN_STATUS,
2275            json!({
2276                "total_count": 5_000,
2277                "workflow_runs": [{ "id": 100 }]
2278            }),
2279        )
2280        .await;
2281        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
2282        mount_jobs(&server, &repo(), 100, jobs_body(&["rm-home-win-x64"], 2, 0)).await;
2283        let gateway = gateway(&server);
2284
2285        let demand = gateway
2286            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2287            .await
2288            .expect("a wrong `total_count` no longer decides anything here");
2289
2290        assert_eq!(
2291            demand.total(),
2292            2,
2293            "the count comes from the jobs of the runs that were actually listed, so a \
2294             `total_count` carrying the unfiltered lifetime total cannot inflate it"
2295        );
2296        assert!(
2297            demand.is_complete(),
2298            "one listed run, no next page, and the cap not reached"
2299        );
2300    }
2301
2302    // -- organization aggregation ------------------------------------------
2303
2304    /// An organization aggregates across its installed repositories, and the
2305    /// request count grows with that repository count.
2306    #[tokio::test]
2307    async fn an_organization_aggregates_its_repositories_and_pays_per_repository() {
2308        let server = MockServer::start().await;
2309        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 2, 0).await;
2310        mount_one_queued_run(&server, &other_repo(), &["rm-home-win-x64"], 5, 0).await;
2311        mount_idle(&server, &third_repo()).await;
2312        let gateway = gateway(&server);
2313
2314        let two = org_scope([repo(), other_repo()]);
2315        let three = org_scope([repo(), other_repo(), third_repo()]);
2316
2317        assert_eq!(
2318            demand_requests_per_poll(&two),
2319            2 * DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL,
2320            "there is no organization-wide workflow-runs endpoint, so the cost is \
2321             per repository"
2322        );
2323        assert!(
2324            demand_requests_per_poll(&three) > demand_requests_per_poll(&two),
2325            "a projection that did not grow with the repository count would understate \
2326             an organization's real spend by exactly that factor"
2327        );
2328
2329        let demand = gateway
2330            .queued_demand(&three, &CancelToken::new())
2331            .await
2332            .expect("an aggregate");
2333
2334        assert_eq!(demand.total(), 7);
2335        assert_eq!(demand.for_repository(&repo()), Some(2));
2336        assert_eq!(demand.for_repository(&other_repo()), Some(5));
2337        assert_eq!(
2338            demand.for_repository(&third_repo()),
2339            Some(0),
2340            "a repository that answered zero is present as a zero, unlike one that \
2341             could not answer at all"
2342        );
2343        assert_eq!(
2344            host_labels().tally(demand.jobs()).demand(),
2345            7,
2346            "an organization policy serves any repository in its scope, so its demand \
2347             is the whole aggregate's rather than one repository's"
2348        );
2349        assert!(
2350            gateway.requests_issued() <= u64::from(max_demand_requests_per_poll(&three)),
2351            "the measured cost must sit inside the projected ceiling, or the budget \
2352             model is a table in a document"
2353        );
2354    }
2355
2356    /// The measured cost is reported to `c3`'s budget model through the seam
2357    /// `c3` left for it, rather than inheriting the estimate.
2358    #[test]
2359    fn the_measured_demand_cost_is_reported_through_c3s_seam() {
2360        use crate::rest::DEMAND_REQUESTS_PER_REPOSITORY_PER_REFRESH;
2361
2362        let scope = org_scope([repo(), other_repo(), third_repo()]);
2363        let estimated = TargetCost::from_activity_scope(&scope);
2364        let measured = target_cost(&scope);
2365
2366        assert_eq!(
2367            DEMAND_REQUESTS_PER_REPOSITORY_PER_REFRESH, 2,
2368            "`c3`'s estimate prices the runs request and one jobs request; this module \
2369             now issues both, plus the in-progress listing and a jobs request per \
2370             additional active run, so the measured figure is higher rather than lower"
2371        );
2372        assert_ne!(
2373            measured, estimated,
2374            "the seam must actually replace the estimate; a `target_cost` that returned \
2375             `from_activity_scope` unchanged would report the estimate as measured"
2376        );
2377        // 1 inventory request + 3 repositories * (1 activity + 4 demand).
2378        assert_eq!(measured.requests_per_refresh(), 16);
2379        // 1 + 3 * (1 + 2), `c3`'s estimate.
2380        assert_eq!(estimated.requests_per_refresh(), 10);
2381        assert!(
2382            measured.requests_per_refresh() > estimated.requests_per_refresh(),
2383            "restoring the per-run job listing added requests; a measured cost that was \
2384             not higher would mean this module is not issuing them"
2385        );
2386    }
2387
2388    /// **A known gap, pinned so it stays visible.** `f2`'s refusal *decision*
2389    /// can consume the measured demand cost; the number it prints alongside the
2390    /// refusal cannot.
2391    ///
2392    /// [`crate::rest::BudgetProjection::admit`] takes the candidate
2393    /// [`TargetCost`] from its caller, so an `f2` that builds it through
2394    /// [`target_cost`] gets an admission computed from the real cost.
2395    /// [`crate::rest::BudgetProjection::max_repository_targets`] builds
2396    /// [`TargetCost::repository`] internally, which cannot see the seam and
2397    /// therefore still prices demand at `c3`'s estimate of two.
2398    ///
2399    /// The two then disagree, and an operator sees both. **The direction of the
2400    /// disagreement inverted when this module started counting jobs**, and that
2401    /// is why this test matters more than it did: the printed ceiling used to be
2402    /// conservative, and is now optimistic. It says a host fits ten repository
2403    /// targets when the cost this module really issues fits six, so an operator
2404    /// planning against the printed number can configure a host that spends more
2405    /// than the projection admitted.
2406    ///
2407    /// What keeps that from being a live budget overrun is
2408    /// `BUDGET_SHARE_DIVISOR`: the projection is compared against half of
2409    /// GitHub's hourly ceiling, so the gap is spent out of the half deliberately
2410    /// left unplanned. It is a reporting defect with a safety margin under it,
2411    /// not a correctness one — and `f1`'s `host show` prints the caveat beside
2412    /// the number.
2413    ///
2414    /// It is not fixable from this file. Both remedies — changing
2415    /// [`crate::rest::DEMAND_REQUESTS_PER_REPOSITORY_PER_REFRESH`], or giving
2416    /// `max_repository_targets` a [`TargetCost`] argument — are edits to
2417    /// `crates/github/src/rest.rs`, which `c3` owns. This test records the
2418    /// discrepancy with its arithmetic so that whoever holds that file can act on
2419    /// it, and fails if it is ever closed, at which point this test and the note
2420    /// above should go.
2421    #[test]
2422    fn the_printed_target_ceiling_still_projects_c3s_estimate() {
2423        use crate::rest::{BudgetProjection, budget_allowance};
2424        use runner_manager_domain::model::RefreshInterval;
2425
2426        let interval = RefreshInterval::default();
2427        let printed = BudgetProjection::max_repository_targets(interval);
2428        let per_hour_estimated = TargetCost::repository().requests_per_hour(interval);
2429        let per_hour_measured = TargetCost::repository()
2430            .with_demand_requests_per_repository(DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL)
2431            .requests_per_hour(interval);
2432
2433        // 4 requests per refresh * 60 refreshes, against 6 * 60.
2434        assert_eq!(per_hour_estimated, 240);
2435        assert_eq!(per_hour_measured, 360);
2436        assert_eq!(
2437            printed, 10,
2438            "the printed ceiling is `04-subsystem-contracts.md`'s figure, computed from \
2439             `c3`'s estimate"
2440        );
2441        assert_eq!(
2442            budget_allowance() / per_hour_measured,
2443            6,
2444            "while the cost this module actually issues allows six"
2445        );
2446        assert!(
2447            printed > budget_allowance() / per_hour_measured,
2448            "the gap now runs in the optimistic direction: the printed ceiling is larger \
2449             than the measured cost supports. `BUDGET_SHARE_DIVISOR` is what absorbs it \
2450             -- see this test's documentation before treating the inequality as harmless"
2451        );
2452    }
2453
2454    /// One archived repository must not take down an organization's whole
2455    /// demand poll — and must not read as zero either.
2456    #[tokio::test]
2457    async fn an_organization_steps_over_a_repository_local_failure_without_reading_it_as_zero() {
2458        let server = MockServer::start().await;
2459        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 4, 0).await;
2460        Mock::given(method("GET"))
2461            .and(path(runs_path(&other_repo())))
2462            .respond_with(
2463                ResponseTemplate::new(404).set_body_json(json!({ "message": "Not Found" })),
2464            )
2465            .mount(&server)
2466            .await;
2467        let gateway = gateway(&server);
2468
2469        let demand = gateway
2470            .queued_demand(&org_scope([repo(), other_repo()]), &CancelToken::new())
2471            .await
2472            .expect("an aggregate steps over a repository it cannot read");
2473
2474        assert_eq!(demand.total(), 4);
2475        assert_eq!(demand.unavailable().len(), 1);
2476        assert_eq!(demand.unavailable()[0].repository, other_repo());
2477        assert_eq!(
2478            demand.for_repository(&other_repo()),
2479            None,
2480            "a repository that could not be polled is absent from the map, not present \
2481             as a zero"
2482        );
2483        assert!(
2484            demand.jobs_for(&other_repo()).is_empty(),
2485            "and its job list is empty rather than absent, so a caller tallying it \
2486             cannot accidentally read an unavailable repository as demand"
2487        );
2488        assert!(
2489            !demand.is_complete(),
2490            "an aggregate missing a repository is not a complete reading"
2491        );
2492    }
2493
2494    /// The same `404`, on a repository *target*, propagates instead.
2495    ///
2496    /// Stepping over the only repository in scope would answer demand `0` for a
2497    /// target this host cannot see at all, and `e1` would then correctly start
2498    /// no runners for the wrong reason — with no error anywhere to explain it.
2499    #[tokio::test]
2500    async fn a_repository_target_propagates_the_failure_rather_than_reporting_zero_demand() {
2501        let server = MockServer::start().await;
2502        Mock::given(method("GET"))
2503            .and(path(runs_path(&repo())))
2504            .respond_with(
2505                ResponseTemplate::new(404).set_body_json(json!({ "message": "Not Found" })),
2506            )
2507            .mount(&server)
2508            .await;
2509        let gateway = gateway(&server);
2510
2511        let error = gateway
2512            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2513            .await
2514            .expect_err("a scope of one has no aggregate to step over into");
2515        assert!(matches!(
2516            error,
2517            InventoryError::Github(GithubError::Status { status: 404, .. })
2518        ));
2519    }
2520
2521    /// A failure on the *job* listing is a failure of the whole poll, not a
2522    /// silently short count.
2523    ///
2524    /// The job listing is where the new requests are, so it is where a new way
2525    /// to under-count could enter: a gateway that swallowed a failed job listing
2526    /// would report the run's jobs as zero, which is indistinguishable from a
2527    /// run whose jobs have all been dispatched.
2528    #[tokio::test]
2529    async fn a_failed_job_listing_is_not_read_as_a_run_with_no_queued_jobs() {
2530        let server = MockServer::start().await;
2531        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&[100])).await;
2532        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
2533        Mock::given(method("GET"))
2534            .and(path(jobs_path(&repo(), 100)))
2535            .respond_with(
2536                ResponseTemplate::new(500).set_body_json(json!({ "message": "Server Error" })),
2537            )
2538            .mount(&server)
2539            .await;
2540        let gateway = gateway(&server);
2541
2542        let error = gateway
2543            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2544            .await
2545            .expect_err("a job listing that failed is not a run with nothing queued");
2546        assert!(matches!(
2547            error,
2548            InventoryError::Github(GithubError::Status { status: 500, .. })
2549        ));
2550    }
2551
2552    /// A credential failure aborts the aggregate rather than being stepped over.
2553    ///
2554    /// A revoked token is a fact about the credential, not about the repository:
2555    /// stepping over it would report every remaining repository as unavailable
2556    /// and the total as a number, when in truth nothing can be read at all.
2557    #[tokio::test]
2558    async fn a_rate_limit_aborts_the_aggregate_rather_than_being_stepped_over() {
2559        let server = MockServer::start().await;
2560        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 1, 0).await;
2561        Mock::given(method("GET"))
2562            .and(path(runs_path(&other_repo())))
2563            .respond_with(
2564                ResponseTemplate::new(429)
2565                    .insert_header("retry-after", "42")
2566                    .set_body_json(json!({
2567                        "message": "You have exceeded a secondary rate limit"
2568                    })),
2569            )
2570            .mount(&server)
2571            .await;
2572        let gateway = gateway(&server);
2573
2574        let error = gateway
2575            .queued_demand(&org_scope([repo(), other_repo()]), &CancelToken::new())
2576            .await
2577            .expect_err("a rate limit is a fact about the credential, not the repository");
2578
2579        let limit = error
2580            .rate_limited()
2581            .expect("`c3`'s detector is what decides this, and it decided rate limit");
2582        assert_eq!(limit.retry_after, Some(std::time::Duration::from_secs(42)));
2583    }
2584
2585    // -- conditional polling, the shared window, and the quiet period -------
2586
2587    fn gateway_at(server: &MockServer, clock: &Arc<TestClock>) -> RestDemand {
2588        let endpoints = Endpoints::for_test_server(&server.uri()).expect("a test server base");
2589        let token = UserAccessToken::from_stored(SecretString::from(FIXTURE_TOKEN));
2590        let client =
2591            AuthenticatedClient::new(endpoints, token, Arc::clone(clock) as Arc<dyn Clock>)
2592                .expect("a client over the test server");
2593        RestDemand::new(Arc::new(client), Arc::clone(clock) as Arc<dyn Clock>)
2594    }
2595
2596    /// The account-wide quota headers GitHub puts on every response, `304`s
2597    /// included.
2598    fn with_quota(template: ResponseTemplate, remaining: u64) -> ResponseTemplate {
2599        template
2600            .insert_header("x-ratelimit-limit", "5000")
2601            .insert_header("x-ratelimit-remaining", remaining.to_string().as_str())
2602            .insert_header("x-ratelimit-used", (5000 - remaining).to_string().as_str())
2603            .insert_header("x-ratelimit-reset", "1787274000")
2604            .insert_header("x-ratelimit-resource", "core")
2605    }
2606
2607    /// One listing that answers `304` to its own tag and `200` + tag
2608    /// otherwise. Mounted conditional-first, because wiremock answers with the
2609    /// first mock whose matchers all pass.
2610    async fn mount_tagged(
2611        server: &MockServer,
2612        listing: &str,
2613        status: Option<&str>,
2614        etag: &str,
2615        body: serde_json::Value,
2616    ) {
2617        let mut not_modified = Mock::given(method("GET"))
2618            .and(path(listing.to_string()))
2619            .and(wiremock::matchers::header("if-none-match", etag));
2620        if let Some(status) = status {
2621            not_modified = not_modified.and(query_param("status", status));
2622        }
2623        not_modified
2624            .respond_with(with_quota(
2625                ResponseTemplate::new(304).insert_header("etag", etag),
2626                4_000,
2627            ))
2628            .mount(server)
2629            .await;
2630        let mut full = Mock::given(method("GET")).and(path(listing.to_string()));
2631        if let Some(status) = status {
2632            full = full.and(query_param("status", status));
2633        }
2634        full.respond_with(with_quota(
2635            ResponseTemplate::new(200)
2636                .insert_header("etag", etag)
2637                .set_body_json(body),
2638            4_000,
2639        ))
2640        .mount(server)
2641        .await;
2642    }
2643
2644    async fn mount_tagged_idle(server: &MockServer, repository: &OwnerRepo) {
2645        let runs = runs_path(repository);
2646        mount_tagged(
2647            server,
2648            &runs,
2649            Some(QUEUED_RUN_STATUS),
2650            r#"W/"queued""#,
2651            no_runs(),
2652        )
2653        .await;
2654        mount_tagged(
2655            server,
2656            &runs,
2657            Some(IN_PROGRESS_RUN_STATUS),
2658            r#"W/"in-progress""#,
2659            no_runs(),
2660        )
2661        .await;
2662    }
2663
2664    fn conditional_requests(received: &[wiremock::Request]) -> usize {
2665        received
2666            .iter()
2667            .filter(|request| request.headers.contains_key("if-none-match"))
2668            .count()
2669    }
2670
2671    /// The owner's requirement in one test: an idle repository polled again
2672    /// sends its tags back, GitHub answers `304`, and the reading is the same.
2673    #[tokio::test]
2674    async fn an_unchanged_repository_is_polled_with_its_etags_and_answered_304() {
2675        let server = MockServer::start().await;
2676        mount_tagged_idle(&server, &repo()).await;
2677        let clock = Arc::new(TestClock::default());
2678        let gateway = gateway_at(&server, &clock);
2679        let scope = ActivityScope::repository(repo());
2680
2681        let first = gateway
2682            .queued_demand(&scope, &CancelToken::new())
2683            .await
2684            .expect("a first reading");
2685        let second = gateway
2686            .queued_demand(&scope, &CancelToken::new())
2687            .await
2688            .expect("a second reading");
2689
2690        assert_eq!(first.per_repository(), second.per_repository());
2691        let received = server.received_requests().await.expect("recorded requests");
2692        assert_eq!(received.len(), 4, "two listings, twice");
2693        assert_eq!(
2694            conditional_requests(&received),
2695            2,
2696            "the second poll sends both tags back"
2697        );
2698        let traffic = gateway.client().traffic().summary(clock.now());
2699        assert_eq!((traffic.full, traffic.not_modified), (2, 2));
2700        let stats = gateway.stats();
2701        assert_eq!((stats.reads, stats.unchanged_reads), (2, 1));
2702        assert!(second.is_quiet());
2703    }
2704
2705    /// A conditional request must never hide a change: a new run on the very
2706    /// next poll is counted on that poll.
2707    #[tokio::test]
2708    async fn a_run_that_arrives_between_polls_is_counted_on_the_next_one() {
2709        let server = MockServer::start().await;
2710        let runs = runs_path(&repo());
2711        // Asked with the first tag, the queue has moved on: a full answer with
2712        // a new tag.
2713        Mock::given(method("GET"))
2714            .and(path(runs.clone()))
2715            .and(query_param("status", QUEUED_RUN_STATUS))
2716            .and(wiremock::matchers::header("if-none-match", r#"W/"empty""#))
2717            .respond_with(
2718                ResponseTemplate::new(200)
2719                    .insert_header("etag", r#"W/"one-run""#)
2720                    .set_body_json(runs_body(&[100])),
2721            )
2722            .mount(&server)
2723            .await;
2724        Mock::given(method("GET"))
2725            .and(path(runs.clone()))
2726            .and(query_param("status", QUEUED_RUN_STATUS))
2727            .respond_with(
2728                ResponseTemplate::new(200)
2729                    .insert_header("etag", r#"W/"empty""#)
2730                    .set_body_json(no_runs()),
2731            )
2732            .mount(&server)
2733            .await;
2734        mount_tagged(
2735            &server,
2736            &runs,
2737            Some(IN_PROGRESS_RUN_STATUS),
2738            r#"W/"in-progress""#,
2739            no_runs(),
2740        )
2741        .await;
2742        mount_jobs(&server, &repo(), 100, jobs_body(&["rm-home-win-x64"], 2, 0)).await;
2743        let clock = Arc::new(TestClock::default());
2744        let gateway = gateway_at(&server, &clock);
2745        let scope = ActivityScope::repository(repo());
2746
2747        let before = gateway
2748            .queued_demand(&scope, &CancelToken::new())
2749            .await
2750            .expect("an idle reading");
2751        let after = gateway
2752            .queued_demand(&scope, &CancelToken::new())
2753            .await
2754            .expect("a reading after the run arrived");
2755
2756        assert_eq!(before.total(), 0);
2757        assert_eq!(after.total(), 2, "the change is seen on the very next poll");
2758        assert!(
2759            !after.is_quiet(),
2760            "a run under way whose listing changed is activity"
2761        );
2762    }
2763
2764    /// A run stuck in the queue for a label nobody serves is still in the
2765    /// listing hours later. While its listings answer `304` it costs nothing,
2766    /// and it must not hold the target at the slower active interval.
2767    #[tokio::test]
2768    async fn a_queued_run_whose_listings_are_unchanged_is_quiet() {
2769        let server = MockServer::start().await;
2770        let runs = runs_path(&repo());
2771        mount_tagged(
2772            &server,
2773            &runs,
2774            Some(QUEUED_RUN_STATUS),
2775            r#"W/"stuck""#,
2776            runs_body(&[100]),
2777        )
2778        .await;
2779        mount_tagged(
2780            &server,
2781            &runs,
2782            Some(IN_PROGRESS_RUN_STATUS),
2783            r#"W/"in-progress""#,
2784            no_runs(),
2785        )
2786        .await;
2787        mount_tagged(
2788            &server,
2789            &jobs_path(&repo(), 100),
2790            None,
2791            r#"W/"jobs""#,
2792            jobs_body(&["ubuntu-latest"], 1, 0),
2793        )
2794        .await;
2795        let clock = Arc::new(TestClock::default());
2796        let gateway = gateway_at(&server, &clock);
2797        let scope = ActivityScope::repository(repo());
2798
2799        let first = gateway
2800            .queued_demand(&scope, &CancelToken::new())
2801            .await
2802            .expect("a first reading");
2803        let second = gateway
2804            .queued_demand(&scope, &CancelToken::new())
2805            .await
2806            .expect("a second reading");
2807
2808        assert!(
2809            !first.is_quiet(),
2810            "the first sight of a run is a change, and the target must look at it"
2811        );
2812        assert!(second.is_quiet(), "nothing changed; three 304s");
2813        assert_eq!(second.total(), 1, "the job is still counted from the cache");
2814        let received = server.received_requests().await.expect("recorded requests");
2815        assert_eq!(conditional_requests(&received), 3);
2816    }
2817
2818    /// The quota GitHub reports during the poll travels with the reading, so
2819    /// `e1` can slow down on it.
2820    #[tokio::test]
2821    async fn the_accounts_quota_travels_with_the_reading() {
2822        let server = MockServer::start().await;
2823        mount_tagged_idle(&server, &repo()).await;
2824        let clock = Arc::new(TestClock::default());
2825        let gateway = gateway_at(&server, &clock);
2826
2827        let reading = gateway
2828            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2829            .await
2830            .expect("a reading");
2831
2832        let quota = reading
2833            .rate_limit()
2834            .expect("every response carries the quota");
2835        assert_eq!(
2836            (quota.limit, quota.remaining, quota.used),
2837            (5000, 4000, Some(1000))
2838        );
2839    }
2840
2841    /// Two targets covering one repository make one read between them.
2842    #[tokio::test]
2843    async fn a_repository_is_read_once_for_every_target_that_covers_it() {
2844        let server = MockServer::start().await;
2845        mount_tagged_idle(&server, &repo()).await;
2846        mount_tagged_idle(&server, &other_repo()).await;
2847        let clock = Arc::new(TestClock::default());
2848        let gateway = gateway_at(&server, &clock).with_shared_readings(Duration::from_secs(10));
2849
2850        // A repository target and an organization target that contains it.
2851        gateway
2852            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2853            .await
2854            .expect("the repository target's reading");
2855        let organization = gateway
2856            .queued_demand(&org_scope([repo(), other_repo()]), &CancelToken::new())
2857            .await
2858            .expect("the organization target's reading");
2859
2860        assert_eq!(organization.per_repository().len(), 2);
2861        assert_eq!(
2862            gateway.requests_issued(),
2863            4,
2864            "dashboard once (2 listings) and api once (2): the organization target is \
2865             handed the repository target's reading of dashboard"
2866        );
2867        assert_eq!(gateway.stats().shared_reads, 1);
2868
2869        // Past the window the repository is read again.
2870        clock.advance_secs(10);
2871        gateway
2872            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2873            .await
2874            .expect("a later reading");
2875        assert_eq!(gateway.requests_issued(), 6);
2876    }
2877
2878    /// A coordinator's wake drops the shared reading, so the woken poll reads
2879    /// GitHub inside the window instead of being handed the stale one.
2880    #[tokio::test]
2881    async fn a_forgotten_reading_is_read_again_inside_the_window() {
2882        let server = MockServer::start().await;
2883        mount_tagged_idle(&server, &repo()).await;
2884        let clock = Arc::new(TestClock::default());
2885        let gateway = gateway_at(&server, &clock).with_shared_readings(Duration::from_secs(10));
2886        let scope = ActivityScope::repository(repo());
2887
2888        gateway
2889            .queued_demand(&scope, &CancelToken::new())
2890            .await
2891            .expect("a first reading");
2892        gateway
2893            .queued_demand(&scope, &CancelToken::new())
2894            .await
2895            .expect("shared");
2896        assert_eq!(gateway.requests_issued(), 2, "the second was shared");
2897
2898        gateway.forget_shared_reading(&repo());
2899        gateway
2900            .queued_demand(&scope, &CancelToken::new())
2901            .await
2902            .expect("read again");
2903        assert_eq!(gateway.requests_issued(), 4);
2904    }
2905
2906    /// Two loops asking at the same moment make one read between them.
2907    #[tokio::test]
2908    async fn concurrent_targets_wait_for_one_read_instead_of_making_two() {
2909        let server = MockServer::start().await;
2910        mount_tagged_idle(&server, &repo()).await;
2911        let clock = Arc::new(TestClock::default());
2912        let gateway =
2913            Arc::new(gateway_at(&server, &clock).with_shared_readings(Duration::from_secs(10)));
2914
2915        let scope = ActivityScope::repository(repo());
2916        let cancel = CancelToken::new();
2917        let (left, right) = tokio::join!(
2918            gateway.queued_demand(&scope, &cancel),
2919            gateway.queued_demand(&scope, &cancel),
2920        );
2921        left.expect("one reading");
2922        right.expect("the other reading");
2923        assert_eq!(gateway.requests_issued(), 2, "one read: two listings");
2924    }
2925
2926    fn secondary_limit(retry_after: Option<&str>) -> ResponseTemplate {
2927        let template = ResponseTemplate::new(429).set_body_json(json!({
2928            "message": "You have exceeded a secondary rate limit"
2929        }));
2930        match retry_after {
2931            Some(seconds) => template.insert_header("retry-after", seconds),
2932            None => template,
2933        }
2934    }
2935
2936    /// GitHub: "If the `retry-after` response header is present, you should
2937    /// not retry your request until after that many seconds has elapsed." Not
2938    /// this poll, and not any other target's poll on this host either.
2939    #[tokio::test]
2940    async fn a_secondary_limit_stops_every_demand_request_until_retry_after() {
2941        let server = MockServer::start().await;
2942        Mock::given(method("GET"))
2943            .respond_with(secondary_limit(Some("42")))
2944            .mount(&server)
2945            .await;
2946        let clock = Arc::new(TestClock::default());
2947        let gateway = gateway_at(&server, &clock);
2948
2949        let first = gateway
2950            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2951            .await
2952            .expect_err("a rate limit");
2953        assert_eq!(
2954            first.rate_limited().and_then(|limit| limit.retry_after),
2955            Some(Duration::from_secs(42))
2956        );
2957
2958        // Another target, half-way through the window: no request at all.
2959        clock.advance_secs(20);
2960        let held = gateway
2961            .queued_demand(
2962                &ActivityScope::repository(other_repo()),
2963                &CancelToken::new(),
2964            )
2965            .await
2966            .expect_err("still inside the quiet period");
2967        assert_eq!(
2968            held.rate_limited().and_then(|limit| limit.retry_after),
2969            Some(Duration::from_secs(22)),
2970            "the wait left, so the loop's schedule sleeps exactly that"
2971        );
2972        assert_eq!(
2973            server.received_requests().await.expect("recorded").len(),
2974            1,
2975            "a request inside the quiet period is the one GitHub said not to send"
2976        );
2977        assert_eq!(gateway.stats().suppressed, 1);
2978
2979        // At the end of the window, the next poll asks again.
2980        clock.advance_secs(22);
2981        let _ = gateway
2982            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2983            .await;
2984        assert_eq!(server.received_requests().await.expect("recorded").len(), 2);
2985    }
2986
2987    /// GitHub: "Otherwise, wait for at least one minute before retrying. If
2988    /// your request continues to fail due to a secondary rate limit, wait for
2989    /// an exponentially increasing amount of time between retries."
2990    #[tokio::test]
2991    async fn a_recurring_secondary_limit_doubles_the_quiet_period() {
2992        let server = MockServer::start().await;
2993        Mock::given(method("GET"))
2994            .respond_with(secondary_limit(None))
2995            .mount(&server)
2996            .await;
2997        let clock = Arc::new(TestClock::default());
2998        let gateway = gateway_at(&server, &clock);
2999        let scope = ActivityScope::repository(repo());
3000
3001        let mut waits = Vec::new();
3002        for _ in 0..4 {
3003            let error = gateway
3004                .queued_demand(&scope, &CancelToken::new())
3005                .await
3006                .expect_err("a rate limit");
3007            let wait = error
3008                .rate_limited()
3009                .and_then(|limit| limit.retry_after)
3010                .expect("a wait");
3011            waits.push(wait.as_secs());
3012            clock.advance_secs(i64::try_from(wait.as_secs()).expect("fits"));
3013        }
3014        assert_eq!(waits, [60, 120, 240, 480]);
3015    }
3016
3017    fn secondary(retry_after: Option<u64>) -> RateLimited {
3018        RateLimited {
3019            kind: RateLimitKind::Secondary,
3020            retry_after: retry_after.map(Duration::from_secs),
3021            remaining: Some(4_000),
3022            reset_unix_secs: None,
3023        }
3024    }
3025
3026    /// Every loop shares the gateway, so one secondary limit can come back on
3027    /// several requests that were in flight together. That is one episode.
3028    #[tokio::test]
3029    async fn answers_to_one_secondary_limit_in_flight_together_are_one_episode() {
3030        let server = MockServer::start().await;
3031        let clock = Arc::new(TestClock::default());
3032        let gateway = gateway_at(&server, &clock);
3033        let now = clock.now();
3034
3035        let waits: Vec<u64> = (0..4)
3036            .map(|_| {
3037                gateway
3038                    .hold_for(secondary(None), now)
3039                    .retry_after
3040                    .expect("a wait")
3041                    .as_secs()
3042            })
3043            .collect();
3044        assert_eq!(waits, [60, 60, 60, 60], "four answers, one limit");
3045
3046        clock.advance_secs(60);
3047        let again = gateway.hold_for(secondary(None), clock.now());
3048        assert_eq!(
3049            again.retry_after,
3050            Some(Duration::from_secs(120)),
3051            "an answer after the hold ended is GitHub saying \"still limited\""
3052        );
3053    }
3054
3055    /// A primary limit with a near reset must not reopen what a secondary
3056    /// limit closed.
3057    #[tokio::test]
3058    async fn a_later_answer_never_shortens_a_hold_in_force() {
3059        let server = MockServer::start().await;
3060        let clock = Arc::new(TestClock::default());
3061        let gateway = gateway_at(&server, &clock);
3062
3063        let _ = gateway.hold_for(secondary(Some(600)), clock.now());
3064        let primary = RateLimited {
3065            kind: RateLimitKind::Primary,
3066            retry_after: None,
3067            remaining: Some(0),
3068            reset_unix_secs: Some(u64::try_from(clock.now().timestamp() + 30).expect("positive")),
3069        };
3070        let after = gateway.hold_for(primary, clock.now());
3071        assert_eq!(after.retry_after, Some(Duration::from_secs(600)));
3072        clock.advance_secs(300);
3073        assert_eq!(
3074            gateway
3075                .held(clock.now())
3076                .and_then(|limit| limit.retry_after),
3077            Some(Duration::from_secs(300))
3078        );
3079    }
3080
3081    #[test]
3082    fn an_unavailable_repository_is_not_quiet() {
3083        assert!(QueuedDemand::default().is_quiet());
3084        assert!(
3085            !QueuedDemand::default()
3086                .with_unavailable(repo(), "404")
3087                .is_quiet(),
3088            "its failing listing is charged on every poll; polling it every few seconds \
3089             would multiply that"
3090        );
3091    }
3092
3093    /// A draining loop must not wait behind another loop's read.
3094    #[tokio::test]
3095    async fn a_cancelled_loop_does_not_wait_for_another_loops_read() {
3096        let server = MockServer::start().await;
3097        let clock = Arc::new(TestClock::default());
3098        let gateway = gateway_at(&server, &clock).with_shared_readings(Duration::from_secs(10));
3099        let gate = Arc::clone(
3100            gateway
3101                .shared
3102                .gates
3103                .lock()
3104                .expect("gates")
3105                .entry(repo())
3106                .or_default(),
3107        );
3108        let _another_loop = gate.lock().await;
3109        let cancel = CancelToken::new();
3110        cancel.cancel();
3111
3112        let answer = tokio::time::timeout(
3113            Duration::from_secs(5),
3114            gateway.repository_reading(&repo(), &cancel),
3115        )
3116        .await
3117        .expect("a cancelled loop returns at once instead of queueing on the gate");
3118        assert!(answer.is_err_and(|error| error.is_cancelled()));
3119    }
3120
3121    /// A success in between resets the doubling.
3122    #[tokio::test]
3123    async fn a_success_resets_the_doubling() {
3124        let server = MockServer::start().await;
3125        Mock::given(method("GET"))
3126            .respond_with(secondary_limit(None))
3127            .up_to_n_times(1)
3128            .mount(&server)
3129            .await;
3130        mount_idle(&server, &repo()).await;
3131        let clock = Arc::new(TestClock::default());
3132        let gateway = gateway_at(&server, &clock);
3133        let scope = ActivityScope::repository(repo());
3134
3135        let _ = gateway.queued_demand(&scope, &CancelToken::new()).await;
3136        clock.advance_secs(60);
3137        gateway
3138            .queued_demand(&scope, &CancelToken::new())
3139            .await
3140            .expect("GitHub answered");
3141        server.reset().await;
3142        Mock::given(method("GET"))
3143            .respond_with(secondary_limit(None))
3144            .mount(&server)
3145            .await;
3146        let again = gateway
3147            .queued_demand(&scope, &CancelToken::new())
3148            .await
3149            .expect_err("a fresh rate limit");
3150        assert_eq!(
3151            again.rate_limited().and_then(|limit| limit.retry_after),
3152            Some(Duration::from_secs(60)),
3153            "a limit after a success is a first limit again"
3154        );
3155    }
3156
3157    // -- cancellation -------------------------------------------------------
3158
3159    /// A token flipped between requests stops the poll before the next one.
3160    #[tokio::test]
3161    async fn cancellation_between_requests_stops_the_poll() {
3162        let server = MockServer::start().await;
3163        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 3, 0).await;
3164
3165        let gateway = gateway(&server);
3166        let cancel = CancelToken::new();
3167
3168        let first = gateway
3169            .repository_queued(&repo(), &cancel)
3170            .await
3171            .is_ok_and(|reading| reading.jobs.len() == 3);
3172        assert!(first, "the uncancelled poll reads both lists and the jobs");
3173        assert_eq!(gateway.requests_issued(), 3);
3174
3175        cancel.cancel();
3176        let error = gateway
3177            .repository_queued(&repo(), &cancel)
3178            .await
3179            .expect_err("a cancelled token opens no socket at all");
3180        assert!(error.is_cancelled());
3181        assert_eq!(
3182            gateway.requests_issued(),
3183            3,
3184            "a cancelled poll must spend nothing; the count is of requests attempted"
3185        );
3186    }
3187
3188    // -- the seam this module does not own ---------------------------------
3189
3190    /// The `runs-on` predicate is `b1`'s. This module builds its **input** and
3191    /// implements no part of the matching.
3192    ///
3193    /// # Read this before concluding the test is in the wrong file
3194    ///
3195    /// `c4`'s specification asks for "a `runs-on` table covering forms that must
3196    /// match, forms that must not, and an unresolvable expression, delegating
3197    /// the predicate to `b1`". For a while that table had no input: an owner
3198    /// decision had removed the per-run job listing, a workflow *run* carries no
3199    /// `runs-on`, and this gateway therefore produced nothing to match. That
3200    /// decision has been reversed — the module documentation says why — so the
3201    /// table has its input back and this test asserts both halves of the seam
3202    /// rather than only the delegation half.
3203    ///
3204    /// The division of labour is: `c4` reads each queued job's `labels` array
3205    /// and builds a [`RunsOn`], `b1` decides what matches, and `e1` applies the
3206    /// decision per policy. Constructing a `RunsOn` here is the correct side of
3207    /// that line; comparing labels here is not.
3208    ///
3209    /// # How the second half of that claim is asserted, and how far it reaches
3210    ///
3211    /// By reading this file's own source, because nothing done to `b1` can prove
3212    /// anything about what *this* module contains: every assertion in the body
3213    /// below would pass unchanged with a full label matcher sitting beside it.
3214    /// The scan takes the production half — everything above `#[cfg(test)]`,
3215    /// with comment lines dropped so that the module documentation may keep
3216    /// explaining the seam — and requires that it names none of `b1`'s
3217    /// *decision* vocabulary.
3218    ///
3219    /// `RunsOn` is no longer in the forbidden set, and could not be: this module
3220    /// constructs one per queued job, which is the whole point of the reversal.
3221    /// What stays forbidden is everything that would mean deciding rather than
3222    /// describing — `RoutingLabels`, whose `matches` and `tally` are the
3223    /// predicate, and `DemandTally`, which is the predicate's result. A `c4`
3224    /// that named either would be filtering, and filtering here would make the
3225    /// poll per-policy rather than per-target; the module documentation explains
3226    /// why that trade is refused.
3227    ///
3228    /// Like the needles in `nothing_in_this_crate_reserves_or_claims_a_job`, it
3229    /// is a tripwire on the obvious shape rather than a proof: a hand-rolled
3230    /// comparison of raw label strings that never names a `policy` type would
3231    /// walk past it. Stated rather than implied, for the same reason it is
3232    /// stated there.
3233    #[test]
3234    fn the_runs_on_predicate_is_b1s_and_this_module_only_feeds_it() {
3235        let labels = RoutingLabels::derive(
3236            &HostLabel::new("home").expect("a valid host label"),
3237            Os::Windows,
3238            Arch::X64,
3239        );
3240        let host = labels.host_label().as_str().to_string();
3241        assert_eq!(host, "rm-home-win-x64");
3242
3243        // Must match: the host label alone, in each documented form.
3244        for form in [
3245            RunsOn::Single(host.clone()),
3246            RunsOn::Many(vec![host.clone()]),
3247            RunsOn::Grouped {
3248                group: Some("Default".into()),
3249                labels: runner_manager_domain::policy::RunsOnLabels::One(host.clone()),
3250            },
3251        ] {
3252            assert!(
3253                labels.matches(&form).is_match(),
3254                "a job requiring only this policy's own label must match: {form:?}"
3255            );
3256        }
3257
3258        // Must not match: GitHub-hosted, and another host's label.
3259        for form in [
3260            RunsOn::Single("ubuntu-latest".into()),
3261            RunsOn::Many(vec![host.clone(), "rm-office-win-x64".into()]),
3262        ] {
3263            assert!(
3264                !labels.matches(&form).is_match(),
3265                "a job requiring a label this policy does not carry must not match: {form:?}"
3266            );
3267        }
3268
3269        // Unresolvable: an expression only GitHub can evaluate. Never demand and
3270        // never discarded.
3271        let expression = RunsOn::Single("${{ matrix.runner }}".into());
3272        assert!(matches!(
3273            labels.matches(&expression),
3274            RunsOnMatch::Unresolvable(UnresolvableRunsOn::Expression { .. })
3275        ));
3276
3277        // And the tally keeps the three apart, which is what `e1` clamps.
3278        let tally = labels.tally(&[
3279            RunsOn::Single(host.clone()),
3280            RunsOn::Single("ubuntu-latest".into()),
3281            expression,
3282        ]);
3283        assert_eq!(tally.demand(), 1);
3284        assert_eq!(tally.not_matched, 1);
3285        assert_eq!(tally.unresolvable.len(), 1);
3286        assert_eq!(tally.total_seen(), 3);
3287
3288        // The form this gateway actually builds is the array one, because that
3289        // is the shape the jobs API returns. Pinned so that a `RunsOn` built
3290        // from a job's `labels` really is a value `b1`'s predicate accepts,
3291        // rather than one that happens to compile.
3292        assert_eq!(
3293            RunsOn::from_job_labels(["self-hosted", host.as_str()]),
3294            RunsOn::Many(vec!["self-hosted".into(), host.clone()])
3295        );
3296        assert!(
3297            labels
3298                .matches(&RunsOn::from_job_labels([host.as_str()]))
3299                .is_match()
3300        );
3301        // And the direction that surprises people: a bare derived set does not
3302        // carry `self-hosted`, so the shape most workflows are written in --
3303        // `runs-on: [self-hosted, windows]` -- does **not** match a policy whose
3304        // operator never added those labels. That is `b1`'s superset rule
3305        // working as specified rather than a gap, and it is asserted here
3306        // because the job listing is what finally made it observable.
3307        assert!(
3308            !labels
3309                .matches(&RunsOn::from_job_labels(["self-hosted", host.as_str()]))
3310                .is_match(),
3311            "a job requiring `self-hosted` needs a policy carrying `self-hosted`"
3312        );
3313
3314        // And the other half of this test's title, which everything above leaves
3315        // untouched: that the predicate exercised here has no second
3316        // implementation in this file. See the documentation on this test for
3317        // what the scan covers, what it does not, and why `RunsOn` is absent
3318        // from the list.
3319        let production = this_file_above_its_tests_without_prose();
3320        for owned_by_b1 in ["RoutingLabels", "DemandTally"] {
3321            assert!(
3322                !production.contains(owned_by_b1),
3323                "the demand gateway names `{owned_by_b1}`, which belongs to `b1`: this \
3324                 module builds the predicate's input and does not apply it. Filtering \
3325                 here would make the poll per-policy rather than per-target and multiply \
3326                 its request cost by the number of policies sharing a target -- if an \
3327                 owner decision changed that, it belongs in this module's documentation \
3328                 and in this test before it belongs in the code"
3329            );
3330        }
3331        assert!(
3332            production.contains("RunsOn"),
3333            "and the gateway must still *build* a `RunsOn` per queued job; a production \
3334             half that named none would mean the job listing had been removed again and \
3335             the serial-matrix defect restored"
3336        );
3337    }
3338
3339    /// This file's source above its test module, with comment lines dropped.
3340    ///
3341    /// Two exclusions, each load-bearing. The **test module** goes because the
3342    /// tests above legitimately drive `b1`'s predicate and would accuse the file
3343    /// of owning what they are proving it delegates. The **comments** go because
3344    /// this module's documentation explains the seam at length and names the
3345    /// types to do it — a scan that forbade the explanation would get the
3346    /// explanation deleted, which is the trade
3347    /// `nothing_in_this_crate_reserves_or_claims_a_job` records making in the
3348    /// other direction.
3349    fn this_file_above_its_tests_without_prose() -> String {
3350        let (production, _) = include_str!("demand.rs")
3351            .split_once("\n#[cfg(test)]")
3352            .expect("this file has a test module, and the scan is meaningless without one");
3353        production
3354            .lines()
3355            .filter(|line| !line.trim_start().starts_with("//"))
3356            .collect::<Vec<_>>()
3357            .join("\n")
3358    }
3359
3360    /// The one normalisation both halves of the reservation scan use.
3361    ///
3362    /// Shared rather than written twice, because the defect it closes was two
3363    /// spellings of "the same" normalisation drifting apart: the haystack was
3364    /// lower-cased and the needle was not, so every needle carrying a capital —
3365    /// which is every type-shaped one — could not match a lower-cased haystack,
3366    /// and three of the seven assertions were vacuously true from the day they
3367    /// were written. One function cannot disagree with itself.
3368    fn normalise_for_scan(text: &str) -> String {
3369        text.to_ascii_lowercase().replace(['_', ' '], "")
3370    }
3371
3372    // The Actions-service call this design has no equivalent of, plus the shapes
3373    // an implementer would invent in its place. Matched case-insensitively with
3374    // `_` and spaces removed, so one needle catches the snake, camel and Pascal
3375    // spellings of an identifier at once — and so that the singular needle
3376    // catches the plural.
3377    //
3378    // # Why every needle carries `fn` or `struct`
3379    //
3380    // A bare `acquirejobs` fires on this crate's own prose, and it was written
3381    // that way first: three modules explain *why* there is no job reservation,
3382    // and each has to name the call that does not exist in order to say so. A
3383    // scan that forbids the explanation is a scan that gets the explanation
3384    // deleted, which costs more than it protects. Requiring the item keyword
3385    // narrows the needle to a *definition*, which is what the rule is actually
3386    // about.
3387    //
3388    // What this therefore does **not** catch is stated rather than implied: a
3389    // reservation reached through a trait method, a closure, or a
3390    // differently-named helper. It is a tripwire on the obvious shape, and
3391    // `c4`'s Definition of Done names review as the primary control.
3392    //
3393    // # And why every needle is spelled in halves
3394    //
3395    // `lib.rs`'s confidential-credential scan solves the same problem the same
3396    // way: a needle written out whole would appear in this file's own source and
3397    // the scan would accuse itself. Normalising
3398    // `concat!("fn ", "acquire", "_job")` leaves the quote-comma-quote between
3399    // the halves, so no needle ever appears whole in the text being scanned.
3400    const FORBIDDEN: &[&str] = &[
3401        concat!("fn ", "acquire", "_job"),
3402        concat!("fn ", "claim", "_job"),
3403        concat!("fn ", "lease", "_job"),
3404        concat!("fn ", "reserve", "_job"),
3405        // The acknowledgement this test's own title names alongside the other
3406        // three, and which the list did not actually carry. Spelled to the verb
3407        // rather than to a `_job` suffix, because the shape an implementer
3408        // reaches for acknowledges a *message* or an *assignment* as readily as
3409        // a job, and a suffixed needle would walk straight past those.
3410        concat!("fn ", "ack", "nowledge"),
3411        concat!("struct ", "Job", "Lease"),
3412        concat!("struct ", "Job", "Claim"),
3413        concat!("struct ", "Job", "Reservation"),
3414    ];
3415
3416    /// Which forbidden shape a source text names, if any.
3417    ///
3418    /// The whole-crate scan and its positive control both go through here, so a
3419    /// normalisation that cannot see a shape fails the control loudly instead of
3420    /// passing the scan silently. That is the entire point of the indirection:
3421    /// the arrangement this replaced had the control re-deriving the needle
3422    /// itself, and a copy that agrees with a buggy original proves nothing — it
3423    /// re-derived the needle the same wrong way and went green.
3424    fn forbidden_shape_in(source: &str) -> Option<&'static str> {
3425        let haystack = normalise_for_scan(source);
3426        FORBIDDEN
3427            .iter()
3428            .copied()
3429            .find(|forbidden| haystack.contains(&normalise_for_scan(forbidden)))
3430    }
3431
3432    /// No reservation, claim, lease, or acknowledgement call exists anywhere in
3433    /// this crate.
3434    ///
3435    /// `AcquireJobs` had no REST replacement, so a well-meaning implementer
3436    /// reaches for a local lease to "fix" the surplus-runner case. Three
3437    /// specifications say not to; this makes the instruction executable, over
3438    /// the whole crate rather than only this file, because the edit would most
3439    /// likely land in a new module rather than here.
3440    #[test]
3441    fn nothing_in_this_crate_reserves_or_claims_a_job() {
3442        const SOURCES: &[(&str, &str)] = &[
3443            ("conditional.rs", include_str!("conditional.rs")),
3444            ("demand.rs", include_str!("demand.rs")),
3445            ("device_flow.rs", include_str!("device_flow.rs")),
3446            ("jit.rs", include_str!("jit.rs")),
3447            ("lib.rs", include_str!("lib.rs")),
3448            ("rest.rs", include_str!("rest.rs")),
3449            ("traffic.rs", include_str!("traffic.rs")),
3450        ];
3451        // `SOURCES` is a snapshot, and a snapshot makes "anywhere in the crate"
3452        // false the moment a file is added. The walk below turns the claim back
3453        // into a claim.
3454        //
3455        // It **recurses**, and that is not incidental. `lib.rs` records the
3456        // defect a single `read_dir` produced for the same pin: a module
3457        // directory (`src/rest/mod.rs`) arrives as the entry `rest`, which does
3458        // not end in `.rs`, so a flat filter drops it and takes every file
3459        // underneath with it — leaving the pin passing while the files it exists
3460        // to cover are scanned by nothing at all.
3461        fn walk(directory: &std::path::Path, prefix: &str, found: &mut Vec<String>) {
3462            for entry in std::fs::read_dir(directory).expect("the crate's own src/ is readable") {
3463                let entry = entry.expect("a readable directory entry");
3464                let name = entry.file_name().to_string_lossy().into_owned();
3465                // `/`-joined, which is what `include_str!` takes on every
3466                // platform, so the two sides compare directly.
3467                let joined = if prefix.is_empty() {
3468                    name.clone()
3469                } else {
3470                    format!("{prefix}/{name}")
3471                };
3472                if entry.path().is_dir() {
3473                    walk(&entry.path(), &joined, found);
3474                } else if name.ends_with(".rs") {
3475                    found.push(joined);
3476                }
3477            }
3478        }
3479
3480        let mut listed: Vec<&str> = SOURCES.iter().map(|(name, _)| *name).collect();
3481        listed.sort_unstable();
3482        let mut on_disk = Vec::new();
3483        walk(
3484            std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")),
3485            "",
3486            &mut on_disk,
3487        );
3488        on_disk.sort_unstable();
3489        assert_eq!(
3490            listed, on_disk,
3491            "a source file was added or removed; this scan claims to cover the whole \
3492             crate and a stale list makes that claim false"
3493        );
3494
3495        for (name, source) in SOURCES {
3496            assert_eq!(
3497                forbidden_shape_in(source),
3498                None,
3499                "{name} names a forbidden shape: there is no job reservation on the REST \
3500                 path, and a local lease coordinates this host with itself and with \
3501                 nothing else"
3502            );
3503        }
3504    }
3505
3506    /// The scan above can actually see the things it forbids.
3507    ///
3508    /// A substring scan that never matches passes for the wrong reason. This
3509    /// plants the exact shapes and runs them through [`forbidden_shape_in`] —
3510    /// the same matcher the scan uses, rather than a second copy of it.
3511    ///
3512    /// # Why one planted shape was not enough
3513    ///
3514    /// It planted only the `fn` form, and that form is the one that could not
3515    /// fail: a `fn` needle is already lower-case, so it survived a
3516    /// normalisation that lower-cased the haystack and not the needle. Every
3517    /// type-shaped needle carries capitals and therefore could never match the
3518    /// lower-cased haystack — all three of them were un-catchable, and their
3519    /// three assertions vacuously true, while this control stayed green. (They
3520    /// are not written out here for the reason the list itself is spelled in
3521    /// halves: a literal would make this file fail its own gate.) Both kinds
3522    /// are planted now, and the case-shape of the plant is the property under
3523    /// test rather than an incidental detail of it.
3524    #[test]
3525    fn the_reservation_scan_catches_an_injected_reservation() {
3526        // Assembled from fragments rather than written out, because the scan
3527        // above reads this very file: a literal here would make the crate fail
3528        // its own gate, which is the trap that forced the needles to carry an
3529        // item keyword in the first place.
3530        let call = format!(
3531            "    async {} {}{}(&self) -> Result<Vec<Job>, InventoryError> {{",
3532            "fn", "acquire", "_jobs"
3533        );
3534        let item = format!("{} {}{} {{ id: u64 }}", "struct", "Job", "Lease");
3535        let acknowledgement = format!(
3536            "    async {} {}{}(&self, id: u64) {{",
3537            "fn", "ack", "nowledge_assignment"
3538        );
3539
3540        for (planted, expected) in [
3541            (&call, concat!("fn ", "acquire", "_job")),
3542            (&item, concat!("struct ", "Job", "Lease")),
3543            (&acknowledgement, concat!("fn ", "ack", "nowledge")),
3544        ] {
3545            assert_eq!(
3546                forbidden_shape_in(planted),
3547                Some(expected),
3548                "the scan's own matcher cannot see {planted:?}, so every negative \
3549                 assertion it makes about that shape is worthless"
3550            );
3551        }
3552
3553        // And the plural really is caught by the singular needle, which is the
3554        // one thing about the list above that is not obvious from reading it.
3555        assert!(
3556            call.contains("acquire_jobs"),
3557            "the planted shape is the plural the Actions-service protocol used"
3558        );
3559        // Likewise the acknowledgement needle stops at the verb, so it catches
3560        // the shapes that acknowledge something other than a job by name.
3561        assert!(
3562            acknowledgement.contains("_assignment"),
3563            "the planted acknowledgement names no job, which is why the needle \
3564             carrying a `_job` suffix would have missed it"
3565        );
3566    }
3567}