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    /// The window readings are shared for.
834    fn shared_window(&self) -> Duration {
835        Duration::from_millis(self.shared.window_ms.load(Ordering::SeqCst))
836    }
837
838    /// What this gateway has done.
839    #[must_use]
840    pub fn stats(&self) -> DemandStats {
841        DemandStats {
842            reads: self.stats.reads.load(Ordering::SeqCst),
843            unchanged_reads: self.stats.unchanged_reads.load(Ordering::SeqCst),
844            shared_reads: self.stats.shared_reads.load(Ordering::SeqCst),
845            suppressed: self.stats.suppressed.load(Ordering::SeqCst),
846        }
847    }
848
849    /// The client every request goes through, for its traffic counters.
850    #[must_use]
851    pub const fn client(&self) -> &Arc<AuthenticatedClient> {
852        &self.client
853    }
854
855    /// The rate limit still being waited out, with the time left on it.
856    fn held(&self, now: Timestamp) -> Option<RateLimited> {
857        let hold = (*self
858            .hold
859            .lock()
860            .unwrap_or_else(std::sync::PoisonError::into_inner))?;
861        let left = hold
862            .until
863            .signed_duration_since(now)
864            .to_std()
865            .ok()?
866            // A clock that jumped backwards must not stretch the hold past
867            // the longest one this gateway ever sets.
868            .min(MAX_RATE_LIMIT_BACKOFF);
869        if left.is_zero() {
870            return None;
871        }
872        Some(RateLimited {
873            retry_after: Some(left),
874            ..hold.limit
875        })
876    }
877
878    /// Start, or lengthen, the host-wide quiet period for `limit`, and say
879    /// how long it is.
880    ///
881    /// # Why a quiet period here, when `e1` already waits
882    ///
883    /// `e1`'s schedule waits per loop, and the daemon runs one loop per
884    /// target. A secondary limit hit by one target's poll used to leave every
885    /// other target's loop polling on its own schedule, which is exactly the
886    /// "continuing to make requests while you are rate limited" GitHub warns
887    /// "may result in the banning of your integration"
888    /// (<https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api#handle-rate-limit-errors-appropriately>).
889    /// Every loop shares this gateway, so a quiet period here silences them
890    /// all.
891    ///
892    /// The wait is GitHub's own: `retry-after` when sent, else until
893    /// `x-ratelimit-reset` for the primary limit, else one minute. A secondary
894    /// limit that recurs doubles it each time, up to
895    /// [`MAX_RATE_LIMIT_BACKOFF`], which is GitHub's "exponentially increasing
896    /// amount of time between retries".
897    fn hold_for(&self, limit: RateLimited, now: Timestamp) -> RateLimited {
898        let mut hold = self
899            .hold
900            .lock()
901            .unwrap_or_else(std::sync::PoisonError::into_inner);
902        // A hold that ended long ago is not part of this episode: a secondary
903        // limit days after the last one starts from one minute again, even if
904        // nothing but errors came back in between.
905        let previous = (*hold).filter(|previous| {
906            now.signed_duration_since(previous.until)
907                < chrono::TimeDelta::from_std(HOLD_MEMORY).unwrap_or(chrono::TimeDelta::MAX)
908        });
909        // The doubling counts EPISODES, not answers. Every target loop shares
910        // this gateway, so one secondary limit can come back on several
911        // requests that were in flight together; each of those is the same
912        // limit, and only an answer arriving after the previous hold ended is
913        // GitHub saying "still limited".
914        let live = previous.filter(|previous| previous.until > now);
915        let consecutive_secondary = match (limit.kind, previous, live) {
916            (RateLimitKind::Primary, _, _) => 0,
917            (RateLimitKind::Secondary, _, Some(live)) => live.consecutive_secondary.max(1),
918            (RateLimitKind::Secondary, Some(previous), None) => {
919                previous.consecutive_secondary.saturating_add(1)
920            }
921            (RateLimitKind::Secondary, None, None) => 1,
922        };
923        let mut wait = limit.delay_from(now);
924        if consecutive_secondary > 1 {
925            let doubled = DEFAULT_RATE_LIMIT_BACKOFF
926                .saturating_mul(1_u32 << (consecutive_secondary - 1).min(10));
927            wait = wait.max(doubled).min(MAX_RATE_LIMIT_BACKOFF);
928        }
929        let mut until = now
930            .checked_add_signed(chrono::TimeDelta::from_std(wait).unwrap_or(chrono::TimeDelta::MAX))
931            .unwrap_or(now);
932        // A later answer never SHORTENS a hold in force: a primary limit with
933        // a near reset must not reopen traffic a secondary limit closed.
934        if let Some(live) = live
935            && live.until > until
936        {
937            until = live.until;
938            wait = until.signed_duration_since(now).to_std().unwrap_or(wait);
939        }
940        *hold = Some(RateLimitHold {
941            until,
942            limit,
943            consecutive_secondary: consecutive_secondary
944                .max(live.map_or(0, |live| live.consecutive_secondary)),
945        });
946        RateLimited {
947            retry_after: Some(wait),
948            ..limit
949        }
950    }
951
952    /// A request went through: the next secondary limit starts the doubling
953    /// again from one minute.
954    fn clear_hold(&self) {
955        let mut hold = self
956            .hold
957            .lock()
958            .unwrap_or_else(std::sync::PoisonError::into_inner);
959        if hold.is_some_and(|h| h.until <= self.clock.now()) {
960            *hold = None;
961        }
962    }
963
964    /// How many HTTP requests this gateway has issued.
965    ///
966    /// [`demand_requests_per_poll`] projects a cost and this measures it. A
967    /// projection nothing measures is a table in a document, which is why `c3`
968    /// exposes the same counter and why the tests below assert one against the
969    /// other.
970    #[must_use]
971    pub fn requests_issued(&self) -> u64 {
972        self.requests_issued.load(Ordering::SeqCst)
973    }
974
975    /// One request, with cancellation applied and a rate limit recognised.
976    ///
977    /// Cancellation is consulted twice for `c3`'s reason, and the two are not
978    /// redundant: [`CancelToken::check`] stops a multi-page walk *between*
979    /// pages, and [`CancelToken::run`] stops one already blocked on a socket.
980    ///
981    /// Every request is **conditional** once its listing has been seen: see
982    /// [`crate::conditional`]. And none is sent at all inside the host-wide
983    /// rate-limit quiet period; see [`Self::hold_for`].
984    async fn get(
985        &self,
986        request: &ApiRequest,
987        cancel: &CancelToken,
988    ) -> Result<Fetched, InventoryError> {
989        cancel.check()?;
990        if let Some(limit) = self.held(self.clock.now()) {
991            self.stats.suppressed.fetch_add(1, Ordering::SeqCst);
992            return Err(InventoryError::RateLimited(limit));
993        }
994
995        let result = cancel
996            .run(async {
997                // Counted inside the future, so the count is of requests
998                // actually attempted: `run`'s biased `select!` answers
999                // `Cancelled` without polling this block when the token is
1000                // already flipped, and no socket is opened.
1001                self.requests_issued.fetch_add(1, Ordering::SeqCst);
1002                self.conditional
1003                    .send(&self.client, request)
1004                    .await
1005                    .map_err(InventoryError::from)
1006            })
1007            .await;
1008        match result {
1009            Ok(fetched) => {
1010                self.clear_hold();
1011                Ok(fetched)
1012            }
1013            Err(InventoryError::Github(error)) => Err(self.classify(error)),
1014            Err(other) => Err(other),
1015        }
1016    }
1017
1018    /// Turn a failure into a rate limit when GitHub's own evidence says it is
1019    /// one, using `c3`'s decision procedure rather than a second one, and
1020    /// start the host-wide quiet period for it.
1021    fn classify(&self, error: GithubError) -> InventoryError {
1022        let Some(limit) = RateLimited::detect(&error) else {
1023            return InventoryError::Github(error);
1024        };
1025        let held = self.hold_for(limit, self.clock.now());
1026        tracing::warn!(
1027            kind = %limit.kind,
1028            remaining = limit.remaining,
1029            quiet_secs = held.retry_after.map_or(0, |wait| wait.as_secs()),
1030            "GitHub is rate limiting this credential; demand for this poll is unknown, not zero, \
1031             and no demand request leaves this host until the quiet period ends"
1032        );
1033        InventoryError::RateLimited(held)
1034    }
1035
1036    /// Queued **jobs** for one repository, each with the `runs-on` it requires.
1037    ///
1038    /// Two run listings, then one job listing per run either cap admits. See
1039    /// [`DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL`] for what that costs in steady
1040    /// state and [`max_demand_requests_per_repository_per_poll`] for the bound.
1041    ///
1042    /// # The order of the two passes is load-bearing
1043    ///
1044    /// Queued runs are resolved first and in-progress runs second, because the
1045    /// caps are spent in that order and the first pass carries the signal. A
1046    /// repository busy enough to exhaust the queued cap gets no in-progress pass
1047    /// at all, which is the right trade: its count is already a floor above any
1048    /// realistic host ceiling, and one more `needs:`-gated job cannot change the
1049    /// allocation.
1050    ///
1051    /// # Why a run is resolved at most once, though the two queries are disjoint
1052    ///
1053    /// They are disjoint *at any one instant*, and these are two requests with
1054    /// time between them. A run that is `queued` when the first is answered and
1055    /// `in_progress` when the second is — which is precisely what happens when
1056    /// its last waiting job gets picked up, so it is the common transition
1057    /// rather than an exotic one — appears in **both** lists. Listing its jobs
1058    /// twice would count every queued job it still holds twice, and demand that
1059    /// double-counts starts runners for work that does not exist.
1060    ///
1061    /// The seen set is what stops that. It is deliberately not an argument that
1062    /// the race is too narrow to matter: the window is one HTTP round trip
1063    /// against a poll that repeats every sixty seconds forever, and the failure
1064    /// it produces is silent inflation rather than an error.
1065    async fn repository_queued(
1066        &self,
1067        repository: &OwnerRepo,
1068        cancel: &CancelToken,
1069    ) -> Result<RepositoryDemand, InventoryError> {
1070        let mut jobs: Vec<RunsOn> = Vec::new();
1071        let mut exact = true;
1072        let mut changed = false;
1073        let mut resolved: BTreeSet<u64> = BTreeSet::new();
1074
1075        for (status, cap) in [
1076            (QUEUED_RUN_STATUS, MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL),
1077            (
1078                IN_PROGRESS_RUN_STATUS,
1079                MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL,
1080            ),
1081        ] {
1082            let listing = self.active_runs(repository, status, cap, cancel).await?;
1083            exact &= listing.complete;
1084            changed |= listing.changed;
1085
1086            for run_id in listing.run_ids {
1087                // A run that changed status between the two listings is in both.
1088                // Resolving it twice would double every queued job it holds.
1089                if !resolved.insert(run_id) {
1090                    continue;
1091                }
1092                let run = self.queued_jobs_of_run(repository, run_id, cancel).await?;
1093                exact &= run.complete;
1094                changed |= run.changed;
1095                jobs.extend(run.jobs);
1096            }
1097        }
1098
1099        self.stats.reads.fetch_add(1, Ordering::SeqCst);
1100        if !changed {
1101            self.stats.unchanged_reads.fetch_add(1, Ordering::SeqCst);
1102        }
1103        Ok(RepositoryDemand {
1104            jobs,
1105            exact,
1106            busy: changed && !resolved.is_empty(),
1107        })
1108    }
1109
1110    /// One repository's reading, from the shared window when another target
1111    /// fetched it recently enough, from GitHub otherwise.
1112    async fn repository_reading(
1113        &self,
1114        repository: &OwnerRepo,
1115        cancel: &CancelToken,
1116    ) -> Result<RepositoryDemand, InventoryError> {
1117        let window = self.shared_window();
1118        if window.is_zero() {
1119            return self.repository_queued(repository, cancel).await;
1120        }
1121        let gate = Arc::clone(
1122            self.shared
1123                .gates
1124                .lock()
1125                .unwrap_or_else(std::sync::PoisonError::into_inner)
1126                .entry(repository.clone())
1127                .or_default(),
1128        );
1129        // Held across the fetch, so a second loop asking for this repository
1130        // meanwhile waits for this reading instead of making its own request.
1131        let _gate = cancel.run(async { Ok(gate.lock().await) }).await?;
1132        let now = self.clock.now();
1133        let fresh = self
1134            .shared
1135            .readings
1136            .lock()
1137            .unwrap_or_else(std::sync::PoisonError::into_inner)
1138            .get(repository)
1139            .filter(|(at, _)| {
1140                now.signed_duration_since(*at)
1141                    .to_std()
1142                    .is_ok_and(|age| age < window)
1143            })
1144            .map(|(_, reading)| reading.clone());
1145        if let Some(reading) = fresh {
1146            self.stats.shared_reads.fetch_add(1, Ordering::SeqCst);
1147            return Ok(reading);
1148        }
1149        let reading = self.repository_queued(repository, cancel).await?;
1150        let mut readings = self
1151            .shared
1152            .readings
1153            .lock()
1154            .unwrap_or_else(std::sync::PoisonError::into_inner);
1155        readings.insert(repository.clone(), (now, reading.clone()));
1156        // A repository that left an organization's list stops being asked
1157        // for; its reading goes once nobody could use it.
1158        readings.retain(|_, (at, _)| {
1159            now.signed_duration_since(*at)
1160                .to_std()
1161                .is_ok_and(|age| age < HOLD_MEMORY)
1162        });
1163        Ok(reading)
1164    }
1165
1166    /// The ids of one repository's runs in `status`, up to `cap`.
1167    ///
1168    /// **One request, never a page walk.** Both caps are far below [`PER_PAGE`],
1169    /// so the first page always carries more run ids than this may use, and a
1170    /// second page could only contain runs that are already past the cap. That
1171    /// is the whole reason the caps are stated in *runs* rather than in pages:
1172    /// it turns the run listing back into the fixed one-request cost the
1173    /// previous owner decision valued, and spends the variable cost only where
1174    /// it buys the job-level count.
1175    async fn active_runs(
1176        &self,
1177        repository: &OwnerRepo,
1178        status: &str,
1179        cap: usize,
1180        cancel: &CancelToken,
1181    ) -> Result<RunListing, InventoryError> {
1182        let request = ApiRequest::get(format!(
1183            "/repos/{}/{}/actions/runs",
1184            repository.owner(),
1185            repository.repo()
1186        ))
1187        .query("status", status)
1188        .query("per_page", PER_PAGE);
1189
1190        let Fetched {
1191            response,
1192            not_modified,
1193        } = self.get(&request, cancel).await?;
1194        let has_next_page = response.next_page().is_some();
1195        let page: QueuedRunsPage = response.json()?;
1196
1197        let listed = page.workflow_runs.len();
1198        if let Some(total) = page.total_count
1199            && !has_next_page
1200            && total != listed as u64
1201        {
1202            // Free, and no longer load-bearing: see `MAX_BENIGN_TOTAL_COUNT_SKEW`
1203            // for why this is a log line and not the `debug_assert!` it was
1204            // while `total_count` *was* the demand number. The two levels draw
1205            // the same distinction that constant does. A handful over is the
1206            // documented race of a run leaving the queue mid-serialisation,
1207            // which this module's own documentation calls legitimate — warning
1208            // on it every poll is how an operator learns to ignore the warning.
1209            // Thousands over is the unfiltered lifetime total, which is a real
1210            // finding about the API.
1211            if total > (listed as u64).saturating_add(MAX_BENIGN_TOTAL_COUNT_SKEW) {
1212                tracing::warn!(
1213                    repository = %repository,
1214                    status,
1215                    total_count = total,
1216                    listed,
1217                    "GitHub's `total_count` is far larger than the single page it sent for \
1218                     a filtered query, so it is not the filtered count. Demand is counted \
1219                     from the jobs and does not depend on this field, but `c3` reads the \
1220                     same envelope for a dashboard number and does"
1221                );
1222            } else {
1223                tracing::debug!(
1224                    repository = %repository,
1225                    status,
1226                    total_count = total,
1227                    listed,
1228                    "GitHub's `total_count` disagrees slightly with the page it arrived \
1229                     with; this is the documented race of a run leaving the queue while \
1230                     the response was being built"
1231                );
1232            }
1233        }
1234
1235        let run_ids: Vec<u64> = page
1236            .workflow_runs
1237            .iter()
1238            .take(cap)
1239            .map(|run| run.id)
1240            .collect();
1241
1242        Ok(RunListing {
1243            // More runs exist than this pass will resolve, so the job count it
1244            // produces is a floor. Both conditions matter: `listed > cap` is the
1245            // ordinary case, and `has_next_page` catches a repository whose
1246            // first page was itself short of the whole filtered set.
1247            complete: listed <= cap && !has_next_page,
1248            run_ids,
1249            changed: !not_modified,
1250        })
1251    }
1252
1253    /// One run's jobs that are still waiting for a runner.
1254    ///
1255    /// Jobs in any other state are dropped here rather than downstream, because
1256    /// "queued" is what makes a job demand and a caller holding a mixed list
1257    /// would have to re-derive that. The `runs-on` is rebuilt from the job's
1258    /// `labels` array — which is the array form, so [`RunsOn::from_job_labels`]
1259    /// is the constructor `b1` provides for exactly this.
1260    async fn queued_jobs_of_run(
1261        &self,
1262        repository: &OwnerRepo,
1263        run_id: u64,
1264        cancel: &CancelToken,
1265    ) -> Result<RunJobs, InventoryError> {
1266        let mut request = Some(
1267            ApiRequest::get(format!(
1268                "/repos/{}/{}/actions/runs/{run_id}/jobs",
1269                repository.owner(),
1270                repository.repo()
1271            ))
1272            .query("filter", LATEST_JOBS_FILTER)
1273            .query("per_page", PER_PAGE),
1274        );
1275
1276        let mut jobs = Vec::new();
1277        let mut pages = 0_usize;
1278        let mut changed = false;
1279
1280        while let Some(next) = request.take() {
1281            if pages >= MAX_JOB_PAGES_PER_RUN {
1282                tracing::warn!(
1283                    repository = %repository,
1284                    run_id,
1285                    pages,
1286                    "stopped listing one run's jobs at the page budget; the queued-job \
1287                     count for this repository is a floor, not a total"
1288                );
1289                return Ok(RunJobs {
1290                    jobs,
1291                    complete: false,
1292                    changed,
1293                });
1294            }
1295
1296            let Fetched {
1297                response,
1298                not_modified,
1299            } = self.get(&next, cancel).await?;
1300            changed |= !not_modified;
1301            let following = response
1302                .next_page()
1303                .map(|url| ApiRequest::get(url.as_str()));
1304            let page: RunJobsPage = response.json()?;
1305            pages += 1;
1306
1307            jobs.extend(
1308                page.jobs
1309                    .into_iter()
1310                    .filter(|job| job.status == QUEUED_JOB_STATUS)
1311                    .map(|job| RunsOn::from_job_labels(job.labels)),
1312            );
1313
1314            request = following;
1315        }
1316
1317        Ok(RunJobs {
1318            jobs,
1319            complete: true,
1320            changed,
1321        })
1322    }
1323}
1324
1325/// Whether a per-repository failure should be recorded and stepped over, or
1326/// should abort the whole aggregate.
1327///
1328/// The same line `c3` draws in its private `is_repository_local_failure`, and
1329/// repeated here rather than shared because that function lives in a file this
1330/// task does not own. The line is between a fact about *that repository* — a
1331/// `404` for one deleted or renamed, a plain `403` for one with Actions disabled
1332/// — and a fact about the credential or the connection, which stepping over
1333/// would turn into a total short by an unknown amount while looking complete.
1334///
1335/// It applies to an aggregate only. Stepping over the only repository in scope
1336/// would turn a permissions failure into demand `0`, and `e1` would then read
1337/// "nothing queued" for a target it cannot see at all — so the caller checks
1338/// [`TargetScope`] first.
1339fn is_repository_local_failure(error: &InventoryError) -> bool {
1340    match error {
1341        InventoryError::Github(GithubError::Forbidden { .. }) => true,
1342        InventoryError::Github(GithubError::Status { status, .. }) => *status == 404,
1343        _ => false,
1344    }
1345}
1346
1347#[async_trait::async_trait]
1348impl DemandGateway for RestDemand {
1349    async fn queued_demand(
1350        &self,
1351        scope: &ActivityScope,
1352        cancel: &CancelToken,
1353    ) -> Result<QueuedDemand, InventoryError> {
1354        let mut demand = QueuedDemand::default();
1355        // Only an aggregate steps over a bad repository; see
1356        // `is_repository_local_failure`.
1357        let aggregating = scope.target().scope() == TargetScope::Organization;
1358        self.conditional.evict_idle();
1359
1360        for repository in scope.repositories() {
1361            match self.repository_reading(repository, cancel).await {
1362                Ok(reading) => {
1363                    if reading.busy {
1364                        demand.busy.insert(repository.clone());
1365                    }
1366                    demand
1367                        .per_repository
1368                        .insert(repository.clone(), reading.jobs);
1369                    if !reading.exact {
1370                        // A floor travels with the aggregate rather than being
1371                        // flattened into it: one truncated repository makes the
1372                        // total a floor too, and nothing downstream has another
1373                        // way to know.
1374                        demand.truncated.insert(repository.clone());
1375                    }
1376                }
1377                Err(error) if aggregating && is_repository_local_failure(&error) => {
1378                    tracing::warn!(
1379                        repository = %repository,
1380                        error = %error,
1381                        "a repository in this organization could not be polled for demand; \
1382                         the aggregate reports it as unavailable rather than as zero"
1383                    );
1384                    demand.unavailable.push(UnavailableRepository {
1385                        repository: repository.clone(),
1386                        reason: error.to_string(),
1387                    });
1388                }
1389                Err(error) => return Err(error),
1390            }
1391        }
1392
1393        demand.rate_limit = self.client.traffic().latest_rate_limit();
1394        Ok(demand)
1395    }
1396
1397    fn now(&self) -> Timestamp {
1398        self.clock.now()
1399    }
1400}
1401
1402// ---------------------------------------------------------------------------
1403// Wire shapes
1404// ---------------------------------------------------------------------------
1405
1406/// One repository's queued jobs, and whether that set is the whole truth.
1407#[derive(Debug, Clone, PartialEq, Eq)]
1408struct RepositoryDemand {
1409    /// The `runs-on` of every job still waiting for a runner.
1410    jobs: Vec<RunsOn>,
1411    /// `false` when `jobs` is a **floor**: a run cap or a job page budget
1412    /// stopped the walk before the whole queue had been seen.
1413    exact: bool,
1414    /// Runs were under way and at least one listing changed since the last
1415    /// poll. See [`QueuedDemand::is_quiet`].
1416    busy: bool,
1417}
1418
1419/// One run listing's ids, and whether the cap left any behind.
1420#[derive(Debug, Clone, PartialEq, Eq)]
1421struct RunListing {
1422    run_ids: Vec<u64>,
1423    complete: bool,
1424    /// `false` when GitHub answered `304`.
1425    changed: bool,
1426}
1427
1428/// One run's queued jobs, and whether the page budget saw all of them.
1429#[derive(Debug, Clone, PartialEq, Eq)]
1430struct RunJobs {
1431    jobs: Vec<RunsOn>,
1432    complete: bool,
1433    /// `false` when every page was answered `304`.
1434    changed: bool,
1435}
1436
1437/// One page of `GET …/actions/runs?status=…`.
1438///
1439/// Only the `id` is read, and it is read because the job listing needs it. That
1440/// is the field the previous owner decision deliberately did not have — the
1441/// module documentation used to point at `jobs_url` and ask nobody to follow it
1442/// — and reversing that decision is what put it here.
1443#[derive(Debug, Deserialize)]
1444struct QueuedRunsPage {
1445    total_count: Option<u64>,
1446    #[serde(default)]
1447    workflow_runs: Vec<QueuedRun>,
1448}
1449
1450/// One workflow run, reduced to the identifier its jobs are fetched by.
1451#[derive(Debug, Deserialize)]
1452struct QueuedRun {
1453    id: u64,
1454}
1455
1456/// One page of `GET …/actions/runs/{run_id}/jobs`.
1457#[derive(Debug, Deserialize)]
1458struct RunJobsPage {
1459    #[serde(default)]
1460    jobs: Vec<RunJob>,
1461}
1462
1463/// One job of a run: whether it is still waiting, and what it needs.
1464///
1465/// `labels` is GitHub's flat array form of `runs-on`, which is why
1466/// [`RunsOn::from_job_labels`] exists on `b1`'s side. It defaults to empty
1467/// rather than being required, because a job with no labels is a real answer —
1468/// `b1` reports it as [`runner_manager_domain::policy::UnresolvableRunsOn`] —
1469/// and a missing field should not fail the whole repository's poll.
1470#[derive(Debug, Deserialize)]
1471struct RunJob {
1472    #[serde(default)]
1473    status: String,
1474    #[serde(default)]
1475    labels: Vec<String>,
1476}
1477
1478// The unit tests below are inline rather than in a `src/demand/tests.rs`, and
1479// that is a constraint rather than a preference: `lib.rs`'s
1480// `the_confidential_credential_scan_covers_every_source_file` walks `src/`
1481// recursively and requires every `.rs` file under it to appear in
1482// `CRATE_SOURCES` — a list in `lib.rs`, which `c2` owns. A second file in this
1483// directory would fail that pin, and the only fix would be editing another
1484// task's file.
1485#[cfg(test)]
1486mod tests {
1487    use super::*;
1488    use crate::testing::{FIXTURE_TOKEN, TestClock};
1489    use crate::{Endpoints, UserAccessToken};
1490    use runner_manager_domain::{
1491        model::{Arch, HostLabel, Label, Org, Os},
1492        policy::{RoutingLabels, RunsOn, RunsOnMatch, UnresolvableRunsOn},
1493    };
1494    use secrecy::SecretString;
1495    use serde_json::json;
1496    use wiremock::{
1497        Mock, MockServer, ResponseTemplate,
1498        matchers::{method, path, query_param},
1499    };
1500
1501    fn repo() -> OwnerRepo {
1502        OwnerRepo::parse("octo/dashboard").expect("a valid owner/repo")
1503    }
1504
1505    fn other_repo() -> OwnerRepo {
1506        OwnerRepo::parse("octo/api").expect("a valid owner/repo")
1507    }
1508
1509    fn third_repo() -> OwnerRepo {
1510        OwnerRepo::parse("octo/tools").expect("a valid owner/repo")
1511    }
1512
1513    fn org_scope(repositories: impl IntoIterator<Item = OwnerRepo>) -> ActivityScope {
1514        ActivityScope::organization(
1515            Org::new("octo-org").expect("a valid organization login"),
1516            repositories,
1517        )
1518    }
1519
1520    fn gateway(server: &MockServer) -> RestDemand {
1521        let endpoints = Endpoints::for_test_server(&server.uri()).expect("a test server base");
1522        let token = UserAccessToken::from_stored(SecretString::from(FIXTURE_TOKEN));
1523        let client = AuthenticatedClient::new(endpoints, token, Arc::new(TestClock::default()))
1524            .expect("a client over the test server");
1525        RestDemand::new(Arc::new(client), Arc::new(TestClock::default()))
1526    }
1527
1528    // -- fixtures -----------------------------------------------------------
1529
1530    /// A run list carrying `ids`, and a `total_count` that agrees with it.
1531    fn runs_body(ids: &[u64]) -> serde_json::Value {
1532        json!({
1533            "total_count": ids.len(),
1534            "workflow_runs": ids.iter().map(|id| json!({ "id": id })).collect::<Vec<_>>()
1535        })
1536    }
1537
1538    /// An empty run list, which is what an idle repository answers.
1539    fn no_runs() -> serde_json::Value {
1540        runs_body(&[])
1541    }
1542
1543    /// A jobs page: `queued` jobs carrying `labels`, then `running` that do not
1544    /// count.
1545    fn jobs_body(labels: &[&str], queued: usize, running: usize) -> serde_json::Value {
1546        let mut jobs = Vec::new();
1547        for _ in 0..queued {
1548            jobs.push(json!({ "status": "queued", "labels": labels }));
1549        }
1550        for _ in 0..running {
1551            jobs.push(json!({ "status": "in_progress", "labels": labels }));
1552        }
1553        json!({ "total_count": jobs.len(), "jobs": jobs })
1554    }
1555
1556    fn runs_path(repository: &OwnerRepo) -> String {
1557        format!(
1558            "/repos/{}/{}/actions/runs",
1559            repository.owner(),
1560            repository.repo()
1561        )
1562    }
1563
1564    fn jobs_path(repository: &OwnerRepo, run_id: u64) -> String {
1565        format!("{}/{run_id}/jobs", runs_path(repository))
1566    }
1567
1568    /// Mount one repository's run list for one status filter.
1569    async fn mount_runs(
1570        server: &MockServer,
1571        repository: &OwnerRepo,
1572        status: &str,
1573        body: serde_json::Value,
1574    ) {
1575        Mock::given(method("GET"))
1576            .and(path(runs_path(repository)))
1577            .and(query_param("status", status))
1578            .respond_with(ResponseTemplate::new(200).set_body_json(body))
1579            .mount(server)
1580            .await;
1581    }
1582
1583    /// Mount one run's job list.
1584    async fn mount_jobs(
1585        server: &MockServer,
1586        repository: &OwnerRepo,
1587        run_id: u64,
1588        body: serde_json::Value,
1589    ) {
1590        Mock::given(method("GET"))
1591            .and(path(jobs_path(repository, run_id)))
1592            .respond_with(ResponseTemplate::new(200).set_body_json(body))
1593            .mount(server)
1594            .await;
1595    }
1596
1597    /// The ordinary shape: one queued run of `queued` + `running` jobs, and an
1598    /// empty in-progress list.
1599    async fn mount_one_queued_run(
1600        server: &MockServer,
1601        repository: &OwnerRepo,
1602        labels: &[&str],
1603        queued: usize,
1604        running: usize,
1605    ) {
1606        mount_runs(server, repository, QUEUED_RUN_STATUS, runs_body(&[100])).await;
1607        mount_runs(server, repository, IN_PROGRESS_RUN_STATUS, no_runs()).await;
1608        mount_jobs(server, repository, 100, jobs_body(labels, queued, running)).await;
1609    }
1610
1611    /// A repository with nothing waiting: two run listings, no job listings.
1612    async fn mount_idle(server: &MockServer, repository: &OwnerRepo) {
1613        mount_runs(server, repository, QUEUED_RUN_STATUS, no_runs()).await;
1614        mount_runs(server, repository, IN_PROGRESS_RUN_STATUS, no_runs()).await;
1615    }
1616
1617    /// The routing labels of a realistic policy on this host.
1618    ///
1619    /// Deliberately **not** a bare [`RoutingLabels::derive`]. That produces the
1620    /// derived host label alone, and a job written `runs-on: [self-hosted,
1621    /// windows]` — the shape people actually write — requires labels a bare
1622    /// derived set does not carry, so it would not match. An operator adds those
1623    /// with `repo add --label`, and a fixture that skipped them would test the
1624    /// filtering against a policy nobody configures.
1625    fn host_labels() -> RoutingLabels {
1626        RoutingLabels::from_parts(
1627            Label::new("rm-home-win-x64").expect("a valid label"),
1628            [
1629                Label::new("self-hosted").expect("a valid label"),
1630                Label::new("windows").expect("a valid label"),
1631            ],
1632        )
1633    }
1634
1635    // -- the count itself ---------------------------------------------------
1636
1637    /// The defect this module was rewritten for, as an executable statement.
1638    ///
1639    /// One queued run holding eight matrix jobs. Under the previous owner
1640    /// decision this repository reported demand `1`, `e1` started one runner,
1641    /// and the other seven jobs waited for a machine that was sitting idle. It
1642    /// must now report `8`.
1643    #[tokio::test]
1644    async fn a_matrix_run_of_eight_jobs_is_eight_units_of_demand_and_not_one() {
1645        let server = MockServer::start().await;
1646        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 8, 0).await;
1647        let gateway = gateway(&server);
1648
1649        let demand = gateway
1650            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1651            .await
1652            .expect("a queued-job count");
1653
1654        assert_eq!(
1655            demand.total(),
1656            8,
1657            "eight jobs in one run are eight runners' worth of work; reading the run \
1658             count here is the defect that forced the owner decision back"
1659        );
1660        assert_eq!(demand.for_repository(&repo()), Some(8));
1661        assert!(demand.is_complete());
1662        assert_eq!(
1663            gateway.requests_issued(),
1664            3,
1665            "two run listings and one job listing for the single active run"
1666        );
1667    }
1668
1669    /// A job that already has a runner is not demand.
1670    ///
1671    /// The run-level mistake one level down: `status=in_progress` work already
1672    /// has a runner, and counting it would start a second for the same job.
1673    #[tokio::test]
1674    async fn only_jobs_still_queued_are_counted() {
1675        let server = MockServer::start().await;
1676        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 3, 5).await;
1677        let gateway = gateway(&server);
1678
1679        let demand = gateway
1680            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1681            .await
1682            .expect("a queued-job count");
1683
1684        assert_eq!(
1685            demand.total(),
1686            3,
1687            "five of the eight jobs already have a runner and are not waiting for one"
1688        );
1689    }
1690
1691    /// The labels travel with the job, which is the input `b1`'s predicate never
1692    /// had.
1693    #[tokio::test]
1694    async fn each_queued_job_carries_the_runs_on_it_requires() {
1695        let server = MockServer::start().await;
1696        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&[100, 101])).await;
1697        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
1698        mount_jobs(
1699            &server,
1700            &repo(),
1701            100,
1702            jobs_body(&["rm-home-win-x64", "self-hosted", "windows"], 2, 0),
1703        )
1704        .await;
1705        mount_jobs(&server, &repo(), 101, jobs_body(&["ubuntu-latest"], 4, 0)).await;
1706        let gateway = gateway(&server);
1707
1708        let demand = gateway
1709            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1710            .await
1711            .expect("a queued-job count");
1712
1713        assert_eq!(
1714            demand.total(),
1715            6,
1716            "the unfiltered depth is every queued job"
1717        );
1718
1719        // And the number `e1` clamps, which is the unfiltered depth put through
1720        // `b1`'s predicate. This gateway does not compute it; it supplies it.
1721        let tally = host_labels().tally(demand.jobs_for(&repo()));
1722        assert_eq!(
1723            tally.demand(),
1724            2,
1725            "the four `ubuntu-latest` jobs are somebody else's work; before the job \
1726             listing existed all six would have driven this policy toward max_capacity"
1727        );
1728        assert_eq!(tally.not_matched, 4);
1729    }
1730
1731    /// The two run statuses are both on the wire, and the job filter with them.
1732    ///
1733    /// The queries are one word apart and answer different questions, so a
1734    /// gateway that sent the wrong one would return a plausible number. The
1735    /// mocks match on the exact status, so sending anything else 404s here
1736    /// rather than passing.
1737    #[tokio::test]
1738    async fn both_run_statuses_are_polled_and_the_jobs_request_asks_for_the_latest_attempt() {
1739        let server = MockServer::start().await;
1740        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 1, 0).await;
1741        let gateway = gateway(&server);
1742
1743        gateway
1744            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1745            .await
1746            .expect("both filters are mounted");
1747
1748        let requests = server.received_requests().await.expect("recorded requests");
1749        assert_eq!(requests.len(), 3);
1750
1751        let queries: Vec<String> = requests
1752            .iter()
1753            .map(|r| r.url.query().unwrap_or_default().to_string())
1754            .collect();
1755
1756        assert!(
1757            queries.iter().any(|q| q.contains("status=queued")),
1758            "the primary signal is the queued run list; sent {queries:?}"
1759        );
1760        assert!(
1761            queries.iter().any(|q| q.contains("status=in_progress")),
1762            "the safety net catches a `needs:`-gated job whose run has already \
1763             started; sent {queries:?}"
1764        );
1765        assert!(
1766            queries
1767                .iter()
1768                .any(|q| q.contains(&format!("filter={LATEST_JOBS_FILTER}"))),
1769            "`filter=all` would count every attempt of a re-run job as present \
1770             demand; sent {queries:?}"
1771        );
1772        assert!(
1773            queries
1774                .iter()
1775                .all(|q| q.contains(&format!("per_page={PER_PAGE}"))),
1776            "asking for fewer than GitHub's maximum multiplies the request count \
1777             against the budget this module projects; sent {queries:?}"
1778        );
1779    }
1780
1781    /// The queued run list is read before the in-progress one.
1782    ///
1783    /// The order is what spends the caps on the signal rather than on the safety
1784    /// net, and it is the kind of thing that is only true until somebody
1785    /// reorders a literal.
1786    #[tokio::test]
1787    async fn the_queued_run_list_is_read_before_the_in_progress_one() {
1788        let server = MockServer::start().await;
1789        mount_idle(&server, &repo()).await;
1790        let gateway = gateway(&server);
1791
1792        gateway
1793            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1794            .await
1795            .expect("an idle repository still answers");
1796
1797        let requests = server.received_requests().await.expect("recorded requests");
1798        let queries: Vec<String> = requests
1799            .iter()
1800            .map(|r| r.url.query().unwrap_or_default().to_string())
1801            .collect();
1802        assert_eq!(queries.len(), 2, "an idle repository lists no run's jobs");
1803        assert!(
1804            queries[0].contains("status=queued"),
1805            "the primary signal is read first; sent {queries:?}"
1806        );
1807        assert!(
1808            queries[1].contains("status=in_progress"),
1809            "the safety net is read second; sent {queries:?}"
1810        );
1811    }
1812
1813    /// An idle repository costs the two listings and nothing more.
1814    ///
1815    /// The steady-state figure the budget model prices, asserted against what
1816    /// the gateway really spends rather than left as a claim in a doc comment.
1817    #[tokio::test]
1818    async fn an_idle_repository_costs_only_the_two_run_listings() {
1819        let server = MockServer::start().await;
1820        mount_idle(&server, &repo()).await;
1821        let gateway = gateway(&server);
1822
1823        let demand = gateway
1824            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1825            .await
1826            .expect("an idle repository answers zero rather than failing");
1827
1828        assert_eq!(demand.total(), 0);
1829        assert!(
1830            demand.is_complete(),
1831            "zero from a repository that answered is a measurement, not a floor"
1832        );
1833        assert_eq!(gateway.requests_issued(), 2);
1834        assert!(
1835            gateway.requests_issued() <= u64::from(DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL),
1836            "the idle case must sit inside the projection, which is the number `f2`'s \
1837             refusals are computed from"
1838        );
1839    }
1840
1841    /// A run whose jobs have all been dispatched is found and costs one request.
1842    ///
1843    /// The safety net's ordinary outcome, and the reason it is capped lower than
1844    /// the primary signal: on the common shape it finds nothing.
1845    #[tokio::test]
1846    async fn an_in_progress_run_with_no_queued_job_contributes_only_its_request() {
1847        let server = MockServer::start().await;
1848        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, no_runs()).await;
1849        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, runs_body(&[200])).await;
1850        mount_jobs(&server, &repo(), 200, jobs_body(&["rm-home-win-x64"], 0, 4)).await;
1851        let gateway = gateway(&server);
1852
1853        let demand = gateway
1854            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1855            .await
1856            .expect("a queued-job count");
1857
1858        assert_eq!(demand.total(), 0);
1859        assert!(demand.is_complete());
1860        assert_eq!(gateway.requests_issued(), 3);
1861    }
1862
1863    /// A run caught mid-transition appears in both listings and is counted once.
1864    ///
1865    /// The two GitHub queries are disjoint at any one instant and these are two
1866    /// requests with time between them. A run whose last waiting job is picked
1867    /// up between them is `queued` for the first and `in_progress` for the
1868    /// second — the ordinary transition, not an exotic one — so it comes back in
1869    /// both lists. Counting its jobs twice would inflate demand silently, which
1870    /// is the failure mode with no error to notice.
1871    #[tokio::test]
1872    async fn a_run_in_both_listings_is_resolved_once_and_not_counted_twice() {
1873        let server = MockServer::start().await;
1874        // The same run id in both lists, which is what the race produces.
1875        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&[100])).await;
1876        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, runs_body(&[100])).await;
1877        mount_jobs(&server, &repo(), 100, jobs_body(&["rm-home-win-x64"], 3, 0)).await;
1878        let gateway = gateway(&server);
1879
1880        let demand = gateway
1881            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1882            .await
1883            .expect("a queued-job count");
1884
1885        assert_eq!(
1886            demand.total(),
1887            3,
1888            "the run holds three queued jobs, and appearing in both listings does not              make it six"
1889        );
1890        assert_eq!(
1891            gateway.requests_issued(),
1892            3,
1893            "and the duplicate costs no second job listing either"
1894        );
1895    }
1896
1897    /// A `needs:`-gated job whose run has already started is still demand.
1898    ///
1899    /// This is the whole reason the in-progress pass exists. Live sampling of a
1900    /// repository using this product never caught GitHub reporting a run as
1901    /// `in_progress` while one of its jobs was queued — 44 samples, 25 of them
1902    /// with a queued job — so the primary signal covers everything that was
1903    /// observed. It does not cover a job that becomes queued *after* its run
1904    /// started, which is what `needs:` produces and what this pins.
1905    #[tokio::test]
1906    async fn a_job_that_enters_the_queue_after_its_run_started_is_still_found() {
1907        let server = MockServer::start().await;
1908        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, no_runs()).await;
1909        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, runs_body(&[200])).await;
1910        // One job running, one released by `needs:` and now waiting.
1911        mount_jobs(&server, &repo(), 200, jobs_body(&["rm-home-win-x64"], 1, 1)).await;
1912        let gateway = gateway(&server);
1913
1914        let demand = gateway
1915            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
1916            .await
1917            .expect("a queued-job count");
1918
1919        assert_eq!(
1920            demand.total(),
1921            1,
1922            "polling only `status=queued` runs would report zero here and the \
1923             `needs:`-gated job would wait for a machine that is idle"
1924        );
1925    }
1926
1927    // -- the wire contract, against payloads GitHub really sent -------------
1928
1929    /// The deserializers are pinned against **real** GitHub responses, not only
1930    /// against fixtures written to match them.
1931    ///
1932    /// Every other test here builds its own JSON, so all of them would keep
1933    /// passing if this module's idea of the wire format were wrong in the same
1934    /// way the fixtures are. That is the one failure a mock server cannot catch,
1935    /// and it is the failure this change was most exposed to: the previous owner
1936    /// decision deliberately read *nothing* out of a run and had no job
1937    /// endpoint at all, so `workflow_runs[].id`, `jobs[].status` and
1938    /// `jobs[].labels` are all fields this crate had never parsed before.
1939    ///
1940    /// The payloads below are verbatim excerpts captured from
1941    /// `api.github.com` on 2026-09-05 against a repository using this product,
1942    /// trimmed only by replacing the `steps` array — which is long, which this
1943    /// module does not read, and whose presence is itself part of what is being
1944    /// asserted, since a job object carries twenty-odd fields that must all be
1945    /// ignored without error.
1946    #[test]
1947    fn the_wire_shapes_parse_a_payload_github_really_sent() {
1948        // GET /repos/{o}/{r}/actions/runs/33938794901/jobs?filter=latest&per_page=100
1949        let jobs: RunJobsPage = serde_json::from_value(json!({
1950          "total_count": 5,
1951          "jobs": [
1952            {
1953              "id": 101_231_925_899_i64,
1954              "run_id": 33_938_794_901_i64,
1955              "workflow_name": "tests",
1956              "head_branch": "worktree-p1-lock-and-worktree-set",
1957              "run_url": "https://api.github.com/repos/o/r/actions/runs/33938794901",
1958              "run_attempt": 1,
1959              "node_id": "CR_kwDOS_wnss8AAAAXkeSaiw",
1960              "head_sha": "e78bc5d1865693aba030d83a2c627dd5515edf45",
1961              "url": "https://api.github.com/repos/o/r/actions/jobs/101231925899",
1962              "html_url": "https://github.com/o/r/actions/runs/33938794901/job/101231925899",
1963              "status": "completed",
1964              "conclusion": "success",
1965              "created_at": "2026-09-05T02:20:30Z",
1966              "started_at": "2026-09-05T02:26:03Z",
1967              "completed_at": "2026-09-05T02:28:44Z",
1968              "name": "scripts-tests",
1969              "steps": [],
1970              "check_run_url": "https://api.github.com/repos/o/r/check-runs/101231925899",
1971              "labels": ["self-hosted", "windows"],
1972              "runner_id": 725,
1973              "runner_name": "runner-manager-4bd32f05-088f-4b13-a59c-6900b9142aa1",
1974              "runner_group_id": 1,
1975              "runner_group_name": "Default"
1976            },
1977            {
1978              "id": 101_231_925_900_i64,
1979              "run_id": 33_938_794_901_i64,
1980              "status": "queued",
1981              "conclusion": serde_json::Value::Null,
1982              "started_at": serde_json::Value::Null,
1983              "completed_at": serde_json::Value::Null,
1984              "name": "pipeline-tests",
1985              "steps": [],
1986              "labels": ["self-hosted", "windows"],
1987              "runner_id": serde_json::Value::Null,
1988              "runner_name": "",
1989              "runner_group_name": ""
1990            },
1991            {
1992              "id": 101_231_925_901_i64,
1993              "status": "queued",
1994              "name": "scripts-tests-macos",
1995              "labels": ["self-hosted", "macOS", "rm-macmini-osx-arm64"]
1996            }
1997          ]
1998        }))
1999        .expect("the jobs page GitHub really sends must deserialize");
2000
2001        assert_eq!(
2002            jobs.jobs.len(),
2003            3,
2004            "every job is read, whatever else it carries"
2005        );
2006
2007        // What the gateway does with it: keep the queued ones, and turn each
2008        // one's `labels` array into the `RunsOn` `b1` matches.
2009        let queued: Vec<RunsOn> = jobs
2010            .jobs
2011            .into_iter()
2012            .filter(|job| job.status == QUEUED_JOB_STATUS)
2013            .map(|job| RunsOn::from_job_labels(job.labels))
2014            .collect();
2015
2016        assert_eq!(
2017            queued,
2018            vec![
2019                RunsOn::Many(vec!["self-hosted".into(), "windows".into()]),
2020                RunsOn::Many(vec![
2021                    "self-hosted".into(),
2022                    "macOS".into(),
2023                    "rm-macmini-osx-arm64".into()
2024                ]),
2025            ],
2026            "the completed job is dropped and the two queued ones keep their labels"
2027        );
2028
2029        // The Windows job requires a subset of this policy's labels, even
2030        // without its selector. The macOS job still requires missing labels.
2031        let tally = host_labels().tally(&queued);
2032        assert_eq!(tally.demand(), 1);
2033        assert_eq!(tally.not_matched, 1);
2034
2035        // GET /repos/{o}/{r}/actions/runs?status=queued&per_page=100, as an idle
2036        // repository answers it. `total_count` and an empty array, which is the
2037        // shape that must read as "nothing waiting" rather than as a failure.
2038        let idle: QueuedRunsPage = serde_json::from_value(json!({
2039            "total_count": 0,
2040            "workflow_runs": []
2041        }))
2042        .expect("an idle run listing must deserialize");
2043        assert_eq!(idle.total_count, Some(0));
2044        assert!(idle.workflow_runs.is_empty());
2045
2046        // And a busy one. A run object carries far more than the id, and the id
2047        // is the only field this module reads out of it.
2048        let busy: QueuedRunsPage = serde_json::from_value(json!({
2049            "total_count": 1,
2050            "workflow_runs": [{
2051                "id": 33_938_794_901_i64,
2052                "name": "tests",
2053                "node_id": "WFR_kwLOS_wnss8AAAAH6oSPFQ",
2054                "head_branch": "main",
2055                "head_sha": "e78bc5d1865693aba030d83a2c627dd5515edf45",
2056                "path": ".github/workflows/tests.yml",
2057                "run_number": 412,
2058                "event": "push",
2059                "status": "queued",
2060                "conclusion": serde_json::Value::Null,
2061                "workflow_id": 213_842_591_i64,
2062                "url": "https://api.github.com/repos/o/r/actions/runs/33938794901",
2063                "created_at": "2026-09-05T02:20:30Z",
2064                "updated_at": "2026-09-05T02:20:31Z"
2065            }]
2066        }))
2067        .expect("a busy run listing must deserialize");
2068        assert_eq!(
2069            busy.workflow_runs
2070                .iter()
2071                .map(|run| run.id)
2072                .collect::<Vec<_>>(),
2073            vec![33_938_794_901],
2074            "the run id is what the job listing is fetched by, and it is a u64: \
2075             GitHub's run ids passed 2^32 long ago, so a u32 here would have \
2076             wrapped on every real repository"
2077        );
2078    }
2079
2080    // -- the caps -----------------------------------------------------------
2081
2082    /// More queued runs than the cap resolves makes the answer a floor.
2083    #[tokio::test]
2084    async fn more_queued_runs_than_the_cap_report_a_floor_rather_than_a_total() {
2085        let server = MockServer::start().await;
2086        let ids: Vec<u64> = (0..(MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL as u64 + 4))
2087            .map(|i| 100 + i)
2088            .collect();
2089        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&ids)).await;
2090        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
2091        for id in &ids {
2092            mount_jobs(&server, &repo(), *id, jobs_body(&["rm-home-win-x64"], 1, 0)).await;
2093        }
2094        let gateway = gateway(&server);
2095
2096        let demand = gateway
2097            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2098            .await
2099            .expect("a bounded poll still answers");
2100
2101        assert_eq!(
2102            demand.total() as usize,
2103            MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL,
2104            "one job resolved per run the cap admits"
2105        );
2106        assert!(
2107            !demand.is_complete(),
2108            "a count clipped by the run cap is a floor and must say so; concluding \
2109             `idle` from one would be the mistake the flag exists to prevent"
2110        );
2111        assert!(demand.is_truncated(&repo()));
2112    }
2113
2114    /// The caps bound what one repository can spend, whatever GitHub sends.
2115    ///
2116    /// The projection is a steady-state figure and the worst case is what keeps
2117    /// it honest, so the worst case has to be a real ceiling rather than an
2118    /// estimate. A repository with a hundred active runs must not spend a
2119    /// hundred requests.
2120    #[tokio::test]
2121    async fn a_repository_cannot_spend_more_than_the_documented_worst_case() {
2122        let server = MockServer::start().await;
2123        let queued: Vec<u64> = (0..40).map(|i| 100 + i).collect();
2124        let running: Vec<u64> = (0..40).map(|i| 500 + i).collect();
2125        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&queued)).await;
2126        mount_runs(
2127            &server,
2128            &repo(),
2129            IN_PROGRESS_RUN_STATUS,
2130            runs_body(&running),
2131        )
2132        .await;
2133        for id in queued.iter().chain(running.iter()) {
2134            mount_jobs(&server, &repo(), *id, jobs_body(&["rm-home-win-x64"], 2, 0)).await;
2135        }
2136        let gateway = gateway(&server);
2137
2138        let demand = gateway
2139            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2140            .await
2141            .expect("a bounded poll still answers");
2142
2143        assert_eq!(
2144            gateway.requests_issued(),
2145            u64::from(max_demand_requests_per_repository_per_poll()),
2146            "the measured ceiling must equal the projected one, or the bound is a \
2147             sentence in a doc comment"
2148        );
2149        assert_eq!(
2150            demand.total(),
2151            2 * (MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL
2152                + MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL) as u32
2153        );
2154        assert!(!demand.is_complete());
2155    }
2156
2157    /// The queued pass is served before the in-progress one when both are over
2158    /// their caps.
2159    #[tokio::test]
2160    async fn the_primary_signal_is_resolved_before_the_safety_net() {
2161        let server = MockServer::start().await;
2162        let queued: Vec<u64> = (0..40).map(|i| 100 + i).collect();
2163        let running: Vec<u64> = (0..40).map(|i| 500 + i).collect();
2164        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&queued)).await;
2165        mount_runs(
2166            &server,
2167            &repo(),
2168            IN_PROGRESS_RUN_STATUS,
2169            runs_body(&running),
2170        )
2171        .await;
2172        // Queued runs hold this host's work; in-progress runs hold another
2173        // host's. If the caps were spent in the other order the demand would be
2174        // made of the wrong jobs.
2175        for id in &queued {
2176            mount_jobs(&server, &repo(), *id, jobs_body(&["rm-home-win-x64"], 1, 0)).await;
2177        }
2178        for id in &running {
2179            mount_jobs(&server, &repo(), *id, jobs_body(&["ubuntu-latest"], 1, 0)).await;
2180        }
2181        let gateway = gateway(&server);
2182
2183        let demand = gateway
2184            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2185            .await
2186            .expect("a bounded poll still answers");
2187
2188        let tally = host_labels().tally(demand.jobs_for(&repo()));
2189        assert_eq!(
2190            tally.demand() as usize,
2191            MAX_QUEUED_RUNS_PER_REPOSITORY_PER_POLL,
2192            "the queued cap is spent in full on the primary signal"
2193        );
2194        assert_eq!(
2195            tally.not_matched as usize, MAX_IN_PROGRESS_RUNS_PER_REPOSITORY_PER_POLL,
2196            "and the safety net gets its own smaller cap, not a share of the first"
2197        );
2198    }
2199
2200    /// One run's job listing follows pages, and stops at its budget.
2201    #[tokio::test]
2202    async fn a_runs_job_listing_walks_pages_and_stops_at_its_budget() {
2203        let server = MockServer::start().await;
2204        let base = server.uri();
2205        let path_100 = jobs_path(&repo(), 100);
2206
2207        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&[100])).await;
2208        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
2209        // Every page points at another, forever.
2210        Mock::given(method("GET"))
2211            .and(path(path_100.clone()))
2212            .respond_with(
2213                ResponseTemplate::new(200)
2214                    .set_body_json(jobs_body(&["rm-home-win-x64"], 100, 0))
2215                    .insert_header(
2216                        "link",
2217                        format!("<{base}{path_100}?page=9>; rel=\"next\"").as_str(),
2218                    ),
2219            )
2220            .mount(&server)
2221            .await;
2222        let gateway = gateway(&server);
2223
2224        let demand = gateway
2225            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2226            .await
2227            .expect("a bounded walk still answers");
2228
2229        assert_eq!(
2230            gateway.requests_issued() as usize,
2231            2 + MAX_JOB_PAGES_PER_RUN,
2232            "an endless `Link` chain must stop at the job page budget rather than \
2233             spending the hourly ceiling on one run"
2234        );
2235        assert_eq!(demand.total() as usize, 100 * MAX_JOB_PAGES_PER_RUN);
2236        assert!(
2237            !demand.is_complete(),
2238            "a count clipped by the page bound is a floor and must say so"
2239        );
2240        assert!(demand.is_truncated(&repo()));
2241    }
2242
2243    // -- the `total_count` tripwire ----------------------------------------
2244
2245    /// The zero-cost check that `total_count` is the *filtered* count.
2246    ///
2247    /// A repository with 3 queued runs out of 5,000 lifetime runs would answer
2248    /// `len() == 3`, no `Link`, and `total_count == 5000`. The demand number no
2249    /// longer comes from that field, so the contradiction is a `warn!` rather
2250    /// than a `debug_assert!` — but it still means GitHub is not answering the
2251    /// question this module asked, and it is free to notice.
2252    #[tokio::test]
2253    async fn a_total_count_that_disagrees_with_its_only_page_does_not_derail_the_count() {
2254        let server = MockServer::start().await;
2255        mount_runs(
2256            &server,
2257            &repo(),
2258            QUEUED_RUN_STATUS,
2259            json!({
2260                "total_count": 5_000,
2261                "workflow_runs": [{ "id": 100 }]
2262            }),
2263        )
2264        .await;
2265        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
2266        mount_jobs(&server, &repo(), 100, jobs_body(&["rm-home-win-x64"], 2, 0)).await;
2267        let gateway = gateway(&server);
2268
2269        let demand = gateway
2270            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2271            .await
2272            .expect("a wrong `total_count` no longer decides anything here");
2273
2274        assert_eq!(
2275            demand.total(),
2276            2,
2277            "the count comes from the jobs of the runs that were actually listed, so a \
2278             `total_count` carrying the unfiltered lifetime total cannot inflate it"
2279        );
2280        assert!(
2281            demand.is_complete(),
2282            "one listed run, no next page, and the cap not reached"
2283        );
2284    }
2285
2286    // -- organization aggregation ------------------------------------------
2287
2288    /// An organization aggregates across its installed repositories, and the
2289    /// request count grows with that repository count.
2290    #[tokio::test]
2291    async fn an_organization_aggregates_its_repositories_and_pays_per_repository() {
2292        let server = MockServer::start().await;
2293        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 2, 0).await;
2294        mount_one_queued_run(&server, &other_repo(), &["rm-home-win-x64"], 5, 0).await;
2295        mount_idle(&server, &third_repo()).await;
2296        let gateway = gateway(&server);
2297
2298        let two = org_scope([repo(), other_repo()]);
2299        let three = org_scope([repo(), other_repo(), third_repo()]);
2300
2301        assert_eq!(
2302            demand_requests_per_poll(&two),
2303            2 * DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL,
2304            "there is no organization-wide workflow-runs endpoint, so the cost is \
2305             per repository"
2306        );
2307        assert!(
2308            demand_requests_per_poll(&three) > demand_requests_per_poll(&two),
2309            "a projection that did not grow with the repository count would understate \
2310             an organization's real spend by exactly that factor"
2311        );
2312
2313        let demand = gateway
2314            .queued_demand(&three, &CancelToken::new())
2315            .await
2316            .expect("an aggregate");
2317
2318        assert_eq!(demand.total(), 7);
2319        assert_eq!(demand.for_repository(&repo()), Some(2));
2320        assert_eq!(demand.for_repository(&other_repo()), Some(5));
2321        assert_eq!(
2322            demand.for_repository(&third_repo()),
2323            Some(0),
2324            "a repository that answered zero is present as a zero, unlike one that \
2325             could not answer at all"
2326        );
2327        assert_eq!(
2328            host_labels().tally(demand.jobs()).demand(),
2329            7,
2330            "an organization policy serves any repository in its scope, so its demand \
2331             is the whole aggregate's rather than one repository's"
2332        );
2333        assert!(
2334            gateway.requests_issued() <= u64::from(max_demand_requests_per_poll(&three)),
2335            "the measured cost must sit inside the projected ceiling, or the budget \
2336             model is a table in a document"
2337        );
2338    }
2339
2340    /// The measured cost is reported to `c3`'s budget model through the seam
2341    /// `c3` left for it, rather than inheriting the estimate.
2342    #[test]
2343    fn the_measured_demand_cost_is_reported_through_c3s_seam() {
2344        use crate::rest::DEMAND_REQUESTS_PER_REPOSITORY_PER_REFRESH;
2345
2346        let scope = org_scope([repo(), other_repo(), third_repo()]);
2347        let estimated = TargetCost::from_activity_scope(&scope);
2348        let measured = target_cost(&scope);
2349
2350        assert_eq!(
2351            DEMAND_REQUESTS_PER_REPOSITORY_PER_REFRESH, 2,
2352            "`c3`'s estimate prices the runs request and one jobs request; this module \
2353             now issues both, plus the in-progress listing and a jobs request per \
2354             additional active run, so the measured figure is higher rather than lower"
2355        );
2356        assert_ne!(
2357            measured, estimated,
2358            "the seam must actually replace the estimate; a `target_cost` that returned \
2359             `from_activity_scope` unchanged would report the estimate as measured"
2360        );
2361        // 1 inventory request + 3 repositories * (1 activity + 4 demand).
2362        assert_eq!(measured.requests_per_refresh(), 16);
2363        // 1 + 3 * (1 + 2), `c3`'s estimate.
2364        assert_eq!(estimated.requests_per_refresh(), 10);
2365        assert!(
2366            measured.requests_per_refresh() > estimated.requests_per_refresh(),
2367            "restoring the per-run job listing added requests; a measured cost that was \
2368             not higher would mean this module is not issuing them"
2369        );
2370    }
2371
2372    /// **A known gap, pinned so it stays visible.** `f2`'s refusal *decision*
2373    /// can consume the measured demand cost; the number it prints alongside the
2374    /// refusal cannot.
2375    ///
2376    /// [`crate::rest::BudgetProjection::admit`] takes the candidate
2377    /// [`TargetCost`] from its caller, so an `f2` that builds it through
2378    /// [`target_cost`] gets an admission computed from the real cost.
2379    /// [`crate::rest::BudgetProjection::max_repository_targets`] builds
2380    /// [`TargetCost::repository`] internally, which cannot see the seam and
2381    /// therefore still prices demand at `c3`'s estimate of two.
2382    ///
2383    /// The two then disagree, and an operator sees both. **The direction of the
2384    /// disagreement inverted when this module started counting jobs**, and that
2385    /// is why this test matters more than it did: the printed ceiling used to be
2386    /// conservative, and is now optimistic. It says a host fits ten repository
2387    /// targets when the cost this module really issues fits six, so an operator
2388    /// planning against the printed number can configure a host that spends more
2389    /// than the projection admitted.
2390    ///
2391    /// What keeps that from being a live budget overrun is
2392    /// `BUDGET_SHARE_DIVISOR`: the projection is compared against half of
2393    /// GitHub's hourly ceiling, so the gap is spent out of the half deliberately
2394    /// left unplanned. It is a reporting defect with a safety margin under it,
2395    /// not a correctness one — and `f1`'s `host show` prints the caveat beside
2396    /// the number.
2397    ///
2398    /// It is not fixable from this file. Both remedies — changing
2399    /// [`crate::rest::DEMAND_REQUESTS_PER_REPOSITORY_PER_REFRESH`], or giving
2400    /// `max_repository_targets` a [`TargetCost`] argument — are edits to
2401    /// `crates/github/src/rest.rs`, which `c3` owns. This test records the
2402    /// discrepancy with its arithmetic so that whoever holds that file can act on
2403    /// it, and fails if it is ever closed, at which point this test and the note
2404    /// above should go.
2405    #[test]
2406    fn the_printed_target_ceiling_still_projects_c3s_estimate() {
2407        use crate::rest::{BudgetProjection, budget_allowance};
2408        use runner_manager_domain::model::RefreshInterval;
2409
2410        let interval = RefreshInterval::default();
2411        let printed = BudgetProjection::max_repository_targets(interval);
2412        let per_hour_estimated = TargetCost::repository().requests_per_hour(interval);
2413        let per_hour_measured = TargetCost::repository()
2414            .with_demand_requests_per_repository(DEMAND_REQUESTS_PER_REPOSITORY_PER_POLL)
2415            .requests_per_hour(interval);
2416
2417        // 4 requests per refresh * 60 refreshes, against 6 * 60.
2418        assert_eq!(per_hour_estimated, 240);
2419        assert_eq!(per_hour_measured, 360);
2420        assert_eq!(
2421            printed, 10,
2422            "the printed ceiling is `04-subsystem-contracts.md`'s figure, computed from \
2423             `c3`'s estimate"
2424        );
2425        assert_eq!(
2426            budget_allowance() / per_hour_measured,
2427            6,
2428            "while the cost this module actually issues allows six"
2429        );
2430        assert!(
2431            printed > budget_allowance() / per_hour_measured,
2432            "the gap now runs in the optimistic direction: the printed ceiling is larger \
2433             than the measured cost supports. `BUDGET_SHARE_DIVISOR` is what absorbs it \
2434             -- see this test's documentation before treating the inequality as harmless"
2435        );
2436    }
2437
2438    /// One archived repository must not take down an organization's whole
2439    /// demand poll — and must not read as zero either.
2440    #[tokio::test]
2441    async fn an_organization_steps_over_a_repository_local_failure_without_reading_it_as_zero() {
2442        let server = MockServer::start().await;
2443        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 4, 0).await;
2444        Mock::given(method("GET"))
2445            .and(path(runs_path(&other_repo())))
2446            .respond_with(
2447                ResponseTemplate::new(404).set_body_json(json!({ "message": "Not Found" })),
2448            )
2449            .mount(&server)
2450            .await;
2451        let gateway = gateway(&server);
2452
2453        let demand = gateway
2454            .queued_demand(&org_scope([repo(), other_repo()]), &CancelToken::new())
2455            .await
2456            .expect("an aggregate steps over a repository it cannot read");
2457
2458        assert_eq!(demand.total(), 4);
2459        assert_eq!(demand.unavailable().len(), 1);
2460        assert_eq!(demand.unavailable()[0].repository, other_repo());
2461        assert_eq!(
2462            demand.for_repository(&other_repo()),
2463            None,
2464            "a repository that could not be polled is absent from the map, not present \
2465             as a zero"
2466        );
2467        assert!(
2468            demand.jobs_for(&other_repo()).is_empty(),
2469            "and its job list is empty rather than absent, so a caller tallying it \
2470             cannot accidentally read an unavailable repository as demand"
2471        );
2472        assert!(
2473            !demand.is_complete(),
2474            "an aggregate missing a repository is not a complete reading"
2475        );
2476    }
2477
2478    /// The same `404`, on a repository *target*, propagates instead.
2479    ///
2480    /// Stepping over the only repository in scope would answer demand `0` for a
2481    /// target this host cannot see at all, and `e1` would then correctly start
2482    /// no runners for the wrong reason — with no error anywhere to explain it.
2483    #[tokio::test]
2484    async fn a_repository_target_propagates_the_failure_rather_than_reporting_zero_demand() {
2485        let server = MockServer::start().await;
2486        Mock::given(method("GET"))
2487            .and(path(runs_path(&repo())))
2488            .respond_with(
2489                ResponseTemplate::new(404).set_body_json(json!({ "message": "Not Found" })),
2490            )
2491            .mount(&server)
2492            .await;
2493        let gateway = gateway(&server);
2494
2495        let error = gateway
2496            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2497            .await
2498            .expect_err("a scope of one has no aggregate to step over into");
2499        assert!(matches!(
2500            error,
2501            InventoryError::Github(GithubError::Status { status: 404, .. })
2502        ));
2503    }
2504
2505    /// A failure on the *job* listing is a failure of the whole poll, not a
2506    /// silently short count.
2507    ///
2508    /// The job listing is where the new requests are, so it is where a new way
2509    /// to under-count could enter: a gateway that swallowed a failed job listing
2510    /// would report the run's jobs as zero, which is indistinguishable from a
2511    /// run whose jobs have all been dispatched.
2512    #[tokio::test]
2513    async fn a_failed_job_listing_is_not_read_as_a_run_with_no_queued_jobs() {
2514        let server = MockServer::start().await;
2515        mount_runs(&server, &repo(), QUEUED_RUN_STATUS, runs_body(&[100])).await;
2516        mount_runs(&server, &repo(), IN_PROGRESS_RUN_STATUS, no_runs()).await;
2517        Mock::given(method("GET"))
2518            .and(path(jobs_path(&repo(), 100)))
2519            .respond_with(
2520                ResponseTemplate::new(500).set_body_json(json!({ "message": "Server Error" })),
2521            )
2522            .mount(&server)
2523            .await;
2524        let gateway = gateway(&server);
2525
2526        let error = gateway
2527            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2528            .await
2529            .expect_err("a job listing that failed is not a run with nothing queued");
2530        assert!(matches!(
2531            error,
2532            InventoryError::Github(GithubError::Status { status: 500, .. })
2533        ));
2534    }
2535
2536    /// A credential failure aborts the aggregate rather than being stepped over.
2537    ///
2538    /// A revoked token is a fact about the credential, not about the repository:
2539    /// stepping over it would report every remaining repository as unavailable
2540    /// and the total as a number, when in truth nothing can be read at all.
2541    #[tokio::test]
2542    async fn a_rate_limit_aborts_the_aggregate_rather_than_being_stepped_over() {
2543        let server = MockServer::start().await;
2544        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 1, 0).await;
2545        Mock::given(method("GET"))
2546            .and(path(runs_path(&other_repo())))
2547            .respond_with(
2548                ResponseTemplate::new(429)
2549                    .insert_header("retry-after", "42")
2550                    .set_body_json(json!({
2551                        "message": "You have exceeded a secondary rate limit"
2552                    })),
2553            )
2554            .mount(&server)
2555            .await;
2556        let gateway = gateway(&server);
2557
2558        let error = gateway
2559            .queued_demand(&org_scope([repo(), other_repo()]), &CancelToken::new())
2560            .await
2561            .expect_err("a rate limit is a fact about the credential, not the repository");
2562
2563        let limit = error
2564            .rate_limited()
2565            .expect("`c3`'s detector is what decides this, and it decided rate limit");
2566        assert_eq!(limit.retry_after, Some(std::time::Duration::from_secs(42)));
2567    }
2568
2569    // -- conditional polling, the shared window, and the quiet period -------
2570
2571    fn gateway_at(server: &MockServer, clock: &Arc<TestClock>) -> RestDemand {
2572        let endpoints = Endpoints::for_test_server(&server.uri()).expect("a test server base");
2573        let token = UserAccessToken::from_stored(SecretString::from(FIXTURE_TOKEN));
2574        let client =
2575            AuthenticatedClient::new(endpoints, token, Arc::clone(clock) as Arc<dyn Clock>)
2576                .expect("a client over the test server");
2577        RestDemand::new(Arc::new(client), Arc::clone(clock) as Arc<dyn Clock>)
2578    }
2579
2580    /// The account-wide quota headers GitHub puts on every response, `304`s
2581    /// included.
2582    fn with_quota(template: ResponseTemplate, remaining: u64) -> ResponseTemplate {
2583        template
2584            .insert_header("x-ratelimit-limit", "5000")
2585            .insert_header("x-ratelimit-remaining", remaining.to_string().as_str())
2586            .insert_header("x-ratelimit-used", (5000 - remaining).to_string().as_str())
2587            .insert_header("x-ratelimit-reset", "1787274000")
2588            .insert_header("x-ratelimit-resource", "core")
2589    }
2590
2591    /// One listing that answers `304` to its own tag and `200` + tag
2592    /// otherwise. Mounted conditional-first, because wiremock answers with the
2593    /// first mock whose matchers all pass.
2594    async fn mount_tagged(
2595        server: &MockServer,
2596        listing: &str,
2597        status: Option<&str>,
2598        etag: &str,
2599        body: serde_json::Value,
2600    ) {
2601        let mut not_modified = Mock::given(method("GET"))
2602            .and(path(listing.to_string()))
2603            .and(wiremock::matchers::header("if-none-match", etag));
2604        if let Some(status) = status {
2605            not_modified = not_modified.and(query_param("status", status));
2606        }
2607        not_modified
2608            .respond_with(with_quota(
2609                ResponseTemplate::new(304).insert_header("etag", etag),
2610                4_000,
2611            ))
2612            .mount(server)
2613            .await;
2614        let mut full = Mock::given(method("GET")).and(path(listing.to_string()));
2615        if let Some(status) = status {
2616            full = full.and(query_param("status", status));
2617        }
2618        full.respond_with(with_quota(
2619            ResponseTemplate::new(200)
2620                .insert_header("etag", etag)
2621                .set_body_json(body),
2622            4_000,
2623        ))
2624        .mount(server)
2625        .await;
2626    }
2627
2628    async fn mount_tagged_idle(server: &MockServer, repository: &OwnerRepo) {
2629        let runs = runs_path(repository);
2630        mount_tagged(
2631            server,
2632            &runs,
2633            Some(QUEUED_RUN_STATUS),
2634            r#"W/"queued""#,
2635            no_runs(),
2636        )
2637        .await;
2638        mount_tagged(
2639            server,
2640            &runs,
2641            Some(IN_PROGRESS_RUN_STATUS),
2642            r#"W/"in-progress""#,
2643            no_runs(),
2644        )
2645        .await;
2646    }
2647
2648    fn conditional_requests(received: &[wiremock::Request]) -> usize {
2649        received
2650            .iter()
2651            .filter(|request| request.headers.contains_key("if-none-match"))
2652            .count()
2653    }
2654
2655    /// The owner's requirement in one test: an idle repository polled again
2656    /// sends its tags back, GitHub answers `304`, and the reading is the same.
2657    #[tokio::test]
2658    async fn an_unchanged_repository_is_polled_with_its_etags_and_answered_304() {
2659        let server = MockServer::start().await;
2660        mount_tagged_idle(&server, &repo()).await;
2661        let clock = Arc::new(TestClock::default());
2662        let gateway = gateway_at(&server, &clock);
2663        let scope = ActivityScope::repository(repo());
2664
2665        let first = gateway
2666            .queued_demand(&scope, &CancelToken::new())
2667            .await
2668            .expect("a first reading");
2669        let second = gateway
2670            .queued_demand(&scope, &CancelToken::new())
2671            .await
2672            .expect("a second reading");
2673
2674        assert_eq!(first.per_repository(), second.per_repository());
2675        let received = server.received_requests().await.expect("recorded requests");
2676        assert_eq!(received.len(), 4, "two listings, twice");
2677        assert_eq!(
2678            conditional_requests(&received),
2679            2,
2680            "the second poll sends both tags back"
2681        );
2682        let traffic = gateway.client().traffic().summary(clock.now());
2683        assert_eq!((traffic.full, traffic.not_modified), (2, 2));
2684        let stats = gateway.stats();
2685        assert_eq!((stats.reads, stats.unchanged_reads), (2, 1));
2686        assert!(second.is_quiet());
2687    }
2688
2689    /// A conditional request must never hide a change: a new run on the very
2690    /// next poll is counted on that poll.
2691    #[tokio::test]
2692    async fn a_run_that_arrives_between_polls_is_counted_on_the_next_one() {
2693        let server = MockServer::start().await;
2694        let runs = runs_path(&repo());
2695        // Asked with the first tag, the queue has moved on: a full answer with
2696        // a new tag.
2697        Mock::given(method("GET"))
2698            .and(path(runs.clone()))
2699            .and(query_param("status", QUEUED_RUN_STATUS))
2700            .and(wiremock::matchers::header("if-none-match", r#"W/"empty""#))
2701            .respond_with(
2702                ResponseTemplate::new(200)
2703                    .insert_header("etag", r#"W/"one-run""#)
2704                    .set_body_json(runs_body(&[100])),
2705            )
2706            .mount(&server)
2707            .await;
2708        Mock::given(method("GET"))
2709            .and(path(runs.clone()))
2710            .and(query_param("status", QUEUED_RUN_STATUS))
2711            .respond_with(
2712                ResponseTemplate::new(200)
2713                    .insert_header("etag", r#"W/"empty""#)
2714                    .set_body_json(no_runs()),
2715            )
2716            .mount(&server)
2717            .await;
2718        mount_tagged(
2719            &server,
2720            &runs,
2721            Some(IN_PROGRESS_RUN_STATUS),
2722            r#"W/"in-progress""#,
2723            no_runs(),
2724        )
2725        .await;
2726        mount_jobs(&server, &repo(), 100, jobs_body(&["rm-home-win-x64"], 2, 0)).await;
2727        let clock = Arc::new(TestClock::default());
2728        let gateway = gateway_at(&server, &clock);
2729        let scope = ActivityScope::repository(repo());
2730
2731        let before = gateway
2732            .queued_demand(&scope, &CancelToken::new())
2733            .await
2734            .expect("an idle reading");
2735        let after = gateway
2736            .queued_demand(&scope, &CancelToken::new())
2737            .await
2738            .expect("a reading after the run arrived");
2739
2740        assert_eq!(before.total(), 0);
2741        assert_eq!(after.total(), 2, "the change is seen on the very next poll");
2742        assert!(
2743            !after.is_quiet(),
2744            "a run under way whose listing changed is activity"
2745        );
2746    }
2747
2748    /// A run stuck in the queue for a label nobody serves is still in the
2749    /// listing hours later. While its listings answer `304` it costs nothing,
2750    /// and it must not hold the target at the slower active interval.
2751    #[tokio::test]
2752    async fn a_queued_run_whose_listings_are_unchanged_is_quiet() {
2753        let server = MockServer::start().await;
2754        let runs = runs_path(&repo());
2755        mount_tagged(
2756            &server,
2757            &runs,
2758            Some(QUEUED_RUN_STATUS),
2759            r#"W/"stuck""#,
2760            runs_body(&[100]),
2761        )
2762        .await;
2763        mount_tagged(
2764            &server,
2765            &runs,
2766            Some(IN_PROGRESS_RUN_STATUS),
2767            r#"W/"in-progress""#,
2768            no_runs(),
2769        )
2770        .await;
2771        mount_tagged(
2772            &server,
2773            &jobs_path(&repo(), 100),
2774            None,
2775            r#"W/"jobs""#,
2776            jobs_body(&["ubuntu-latest"], 1, 0),
2777        )
2778        .await;
2779        let clock = Arc::new(TestClock::default());
2780        let gateway = gateway_at(&server, &clock);
2781        let scope = ActivityScope::repository(repo());
2782
2783        let first = gateway
2784            .queued_demand(&scope, &CancelToken::new())
2785            .await
2786            .expect("a first reading");
2787        let second = gateway
2788            .queued_demand(&scope, &CancelToken::new())
2789            .await
2790            .expect("a second reading");
2791
2792        assert!(
2793            !first.is_quiet(),
2794            "the first sight of a run is a change, and the target must look at it"
2795        );
2796        assert!(second.is_quiet(), "nothing changed; three 304s");
2797        assert_eq!(second.total(), 1, "the job is still counted from the cache");
2798        let received = server.received_requests().await.expect("recorded requests");
2799        assert_eq!(conditional_requests(&received), 3);
2800    }
2801
2802    /// The quota GitHub reports during the poll travels with the reading, so
2803    /// `e1` can slow down on it.
2804    #[tokio::test]
2805    async fn the_accounts_quota_travels_with_the_reading() {
2806        let server = MockServer::start().await;
2807        mount_tagged_idle(&server, &repo()).await;
2808        let clock = Arc::new(TestClock::default());
2809        let gateway = gateway_at(&server, &clock);
2810
2811        let reading = gateway
2812            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2813            .await
2814            .expect("a reading");
2815
2816        let quota = reading
2817            .rate_limit()
2818            .expect("every response carries the quota");
2819        assert_eq!(
2820            (quota.limit, quota.remaining, quota.used),
2821            (5000, 4000, Some(1000))
2822        );
2823    }
2824
2825    /// Two targets covering one repository make one read between them.
2826    #[tokio::test]
2827    async fn a_repository_is_read_once_for_every_target_that_covers_it() {
2828        let server = MockServer::start().await;
2829        mount_tagged_idle(&server, &repo()).await;
2830        mount_tagged_idle(&server, &other_repo()).await;
2831        let clock = Arc::new(TestClock::default());
2832        let gateway = gateway_at(&server, &clock).with_shared_readings(Duration::from_secs(10));
2833
2834        // A repository target and an organization target that contains it.
2835        gateway
2836            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2837            .await
2838            .expect("the repository target's reading");
2839        let organization = gateway
2840            .queued_demand(&org_scope([repo(), other_repo()]), &CancelToken::new())
2841            .await
2842            .expect("the organization target's reading");
2843
2844        assert_eq!(organization.per_repository().len(), 2);
2845        assert_eq!(
2846            gateway.requests_issued(),
2847            4,
2848            "dashboard once (2 listings) and api once (2): the organization target is \
2849             handed the repository target's reading of dashboard"
2850        );
2851        assert_eq!(gateway.stats().shared_reads, 1);
2852
2853        // Past the window the repository is read again.
2854        clock.advance_secs(10);
2855        gateway
2856            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2857            .await
2858            .expect("a later reading");
2859        assert_eq!(gateway.requests_issued(), 6);
2860    }
2861
2862    /// Two loops asking at the same moment make one read between them.
2863    #[tokio::test]
2864    async fn concurrent_targets_wait_for_one_read_instead_of_making_two() {
2865        let server = MockServer::start().await;
2866        mount_tagged_idle(&server, &repo()).await;
2867        let clock = Arc::new(TestClock::default());
2868        let gateway =
2869            Arc::new(gateway_at(&server, &clock).with_shared_readings(Duration::from_secs(10)));
2870
2871        let scope = ActivityScope::repository(repo());
2872        let cancel = CancelToken::new();
2873        let (left, right) = tokio::join!(
2874            gateway.queued_demand(&scope, &cancel),
2875            gateway.queued_demand(&scope, &cancel),
2876        );
2877        left.expect("one reading");
2878        right.expect("the other reading");
2879        assert_eq!(gateway.requests_issued(), 2, "one read: two listings");
2880    }
2881
2882    fn secondary_limit(retry_after: Option<&str>) -> ResponseTemplate {
2883        let template = ResponseTemplate::new(429).set_body_json(json!({
2884            "message": "You have exceeded a secondary rate limit"
2885        }));
2886        match retry_after {
2887            Some(seconds) => template.insert_header("retry-after", seconds),
2888            None => template,
2889        }
2890    }
2891
2892    /// GitHub: "If the `retry-after` response header is present, you should
2893    /// not retry your request until after that many seconds has elapsed." Not
2894    /// this poll, and not any other target's poll on this host either.
2895    #[tokio::test]
2896    async fn a_secondary_limit_stops_every_demand_request_until_retry_after() {
2897        let server = MockServer::start().await;
2898        Mock::given(method("GET"))
2899            .respond_with(secondary_limit(Some("42")))
2900            .mount(&server)
2901            .await;
2902        let clock = Arc::new(TestClock::default());
2903        let gateway = gateway_at(&server, &clock);
2904
2905        let first = gateway
2906            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2907            .await
2908            .expect_err("a rate limit");
2909        assert_eq!(
2910            first.rate_limited().and_then(|limit| limit.retry_after),
2911            Some(Duration::from_secs(42))
2912        );
2913
2914        // Another target, half-way through the window: no request at all.
2915        clock.advance_secs(20);
2916        let held = gateway
2917            .queued_demand(
2918                &ActivityScope::repository(other_repo()),
2919                &CancelToken::new(),
2920            )
2921            .await
2922            .expect_err("still inside the quiet period");
2923        assert_eq!(
2924            held.rate_limited().and_then(|limit| limit.retry_after),
2925            Some(Duration::from_secs(22)),
2926            "the wait left, so the loop's schedule sleeps exactly that"
2927        );
2928        assert_eq!(
2929            server.received_requests().await.expect("recorded").len(),
2930            1,
2931            "a request inside the quiet period is the one GitHub said not to send"
2932        );
2933        assert_eq!(gateway.stats().suppressed, 1);
2934
2935        // At the end of the window, the next poll asks again.
2936        clock.advance_secs(22);
2937        let _ = gateway
2938            .queued_demand(&ActivityScope::repository(repo()), &CancelToken::new())
2939            .await;
2940        assert_eq!(server.received_requests().await.expect("recorded").len(), 2);
2941    }
2942
2943    /// GitHub: "Otherwise, wait for at least one minute before retrying. If
2944    /// your request continues to fail due to a secondary rate limit, wait for
2945    /// an exponentially increasing amount of time between retries."
2946    #[tokio::test]
2947    async fn a_recurring_secondary_limit_doubles_the_quiet_period() {
2948        let server = MockServer::start().await;
2949        Mock::given(method("GET"))
2950            .respond_with(secondary_limit(None))
2951            .mount(&server)
2952            .await;
2953        let clock = Arc::new(TestClock::default());
2954        let gateway = gateway_at(&server, &clock);
2955        let scope = ActivityScope::repository(repo());
2956
2957        let mut waits = Vec::new();
2958        for _ in 0..4 {
2959            let error = gateway
2960                .queued_demand(&scope, &CancelToken::new())
2961                .await
2962                .expect_err("a rate limit");
2963            let wait = error
2964                .rate_limited()
2965                .and_then(|limit| limit.retry_after)
2966                .expect("a wait");
2967            waits.push(wait.as_secs());
2968            clock.advance_secs(i64::try_from(wait.as_secs()).expect("fits"));
2969        }
2970        assert_eq!(waits, [60, 120, 240, 480]);
2971    }
2972
2973    fn secondary(retry_after: Option<u64>) -> RateLimited {
2974        RateLimited {
2975            kind: RateLimitKind::Secondary,
2976            retry_after: retry_after.map(Duration::from_secs),
2977            remaining: Some(4_000),
2978            reset_unix_secs: None,
2979        }
2980    }
2981
2982    /// Every loop shares the gateway, so one secondary limit can come back on
2983    /// several requests that were in flight together. That is one episode.
2984    #[tokio::test]
2985    async fn answers_to_one_secondary_limit_in_flight_together_are_one_episode() {
2986        let server = MockServer::start().await;
2987        let clock = Arc::new(TestClock::default());
2988        let gateway = gateway_at(&server, &clock);
2989        let now = clock.now();
2990
2991        let waits: Vec<u64> = (0..4)
2992            .map(|_| {
2993                gateway
2994                    .hold_for(secondary(None), now)
2995                    .retry_after
2996                    .expect("a wait")
2997                    .as_secs()
2998            })
2999            .collect();
3000        assert_eq!(waits, [60, 60, 60, 60], "four answers, one limit");
3001
3002        clock.advance_secs(60);
3003        let again = gateway.hold_for(secondary(None), clock.now());
3004        assert_eq!(
3005            again.retry_after,
3006            Some(Duration::from_secs(120)),
3007            "an answer after the hold ended is GitHub saying \"still limited\""
3008        );
3009    }
3010
3011    /// A primary limit with a near reset must not reopen what a secondary
3012    /// limit closed.
3013    #[tokio::test]
3014    async fn a_later_answer_never_shortens_a_hold_in_force() {
3015        let server = MockServer::start().await;
3016        let clock = Arc::new(TestClock::default());
3017        let gateway = gateway_at(&server, &clock);
3018
3019        let _ = gateway.hold_for(secondary(Some(600)), clock.now());
3020        let primary = RateLimited {
3021            kind: RateLimitKind::Primary,
3022            retry_after: None,
3023            remaining: Some(0),
3024            reset_unix_secs: Some(u64::try_from(clock.now().timestamp() + 30).expect("positive")),
3025        };
3026        let after = gateway.hold_for(primary, clock.now());
3027        assert_eq!(after.retry_after, Some(Duration::from_secs(600)));
3028        clock.advance_secs(300);
3029        assert_eq!(
3030            gateway
3031                .held(clock.now())
3032                .and_then(|limit| limit.retry_after),
3033            Some(Duration::from_secs(300))
3034        );
3035    }
3036
3037    #[test]
3038    fn an_unavailable_repository_is_not_quiet() {
3039        assert!(QueuedDemand::default().is_quiet());
3040        assert!(
3041            !QueuedDemand::default()
3042                .with_unavailable(repo(), "404")
3043                .is_quiet(),
3044            "its failing listing is charged on every poll; polling it every few seconds \
3045             would multiply that"
3046        );
3047    }
3048
3049    /// A draining loop must not wait behind another loop's read.
3050    #[tokio::test]
3051    async fn a_cancelled_loop_does_not_wait_for_another_loops_read() {
3052        let server = MockServer::start().await;
3053        let clock = Arc::new(TestClock::default());
3054        let gateway = gateway_at(&server, &clock).with_shared_readings(Duration::from_secs(10));
3055        let gate = Arc::clone(
3056            gateway
3057                .shared
3058                .gates
3059                .lock()
3060                .expect("gates")
3061                .entry(repo())
3062                .or_default(),
3063        );
3064        let _another_loop = gate.lock().await;
3065        let cancel = CancelToken::new();
3066        cancel.cancel();
3067
3068        let answer = tokio::time::timeout(
3069            Duration::from_secs(5),
3070            gateway.repository_reading(&repo(), &cancel),
3071        )
3072        .await
3073        .expect("a cancelled loop returns at once instead of queueing on the gate");
3074        assert!(answer.is_err_and(|error| error.is_cancelled()));
3075    }
3076
3077    /// A success in between resets the doubling.
3078    #[tokio::test]
3079    async fn a_success_resets_the_doubling() {
3080        let server = MockServer::start().await;
3081        Mock::given(method("GET"))
3082            .respond_with(secondary_limit(None))
3083            .up_to_n_times(1)
3084            .mount(&server)
3085            .await;
3086        mount_idle(&server, &repo()).await;
3087        let clock = Arc::new(TestClock::default());
3088        let gateway = gateway_at(&server, &clock);
3089        let scope = ActivityScope::repository(repo());
3090
3091        let _ = gateway.queued_demand(&scope, &CancelToken::new()).await;
3092        clock.advance_secs(60);
3093        gateway
3094            .queued_demand(&scope, &CancelToken::new())
3095            .await
3096            .expect("GitHub answered");
3097        server.reset().await;
3098        Mock::given(method("GET"))
3099            .respond_with(secondary_limit(None))
3100            .mount(&server)
3101            .await;
3102        let again = gateway
3103            .queued_demand(&scope, &CancelToken::new())
3104            .await
3105            .expect_err("a fresh rate limit");
3106        assert_eq!(
3107            again.rate_limited().and_then(|limit| limit.retry_after),
3108            Some(Duration::from_secs(60)),
3109            "a limit after a success is a first limit again"
3110        );
3111    }
3112
3113    // -- cancellation -------------------------------------------------------
3114
3115    /// A token flipped between requests stops the poll before the next one.
3116    #[tokio::test]
3117    async fn cancellation_between_requests_stops_the_poll() {
3118        let server = MockServer::start().await;
3119        mount_one_queued_run(&server, &repo(), &["rm-home-win-x64"], 3, 0).await;
3120
3121        let gateway = gateway(&server);
3122        let cancel = CancelToken::new();
3123
3124        let first = gateway
3125            .repository_queued(&repo(), &cancel)
3126            .await
3127            .is_ok_and(|reading| reading.jobs.len() == 3);
3128        assert!(first, "the uncancelled poll reads both lists and the jobs");
3129        assert_eq!(gateway.requests_issued(), 3);
3130
3131        cancel.cancel();
3132        let error = gateway
3133            .repository_queued(&repo(), &cancel)
3134            .await
3135            .expect_err("a cancelled token opens no socket at all");
3136        assert!(error.is_cancelled());
3137        assert_eq!(
3138            gateway.requests_issued(),
3139            3,
3140            "a cancelled poll must spend nothing; the count is of requests attempted"
3141        );
3142    }
3143
3144    // -- the seam this module does not own ---------------------------------
3145
3146    /// The `runs-on` predicate is `b1`'s. This module builds its **input** and
3147    /// implements no part of the matching.
3148    ///
3149    /// # Read this before concluding the test is in the wrong file
3150    ///
3151    /// `c4`'s specification asks for "a `runs-on` table covering forms that must
3152    /// match, forms that must not, and an unresolvable expression, delegating
3153    /// the predicate to `b1`". For a while that table had no input: an owner
3154    /// decision had removed the per-run job listing, a workflow *run* carries no
3155    /// `runs-on`, and this gateway therefore produced nothing to match. That
3156    /// decision has been reversed — the module documentation says why — so the
3157    /// table has its input back and this test asserts both halves of the seam
3158    /// rather than only the delegation half.
3159    ///
3160    /// The division of labour is: `c4` reads each queued job's `labels` array
3161    /// and builds a [`RunsOn`], `b1` decides what matches, and `e1` applies the
3162    /// decision per policy. Constructing a `RunsOn` here is the correct side of
3163    /// that line; comparing labels here is not.
3164    ///
3165    /// # How the second half of that claim is asserted, and how far it reaches
3166    ///
3167    /// By reading this file's own source, because nothing done to `b1` can prove
3168    /// anything about what *this* module contains: every assertion in the body
3169    /// below would pass unchanged with a full label matcher sitting beside it.
3170    /// The scan takes the production half — everything above `#[cfg(test)]`,
3171    /// with comment lines dropped so that the module documentation may keep
3172    /// explaining the seam — and requires that it names none of `b1`'s
3173    /// *decision* vocabulary.
3174    ///
3175    /// `RunsOn` is no longer in the forbidden set, and could not be: this module
3176    /// constructs one per queued job, which is the whole point of the reversal.
3177    /// What stays forbidden is everything that would mean deciding rather than
3178    /// describing — `RoutingLabels`, whose `matches` and `tally` are the
3179    /// predicate, and `DemandTally`, which is the predicate's result. A `c4`
3180    /// that named either would be filtering, and filtering here would make the
3181    /// poll per-policy rather than per-target; the module documentation explains
3182    /// why that trade is refused.
3183    ///
3184    /// Like the needles in `nothing_in_this_crate_reserves_or_claims_a_job`, it
3185    /// is a tripwire on the obvious shape rather than a proof: a hand-rolled
3186    /// comparison of raw label strings that never names a `policy` type would
3187    /// walk past it. Stated rather than implied, for the same reason it is
3188    /// stated there.
3189    #[test]
3190    fn the_runs_on_predicate_is_b1s_and_this_module_only_feeds_it() {
3191        let labels = RoutingLabels::derive(
3192            &HostLabel::new("home").expect("a valid host label"),
3193            Os::Windows,
3194            Arch::X64,
3195        );
3196        let host = labels.host_label().as_str().to_string();
3197        assert_eq!(host, "rm-home-win-x64");
3198
3199        // Must match: the host label alone, in each documented form.
3200        for form in [
3201            RunsOn::Single(host.clone()),
3202            RunsOn::Many(vec![host.clone()]),
3203            RunsOn::Grouped {
3204                group: Some("Default".into()),
3205                labels: runner_manager_domain::policy::RunsOnLabels::One(host.clone()),
3206            },
3207        ] {
3208            assert!(
3209                labels.matches(&form).is_match(),
3210                "a job requiring only this policy's own label must match: {form:?}"
3211            );
3212        }
3213
3214        // Must not match: GitHub-hosted, and another host's label.
3215        for form in [
3216            RunsOn::Single("ubuntu-latest".into()),
3217            RunsOn::Many(vec![host.clone(), "rm-office-win-x64".into()]),
3218        ] {
3219            assert!(
3220                !labels.matches(&form).is_match(),
3221                "a job requiring a label this policy does not carry must not match: {form:?}"
3222            );
3223        }
3224
3225        // Unresolvable: an expression only GitHub can evaluate. Never demand and
3226        // never discarded.
3227        let expression = RunsOn::Single("${{ matrix.runner }}".into());
3228        assert!(matches!(
3229            labels.matches(&expression),
3230            RunsOnMatch::Unresolvable(UnresolvableRunsOn::Expression { .. })
3231        ));
3232
3233        // And the tally keeps the three apart, which is what `e1` clamps.
3234        let tally = labels.tally(&[
3235            RunsOn::Single(host.clone()),
3236            RunsOn::Single("ubuntu-latest".into()),
3237            expression,
3238        ]);
3239        assert_eq!(tally.demand(), 1);
3240        assert_eq!(tally.not_matched, 1);
3241        assert_eq!(tally.unresolvable.len(), 1);
3242        assert_eq!(tally.total_seen(), 3);
3243
3244        // The form this gateway actually builds is the array one, because that
3245        // is the shape the jobs API returns. Pinned so that a `RunsOn` built
3246        // from a job's `labels` really is a value `b1`'s predicate accepts,
3247        // rather than one that happens to compile.
3248        assert_eq!(
3249            RunsOn::from_job_labels(["self-hosted", host.as_str()]),
3250            RunsOn::Many(vec!["self-hosted".into(), host.clone()])
3251        );
3252        assert!(
3253            labels
3254                .matches(&RunsOn::from_job_labels([host.as_str()]))
3255                .is_match()
3256        );
3257        // And the direction that surprises people: a bare derived set does not
3258        // carry `self-hosted`, so the shape most workflows are written in --
3259        // `runs-on: [self-hosted, windows]` -- does **not** match a policy whose
3260        // operator never added those labels. That is `b1`'s superset rule
3261        // working as specified rather than a gap, and it is asserted here
3262        // because the job listing is what finally made it observable.
3263        assert!(
3264            !labels
3265                .matches(&RunsOn::from_job_labels(["self-hosted", host.as_str()]))
3266                .is_match(),
3267            "a job requiring `self-hosted` needs a policy carrying `self-hosted`"
3268        );
3269
3270        // And the other half of this test's title, which everything above leaves
3271        // untouched: that the predicate exercised here has no second
3272        // implementation in this file. See the documentation on this test for
3273        // what the scan covers, what it does not, and why `RunsOn` is absent
3274        // from the list.
3275        let production = this_file_above_its_tests_without_prose();
3276        for owned_by_b1 in ["RoutingLabels", "DemandTally"] {
3277            assert!(
3278                !production.contains(owned_by_b1),
3279                "the demand gateway names `{owned_by_b1}`, which belongs to `b1`: this \
3280                 module builds the predicate's input and does not apply it. Filtering \
3281                 here would make the poll per-policy rather than per-target and multiply \
3282                 its request cost by the number of policies sharing a target -- if an \
3283                 owner decision changed that, it belongs in this module's documentation \
3284                 and in this test before it belongs in the code"
3285            );
3286        }
3287        assert!(
3288            production.contains("RunsOn"),
3289            "and the gateway must still *build* a `RunsOn` per queued job; a production \
3290             half that named none would mean the job listing had been removed again and \
3291             the serial-matrix defect restored"
3292        );
3293    }
3294
3295    /// This file's source above its test module, with comment lines dropped.
3296    ///
3297    /// Two exclusions, each load-bearing. The **test module** goes because the
3298    /// tests above legitimately drive `b1`'s predicate and would accuse the file
3299    /// of owning what they are proving it delegates. The **comments** go because
3300    /// this module's documentation explains the seam at length and names the
3301    /// types to do it — a scan that forbade the explanation would get the
3302    /// explanation deleted, which is the trade
3303    /// `nothing_in_this_crate_reserves_or_claims_a_job` records making in the
3304    /// other direction.
3305    fn this_file_above_its_tests_without_prose() -> String {
3306        let (production, _) = include_str!("demand.rs")
3307            .split_once("\n#[cfg(test)]")
3308            .expect("this file has a test module, and the scan is meaningless without one");
3309        production
3310            .lines()
3311            .filter(|line| !line.trim_start().starts_with("//"))
3312            .collect::<Vec<_>>()
3313            .join("\n")
3314    }
3315
3316    /// The one normalisation both halves of the reservation scan use.
3317    ///
3318    /// Shared rather than written twice, because the defect it closes was two
3319    /// spellings of "the same" normalisation drifting apart: the haystack was
3320    /// lower-cased and the needle was not, so every needle carrying a capital —
3321    /// which is every type-shaped one — could not match a lower-cased haystack,
3322    /// and three of the seven assertions were vacuously true from the day they
3323    /// were written. One function cannot disagree with itself.
3324    fn normalise_for_scan(text: &str) -> String {
3325        text.to_ascii_lowercase().replace(['_', ' '], "")
3326    }
3327
3328    // The Actions-service call this design has no equivalent of, plus the shapes
3329    // an implementer would invent in its place. Matched case-insensitively with
3330    // `_` and spaces removed, so one needle catches the snake, camel and Pascal
3331    // spellings of an identifier at once — and so that the singular needle
3332    // catches the plural.
3333    //
3334    // # Why every needle carries `fn` or `struct`
3335    //
3336    // A bare `acquirejobs` fires on this crate's own prose, and it was written
3337    // that way first: three modules explain *why* there is no job reservation,
3338    // and each has to name the call that does not exist in order to say so. A
3339    // scan that forbids the explanation is a scan that gets the explanation
3340    // deleted, which costs more than it protects. Requiring the item keyword
3341    // narrows the needle to a *definition*, which is what the rule is actually
3342    // about.
3343    //
3344    // What this therefore does **not** catch is stated rather than implied: a
3345    // reservation reached through a trait method, a closure, or a
3346    // differently-named helper. It is a tripwire on the obvious shape, and
3347    // `c4`'s Definition of Done names review as the primary control.
3348    //
3349    // # And why every needle is spelled in halves
3350    //
3351    // `lib.rs`'s confidential-credential scan solves the same problem the same
3352    // way: a needle written out whole would appear in this file's own source and
3353    // the scan would accuse itself. Normalising
3354    // `concat!("fn ", "acquire", "_job")` leaves the quote-comma-quote between
3355    // the halves, so no needle ever appears whole in the text being scanned.
3356    const FORBIDDEN: &[&str] = &[
3357        concat!("fn ", "acquire", "_job"),
3358        concat!("fn ", "claim", "_job"),
3359        concat!("fn ", "lease", "_job"),
3360        concat!("fn ", "reserve", "_job"),
3361        // The acknowledgement this test's own title names alongside the other
3362        // three, and which the list did not actually carry. Spelled to the verb
3363        // rather than to a `_job` suffix, because the shape an implementer
3364        // reaches for acknowledges a *message* or an *assignment* as readily as
3365        // a job, and a suffixed needle would walk straight past those.
3366        concat!("fn ", "ack", "nowledge"),
3367        concat!("struct ", "Job", "Lease"),
3368        concat!("struct ", "Job", "Claim"),
3369        concat!("struct ", "Job", "Reservation"),
3370    ];
3371
3372    /// Which forbidden shape a source text names, if any.
3373    ///
3374    /// The whole-crate scan and its positive control both go through here, so a
3375    /// normalisation that cannot see a shape fails the control loudly instead of
3376    /// passing the scan silently. That is the entire point of the indirection:
3377    /// the arrangement this replaced had the control re-deriving the needle
3378    /// itself, and a copy that agrees with a buggy original proves nothing — it
3379    /// re-derived the needle the same wrong way and went green.
3380    fn forbidden_shape_in(source: &str) -> Option<&'static str> {
3381        let haystack = normalise_for_scan(source);
3382        FORBIDDEN
3383            .iter()
3384            .copied()
3385            .find(|forbidden| haystack.contains(&normalise_for_scan(forbidden)))
3386    }
3387
3388    /// No reservation, claim, lease, or acknowledgement call exists anywhere in
3389    /// this crate.
3390    ///
3391    /// `AcquireJobs` had no REST replacement, so a well-meaning implementer
3392    /// reaches for a local lease to "fix" the surplus-runner case. Three
3393    /// specifications say not to; this makes the instruction executable, over
3394    /// the whole crate rather than only this file, because the edit would most
3395    /// likely land in a new module rather than here.
3396    #[test]
3397    fn nothing_in_this_crate_reserves_or_claims_a_job() {
3398        const SOURCES: &[(&str, &str)] = &[
3399            ("conditional.rs", include_str!("conditional.rs")),
3400            ("demand.rs", include_str!("demand.rs")),
3401            ("device_flow.rs", include_str!("device_flow.rs")),
3402            ("jit.rs", include_str!("jit.rs")),
3403            ("lib.rs", include_str!("lib.rs")),
3404            ("rest.rs", include_str!("rest.rs")),
3405            ("traffic.rs", include_str!("traffic.rs")),
3406        ];
3407        // `SOURCES` is a snapshot, and a snapshot makes "anywhere in the crate"
3408        // false the moment a file is added. The walk below turns the claim back
3409        // into a claim.
3410        //
3411        // It **recurses**, and that is not incidental. `lib.rs` records the
3412        // defect a single `read_dir` produced for the same pin: a module
3413        // directory (`src/rest/mod.rs`) arrives as the entry `rest`, which does
3414        // not end in `.rs`, so a flat filter drops it and takes every file
3415        // underneath with it — leaving the pin passing while the files it exists
3416        // to cover are scanned by nothing at all.
3417        fn walk(directory: &std::path::Path, prefix: &str, found: &mut Vec<String>) {
3418            for entry in std::fs::read_dir(directory).expect("the crate's own src/ is readable") {
3419                let entry = entry.expect("a readable directory entry");
3420                let name = entry.file_name().to_string_lossy().into_owned();
3421                // `/`-joined, which is what `include_str!` takes on every
3422                // platform, so the two sides compare directly.
3423                let joined = if prefix.is_empty() {
3424                    name.clone()
3425                } else {
3426                    format!("{prefix}/{name}")
3427                };
3428                if entry.path().is_dir() {
3429                    walk(&entry.path(), &joined, found);
3430                } else if name.ends_with(".rs") {
3431                    found.push(joined);
3432                }
3433            }
3434        }
3435
3436        let mut listed: Vec<&str> = SOURCES.iter().map(|(name, _)| *name).collect();
3437        listed.sort_unstable();
3438        let mut on_disk = Vec::new();
3439        walk(
3440            std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")),
3441            "",
3442            &mut on_disk,
3443        );
3444        on_disk.sort_unstable();
3445        assert_eq!(
3446            listed, on_disk,
3447            "a source file was added or removed; this scan claims to cover the whole \
3448             crate and a stale list makes that claim false"
3449        );
3450
3451        for (name, source) in SOURCES {
3452            assert_eq!(
3453                forbidden_shape_in(source),
3454                None,
3455                "{name} names a forbidden shape: there is no job reservation on the REST \
3456                 path, and a local lease coordinates this host with itself and with \
3457                 nothing else"
3458            );
3459        }
3460    }
3461
3462    /// The scan above can actually see the things it forbids.
3463    ///
3464    /// A substring scan that never matches passes for the wrong reason. This
3465    /// plants the exact shapes and runs them through [`forbidden_shape_in`] —
3466    /// the same matcher the scan uses, rather than a second copy of it.
3467    ///
3468    /// # Why one planted shape was not enough
3469    ///
3470    /// It planted only the `fn` form, and that form is the one that could not
3471    /// fail: a `fn` needle is already lower-case, so it survived a
3472    /// normalisation that lower-cased the haystack and not the needle. Every
3473    /// type-shaped needle carries capitals and therefore could never match the
3474    /// lower-cased haystack — all three of them were un-catchable, and their
3475    /// three assertions vacuously true, while this control stayed green. (They
3476    /// are not written out here for the reason the list itself is spelled in
3477    /// halves: a literal would make this file fail its own gate.) Both kinds
3478    /// are planted now, and the case-shape of the plant is the property under
3479    /// test rather than an incidental detail of it.
3480    #[test]
3481    fn the_reservation_scan_catches_an_injected_reservation() {
3482        // Assembled from fragments rather than written out, because the scan
3483        // above reads this very file: a literal here would make the crate fail
3484        // its own gate, which is the trap that forced the needles to carry an
3485        // item keyword in the first place.
3486        let call = format!(
3487            "    async {} {}{}(&self) -> Result<Vec<Job>, InventoryError> {{",
3488            "fn", "acquire", "_jobs"
3489        );
3490        let item = format!("{} {}{} {{ id: u64 }}", "struct", "Job", "Lease");
3491        let acknowledgement = format!(
3492            "    async {} {}{}(&self, id: u64) {{",
3493            "fn", "ack", "nowledge_assignment"
3494        );
3495
3496        for (planted, expected) in [
3497            (&call, concat!("fn ", "acquire", "_job")),
3498            (&item, concat!("struct ", "Job", "Lease")),
3499            (&acknowledgement, concat!("fn ", "ack", "nowledge")),
3500        ] {
3501            assert_eq!(
3502                forbidden_shape_in(planted),
3503                Some(expected),
3504                "the scan's own matcher cannot see {planted:?}, so every negative \
3505                 assertion it makes about that shape is worthless"
3506            );
3507        }
3508
3509        // And the plural really is caught by the singular needle, which is the
3510        // one thing about the list above that is not obvious from reading it.
3511        assert!(
3512            call.contains("acquire_jobs"),
3513            "the planted shape is the plural the Actions-service protocol used"
3514        );
3515        // Likewise the acknowledgement needle stops at the verb, so it catches
3516        // the shapes that acknowledge something other than a job by name.
3517        assert!(
3518            acknowledgement.contains("_assignment"),
3519            "the planted acknowledgement names no job, which is why the needle \
3520             carrying a `_job` suffix would have missed it"
3521        );
3522    }
3523}